code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import os
import csv
import string
comment initialize needed variables
set months = 0
set profit_sum = 0
set greatest_inc = 0
set greatest_incMonth = string
set greatest_dec = 0
set greatest_decMonth = string
set csvpath = join path string Resources string budget_data.csv
with open csvpath newline=string as csvfile
b... | import os
import csv
import string
# initialize needed variables
months = 0
profit_sum = 0
greatest_inc = 0
greatest_incMonth = ''
greatest_dec = 0
greatest_decMonth = ''
csvpath = os.path.join('Resources', 'budget_data.csv')
with open(csvpath, newline='') as csvfile:
# CSV reader specifies delimiter and variab... | Python | zaydzuhri_stack_edu_python |
function is_divisible n m
begin
if n % m == 0
begin
return true
end
else
begin
return false
end
end function
comment Outputs False
print call is_divisible 7 2 | def is_divisible(n, m):
if (n % m == 0):
return True
else:
return False
print(is_divisible(7, 2)) # Outputs False | Python | iamtarun_python_18k_alpaca |
import cv2 as cv
set img = call imread string C:\Users\91821\OneDrive\Pictures/group.jpg
comment resize=cv.resize(img,(500,500),interpolation=cv.INTER_CUBIC)
comment cv.imshow('img',resize)
set gray = call cvtColor resize COLOR_BGR2GRAY
comment cv.imshow('gray',gray)
set haar_cas = call CascadeClassifier string haar_ca... | import cv2 as cv
img= cv.imread(r"C:\Users\91821\OneDrive\Pictures/group.jpg")
#resize=cv.resize(img,(500,500),interpolation=cv.INTER_CUBIC)
#cv.imshow('img',resize)
gray=cv.cvtColor(resize,cv.COLOR_BGR2GRAY)
#cv.imshow('gray',gray)
haar_cas=cv.CascadeClassifier('haar_cas.xml')
face_react=haar_cas.detectMu... | Python | zaydzuhri_stack_edu_python |
import shlex
import string
import random
import caves
from items import Item
import Valmoor
import factory
class Player extends object
begin
function __init__ self location
begin
set location = location
comment self.password = " "
comment self.location.players_here.append(self)
set playing = true
set inventory = list
... | import shlex
import string
import random
import caves
from items import Item
import Valmoor
import factory
class Player(object):
def __init__(self, location):
self.location = location
# self.password = " "
# self.location.players_here.append(self)
self.playing = True
self.i... | Python | zaydzuhri_stack_edu_python |
import base64
import json
from flask import current_app , session , request
from requests_oauthlib import OAuth2Session
class OAuth
begin
function __init__ self app=none
begin
set _app = app
end function
decorator property
function app self
begin
if _app
begin
return _app
end
return current_app
end function
function in... | import base64
import json
from flask import current_app, session, request
from requests_oauthlib import OAuth2Session
class OAuth:
def __init__(self, app=None):
self._app = app
@property
def app(self):
if self._app:
return self._app
return current_app
def init_app... | Python | zaydzuhri_stack_edu_python |
function fade_rgb_strip
begin
call all_off
call set_pwm pin_red 0.1
call fade_up pin_green
call fade_down pin_red
call fade_up pin_blue
call fade_down pin_green
call fade_up pin_red
call fade_down pin_blue
call all_off
end function | def fade_rgb_strip():
all_off()
cg.set_pwm(pin_red, 0.1)
fade_up(pin_green)
fade_down(pin_red)
fade_up(pin_blue)
fade_down(pin_green)
fade_up(pin_red)
fade_down(pin_blue)
all_off() | Python | nomic_cornstack_python_v1 |
from typing import Iterator , List , Tuple
function is_caught time height
begin
return time % 2 * height - 1 == 0
end function
function calculate_delay layers
begin
set delay = - 1
set caught = true
while caught
begin
set delay = delay + 1
set caught = false
for tuple depth height in layers
begin
if call is_caught dept... | from typing import Iterator, List, Tuple
def is_caught(time: int, height: int):
return time % (2 * (height - 1)) == 0
def calculate_delay(layers: List[Tuple[int, int]]) -> int:
delay = -1
caught = True
while caught:
delay += 1
caught = False
for depth, height in layers:
... | Python | zaydzuhri_stack_edu_python |
from pythonisms.iterators.tree_iterator import IterableBinaryTree
import string
function test_lowercase_iterable_binary_tree
begin
set tree = call IterableBinaryTree values=ascii_lowercase
set actual = list tree
set expected = list string a string b string d string h string p string q string i string r string s string ... | from pythonisms.iterators.tree_iterator import IterableBinaryTree
import string
def test_lowercase_iterable_binary_tree():
tree = IterableBinaryTree(values=string.ascii_lowercase)
actual = list(tree)
expected = ['a','b','d','h','p','q','i','r','s','e','j','t','u','k','v','w','c','f','l','x','y','m','z','g'... | Python | zaydzuhri_stack_edu_python |
function main
begin
comment Gets valid starting board from user
set start_board = call get_start
comment Gets valid end board from user
set end_board = call get_end
comment Gets desired search from user
set search_type = call get_search
while search_type != - 1
begin
comment Runs searches
if call run_search start_board... | def main():
# Gets valid starting board from user
start_board = get_start()
# Gets valid end board from user
end_board = get_end()
# Gets desired search from user
search_type = get_search()
while search_type != -1:
# Runs searches
if (run_search(start_board, end_board, sear... | Python | nomic_cornstack_python_v1 |
function get_labels self
begin
set labels = list meta_data at target_column
return labels
end function | def get_labels(self):
labels = list(self.meta_data[self.target_column])
return labels | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import rospy
import sys
from std_msgs.msg import String
set decision_pub = call Publisher string /receptionist_decision_input String queue_size=10
function perceptionCallback data
begin
call loginfo string you said:%s data
flush stdout
call publish data
end function
function decisionCallbac... | #!/usr/bin/env python
import rospy
import sys
from std_msgs.msg import String
decision_pub = rospy.Publisher('/receptionist_decision_input', String, queue_size=10)
def perceptionCallback(data):
rospy.loginfo("you said:%s", data.data)
sys.stdout.flush()
decision_pub.publish(data.data)
def decisionCall... | Python | zaydzuhri_stack_edu_python |
function _split_module_dicts
begin
set funcs = __salt__
if is instance __salt__ NamedLoaderContext and is instance call value dict
begin
set funcs = call value
end
if not is instance funcs dict
begin
return funcs
end
set mod_dict = dictionary funcs
for tuple module_func_name mod_fun in items copy mod_dict
begin
set tup... | def _split_module_dicts():
funcs = __salt__
if isinstance(__salt__, NamedLoaderContext) and isinstance(__salt__.value(), dict):
funcs = __salt__.value()
if not isinstance(funcs, dict):
return funcs
mod_dict = dict(funcs)
for module_func_name, mod_fun in mod_dict.copy().items():
... | Python | nomic_cornstack_python_v1 |
function gen_single_anchor self
begin
set scale = array scale dtype=float32
set s = base_size * base_size
set tuple w h = tuple square root s / scale square root s * scale
set tuple center_x center_y = tuple anchor_stride - 1 // 2 anchor_stride - 1 // 2
set anchor = transpose vertical stack list center_x * ones like sc... | def gen_single_anchor(self):
scale = np.array(self.scale, dtype=np.float32)
s = self.base_size * self.base_size
w, h = np.sqrt(s/scale), np.sqrt(s*scale)
center_x, center_y = (self.anchor_stride - 1) // 2, (self.anchor_stride - 1) // 2
anchor = np.vstack([center_x * np.ones_like... | Python | nomic_cornstack_python_v1 |
function find_subtitle self pat=string ^~+$
begin
set inds = call findallre pat
assert length inds < 2 msg string bad pattern, mulitple matches for subtitle decorator
if length inds == 0
begin
set subtitle = none
set subtitle_ind = none
end
else
begin
set subtitle_ind = inds at 0 - 1
set subtitle = list at subtitle_ind... | def find_subtitle(self, pat='^~+$'):
inds = self.findallre(pat)
assert len(inds) < 2, "bad pattern, mulitple matches for subtitle decorator"
if len(inds) == 0:
self.subtitle = None
self.subtitle_ind = None
else:
self.subtitle_ind = inds[0] - 1
... | Python | nomic_cornstack_python_v1 |
class MaximumSubarraySum
begin
function find_max_subarray_sum self nums
begin
comment empty array
if not nums
begin
return 0
end
comment Initialize variables
set max_sum = decimal string -inf
set current_sum = 0
for num in nums
begin
comment Calculate the maximum subarray sum ending at the current element
set current_s... | class MaximumSubarraySum:
def find_max_subarray_sum(self, nums):
if not nums: # empty array
return 0
# Initialize variables
max_sum = float('-inf')
current_sum = 0
for num in nums:
# Calculate the maximum subarray sum ending at the c... | Python | jtatman_500k |
function __call__ self ws
begin
set app = call WSApplication ws
set messages = messages
set _queue_class = _queue_class
return app
end function | def __call__(self, ws):
app = WSApplication(ws)
app.messages = self.messages
app._queue_class = self._queue_class
return app | Python | nomic_cornstack_python_v1 |
function _set_cleanup_delay self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=call RestrictedClassType base_type=int restriction_dict=dict string range list string 0..65535 int_size=16 is_leaf=true yang_name=string cleanup-delay parent=se... | def _set_cleanup_delay(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), is_leaf=True, yang_name="cleanup-delay", parent=self, path_helper=self._path_helper, extmethods... | Python | nomic_cornstack_python_v1 |
function dnda asize grain_type
begin
comment Favoured distribution. See Figure 2 WD01.
set bc = 6e-05
if grain_type == string carbonaceous
begin
comment Carbonaceous grains:
comment Adjustable parameters: bc, Cg, a_t_g, a_c_g, alpha_g, beta_g
set Cg = 9.99e-12
comment micron
set a_t_g = 0.0107 * microntoAA
comment micr... | def dnda(asize, grain_type):
bc = 6.e-5 # Favoured distribution. See Figure 2 WD01.
if grain_type == "carbonaceous":
# Carbonaceous grains:
# Adjustable parameters: bc, Cg, a_t_g, a_c_g, alpha_g, beta_g
Cg = 9.99e-12
a_t_g = 0.0107*microntoAA # micron
a... | Python | nomic_cornstack_python_v1 |
function procesar
begin
set archivo = open string src/recursos/aterrizajes-y-despegues-2021.csv string r encoding=string utf8
set csvreader = reader archivo delimiter=string ,
set tuple encabezado datos = tuple next csvreader list csvreader
close archivo
comment Devuelve todos los aterrizajes de aeronaves privadas entr... | def procesar():
archivo = open("src/recursos/aterrizajes-y-despegues-2021.csv", "r", encoding="utf8")
csvreader = csv.reader(archivo, delimiter=',')
encabezado, datos = next(csvreader), list(csvreader)
archivo.close()
# Devuelve todos los aterrizajes de aeronaves privadas entre aeropuertos... | Python | nomic_cornstack_python_v1 |
function hashFunction self a capacity
begin
if type a == str
begin
set temp = a
set a = 0
for i in temp
begin
set a = a + ordinal i
end
end
return a % capacity
end function | def hashFunction(self, a, capacity):
if type(a) == str:
temp = a
a = 0
for i in temp:
a += ord(i)
return a % capacity | Python | nomic_cornstack_python_v1 |
function clearGroupDataSlidingFactor self groupName
begin
call clearGroupSetting groupName _dataSlidingFactorToken
end function | def clearGroupDataSlidingFactor(self, groupName):
self.clearGroupSetting(groupName, self._dataSlidingFactorToken) | Python | nomic_cornstack_python_v1 |
import datetime
function get_week_number date_string
begin
set d = string parse time date_string string %Y-%m-%d
comment isocalendar() is used to get the ISO week number
return call isocalendar at 1
end function | import datetime
def get_week_number(date_string):
d = datetime.datetime.strptime(date_string, '%Y-%m-%d')
return d.isocalendar()[1] # isocalendar() is used to get the ISO week number | Python | jtatman_500k |
function get_market_depth_data index=none retry_count=3 pause=0.001
begin
comment data to be sent to post request
set data = dict string inst index
for _ in range retry_count
begin
sleep pause
try
begin
set r = post url=DSE_URL + DSE_MARKET_DEPTH_URL params=data
if status_code != 200
begin
set r = post url=DSE_ALT_URL ... | def get_market_depth_data(index=None, retry_count=3, pause=0.001):
# data to be sent to post request
data = {'inst': index}
for _ in range(retry_count):
time.sleep(pause)
try:
r = requests.post(
url=vs.DSE_URL+vs.DSE_MARKET_DEPTH_URL, params=data)
if ... | Python | nomic_cornstack_python_v1 |
class mummy
begin
function boast self
begin
print string goyna ache
end function
end class
class nalayak extends mummy
begin
function boast self
begin
call boast
print string lskdwfhhd hdsi
end function
end class
set bunty = call nalayak
call boast | class mummy():
def boast(self):
print('goyna ache')
class nalayak(mummy):
def boast(self):
super().boast()
print('lskdwfhhd hdsi')
bunty=nalayak()
bunty.boast()
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Nov 03 19:26:38 2017 @author: user
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
from skimage.feature import hog
import random
import time
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.cross... | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 03 19:26:38 2017
@author: user
"""
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
from skimage.feature import hog
import random
import time
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.cross_va... | Python | zaydzuhri_stack_edu_python |
function init_cache_from_geojson self path
begin
call copy_file path_from=path path_to=path
end function | def init_cache_from_geojson(self, path):
io.copy_file(path_from=path, path_to=self.path) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import datetime
import logging
set log = call getLogger string qi.data.calc
class CalcException extends Exception
begin
pass
end class
class DateRangeError extends CalcException
begin
pass
end class
class DateCalc
begin
function __init__ self st_date
begin
set st_date = st_date
call _split... | #-*- coding: utf-8 -*-
import datetime
import logging
log = logging.getLogger("qi.data.calc")
class CalcException(Exception):
pass
class DateRangeError(CalcException):
pass
class DateCalc:
def __init__(self, st_date):
self.st_date = st_date
self._split()
def _split(self):
da... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
set __author__ = string Raphael Leber
from abc import ABC , abstractmethod
class Vehicle
begin
decorator abstractmethod
function model self speed guidon dt
begin
pass
end function
decorator abstractmethod
function toPoint self x y eps=0.5
begin
string Move to a point (x, y) Parameters: x (i... | #!/usr/bin/env python
__author__ = 'Raphael Leber'
from abc import ABC, abstractmethod
class Vehicle:
@abstractmethod
def model(self, speed, guidon, dt):
pass
@abstractmethod
def toPoint(self, x, y, eps=0.5):
""" Move to a point (x, y)
Parameters:
... | Python | zaydzuhri_stack_edu_python |
function _get_config self state controller option
begin
set config = get config string { controller } . { option } Recollection
if config is Recollection
begin
set s = get get state controller dict option none
end
else
begin
set s = config
end
debug string _get_config(%s, %s, %s) = %s state controller option s
return s... | def _get_config(self, state, controller, option):
config = self.config.get(f'{controller}.{option}', Recollection)
if config is Recollection:
s = state.get(controller, {}).get(option, None)
else:
s = config
logger.debug(
"_get_config(%s, %s, %s) = %s",... | Python | nomic_cornstack_python_v1 |
function description self
begin
return _description
end function | def description(self):
return self._description | Python | nomic_cornstack_python_v1 |
from tkinter import *
from PIL import ImageTk , Image
class Ethnicity_Labeler
begin
function __init__ self master
begin
set master = master
title master string Ethnicity Labeler
set THRESHOLD = 0.35
with open string still_uncertain.txt as f
begin
set lines = list comprehension line for line in f
end
set names = list co... | from tkinter import *
from PIL import ImageTk, Image
class Ethnicity_Labeler:
def __init__(self, master):
self.master = master
master.title("Ethnicity Labeler")
self.THRESHOLD = 0.35
with open('still_uncertain.txt') as f:
lines = [line for line in f]
... | Python | zaydzuhri_stack_edu_python |
function get_filter self
begin
return _filter
end function | def get_filter(self):
return self._filter | Python | nomic_cornstack_python_v1 |
import collections
comment 空间占用多,速度慢
function leastInterval tasks n
begin
set dic = dict
for i in tasks
begin
if i not in keys dic
begin
set dic at i = 1
end
else
begin
set dic at i = dic at i + 1
end
end
set dic = sorted items dic key=lambda x -> x at 1 reverse=true
set max_len = 0
set same_count = 0
for i in dic
beg... | import collections
#空间占用多,速度慢
def leastInterval(tasks, n):
dic = {}
for i in tasks:
if i not in dic.keys():
dic[i] = 1
else:
dic[i] += 1
dic = sorted(dic.items(),key = lambda x:x[1],reverse=True)
max_len = 0
same_count = 0
for i in dic:
if i[1] ... | Python | zaydzuhri_stack_edu_python |
function Score i
begin
set text = call render string Score: + string i true black
call blit text tuple 210 0
end function | def Score (i):
text = font.render("Score: "+str(i), True, black)
window.blit(text,(210,0)) | Python | nomic_cornstack_python_v1 |
import discord
from discord.ext import commands
class Unload extends Cog
begin
function __init__ self client
begin
set client = client
end function
decorator call command
decorator call has_permissions administrator=true
async function unload self ctx extension=none
begin
try
begin
call unload_extension extension
end
e... | import discord
from discord.ext import commands
class Unload(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@commands.has_permissions(administrator=True)
async def unload(self, ctx, extension: str = None) -> None:
try:
self.client.unloa... | Python | zaydzuhri_stack_edu_python |
comment This will return abs value of integer as Unsigned Integer
function toUInt8 self
begin
from UInt8 import UInt8
return call UInt8 bits=bits
end function | def toUInt8(self): # This will return abs value of integer as Unsigned Integer
from UInt8 import UInt8
return UInt8(bits=abs(self).bits) | Python | nomic_cornstack_python_v1 |
function _bind obj form memo
begin
if memo is none
begin
set memo = dict
end
set obj_id = call id obj
if obj_id in memo
begin
return memo at obj_id
end
set rv = call _bind form memo
set memo at obj_id = rv
return rv
end function | def _bind(obj, form, memo):
if memo is None:
memo = {}
obj_id = id(obj)
if obj_id in memo:
return memo[obj_id]
rv = obj._bind(form, memo)
memo[obj_id] = rv
return rv | Python | nomic_cornstack_python_v1 |
function go self
begin
call send_start
for tuple cell color in items dirty
begin
set tuple h s v = tuple call byte_clamp color at 0 wrap=true call byte_clamp color at 1 call byte_clamp color at 2
comment r, g, b = hsv_to_rgb((byte_clamp(color[0], wrap=True), byte_clamp(color[1]), byte_clamp(color[2])))
set msg = format... | def go(self):
self.send_start()
for (cell, color) in self.dirty.items():
h, s, v = byte_clamp(color[0], wrap=True), byte_clamp(color[1]), byte_clamp(color[2])
# r, g, b = hsv_to_rgb((byte_clamp(color[0], wrap=True), byte_clamp(color[1]), byte_clamp(color[2])))
msg = "... | Python | nomic_cornstack_python_v1 |
function new cls slide_layout partname package
begin
set slide_elm = call new
set slide = call cls partname PML_SLIDE slide_elm package
call clone_layout_placeholders slide_layout
call relate_to slide_layout SLIDE_LAYOUT
return slide
end function | def new(cls, slide_layout, partname, package):
slide_elm = CT_Slide.new()
slide = cls(partname, CT.PML_SLIDE, slide_elm, package)
slide.shapes.clone_layout_placeholders(slide_layout)
slide.relate_to(slide_layout, RT.SLIDE_LAYOUT)
return slide | Python | nomic_cornstack_python_v1 |
comment Order:
comment ()
comment **
comment *
comment /
comment +
comment -
print 5 + 4 * 10 / 2
comment remember the float answer 45.0 | #Order:
# ()
# **
# *
# /
# +
# -
print((5 + 4) * 10 / 2)
# remember the float answer 45.0
| Python | zaydzuhri_stack_edu_python |
comment 1043
set tuple a b c = list map float split input
if a < b + c and a > absolute b - c
begin
set p = a + b + c
print format string Perimetro = {:0.1f} p
end
else
begin
set area = c * a + b / 2
print format string Area = {:0.1f} area
end | #1043
a, b, c = list(map(float, input().split()))
if a < (b+c) and a > abs(b-c):
p = a+b+c
print ("Perimetro = {:0.1f}".format(p))
else:
area = c*(a+b)/2
print("Area = {:0.1f}".format(area))
| Python | zaydzuhri_stack_edu_python |
comment Problem 30
comment Digit fifth powers
set upper_limit = 1000000
function main
begin
set valid_number = list
for i in range 2 upper_limit
begin
if i == sum list comprehension integer s ^ 5 for s in list string i
begin
append valid_number i
end
end
return sum valid_number
end function
if __name__ == string __mai... | ## Problem 30
## Digit fifth powers
upper_limit = 1000000
def main():
valid_number = []
for i in range(2, upper_limit):
if i == sum([int(s)**5 for s in list(str(i))]):
valid_number.append(i)
return sum(valid_number)
if __name__ == "__main__":
answer = main()
print(answer... | Python | zaydzuhri_stack_edu_python |
comment It looks like this creates haikus which evaluate to particular numbers.
comment It doesn't work for every number, though it probably could.
comment I have no idea when I wrote this.
from math import sqrt
import random
set syllables = dict 0 1 ; 1 1 ; 2 1 ; 3 1 ; 4 1 ; 5 1 ; 6 1 ; 7 2 ; 8 1 ; 9 1 ; 10 1 ; 11 3 ;... | # It looks like this creates haikus which evaluate to particular numbers.
# It doesn't work for every number, though it probably could.
# I have no idea when I wrote this.
from math import sqrt
import random
syllables={
0: 1,
1: 1,
2: 1,
3: 1,
4: 1,
5: 1,
6: 1,
7: 2,
8: 1,
9: 1,
10: 1,
11: 3,
12: 1,
13:... | Python | zaydzuhri_stack_edu_python |
function longest_common_substring s1 s2
begin
function helper i j substring
begin
if i == 0 or j == 0
begin
return if expression is upper substring then substring at slice : : - 1 else string
end
if s1 at i - 1 == s2 at j - 1 and is upper s1 at i - 1
begin
return call helper i - 1 j - 1 substring + s1 at i - 1
end
e... | def longest_common_substring(s1, s2):
def helper(i, j, substring):
if i == 0 or j == 0:
return substring[::-1] if substring.isupper() else ""
if s1[i-1] == s2[j-1] and s1[i-1].isupper():
return helper(i-1, j-1, substring + s1[i-1])
else:
return max(helper(... | Python | jtatman_500k |
import socket
set _TIMEOUT = 2
class Request
begin
function __init__ self url port
begin
set url = split url string / 1
set host = url at 0
set path = if expression length url <= 1 then string else url at 1
set port = port
end function
comment Cria o socket
function startSocket self
begin
try
begin
set s = call socket... | import socket
_TIMEOUT = 2
class Request:
def __init__(self, url, port):
url = url.split("/", 1)
self.host = url[0]
self.path = "" if len(url)<=1 else url[1]
self.port = port
# Cria o socket
def startSocket(self):
try:
s = socket.socket(socket... | Python | zaydzuhri_stack_edu_python |
string Example Enter the number of rows: 5 E D C B A E D C B E D C E D E
print string Alphabet Pattern:
set number_rows = integer input string Enter number of rows:
for row in range 1 number_rows + 1
begin
for column in range 1 number_rows + 2 - row
begin
print character 65 + number_rows - column end=string
end
print
e... | """
Example
Enter the number of rows: 5
E D C B A
E D C B
E D C
E D
E
"""
print('Alphabet Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(1,number_rows+2-row):
print(chr(65+(number_rows-column)),end=' ')
print() | Python | zaydzuhri_stack_edu_python |
function group lst n
begin
for i in range 0 length lst n
begin
set val = lst at slice i : i + n :
if length val == n
begin
yield list val
end
end
end function | def group(lst, n):
for i in range(0, len(lst), n):
val = lst[i:i+n]
if len(val) == n:
yield list(val) | Python | nomic_cornstack_python_v1 |
function hay_partida_guardada
begin
import pickle
import os
set dir_actual = get current directory
set ubicacion_archivo = dir_actual + string /Data/Files/ + string partidaguardada.obj
set f = open ubicacion_archivo string rb
set datos = load pickle f
close f
return datos at 0
end function | def hay_partida_guardada():
import pickle
import os
dir_actual = os.getcwd()
ubicacion_archivo = (dir_actual+'/Data/Files/'+'partidaguardada.obj')
f = open(ubicacion_archivo,'rb')
datos = pickle.load(f)
f.close()
return datos[0] | Python | nomic_cornstack_python_v1 |
function connect self path=none
begin
if not connected
begin
call initialize
if not path
begin
set path = path
end
try
begin
call connect path
end
except error
begin
raise call ConnectionError path
end
end
end function | def connect(self, path=None):
if not self.connected:
self.initialize()
if not path:
path = self.path
try:
self.socket.connect(path)
except socket.error:
raise ConnectionError(path) | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss
set x = 25
function pseudo_random x_=none
begin
set M = 27
set m = 2
global x
if x is float
begin
set x = x_
end
set x = x * M % 2 ^ m / 2 ^ m
return x
end function
set l = 0.05
set ranges = list 0 * integer 1 / l
set rand_list = list
set itera... | import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss
x = 25
def pseudo_random(x_=None):
M = 27
m = 2
global x
if x is float:
x = x_
x = x * M % (2**m) / (2**m)
return x
l = 0.05
ranges = [0]*int(1 / l)
rand_list = list()
iterations = 20000
for i in range(iter... | Python | zaydzuhri_stack_edu_python |
function get_right_number numbers i
begin
if i >= length numbers - 1
begin
set right = - 99
end
else
begin
set right = numbers at i + 1
if right == - 99
begin
set right = call get_right_number numbers i + 1
end
end
return right
end function
function clean_missing_data numbers
begin
print string Input: { numbers }
if al... | def get_right_number(numbers, i):
if i >= len(numbers) - 1:
right = -99
else:
right = numbers[i + 1]
if right == -99:
right = get_right_number(numbers, i+1)
return right
def clean_missing_data(numbers):
print(f'Input: {numbers}')
if all(x == -99 for x in number... | Python | zaydzuhri_stack_edu_python |
function conjunctive_MI these_vars those_vars
begin
set tuple _ c1 = unique these_vars axis=0 return_inverse=true
set tuple _ c2 = unique those_vars axis=0 return_inverse=true
return call mutual_information T
end function | def conjunctive_MI(these_vars, those_vars):
_, c1 = np.unique(these_vars, axis=0, return_inverse=True)
_, c2 = np.unique(those_vars, axis=0, return_inverse=True)
return mutual_information(np.stack([c1,c2]).T) | Python | nomic_cornstack_python_v1 |
function isPalindrome s
begin
set i = 0
set j = length s - 1
while i < j
begin
if s at i != s at j
begin
return false
end
set i = i + 1
set j = j - 1
end
return true
end function
comment Driver code
set s = string level
if call isPalindrome s
begin
print string Yes
end
else
begin
print string No
end | def isPalindrome(s):
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
# Driver code
s = "level"
if isPalindrome(s):
print("Yes")
else:
print("No")
| Python | flytech_python_25k |
comment from vidstream import AudioSender, AudioReceiver,ScreenShareClient, CameraClient, StreamingServer
comment screenshare data and camera data received by streamingserver and audio data by audioreceiver
from vidstream import *
import tkinter as tk
comment to getting your private ip
import socket
comment because we ... | #from vidstream import AudioSender, AudioReceiver,ScreenShareClient, CameraClient, StreamingServer
#screenshare data and camera data received by streamingserver and audio data by audioreceiver
from vidstream import *
import tkinter as tk
import socket #to getting your private ip
import threading #because we have many c... | Python | zaydzuhri_stack_edu_python |
function expand_group_users self group_dn
begin
comment -- check memcache
set users = call _cache_get group_dn
if users
begin
return users
end
comment -- where to look
set base_dn = group_basedn or dir_basedn
set users = list
if group_expand
begin
set group_member_attr = decode group_member_attr string ascii
set group... | def expand_group_users(self, group_dn):
#-- check memcache
users = self._cache_get(group_dn)
if users:
return users
#-- where to look
base_dn = self.group_basedn or self.dir_basedn
users = []
if self.group_expand:
group_member_attr = self... | Python | nomic_cornstack_python_v1 |
comment print(dic['girl'])
comment 키와값의 쌍
set dic = dict string boy string 소년 ; string school string 학교 ; string book string 책
print get dic string boy
print get dic string girl
print get dic string girl string 사전에 없는 단어입니다.
set dic at string boy = string 남자아이
set dic at string girl = string 소녀
del dic at string book
p... | # print(dic['girl'])
#키와값의 쌍
dic = {
'boy':'소년',
'school':'학교',
'book':'책'
}
print(dic.get('boy'))
print(dic.get('girl'))
print(dic.get('girl',"사전에 없는 단어입니다."))
dic['boy'] ='남자아이'
dic['girl'] ='소녀'
del dic['book']
print(dic)
print(dic.keys()) #리스트처럼 보이지만 data-type 이 dict_keys 이다.
print(dic.values())
pri... | Python | zaydzuhri_stack_edu_python |
function __init__ self flow_cell
begin
set flow_cell = flow_cell
end function | def __init__(self, flow_cell):
self.flow_cell = flow_cell | Python | nomic_cornstack_python_v1 |
function _check_writable_ self
begin
call _check_within_context_
if _mode != string w
begin
raise exception string Cannot update database: read only mode
end
end function | def _check_writable_(self):
self._check_within_context_()
if self._mode != 'w':
raise Exception('Cannot update database: read only mode') | Python | nomic_cornstack_python_v1 |
comment Author: Ryan Auger
comment Purpose:
comment Control Servo Motor With MQTT
comment Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from time import sleep
import RPi.GPIO as GPIO
import sys
comment GPIO Setup
comment GPIOPin - Pin on the raspberry pi that is controlling the servo
comment ... | #
# Author: Ryan Auger
# Purpose:
# Control Servo Motor With MQTT
#
#Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
from time import sleep
import RPi.GPIO as GPIO
import sys
# GPIO Setup
# GPIOPin - Pin on the raspberry pi that is controlling the servo
# PulseFrequency- Freque... | Python | zaydzuhri_stack_edu_python |
function get_chip_type self
begin
return SENSOR_TYPE_NAME
end function | def get_chip_type(self):
return SENSOR_TYPE_NAME | Python | nomic_cornstack_python_v1 |
import random
import sys
comment compatibility
if version_info at 0 == 2
begin
function _to_bytes n length byteorder
begin
assert byteorder == string little
return decode call zfill length * 2 string hex at slice : : - 1
end function
function _from_bytes s byteorder
begin
assert byteorder == string little
return inte... | import random
import sys
# compatibility
if sys.version_info[0] == 2:
def _to_bytes(n, length, byteorder):
assert byteorder == 'little'
return ('%x' % n).zfill(length * 2).decode('hex')[: : -1]
def _from_bytes(s, byteorder):
assert byteorder == 'little'
return int(str(s[: : -1])... | Python | zaydzuhri_stack_edu_python |
function scanBuiltInCmaps
begin
set basedir = call getCmapDir
set cmapIDs = call _walk basedir string .cmap
set cmapIDs = list comprehension call splitext i at 0 for i in cmapIDs
set cmapIDs = list comprehension call relpath i basedir for i in cmapIDs
set cmapIDs = list comprehension replace i sep string _ for i in cma... | def scanBuiltInCmaps():
basedir = getCmapDir()
cmapIDs = _walk(basedir, '.cmap')
cmapIDs = [op.splitext(i)[0] for i in cmapIDs]
cmapIDs = [op.relpath(i, basedir) for i in cmapIDs]
cmapIDs = [i.replace(op.sep, '_') for i in cmapIDs]
return cmapIDs | Python | nomic_cornstack_python_v1 |
function from_value cls value **kwds
begin
set class_ = call reflect_subclass_by_value_or_raise value
return call class_ value=value keyword kwds
end function | def from_value(cls, value: Value, **kwds: Any) -> "Constant":
class_ = cls.reflect_subclass_by_value_or_raise(value)
return class_(value=value, **kwds) | Python | nomic_cornstack_python_v1 |
string Largest product in a series Problem 8
function gpc_adj_digits number adj_digits
begin
string given full number and number of adjacent digits returns int greatest product count and list of single string associated digits using specified adjacent digits in number
set our_number = number
set greatest_product_count ... | """
Largest product in a series
Problem 8
"""
def gpc_adj_digits(number, adj_digits):
"""
given full number and number of adjacent digits
returns int greatest product count and list of single string associated digits using specified adjacent digits in number
"""
our_number = number
... | Python | zaydzuhri_stack_edu_python |
for i in dic
begin
print i
end | for i in dic:
print(i) | Python | zaydzuhri_stack_edu_python |
function _type_to_string t_type
begin
if t_type == Current
begin
return string Actual
end
else
if t_type == NextWeek
begin
return string Next
end
else
begin
return string Permanent
end
end function | def _type_to_string(t_type: TimetableType) -> str:
if t_type == TimetableType.Current:
return "Actual"
elif t_type == TimetableType.NextWeek:
return "Next"
else:
return "Permanent" | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string 路径和:四个方向 注意:这是第81题的一个极具挑战性的版本。 在如下的5乘5矩阵中,从左上角到右下角任意地向上、向下、向左或向右移动的最小路径和为2297,由标注红色的路径给出。 131 673 234 103 18 201 96 342 965 150 630 803 746 422 111 537 699 497 121 956 805 732 524 37 331 在这个31K的文本文件matrix.txt(右击并选择“目标另存为……”)中包含了一个80乘80的矩阵,求出从左上角到右下角任意地向上... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
路径和:四个方向
注意:这是第81题的一个极具挑战性的版本。
在如下的5乘5矩阵中,从左上角到右下角任意地向上、向下、向左或向右移动的最小路径和为2297,由标注红色的路径给出。
131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331
在这个31K的文本文件matrix.txt(右击并选择“目标另存为……”)中包含了一个80乘80的矩阵,求出从左上角到右下角任意地向上、向下、向左或向右移动的最小路径... | Python | zaydzuhri_stack_edu_python |
function test_spa_get app client
begin
with call capture_flashes as flashes
begin
with call capture_passwordless_login_requests as requests
begin
set response = post string /login json=dictionary email=string matt@lp.com headers=dict string Content-Type string application/json
assert headers at string Content-Type == s... | def test_spa_get(app, client):
with capture_flashes() as flashes:
with capture_passwordless_login_requests() as requests:
response = client.post(
"/login",
json=dict(email="matt@lp.com"),
headers={"Content-Type": "application/json"},
)
... | Python | nomic_cornstack_python_v1 |
function main params
begin
call mpi_vs_multiprocess_logging string process params
set ifg_paths = list
for ifg_path in params at INTERFEROGRAM_FILES
begin
append ifg_paths sampled_path
end
set tuple rows cols = tuple params at string rows params at string cols
return call process_ifgs ifg_paths params rows cols
end fu... | def main(params):
mpi_vs_multiprocess_logging("process", params)
ifg_paths = []
for ifg_path in params[cf.INTERFEROGRAM_FILES]:
ifg_paths.append(ifg_path.sampled_path)
rows, cols = params["rows"], params["cols"]
return process_ifgs(ifg_paths, params, rows, cols) | Python | nomic_cornstack_python_v1 |
comment Valid Ip AddressesBookmark Suggest Edit
comment Given a string containing only digits, restore it by returning all possible
comment valid IP address combinations.
comment A valid IP address must be in the form of A.B.C.D, where A,B,C and D are
comment numbers from 0-255. The numbers cannot be 0 prefixed unless ... | # Valid Ip AddressesBookmark Suggest Edit
# Given a string containing only digits, restore it by returning all possible
# valid IP address combinations.
#
# A valid IP address must be in the form of A.B.C.D, where A,B,C and D are
# numbers from 0-255. The numbers cannot be 0 prefixed unless they are 0.
#
# Example:
#
... | Python | zaydzuhri_stack_edu_python |
function add_close_handler self func
begin
if func not in _close_handlers
begin
append _close_handlers func
end
end function | def add_close_handler(self, func):
if func not in self._close_handlers:
self._close_handlers.append(func) | Python | nomic_cornstack_python_v1 |
import pygame
import sys
import random
call init
set koko = tuple 600 600
set naytto = call set_mode koko
set kolikko = load image string kolikko.png
set kolikko = call scale kolikko list 64 64
set koordinaatit = list 0 0
while true
begin
set koordinaatit at 0 = random integer 0 600
set koordinaatit at 1 = random integ... | import pygame
import sys
import random
pygame.init()
koko = (600, 600)
naytto = pygame.display.set_mode(koko)
kolikko = pygame.image.load("kolikko.png")
kolikko = pygame.transform.scale(kolikko, [64, 64])
koordinaatit = [0, 0]
while True:
koordinaatit[0] = random.randint(0, 600)
koordinaatit[1] = random.rand... | Python | zaydzuhri_stack_edu_python |
import json
import Ability
class Card extends object
begin
comment The class "constructor" - It's actually an initializer
function __init__ self
begin
set layout = string
set name = string
set manaCost = string
set cmc = string
set colors = string
set type = string
set types = string
set subtypes = string
set t... | import json
import Ability
class Card(object):
# The class "constructor" - It's actually an initializer
def __init__(self):
self.layout = ""
self.name = ""
self.manaCost = ""
self.cmc = ""
self.colors = ""
self.type = ""
self.types = ""
... | Python | zaydzuhri_stack_edu_python |
async function get_playlist self channel_id use_cache=true
begin
set url = await call _get_playlist_url channel_id use_cache
if url is none
begin
return none
end
set response = none
try
begin
set response = await call _make_request string GET url call _token_params
if status_code == 403
begin
info string Received statu... | async def get_playlist(
self, channel_id: str, use_cache: bool = True
) -> Union[str, None]:
url = await self._get_playlist_url(channel_id, use_cache)
if url is None:
return None
response = None
try:
response = await self._make_request("GET", url, se... | Python | nomic_cornstack_python_v1 |
function prepare_db self
begin
try
begin
if is file path string ../db/schema.sql
begin
with open string ../db/schema.sql string r as file
begin
set init_sql = read file
end
call executescript init_sql
commit connection
end
end
comment todo create user in empty database add user to schema or prompt to create wia new win... | def prepare_db(self):
try:
if os.path.isfile("../db/schema.sql"):
with open("../db/schema.sql", 'r') as file:
init_sql = file.read()
self.cursor.executescript(init_sql)
self.connection.commit()
# todo create user in ... | Python | nomic_cornstack_python_v1 |
function fix_student_names csvin
begin
comment Last Name First Name
set mydb = call db_from_file csvin
set lower_labels = list comprehension lower item for item in labels
set mylist = list string last name string lastname string lname
for label in mylist
begin
if label in lower_labels
begin
comment exit now
return
end
... | def fix_student_names(csvin):
#Last Name First Name
mydb = txt_database.db_from_file(csvin)
lower_labels = [item.lower() for item in mydb.labels]
mylist = ['last name', 'lastname', 'lname']
for label in mylist:
if label in lower_labels:
#exit now
return
#... | Python | nomic_cornstack_python_v1 |
function read self request project_number
begin
debug string GET request from user %s for risk list % user
set proj = get objects project_number=project_number
if not call check_project_read_acl proj user
begin
debug string Refusing GET request for project list %s from user %s % tuple project_number user
return FORBIDD... | def read(self, request, project_number):
log.debug("GET request from user %s for risk list" % request.user)
proj = Project.objects.get(project_number=project_number)
if not check_project_read_acl(proj, request.user):
log.debug("Refusing GET request for project list %s from user %s"... | Python | nomic_cornstack_python_v1 |
function is_word_guessed secret_word letters_guessed
begin
set unguessed_letters = set secret_word - set letters_guessed
if length unguessed_letters > 0
begin
return false
end
else
begin
return true
end
end function | def is_word_guessed(secret_word, letters_guessed):
unguessed_letters = set(secret_word) - set(letters_guessed)
if len(unguessed_letters) > 0:
return False
else:
return True | Python | nomic_cornstack_python_v1 |
string ch4 No.3 Program name: repositioned_star_polygon_1.py Objective: Draw a series of stars each with their own start position. Keywords: polygon, anchor point, star ============================================================================79 Comments:Each separate star is drawn relative to a pair variables, x_anc... | """ ch4 No.3
Program name: repositioned_star_polygon_1.py
Objective: Draw a series of stars each with their own start position.
Keywords: polygon, anchor point, star
============================================================================79
Comments:Each separate star is drawn relative to a pair variables,
x... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
from heapq import *
function main
begin
set tot = 0
comment heap for larger half, add normal numbers
set hmax = list
comment hepa for smaller half, add negative values
set hmin = list
comment which heap is due for an insertion, true for min, false for max
set mainSwitch = true
with open strin... | #!/usr/bin/python
from heapq import *
def main():
tot=0
#heap for larger half, add normal numbers
hmax=[]
#hepa for smaller half, add negative values
hmin=[]
# which heap is due for an insertion, true for min, false for max
mainSwitch=True
with open('Median.txt','r') as f:
for i in range(2):
n=int(f.read... | Python | zaydzuhri_stack_edu_python |
async function experiment self id
begin
set experiment = call Experiment await call get_experiment name id self
return experiment
end function | async def experiment(self, id):
experiment = Experiment(await self.repository.get_experiment(self.name, id), self)
return experiment | Python | nomic_cornstack_python_v1 |
from TP21_Downloading_data import *
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
call rc string font family=string Times New Roman
for i in range length index_list
begin
set start = index_list at i at string Close at 0
set end = index_list at i at string Close at length... | from TP21_Downloading_data import *
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
plt.rc('font',family='Times New Roman')
for i in range(len(index_list)):
start = index_list[i]["Close"][0]
end = index_list[i]["Close"][len(index_list[i]["Close"])-1]
print(gra... | Python | zaydzuhri_stack_edu_python |
function create_new_event self
begin
pass
end function | def create_new_event(self):
pass | Python | nomic_cornstack_python_v1 |
string Authors: Orlando Coyoy, Ya'Kuana Davis, Roger Trejo Course Name: CSCI 3725 Assignment Name: PQ1 Date: September 25, 2020 Description: This document can be used to run our modified version of PIERRE. The files classes.py, get_methods.py, reading_files.py and mutations are all imported into this file and utilized ... | """
Authors: Orlando Coyoy, Ya'Kuana Davis, Roger Trejo
Course Name: CSCI 3725
Assignment Name: PQ1
Date: September 25, 2020
Description: This document can be used to run our modified version of PIERRE. The files classes.py, get_methods.py, reading_files.py and mutations are all imported into this file and utilized as... | Python | zaydzuhri_stack_edu_python |
function access_armor self
begin
set access = speed * armor at string speed + armor * armor at string armor + life * armor at string life
return access
end function | def access_armor(self):
access = self.speed * armor['speed'] + self.armor * armor['armor'] + self.life * armor['life']
return access | Python | nomic_cornstack_python_v1 |
comment Beautiful Days at the Movies
comment https://www.hackerrank.com/challenges/beautiful-days-at-the-movies
set tuple i j k = map int split strip call raw_input string
set count = 0
for x in range i j + 1
begin
set n = x
set s = 0
while n != 0
begin
set s = s * 10 + n % 10
set n = n / 10
end
if absolute s - x % k =... | # Beautiful Days at the Movies
# https://www.hackerrank.com/challenges/beautiful-days-at-the-movies
i, j, k = map(int, raw_input().strip().split(' '))
count = 0
for x in range(i, j + 1):
n = x
s = 0
while(n != 0):
s = (s * 10) + n % 10
n = n / 10
if abs(s - x) % k == 0:
count +=... | Python | zaydzuhri_stack_edu_python |
from django.contrib.auth.models import BaseUserManager
class UserAccountManager extends BaseUserManager
begin
function create_user self username password=none
begin
if not username
begin
raise call ValueError string Username must be set!
end
set user = model username=username
call set_password password
save using=_db
r... | from django.contrib.auth.models import BaseUserManager
class UserAccountManager(BaseUserManager):
def create_user(self, username, password=None):
if not username:
raise ValueError('Username must be set!')
user = self.model(username=username)
user.set_password(password)
... | Python | zaydzuhri_stack_edu_python |
function get_matchers
begin
string Get matcher functions from treeherder.autoclassify.matchers We classify matchers as any function treeherder.autoclassify.matchers with a name ending in _matcher. This is currently overkill but protects against the unwarey engineer adding new functions to the matchers module that shoul... | def get_matchers():
"""
Get matcher functions from treeherder.autoclassify.matchers
We classify matchers as any function treeherder.autoclassify.matchers with
a name ending in _matcher. This is currently overkill but protects against
the unwarey engineer adding new functions to the matchers module... | Python | jtatman_500k |
comment Definition for binary tree with next pointer.
class TreeLinkNode
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
set next = none
end function
end class
class Solution
begin
comment @param root, a tree link node
comment @return nothing
function __init__ self
begin
set nodes = li... | # Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def __init__(self):
self.nodes = []
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from flask import Flask , render_template , request
import urllib.parse , urllib.request , urllib.error , json , requests
import logging
comment important methods
import covidfunctions as cf
set app = call Flask __name__
comment initial, total, last
set list1 = call get_covid_projects
set l... | #!/usr/bin/env python
from flask import Flask, render_template, request
import urllib.parse, urllib.request, urllib.error, json, requests
import logging
#important methods
import covidfunctions as cf
app = Flask(__name__)
#initial, total, last
list1 = cf.get_covid_projects()
listrecorder= [list1,list1,... | Python | zaydzuhri_stack_edu_python |
function _get_wav2vec2_requirements self
begin
set pretrained_path = call Path path / string wav2vec2
set processor = call from_pretrained pretrained_path
set model = call from_pretrained pretrained_path
return tuple processor model
end function | def _get_wav2vec2_requirements(self) -> Tuple[Wav2Vec2Processor, Wav2Vec2ForCTC]:
pretrained_path = Path(self.model.path) / "wav2vec2"
processor = Wav2Vec2Processor.from_pretrained(pretrained_path)
model = Wav2Vec2ForCTC.from_pretrained(pretrained_path)
return processor, model | Python | nomic_cornstack_python_v1 |
function get self request
begin
if not model
begin
raise call NotImplementedError string Model not provided
end
if not serializer
begin
raise call NotImplementedError string Serializer not provided
end
function get_donors_from_coordinate latitude longitude
begin
set pnt = call to_internal_value dict string latitude lat... | def get(self, request: Request):
if not self.model:
raise NotImplementedError("Model not provided")
if not self.serializer:
raise NotImplementedError("Serializer not provided")
def get_donors_from_coordinate(latitude: float, longitude: float) -> QuerySet:
pn... | Python | nomic_cornstack_python_v1 |
import time
comment What is Tick?
comment Time intervals are floating-point numbers in units of seconds.
comment Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).
comment There is a popular time module available in Python which provides functions
comment for working with times,... | import time
# What is Tick?
# Time intervals are floating-point numbers in units of seconds.
# Particular instants in time are expressed in seconds since 12:00am, January 1, 1970(epoch).
# There is a popular time module available in Python which provides functions
# for working with times,and for converting between r... | Python | zaydzuhri_stack_edu_python |
import os , csv
import numpy as np
set datadir = string ../data
set city = string lacity
comment category = ''
comment category = '_property'
function readObfile obfile
begin
set tractids = list
set obvalues = dict
set skipped = 0
with open obfile string r as f
begin
set obreader = reader f
set header = next obreader... | import os, csv
import numpy as np
datadir = '../data'
city = 'lacity'
# category = ''
# category = '_property'
def readObfile(obfile):
tractids = []
obvalues = {}
skipped = 0
with open(obfile, 'r') as f:
obreader = csv.reader(f)
header = next(obreader)
for i in range(0, len(he... | Python | zaydzuhri_stack_edu_python |
while length fruits < 5
begin
set customFruit = input string Name a fruit, any fruit!
append fruits customFruit
print fruits
end | while len(fruits) < 5:
customFruit = input("Name a fruit, any fruit! ")
fruits.append(customFruit)
print(fruits) | Python | zaydzuhri_stack_edu_python |
import random
import csv
import math
import operator
set split = 0.66
with open string rock_datasets.csv as csvfile
begin
set lines = reader csvfile
comment remove 1st row of a csv file
set dataset = list lines at slice 1 : :
end
shuffle random dataset
set div = integer split * length dataset
set train_set = dataset ... | import random
import csv
import math
import operator
split = 0.66
with open('rock_datasets.csv') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)[1:] # remove 1st row of a csv file
random.shuffle(dataset)
div = int(split * len(dataset))
train_set = dataset [:div]
test_set = datas... | Python | zaydzuhri_stack_edu_python |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
function makeSubDir dirName
begin
string Makes a given subdirectory if it doesn't already exist, making sure it us public.
if not exists path dirName
begin
make directory os dirName
end
end function | def makeSubDir(dirName):
"""Makes a given subdirectory if it doesn't already exist, making sure it us public.
"""
if not os.path.exists(dirName):
os.mkdir(dirName) | Python | jtatman_500k |
for k in range n
begin
set dp1 at k + 1 = min list dp1 at k + s at k dp2 at k + 10 - s at k
set dp2 at k + 1 = min list dp1 at k + s at k + 1 dp2 at k + 10 - s at k - 1
end
print dp1 at - 1 | for k in range(n):
dp1[k + 1] = min([dp1[k] + s[k] , dp2[k] + 10 - s[k]])
dp2[k + 1] = min([dp1[k] + s[k] + 1, dp2[k] + 10 - s[k] - 1])
print(dp1[-1]) | Python | zaydzuhri_stack_edu_python |
comment -- FILE: features/steps/creating_cryptocurrency_steps.py
from behave import given , when , then
from models.currencies_exchange import CurrenciesExchange
from models.currency_builder import CurrencyBuilder
decorator call given string system with some currencies defined
function step_impl context
begin
set build... | # -- FILE: features/steps/creating_cryptocurrency_steps.py
from behave import given, when, then
from models.currencies_exchange import CurrenciesExchange
from models.currency_builder import CurrencyBuilder
@given('system with some currencies defined')
def step_impl(context):
builder = CurrencyBuilder()
buil... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.