code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function comparison op begin function comp *args begin if args begin set item = args at 0 for o in args at slice 1 : : begin if call op item o begin set item = o end else begin return call Boolean false end end return call Boolean true end else begin return call Boolean true end end function return comp end function
def comparison(op): def comp(*args): if args: item = args[0] for o in args[1:]: if op(item, o): item = o else: return Boolean(False) return Boolean(True) else: return Boolean(True)...
Python
nomic_cornstack_python_v1
import requests import datetime function refresh_stores begin string Refreshes stores for shipstation api set api_key = string db35920edb384162bbecd52d40a7a781 set api_secret = string d6b01ee7d5074ce29243e9fd07c71763 set store_ids = list 222824 222533 251496 246700 230923 set today = today set refresh_date = string for...
import requests import datetime def refresh_stores(): ''' Refreshes stores for shipstation api ''' api_key = 'db35920edb384162bbecd52d40a7a781' api_secret = 'd6b01ee7d5074ce29243e9fd07c71763' store_ids = [222824, 222533, 251496, 246700, 230923] today = datetime.date.today() refresh_date = to...
Python
zaydzuhri_stack_edu_python
comment print("---------------------- 1 ----------------------") comment for i in range(17): comment print("{0:>2} in binary is {0:08b}".format(i)) comment print("---------------------- 2 ----------------------") comment # It seems using {0:08x} will print eight zeros for the hexadecimal ("x") type of numbers.. comment...
# # print("---------------------- 1 ----------------------") # for i in range(17): # print("{0:>2} in binary is {0:08b}".format(i)) # # print("---------------------- 2 ----------------------") # # It seems using {0:08x} will print eight zeros for the hexadecimal ("x") type of numbers.. # # using {0:8x} will just give ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string This is the (GUI) server-side of a server/client application in which the client can create a number of sub-clients. Each client will have its own socket, running on its own thread. The server will then listen infinitely to each client, allowing them to ...
# !/usr/bin/env python # -*- coding: utf-8 -*- """ This is the (GUI) server-side of a server/client application in which the client can create a number of sub-clients. Each client will have its own socket, running on its own thread. The server will then listen infinitely to each client, allowing them to upload message...
Python
zaydzuhri_stack_edu_python
for i in range 30 begin set next_element = string set symbol_last = string for tuple n symbol in enumerate my_list at i + string _ begin if symbol_last == symbol begin set symbol_cnt = symbol_cnt + 1 end else begin if n != 0 begin set next_element = next_element + string symbol_cnt + symbol_last end set symbol_last =...
for i in range(30): next_element = '' symbol_last = '' for n, symbol in enumerate(my_list[i] + '_'): if symbol_last == symbol: symbol_cnt += 1 else: if n != 0: next_element += str(symbol_cnt) + symbol_last symbol_last = symbol s...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import plotly.graph_objs as go import chart_studio.plotly as py import sys import matplotlib.pyplot as plt from pandas import DataFrame from plotly.graph_objs import * from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.cluster impor...
import pandas as pd import numpy as np import plotly.graph_objs as go import chart_studio.plotly as py import sys import matplotlib.pyplot as plt from pandas import DataFrame from plotly.graph_objs import * from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.cluster impor...
Python
zaydzuhri_stack_edu_python
function search_photo_page albumID begin set query = get args string query none set response = call scan FilterExpression=call contains query ? call contains query ? call contains query ? call contains query set results = response at string Items set items = list for item in results begin if item at string photoID != ...
def search_photo_page(albumID): query = request.args.get('query', None) response = table.scan(FilterExpression=Attr('title').contains(query) | Attr('description').contains(query) | Attr('tags').contains(query) | Attr('EXIF').contains(query)) results = response['Items'] items=[] for item in re...
Python
nomic_cornstack_python_v1
comment 🚨 Don't change the code below 👇 print string Welcome to the Love Calculator! set name1 = input string What is your name? set name2 = input string What is their name? comment 🚨 Don't change the code above 👆 comment Write your code below this line 👇 set name1 = lower name1 set name2 = lower name2 set LOVE = ...
# 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 name1 = name1.lower() name2 = name2.lower() LOVE = name1.count("l") + name1.count("o") + na...
Python
zaydzuhri_stack_edu_python
function _parse_response self future response begin if error begin warning string HTTP error from Github get user: %s error call set_exception call AuthError string Github auth get user info error: %s % string response return end try begin set json = call json_decode body end except Exception begin warning string Inval...
def _parse_response(self, future, response): if response.error: logging.warning("HTTP error from Github get user: %s", response.error) future.set_exception(AuthError('Github auth get user info error: %s' % str(response))) return try: json = tornado.escape....
Python
nomic_cornstack_python_v1
comment Created using Python 3.4.1 import datetime import pytz set starter = call localize call datetime 2015 10 21 23 29 function to_timezone timezone_name begin string This function takes a timezone as a user input and converts the starter time to that timezone set new_timezone = call timezone timezone_name return ca...
# Created using Python 3.4.1 import datetime import pytz starter = pytz.utc.localize(datetime.datetime(2015, 10, 21, 23, 29)) def to_timezone(timezone_name): """ This function takes a timezone as a user input and converts the starter time to that timezone """ new_timezone = pytz.timezone(timezone_name) ...
Python
zaydzuhri_stack_edu_python
comment Download the file ert547_hw5.py; Open the file in Spyder; Run the code by clicking the “Run” button import matplotlib.pyplot as plt import numpy as np from math import sqrt import pdb from csv import reader from random import seed from random import randrange from sklearn import linear_model from sklearn.metric...
#Download the file ert547_hw5.py; Open the file in Spyder; Run the code by clicking the “Run” button import matplotlib.pyplot as plt import numpy as np from math import sqrt import pdb from csv import reader from random import seed from random import randrange from sklearn import linear_model from sklearn.metrics impor...
Python
zaydzuhri_stack_edu_python
from itertools import permutations function possible_permutations seq begin for nums in permutations seq begin yield list nums end end function for n in call possible_permutations list 1 2 3 begin print n end
from itertools import permutations def possible_permutations(seq: list): for nums in permutations(seq): yield list(nums) for n in possible_permutations([1, 2, 3]): print(n)
Python
zaydzuhri_stack_edu_python
function find_triplet array target begin comment Iterate through the array from index 0 to len(array) - 3 for i in range length array - 2 begin comment Check if the sum of current element and next two elements equals the target if array at i + array at i + 1 + array at i + 2 == target begin comment Return the indices o...
def find_triplet(array, target): # Iterate through the array from index 0 to len(array) - 3 for i in range(len(array) - 2): # Check if the sum of current element and next two elements equals the target if array[i] + array[i+1] + array[i+2] == target: # Return the indices of the tripl...
Python
jtatman_500k
function create_account begin set email = input string Enter your email set password = input string Enter your password if email in Email begin print string There is an existing account with this email call transaction end else begin append Email email print string Account successfully created end end function function...
def create_account(): email = input("Enter your email\n") password = input("Enter your password") if email in Email: print("There is an existing account with this email") transaction() else: Email.append(email) print("Account successfully created") def transaction(): ...
Python
zaydzuhri_stack_edu_python
function quarantine_replicas args begin set client = call get_client args set chunk = list comment send requests in chunks set chunk_size = 1000 set rse = rse if paths_list begin set replicas_list = paths_list end else begin comment will iterate over file lines set replicas_list = open paths_file string r end for line...
def quarantine_replicas(args): client = get_client(args) chunk = [] # send requests in chunks chunk_size = 1000 rse = args.rse if args.paths_list: replicas_list = args.paths_list else: replicas_list = open(args.paths_file, "r") # will iterate over file lines for li...
Python
nomic_cornstack_python_v1
function user_present username begin if count filter username=username begin return true end return false end function
def user_present(username): if User.objects.filter(username=username).count(): return True return False
Python
nomic_cornstack_python_v1
function get self geocoder_type=none begin if geocoder_type is none begin set geocoder_type = DEFAULT_GEOCODER_TYPE end if geocoder_type not in types begin raise error string Invalid GeoCoder type [%s] % geocoder_type end return get attribute geocoder geocoder_type end function
def get(self, geocoder_type=None): if geocoder_type is None: geocoder_type = DEFAULT_GEOCODER_TYPE if geocoder_type not in self.types: raise Error('Invalid GeoCoder type [%s]' % geocoder_type) return getattr(geocoder, geocoder_type)
Python
nomic_cornstack_python_v1
import tensorflow as tf import numpy as np set dataset = call from_tensor_slices array list 1 2 3 4 5 dtype=int32 for i in dataset begin print call numpy end comment it = iter(dataset) comment for i in dataset: comment print(it.next().numpy()) print call numpy
import tensorflow as tf import numpy as np dataset = tf.data.Dataset.from_tensor_slices(np.array([1, 2, 3, 4, 5], dtype=np.int32)) for i in dataset: print(i.numpy()) # it = iter(dataset) # for i in dataset: # print(it.next().numpy()) print(dataset.reduce(0, lambda state, value: state + value).numpy())
Python
zaydzuhri_stack_edu_python
function parse_programme self elem begin set programme = call elem_to_programme elem set programme at string start_timestamp = call timegm call utctimetuple set programme at string stop_timestamp = call timegm call utctimetuple debug string Programme: %s programme return programme end function
def parse_programme(self, elem): programme = xmltv.elem_to_programme(elem) programme['start_timestamp'] = calendar.timegm(XMLTV.parse_date_tz(programme['start']).utctimetuple()) programme['stop_timestamp'] = calendar.timegm(XMLTV.parse_date_tz(programme['stop']).utctimetuple()) self.logg...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- print string Bienvenido, este programa verifica si un numero es par o impar set num = integer input string I5ngrese un numero if num % 2 == 0 begin print string num + string es par end else begin print string num + string es impar end
# -*- coding: utf-8 -*- print("Bienvenido, este programa verifica si un numero es par o impar") num=int(input("I5ngrese un numero\n")) if(num %2 == 0): print(str(num)+" es par") else: print(str(num)+" es impar")
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd set data = read csv string shufflefile.data print string This is the un shuffled data data set df = read csv string shufflefile.data header=0 set data2 = call reindex call permutation index print string The shuffled data is data2
import numpy as np import pandas as pd data = pd.read_csv('shufflefile.data') print("This is the un shuffled data", data) df = pd.read_csv('shufflefile.data', header=0) data2 = df.reindex(np.random.permutation(df.index)) print("\n The shuffled data is", data2)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Fri Sep 4 16:19:02 2020 Local Info Web Scraping Project @author: Adam ponting's pc import requests from bs4 import BeautifulSoup set url = string https://www.bbc.co.uk/weather/2650225 set page = get requests url set page_html = text set soup = call BeautifulSoup page_html...
# -*- coding: utf-8 -*- """ Created on Fri Sep 4 16:19:02 2020 Local Info Web Scraping Project @author: Adam ponting's pc """ import requests from bs4 import BeautifulSoup url = 'https://www.bbc.co.uk/weather/2650225' page = requests.get(url) page_html = page.text soup = BeautifulSoup(page_html, features = "lxml") ...
Python
zaydzuhri_stack_edu_python
from common import factorial set q = 100 set s = 0 for l in string call factorial q begin set s = s + integer l end
from common import factorial q = 100 s = 0 for l in str(factorial(q)): s += int(l)
Python
zaydzuhri_stack_edu_python
class Settings begin string This class store all settings for this game project function __init__ self begin string Define all initial setings for the game comment Setting for screen set screen_width = 1000 set screen_height = 700 set bg_color = tuple 230 230 230 comment Setting for ships set ship_limit = 3 comment Set...
class Settings(): """This class store all settings for this game project""" def __init__(self): """Define all initial setings for the game""" # Setting for screen self.screen_width = 1000 self.screen_height = 700 self.bg_color = (230, 230, 230) # Setting for shi...
Python
zaydzuhri_stack_edu_python
function walk self maxresults=100 maxdepth=none begin set seen = dict call ignore self __dict__ obj seen _ignore comment Ignore the calling frame, its builtins, globals and locals call ignore_caller set maxdepth = maxdepth set count = 0 for result in call _gen obj begin yield result set count = count + 1 if maxresults...
def walk(self, maxresults=100, maxdepth=None): self.seen = {} self.ignore(self, self.__dict__, self.obj, self.seen, self._ignore) # Ignore the calling frame, its builtins, globals and locals self.ignore_caller() self.maxdepth = maxdepth count = 0...
Python
nomic_cornstack_python_v1
comment Emory University CS378 comment Homework 2 comment Yicheng (Jason) Wang comment NetId: ywan693 import csv import random import copy import sys import numpy as np function load_data inputFile begin set reader = reader open inputFile set df = array list comprehension row for row in reader if row set tuple X y = tu...
# Emory University CS378 # Homework 2 # Yicheng (Jason) Wang # NetId: ywan693 import csv import random import copy import sys import numpy as np def load_data(inputFile): reader = csv.reader(open(inputFile)) df = np.array([row for row in reader if row]) X, y = df[:,:-1],df[:,-1] X = X.astype(np.float) return X, ...
Python
zaydzuhri_stack_edu_python
function get_folder_contact contact_id=none folder_id=none opts=none begin set __args__ = dictionary set __args__ at string contactId = contact_id set __args__ at string folderId = folder_id set opts = merge call get_invoke_opts_defaults opts set __ret__ = value return call AwaitableGetFolderContactResult email=get pul...
def get_folder_contact(contact_id: Optional[str] = None, folder_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetFolderContactResult: __args__ = dict() __args__['contactId'] = contact_id __args__['folderId'] = folder_id o...
Python
nomic_cornstack_python_v1
function l2_norm x y begin set x = call cast x dtype=float32 set y = call cast y dtype=float32 comment [length, 1] set x_sqr = call expand_dims call reduce_sum x * x 1 - 1 comment [length, 1] set y_sqr = call expand_dims call reduce_sum y * y 1 - 1 comment [length, length] set xy = matrix multiply x transpose tf y set ...
def l2_norm(x, y): x = tf.cast(x, dtype=tf.float32) y = tf.cast(y, dtype=tf.float32) x_sqr = tf.expand_dims(tf.reduce_sum(x * x, 1), -1) # [length, 1] y_sqr = tf.expand_dims(tf.reduce_sum(y * y, 1), -1) # [length, 1] xy = tf.matmul(x, tf.transpose(y)) # [length, length] ...
Python
nomic_cornstack_python_v1
import pandas as pd import os from striprtf.striprtf import rtf_to_text set companies = sorted list string 3M Co string American Express Co string Amgen Inc string Apple Inc string Boeing Co string Caterpillar Inc string Cisco Systems Inc string Chevron Corp string Goldman Sachs Group Inc string Home Depot Inc string H...
import pandas as pd import os from striprtf.striprtf import rtf_to_text companies = sorted(["3M Co", "American Express Co", "Amgen Inc", "Apple Inc", "Boeing Co", "Caterpillar Inc", "Cisco Systems Inc", "Chevron Corp", "Goldman Sachs Group Inc", "Home Depot Inc", "Honeywell International Inc", "International Business ...
Python
zaydzuhri_stack_edu_python
function test_parse_action_parameters parameters accepted_result begin set client = call Client BASE_URL string username string password string domain set result = call parse_action_parameters parameters assert result == accepted_result end function
def test_parse_action_parameters(parameters, accepted_result): client = Client(BASE_URL, 'username', 'password', 'domain') result = client.parse_action_parameters(parameters) assert result == accepted_result
Python
nomic_cornstack_python_v1
comment Euler44 Pentagonal Numbers Smallest difference between sum and difference comment Create first 10,000 set PenNum = list set N = list range 1 5000 comment print (N) for i in N begin append PenNum i * 3 * i - 1 / 2 end print PenNum set i = 0 set PenDiffList = list while i < length PenNum begin set steps = 1 whi...
#Euler44 Pentagonal Numbers Smallest difference between sum and difference #Create first 10,000 PenNum = [] N = list(range(1, 5000)) #print (N) for i in N: PenNum.append(i*(3*i-1)/2) print (PenNum) i = 0 PenDiffList = [] while i < len(PenNum): steps = 1 while steps < len(PenNum) - i + 1: PenDiff ...
Python
zaydzuhri_stack_edu_python
function _from_dict cls _dict begin return call from_dict _dict end function
def _from_dict(cls, _dict): return cls.from_dict(_dict)
Python
nomic_cornstack_python_v1
import hashlib , json from myapp.models import Tender comment this function is use for hash data of the user function hashturnover begin comment For convenience, this is a helper function that wraps our hashing algorithm set gmodel = model Tender set turnover1 = turnover set msg = turnover1 if type msg != str begin com...
import hashlib, json from myapp.models import Tender #this function is use for hash data of the user def hashturnover(): # For convenience, this is a helper function that wraps our hashing algorithm gmodel=Model(Tender) turnover1=gmodel.turnover msg= turnover1 if type(msg) != str: msg = js...
Python
zaydzuhri_stack_edu_python
async function current_readings self details=false begin set readings = call CurrentReading set aranet2_char = call get_characteristic AR2_READ_CURRENT_READINGS if aranet2_char begin set uuid = AR2_READ_CURRENT_READINGS comment co2, temp, pressure, humidity, battery, status set value_fmt = string <HHHBHHB set raw_bytes...
async def current_readings(self, details: bool = False): readings = CurrentReading() aranet2_char = self.device.services.get_characteristic( self.AR2_READ_CURRENT_READINGS ) if aranet2_char: uuid = self.AR2_READ_CURRENT_READINGS # co2, temp, pressure...
Python
nomic_cornstack_python_v1
function abc095c_half_and_half begin set tuple a b c x y = map int split input set total = 0 if a + b >= 2 * c begin set v = min x y set total = total + c * v * 2 set x = x - v set y = y - v end if a >= 2 * c begin set total = total + 2 * x * c end else begin set total = total + x * a end if b >= 2 * c begin set total ...
def abc095c_half_and_half(): a, b, c, x, y = map(int, input().split()) total = 0 if a + b >= 2 * c: v = min(x, y) total += c * v * 2 x -= v y -= v if a >= 2 * c: total += 2 * x * c else: total += x * a if b >= 2 * c: total += 2 * y * c ...
Python
zaydzuhri_stack_edu_python
function check_complete_create_booking self *args **kwargs begin if stripe_pid begin if booking_required begin from bookings.models import Booking call create *args keyword kwargs end end end function
def check_complete_create_booking(self, *args, **kwargs): if self.stripe_pid: if self.booking_required: from bookings.models import Booking Booking.objects.create(*args, **kwargs)
Python
nomic_cornstack_python_v1
function finalize_options self begin string Populate the attributes. Args: self (CleanCommand): the ``CleanCommand`` instance Returns: ``None`` set cwd = absolute path path directory name path __file__ set build_dirs = list join path cwd string build join path cwd string htmlcov join path cwd string dist join path cwd ...
def finalize_options(self): """Populate the attributes. Args: self (CleanCommand): the ``CleanCommand`` instance Returns: ``None`` """ self.cwd = os.path.abspath(os.path.dirname(__file__)) self.build_dirs = [ os.path.join(self.cwd, 'build...
Python
jtatman_500k
function OffsetOnSurface3 thisCurve surface distance fittingTolerance multiple=false begin set url = string rhino/geometry/curve/offsetonsurface-curve_surface_double_double if multiple begin set url = url + string ?multiple=true end set args = list thisCurve surface distance fittingTolerance if multiple begin set args ...
def OffsetOnSurface3(thisCurve, surface, distance, fittingTolerance, multiple=False): url = "rhino/geometry/curve/offsetonsurface-curve_surface_double_double" if multiple: url += "?multiple=true" args = [thisCurve, surface, distance, fittingTolerance] if multiple: args = list(zip(thisCurve, surface, dis...
Python
nomic_cornstack_python_v1
function open_acount begin print string 새로운 계좌가 생성되었습니다. end function call open_acount comment 전달값과 반환 값 comment 입금 function deposit balance money begin print format string 입금이 완료되었습니다. 잔액은 {}원 입니다. balance + money return balance + money end function comment 출금 function withdraw balance money begin comment 잔액이 출금액보다 많으...
def open_acount(): print("새로운 계좌가 생성되었습니다.") open_acount() # 전달값과 반환 값 def deposit(balance, money): # 입금 print("입금이 완료되었습니다. 잔액은 {}원 입니다.".format(balance+money)) return balance+money def withdraw(balance, money): # 출금 if balance > money: # 잔액이 출금액보다 많으면 출금 가능 print("출금이 완료되었습니다. 잔액은 {}...
Python
zaydzuhri_stack_edu_python
function addBorder picture begin set border_len = length picture at 0 + 2 append picture string * * border_len insert picture 0 string * * border_len for i in range 1 length picture - 1 begin set picture at i = string * + picture at i + string * end return picture end function
def addBorder(picture): border_len = len(picture[0]) + 2 picture.append('*' * border_len) picture.insert(0, '*' * border_len) for i in range(1, len(picture)-1): picture[i] = "*" + picture[i] + "*" return picture
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment encoding: utf-8 set my_table = list list 0 3 2 3 2 3 4 5 list 3 2 1 2 3 4 3 4 list 2 1 4 3 2 5 4 5 list 3 2 3 2 3 4 3 4 list 2 3 2 3 4 3 4 5 list 3 4 5 4 3 4 5 4 list 4 3 4 3 4 5 4 5 list 5 4 5 4 5 4 5 6 function num2pos num begin return list num / 8 num % 8 end function function an...
#!/usr/bin/env python # encoding: utf-8 my_table = [[0, 3, 2, 3, 2, 3, 4, 5], [3, 2, 1, 2, 3, 4, 3, 4], [2, 1, 4, 3, 2, 5, 4, 5], [3, 2, 3, 2, 3, 4, 3, 4], [2, 3, 2, 3, 4, 3, 4, 5], [3, 4, 5, 4, 3, 4, 5, 4], [4, 3, 4, 3, 4, 5, 4, 5], [...
Python
zaydzuhri_stack_edu_python
string string Pussycat Sonya has an array A consisting of N integers (N is even). She can perform operations of two types: increase value of some element Ai by 1 delete some adjacent elements Ai and Ai+1 such that they are consecutive prime numbers (Ai is a prime number and Ai+1 is the next prime number) She wants to ...
"""""" """ Pussycat Sonya has an array A consisting of N integers (N is even). She can perform operations of two types: increase value of some element Ai by 1 delete some adjacent elements Ai and Ai+1 such that they are consecutive prime numbers (Ai is a prime number and Ai+1 is the next prime number) She wants to de...
Python
zaydzuhri_stack_edu_python
function copy_styles begin set src = call sketchPath + string /styles set dest = call sketchPath + string /data/output/styles try begin copy tree src dest end comment eg. src and dest are the same file comment as err: except Error begin comment print('Error: %s' % err) pass end comment eg. source or destination doesn't...
def copy_styles(): src = sketchPath() + '/styles' dest = sketchPath() + '/data/output/styles' try: shutil.copytree(src, dest) # eg. src and dest are the same file except shutil.Error: # as err: # print('Error: %s' % err) pass # eg. source or destination doesn't exist ...
Python
nomic_cornstack_python_v1
import pygame import math import random import time from random import sample global colors call init set font = call SysFont string Times New Roman 30 set colors = tuple call render string true tuple 0 128 0 tuple 160 165 160 call render string 1 true tuple 0 0 255 tuple 152 157 142 call render string 2 true tuple 0 ...
import pygame import math import random import time from random import sample global colors pygame.font.init() font = pygame.font.SysFont("Times New Roman", 30) colors = font.render(" ", True, (0,128,0), (160, 165, 160)), font.render(" 1 ", True, (0,0,255), (152, 157, 142)), font.render(" 2 ", True, (0,...
Python
zaydzuhri_stack_edu_python
function getPopualrAuthors begin set db = call connect string dbname=news set c = call cursor execute c string select count(*) as views , authors.name from articles + string inner join + string log on concat('/article/', articles.slug) = log.path + string inner join authors on articles.author = authors.id + string grou...
def getPopualrAuthors(): db = psycopg2.connect("dbname=news") c = db.cursor() c.execute(" select count(*) as views , authors.name from articles " + " inner join " + "log on concat('/article/', articles.slug) = log.path " + " inner join authors on articles.author =...
Python
nomic_cornstack_python_v1
from Classes.game import Person , bcolors from Classes.magic import Spell from Classes.Inventory import Item comment Create offensive magic set spell_fire = call Spell string Fire 10 100 string Earth set spell_thunder = call Spell string Thunder 10 120 string Weather set spell_blizzard = call Spell string Blizzard 15 1...
from Classes.game import Person, bcolors from Classes.magic import Spell from Classes.Inventory import Item #Create offensive magic spell_fire = Spell("Fire", 10, 100, "Earth") spell_thunder = Spell("Thunder", 10, 120, "Weather") spell_blizzard = Spell("Blizzard", 15, 140, "Weather") spell_meteor = Spell("Meteor", 20...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- comment 例8.1创建顺序文件 comment 如果文件不存在就会新建一个文件 comment 用with可以不用f.close来手动关闭
# -*- coding:utf-8 -*- #例8.1创建顺序文件 #如果文件不存在就会新建一个文件 #用with可以不用f.close来手动关闭
Python
zaydzuhri_stack_edu_python
function ipset_y_3d begin return call IPSet x=linear space 0 10 11 y=randn 11 2 5 x_new=linear space 1 4 3 end function
def ipset_y_3d(): return IPSet(x=np.linspace(0, 10, 11), y=np.random.randn(11, 2, 5), x_new=np.linspace(1, 4, 3))
Python
nomic_cornstack_python_v1
from collections import deque class TreeNode begin function __init__ self val begin set val = val set tuple left right = tuple none none end function end class comment was not able to handle test case where right subtree ends before left string Failed test case in ownLogic 12 / 7 1 / 9 10 function ownLogic root begin s...
from collections import deque class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None # was not able to handle test case where right subtree ends before left ''' Failed test case in ownLogic 12 /\ 7 1 /\ 9 10 ''' def ownLogic...
Python
zaydzuhri_stack_edu_python
function load_base_weights self begin set base_state_dict = call load_url model_urls at string vgg16 set vgg_state_dict = dictionary comprehension k at slice length string features. : : : v for tuple k v in items base_state_dict if starts with k string features. load state dict vgg vgg_state_dict set vgg_head_params ...
def load_base_weights(self): base_state_dict = model_zoo.load_url(vgg.model_urls['vgg16']) vgg_state_dict = {k[len('features.'):]: v for k, v in base_state_dict.items() if k.startswith('features.')} self.vgg.load_state_dict(vgg_state_dict) ...
Python
nomic_cornstack_python_v1
function request_id self begin return get pulumi self string request_id end function
def request_id(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "request_id")
Python
nomic_cornstack_python_v1
comment only print key for key in student begin print key end comment print both key and value for key in student begin print key end=string print student at key end comment or comment ============================ for key in student begin print key string = student at key end
#only print key for key in student: print(key) #print both key and value for key in student: print(key,end="") print(student[key]) #or #============================ for key in student: print(key,"=",student[key])
Python
zaydzuhri_stack_edu_python
function clear_lazyprop object property_name begin assert is instance property_name str if _LAZY_PROP_VALUES in __dict__ begin if property_name in __dict__ at _LAZY_PROP_VALUES begin del __dict__ at _LAZY_PROP_VALUES at property_name end end if _LAZY_PROP_SUBSCRIBERS in __dict__ begin if property_name in __dict__ at _L...
def clear_lazyprop(object, property_name): assert isinstance(property_name, str) if _LAZY_PROP_VALUES in object.__dict__: if property_name in object.__dict__[_LAZY_PROP_VALUES]: del object.__dict__[_LAZY_PROP_VALUES][property_name] if _LAZY_PROP_SUBSCRIBERS in object.__dict__: ...
Python
nomic_cornstack_python_v1
function get_buildable_units self user building begin set buildable = list set player = call get_player user comment every unit that can be build in this building for u in units_per_building at command_name begin comment get the highest level possible units to build comment sort requirements per level set requirements...
def get_buildable_units(self, user, building): buildable = [] player = self.get_player(user) for u in units_per_building[building.command_name]: # every unit that can be build in this building # get the highest level possible units to build # sort requirements per level ...
Python
nomic_cornstack_python_v1
function seconds self begin return get pulumi self string seconds end function
def seconds(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "seconds")
Python
nomic_cornstack_python_v1
comment coding=utf-8 import tensorflow as tf function test_tf begin set a = call constant list list 1 2 3 list 4 5 6 dtype=float32 set b = a * 0.5 + 3 set c = call random_uniform list 2 3 4 set d = call random_uniform list 2 1 4 with call Session as session begin set tuple c_value d_value value = run list c d c + d pri...
# coding=utf-8 import tensorflow as tf def test_tf(): a = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32) b = a * 0.5 + 3 c = tf.random_uniform([2, 3, 4]) d = tf.random_uniform([2, 1, 4]) with tf.Session() as session: c_value, d_value, value = session.run([c, d, c+d]) pri...
Python
zaydzuhri_stack_edu_python
function test_login_post_route_auth_keeps_auth_tkt_cookie testapp csrf_token begin assert string auth_tkt in cookies post string /login dict string csrf_token csrf_token assert string auth_tkt in cookies end function
def test_login_post_route_auth_keeps_auth_tkt_cookie(testapp, csrf_token): assert 'auth_tkt' in testapp.cookies testapp.post("/login", {'csrf_token': csrf_token}) assert 'auth_tkt' in testapp.cookies
Python
nomic_cornstack_python_v1
async function find_stories url alias response_text name cls_name features config_id=0 begin set news_dump = call NewsDump config_id url alias name cls_name features debug string searching url: { url } set soup = call BeautifulSoup decode encode response_text string ascii errors=string ignore string utf-8 features=feat...
async def find_stories(url: Url, alias: str, response_text: str, name: str, cls_name: str, features: str, config_id: int = 0 ): news_dump = NewsDump(config_id, url, alias, name, cls_name, features) ...
Python
nomic_cornstack_python_v1
function removefromcart request featureid begin set cart = get session string cart dict if featureid in cart begin del cart at featureid call success request string Feature removed end set session at string cart = cart return call redirect reverse string cart end function
def removefromcart(request, featureid): cart = request.session.get('cart', {}) if featureid in cart: del cart[featureid] messages.success(request, "Feature removed") request.session['cart'] = cart return redirect(reverse('cart'))
Python
nomic_cornstack_python_v1
comment coding: utf-8 string Created on 2014��9��24�� canny只能处理灰度图 @author: xhj import cv2 import numpy as np function canny_edge img begin string 只能处理灰度图像 comment gauss降噪 set img = call GaussianBlur img tuple 3 3 0 set canny = call Canny img 50 150 image show string Canny canny call waitKey 0 call destroyAllWindows en...
# coding: utf-8 ''' Created on 2014��9��24�� canny只能处理灰度图 @author: xhj ''' import cv2 import numpy as np def canny_edge(img): ''' 只能处理灰度图像 ''' # gauss降噪 img = cv2.GaussianBlur(img,(3,3),0) canny = cv2.Canny(img, 50, 150) cv2.imshow('Canny', canny) cv2.waitKey(0) cv...
Python
zaydzuhri_stack_edu_python
function SLYTHERIN_RECOVERY_RATE_LVL_2 begin return 4 end function
def SLYTHERIN_RECOVERY_RATE_LVL_2() -> int: return 4
Python
nomic_cornstack_python_v1
import decimal function calculate_pi begin comment Set precision to 110 decimal places set prec = 110 comment Set maximum exponent to avoid overflow set Emax = 9999999999999999 comment Set minimum exponent to avoid underflow set Emin = - 9999999999999999 set pi = call Decimal 0 set numerator = call Decimal 1 set denomi...
import decimal def calculate_pi(): decimal.getcontext().prec = 110 # Set precision to 110 decimal places decimal.getcontext().Emax = 9999999999999999 # Set maximum exponent to avoid overflow decimal.getcontext().Emin = -9999999999999999 # Set minimum exponent to avoid underflow pi = decimal.Decima...
Python
jtatman_500k
import numpy as np function mse y_pred y w regularization=none l=0.1 begin string Assume y_pred and y have the same dim and can be batched. w: weights regularization: None, 'l2' l: regularization parameter (lambda) set b_size = shape at 0 set diff = reshape y_pred b_size - 1 - reshape y b_size - 1 set mse = mean call p...
import numpy as np def mse(y_pred, y, w, regularization = None, l = 0.1): ''' Assume y_pred and y have the same dim and can be batched. w: weights regularization: None, 'l2' l: regularization parameter (lambda) ''' b_size = y_pred.shape[0] diff = y_pred.reshape(b_size,-1) - y.r...
Python
zaydzuhri_stack_edu_python
function _bu self string begin return call bold call underline string end function
def _bu(self, string): return ircutils.bold(ircutils.underline(string))
Python
nomic_cornstack_python_v1
function _converterAFparaGR self automato begin set producoes = list comment para cada um dos estados for estado in keys tabelaTransicao begin set transicoes = string comment para cada uma das transicoes desse estado set transicao = get tabelaTransicao estado for trans in keys transicao begin comment caso o caminho d...
def _converterAFparaGR(self, automato): producoes = [] #para cada um dos estados for estado in automato.tabelaTransicao.keys(): transicoes = "" #para cada uma das transicoes desse estado transicao = automato.tabelaTransicao.get(estado) ...
Python
nomic_cornstack_python_v1
function write self data begin set sendbuf = sendbuf + data end function
def write(self, data): self.sendbuf += data
Python
nomic_cornstack_python_v1
function normalize_profile ph begin return ph / absolute ph at 1 end function
def normalize_profile(ph): return ph/np.abs(ph[1])
Python
nomic_cornstack_python_v1
function get_params self begin return tuple w b end function
def get_params(self): return self.w, self.b
Python
nomic_cornstack_python_v1
function hello_world request begin set dajax = call Dajax call assign string body string innerHTML string Hello world ! comment dajax.alert("Hello World!") return json dajax end function
def hello_world(request): dajax = Dajax() dajax.assign('body','innerHTML', "Hello world !") #dajax.alert("Hello World!") return dajax.json()
Python
nomic_cornstack_python_v1
function __ne__ self other begin return not self == other end function
def __ne__(self, other): return not self == other
Python
nomic_cornstack_python_v1
function __init__ self *args **kwargs begin if length kwargs == 1 and string handle in kwargs begin set handle = kwargs at string handle call IncRef handle end else if length args == 1 and is instance args at 0 GoClass begin set handle = handle call IncRef handle end else if length args == 1 and is instance args at 0 i...
def __init__(self, *args, **kwargs): if len(kwargs) == 1 and 'handle' in kwargs: self.handle = kwargs['handle'] _test.IncRef(self.handle) elif len(args) == 1 and isinstance(args[0], GoClass): self.handle = args[0].handle _test.IncRef(self.handle) elif len(args) == 1 and isinstance(args[0], int): se...
Python
nomic_cornstack_python_v1
function vote_act request begin assert is instance request HttpRequest return call render request string app/vote.html context_instance=call RequestContext request dict string title string Vote the act ; string year year end function
def vote_act(request): assert isinstance(request, HttpRequest) return render( request, 'app/vote.html', context_instance=RequestContext(request, { 'title': 'Vote the act', 'year': datetime.now().year, }) )
Python
nomic_cornstack_python_v1
if inp < 4 begin print string Dude, that was easy to do!! >:( end else begin for i in range 0 inp - 3 begin set first_num = list at a + list at b append list first_num set a = a + 1 set b = b + 1 end print list end
if inp < 4: print("Dude, that was easy to do!! >:( ") else: for i in range(0 , (inp - 3)): first_num = list[a] + list[b] list.append(first_num) a = a + 1 b = b + 1 print(list)
Python
zaydzuhri_stack_edu_python
function unique_id self begin return call BCH_decoder_ATSC_sptr_unique_id self end function
def unique_id(self): return _mack_sdr_rossi_swig.BCH_decoder_ATSC_sptr_unique_id(self)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Aug 21 22:13:04 2019 @author: Bob import numpy as np class ListNode extends object begin function __init__ self elem link=none begin set elem = elem set next = link end function end class class SingleLinkList extends object begin function __init__ self begin set head ...
# -*- coding: utf-8 -*- """ Created on Wed Aug 21 22:13:04 2019 @author: Bob """ import numpy as np class ListNode(object): def __init__(self,elem,link=None): self.elem = elem self.next = link class SingleLinkList(object): def __init__(self): self.head = None def prepend(self...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt comment Input: comment Data: data dictionary comment Algorithm: Algorithm to plot from Data dictionary comment plotWhat: "epoch_loss" or "epoch_accuracy" comment saveToFile: If false, then shows a plot. Otherwise dumps plot to a file function plotAlg data algorithm plotWhat saveToFile=fa...
import matplotlib.pyplot as plt # # Input: # Data: data dictionary # Algorithm: Algorithm to plot from Data dictionary # plotWhat: "epoch_loss" or "epoch_accuracy" # saveToFile: If false, then shows a plot. Otherwise dumps plot to a file # def plotAlg(data, algorithm, plotWhat, saveToFile=False...
Python
zaydzuhri_stack_edu_python
function week_events self begin set event_keys = get memcache string EventHelper.week_events():event_keys if event_keys is not none begin return call get_multi event_keys end set today = today comment Make sure all events to be returned are within range set two_weeks_of_events_keys_future = call fetch_async keys_only=t...
def week_events(self): event_keys = memcache.get('EventHelper.week_events():event_keys') if event_keys is not None: return ndb.get_multi(event_keys) today = datetime.datetime.today() # Make sure all events to be returned are within range two_weeks_of_events_keys_fut...
Python
nomic_cornstack_python_v1
function valid_response line begin comment checksum is last two characters in ASCII hex set cksum = integer line at slice - 2 : : 16 comment remove checksum from data set data = line at slice : - 2 : set calc_cksum = call checksum data if cksum != calc_cksum begin debug string checksum failed (%r): should be %s lin...
def valid_response(line): cksum = int(line[-2:], 16) # checksum is last two characters in ASCII hex data = line[:-2] # remove checksum from data calc_cksum = checksum(data) if cksum != calc_cksum: log.debug('checksum failed (%r): should be %s', line, hex(calc_cksum)) return False ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- set N = integer input set ok = false set lines = list for n in range N begin set line = input if string OO in line and not ok begin set line = replace line string OO string ++ 1 set ok = true end append lines line end if ok begin print string YES print join s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- N = int(input()) ok = False lines = [] for n in range(N): line = input() if "OO" in line and not ok: line = line.replace("OO", "++", 1) ok = True lines.append(line) if ok: print ("YES") print("\n".join(lines)) else: print ("NO")
Python
zaydzuhri_stack_edu_python
function test_fma_nan_param_infarray_okarray_ninfarray_okarray_b_260 self begin comment The expected results. set expected = list comprehension x * y + z for tuple x y z in zip infarrayx okarrayy ninfarrayz comment Exceptions are turned off so we can use the results to test for correct values. call fma infarrayx okarra...
def test_fma_nan_param_infarray_okarray_ninfarray_okarray_b_260(self): # The expected results. expected = [(x * y + z) for x,y,z in zip(self.infarrayx, self.okarrayy, self.ninfarrayz)] # Exceptions are turned off so we can use the results to test for correct values. arrayfunc.fma(self.infarrayx, self.okarrayy,...
Python
nomic_cornstack_python_v1
function cleanup a b begin if find a b == - 1 begin return integer a end else begin return none end end function function get_answer str1 begin set tuple problem answer = split str1 string = set tuple f s = split problem string + set b = string machula set f = call cleanup f b set s = call cleanup s b set answer = call...
def cleanup(a, b): if a.find(b) == -1: return int(a) else: return None def get_answer(str1): problem, answer = str1.split('=') f, s = problem.split('+') b = 'machula' f = cleanup(f, b) s = cleanup(s, b) answer = cleanup(answer, b) if f is None: f = answer - ...
Python
zaydzuhri_stack_edu_python
function serialize_many2many self begin return notes end function
def serialize_many2many(self): return self.notes
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 import sqlite3 class Sqlite3 extends object begin string sqlite3 helper function __init__ self db begin set conn = call connect db set ddlKeywords = list string create string update string delete string insert end function function execute self sql params begin string execute the sql statement...
#!/usr/bin/python3 import sqlite3 class Sqlite3(object): """ sqlite3 helper """ def __init__(self, db): self.conn = sqlite3.connect(db) self.ddlKeywords = ["create", "update", "delete", "insert"] def execute(self, sql, params): """ execute the sql statement expec...
Python
zaydzuhri_stack_edu_python
if __name__ == string __main__ begin set tuple N M = map int split input set n = list for j in range N begin append n 0 end for i in range M begin set tuple a b = map int split input set n at a - 1 = n at a - 1 + 1 set n at b - 1 = n at b - 1 + 1 end for j in range N begin print n at j end end
if __name__ == '__main__': N, M = map(int, input().split()) n=[] for j in range(N): n.append(0) for i in range(M): a, b = map(int, input().split()) n[a-1]+=1 n[b-1]+=1 for j in range(N): print(n[j])
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Sep 26 19:52:17 2018 @author: Francisco import matplotlib as mpl import matplotlib.pyplot as plt import pdsmodulos.generador as gen import numpy as np import pdsmodulos.tools as tools from scipy import signal function testbench begin set fs = 1024 set N = 1024 set a0 ...
# -*- coding: utf-8 -*- """ Created on Wed Sep 26 19:52:17 2018 @author: Francisco """ import matplotlib as mpl import matplotlib.pyplot as plt import pdsmodulos.generador as gen import numpy as np import pdsmodulos.tools as tools from scipy import signal def testbench(): fs = 1024 N = 1024 a0 = 2 ...
Python
zaydzuhri_stack_edu_python
function compare_tar_against_git release begin with call hide string commands begin with call cd string /home/vagrant/repos/sympy begin set git_lsfiles = set list comprehension strip i for i in split run string git ls-files string end set tar_output_orig = set split call show_files release print_=false string set tar_o...
def compare_tar_against_git(release): with hide("commands"): with cd("/home/vagrant/repos/sympy"): git_lsfiles = set([i.strip() for i in run("git ls-files").split("\n")]) tar_output_orig = set(show_files(release, print_=False).split("\n")) tar_output = set() for file in tar_o...
Python
nomic_cornstack_python_v1
function get_trace self trace_id project_id=none options=none begin if project_id is none begin set project_id = project end return call get_trace project_id=project_id trace_id=trace_id options=options end function
def get_trace(self, trace_id, project_id=None, options=None): if project_id is None: project_id = self.project return self.trace_api.get_trace( project_id=project_id, trace_id=trace_id, options=options)
Python
nomic_cornstack_python_v1
function get_state_value_function self **kwargs begin pass end function
def get_state_value_function(self, **kwargs): pass
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt comment In the BlahutArimotoExample() we change different kind of probabilities of X (al) line=75 function BlahutArimato dist_mat p_x beta max_it=500 eps=0.0001 begin string Compute the rate-distortion function of an i.i.d distribution Inputs : 'dist_mat' -- (numpy mat...
import numpy as np import matplotlib.pyplot as plt # In the BlahutArimotoExample() we change different kind of probabilities of X (al) line=75 # def BlahutArimato(dist_mat, p_x, beta, max_it=500, eps=1e-4): """Compute the rate-distortion function of an i.i.d distribution Inputs : 'dist_mat' -- (...
Python
zaydzuhri_stack_edu_python
function read_csv f begin set out = list set reader = reader f set fields = next set fields = list comprehension lower f for f in fields for row in reader begin set record = dict for col in range length fields begin set record at fields at col = row at col end append out record end return out end function
def read_csv( f ): out = [] reader = csv.reader( f ) fields = reader.next() fields = [ f.lower() for f in fields ] for row in reader: record = {} for col in range( len(fields) ): record[ fields[col] ] = row[col] out.append(record) return out
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 import matplotlib.pyplot as plt import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis comment ============================================================================== comment Data functions comment ========================================================...
#!/usr/bin/python3 import matplotlib.pyplot as plt import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis # ============================================================================== # Data functions # =======================================================================...
Python
zaydzuhri_stack_edu_python
import pika import sys import config set user_pwd = call PlainCredentials username pwd comment 创建链接 set s_conn = call BlockingConnection call ConnectionParameters string localhost credentials=user_pwd comment 创建一个频道 set chan = call channel comment 声明一个队列,设置队列持久化 call queue_declare queue=string task_queue durable=true c...
import pika import sys import config user_pwd = pika.PlainCredentials(config.username,config.pwd) # #创建链接 s_conn = pika.BlockingConnection(pika.ConnectionParameters('localhost',credentials=user_pwd)) #创建一个频道 chan = s_conn.channel() #声明一个队列,设置队列持久化 chan.queue_declare(queue='task_queue',durable=True) chan.basic_publ...
Python
zaydzuhri_stack_edu_python
string Program Name: Author: Maya Name Creation Date: Description: import tkinter as tk from tkinter import ttk from tkinter import messagebox import cmath , math import matplotlib.pyplot as plt import numpy as np class App begin function __init__ self master begin comment Define window properties title master string R...
""" Program Name: Author: Maya Name Creation Date: Description: """ import tkinter as tk from tkinter import ttk from tkinter import messagebox import cmath, math import matplotlib.pyplot as plt import numpy as np class App: def __init__(self, master): #Define window properties ...
Python
zaydzuhri_stack_edu_python
string 524. Longest Word in Dictionary through Deleting Medium Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical orde...
''' 524. Longest Word in Dictionary through Deleting Medium Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order....
Python
zaydzuhri_stack_edu_python
function __init__ self filename sheetname=none begin set filename = filename set pd_writer = call ExcelWriter filename engine=string xlsxwriter set sheetname = sheetname end function
def __init__(self, filename, sheetname=None): self.filename = filename self.pd_writer = pd.ExcelWriter(self.filename, engine='xlsxwriter') self.sheetname = sheetname
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Jan 7 09:17:39 2021 @author: rache import pandas as pd from Google import Create_Service import datetime from scipy.stats import pearsonr import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression from statsmodels.tsa.seasonal...
# -*- coding: utf-8 -*- """ Created on Thu Jan 7 09:17:39 2021 @author: rache """ import pandas as pd from Google import Create_Service import datetime from scipy.stats import pearsonr import matplotlib.pyplot as plt import numpy as np from sklearn.linear_model import LinearRegression from statsmodels....
Python
zaydzuhri_stack_edu_python
class Solution begin function spiralOrder self M begin set tuple m n = tuple length M length M at 0 set tuple top bottom = tuple 0 m - 1 set tuple left right = tuple 0 n - 1 set direction = 0 set ans = list while top <= bottom and left <= right begin if direction == 0 begin for j in range left right + 1 begin append a...
class Solution: def spiralOrder(self, M): m, n = len(M), len(M[0]) top, bottom = 0, m - 1 left, right = 0, n - 1 direction = 0 ans = [] while top <= bottom and left <= right: if direction == 0: for j in range(left, right + 1): ...
Python
zaydzuhri_stack_edu_python
comment Area of a room set width = decimal input string Inserisci la larghezza della stanza: set length = decimal input string Inserisci la lunghezza della stanza: set area = width * length print string L'area della stanza è pari a %.2f metri % area
# Area of a room width = float(input("Inserisci la larghezza della stanza: ")) length = float(input("Inserisci la lunghezza della stanza: ")) area = (width * length) print("L'area della stanza è pari a %.2f metri" % area)
Python
zaydzuhri_stack_edu_python
function paint_corners self begin print string PAINTING CORNERS. set titles = list string P string K string $\phi$ string e string $\omega$ if not kplanets begin print string No cornerplots for K0. return end for k in call tqdm range kplanets desc=string Brush number begin set labels = list comprehension t + string + ...
def paint_corners(self): print('\n\t\tPAINTING CORNERS.') titles = ['P', 'K', r'$\phi$', 'e', r'$\omega$'] if not self.kplanets: print('No cornerplots for K0.') return for k in tqdm(range(self.kplanets), desc='Brush number'): labels = [t + ' ' + str(k ...
Python
nomic_cornstack_python_v1
function test_create_model_engines_local_args load_pos_and_neg_data begin set exp = call TSForecastingExperiment set data = load_pos_and_neg_data setup exp data=data fold=2 fh=12 fold_strategy=string sliding verbose=false comment Default Model Engine ---- comment A. Statistical Models assert call get_engine string auto...
def test_create_model_engines_local_args(load_pos_and_neg_data): exp = TSForecastingExperiment() data = load_pos_and_neg_data exp.setup( data=data, fold=2, fh=12, fold_strategy="sliding", verbose=False, ) # Default Model Engine ---- # A. Statistical Mod...
Python
nomic_cornstack_python_v1