code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from flask import Flask , jsonify , render_template , request
set app = call Flask __name__
decorator call route string /
function hello
begin
return call render_template string index.html
end function
decorator call route string /grades/ methods=list string GET
function get_grades
begin
set grades = list dict string g... | from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route("/")
def hello():
return render_template("index.html")
@app.route("/grades/", methods=["GET"])
def get_grades():
grades = [
{
"grade": 95,
"name": "Anton"
},
{
... | Python | zaydzuhri_stack_edu_python |
comment print(repr(fin.readline()))
string Exercise 1_1
function read_long_words
begin
string prints only the words with more than 20 characters
for line in fin
begin
set word = strip line
if length word > 20
begin
print word
end
end
end function
call read_long_words
string Exercise 1_2
function has_no_e word
begin
str... | # print(repr(fin.readline()))
'''Exercise 1_1'''
def read_long_words():
"""
prints only the words with more than 20 characters
"""
for line in fin:
word = line.strip()
if len(word)>20:
print(word)
read_long_words()
'''Exercise 1_2'''
def has_no_e(word):
"""
return... | Python | zaydzuhri_stack_edu_python |
import math
import pandas as pd
function deq x y
begin
return 3 * y
end function
function mid x0 y h x
begin
set maxerror = 0
while x0 < x
begin
set y = y + h * call deq x0 + 0.5 * h y + 0.5 * h * 3 * y
set x0 = x0 + h
set yreal = exp 3 * x0
set error = absolute yreal - y / y * 100
if error > maxerror
begin
set maxerro... | import math
import pandas as pd
def deq( x, y ):
return (3*y)
def mid( x0, y, h, x ):
maxerror=0
while x0 < x:
y = y+h*deq(x0+.5*h, y+.5*h*(3*y))
x0 = x0 + h
yreal = math.exp(3*x0)
error=abs((yreal-y)/y)*100
if error>maxerror:
maxerror=error
print("Approximate solution at ... | Python | zaydzuhri_stack_edu_python |
function test_canInfectionBePrevented2 self
begin
set cities = call generateCities
set miami = cities at string MIAMI
set location = string MIAMI
set role = string quarantineSpecialist
comment the game must be initialized so the prevention works.
set initialized = 1
set result = call canInfectionBePrevented miami strin... | def test_canInfectionBePrevented2(self):
self.testGameBoard.cities = self.testGameBoard.generateCities()
miami = self.testGameBoard.cities["MIAMI"]
self.players[1].location = "MIAMI"
self.players[1].role = "quarantineSpecialist"
self.testGameBoard.initialized = 1 # the game must ... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import AnalyzeModule
comment Dictionary Index:
comment 1 = Student Number Breakdown (a for total; b for met)
comment 2 = Country Breakdown (a for total; b for met)
comment 3 = Admissions Breakdown (a for total; b for met)
comment 4 = School Breakdown (a for total; b for met)
comment 5 = Census Break... | import pandas as pd
import AnalyzeModule
# Dictionary Index:
# 1 = Student Number Breakdown (a for total; b for met)
# 2 = Country Breakdown (a for total; b for met)
# 3 = Admissions Breakdown (a for total; b for met)
# 4 = School Breakdown (a for total; b for met)
# 5 = Census Breakdown (a for total; b for met)
# 6 =... | Python | zaydzuhri_stack_edu_python |
function new_line self tokens line_end line_start
begin
if call _last_token_on_line_is tokens line_end string ;
begin
call add_message string unnecessary-semicolon line=call start_line line_end
end
set line_num = call start_line line_start
set line = call line line_start
if type line_start not in _JUNK_TOKENS
begin
set... | def new_line(self, tokens, line_end, line_start):
if _last_token_on_line_is(tokens, line_end, ';'):
self.add_message('unnecessary-semicolon', line=tokens.start_line(line_end))
line_num = tokens.start_line(line_start)
line = tokens.line(line_start)
if tokens.type(line_s... | Python | nomic_cornstack_python_v1 |
function fn self
begin
return _fn
end function | def fn(self):
return self._fn | Python | nomic_cornstack_python_v1 |
function confidence self
begin
return decimal class_scores at class_num
end function | def confidence(self) -> float:
return float(self.class_scores[self.class_num]) | Python | nomic_cornstack_python_v1 |
comment 导入模块
import matplotlib.pyplot as plt
set input_values = list 1 2 3 4 5
comment 创建列表
set squares = list 1 4 9 16 25
comment 将列表传递个plot函数,并线条粗细
plot input_values squares linewidth=5
comment 设置图表标题,并给坐标轴加上标签
comment 指定主标题,并设置字体大小
title plt string Squares Numbers fontsize=24
comment 指定轴标题,并设置字体大小
x label string Val... | import matplotlib.pyplot as plt # 导入模块
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25] # 创建列表
plt.plot(input_values, squares, linewidth=5) #将列表传递个plot函数,并线条粗细
# 设置图表标题,并给坐标轴加上标签
plt.title('Squares Numbers', fontsize=24) # 指定主标题,并设置字体大小
plt.xlabel('Value', fontsize=14) # 指定轴标题,并设置字体大小
plt.ylabel('Square ... | Python | zaydzuhri_stack_edu_python |
function newCentrifugationStep self **attrlinks
begin
return call CentrifugationStep self keyword attrlinks
end function | def newCentrifugationStep(self, **attrlinks):
return CentrifugationStep(self, **attrlinks) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import random
set c = list string [Blue] Geography string [Pink] Entertainment string [Yellow] History string [Brown] Art & Literature string [Green] Science & Nature string [Orange] Sports & Leisure
set r = random choice c
print r | #!/usr/bin/env python3
import random
c = ["[Blue] Geography",
"[Pink] Entertainment",
"[Yellow] History",
"[Brown] Art & Literature",
"[Green] Science & Nature",
"[Orange] Sports & Leisure"]
r = random.choice(c)
print(r)
| Python | zaydzuhri_stack_edu_python |
function print_attributes lyr_or_fn n=none fields=none geom=true reset=true
begin
set tuple lyr ds = call _get_layer lyr_or_fn
if reset
begin
call ResetReading
end
set n = n or call GetFeatureCount
set geom = geom and call GetGeomType != wkbNone
set fields = fields or list comprehension name for field in schema
set dat... | def print_attributes(lyr_or_fn, n=None, fields=None, geom=True, reset=True):
lyr, ds = _get_layer(lyr_or_fn)
if reset:
lyr.ResetReading()
n = n or lyr.GetFeatureCount()
geom = geom and lyr.GetGeomType() != ogr.wkbNone
fields = fields or [field.name for field in lyr.schema]
data = [['FID... | Python | nomic_cornstack_python_v1 |
function auto_delete_setting self
begin
return get pulumi self string auto_delete_setting
end function | def auto_delete_setting(self) -> Optional['outputs.AutoDeleteSettingResponse']:
return pulumi.get(self, "auto_delete_setting") | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
set cars_info = call read_excel string data_files/cars.xls
comment sneak peak of the data - top 5 rows
comment print(cars_info.head())
set mil_cyl_doors = cars_info at lis... | import pandas as pd
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
cars_info = pd.read_excel('data_files/cars.xls')
# sneak peak of the data - top 5 rows
# print(cars_info.head())
mil_cyl_doors = cars_info[['Mileage', 'Cylinder', 'Door... | Python | zaydzuhri_stack_edu_python |
function no_gain self
begin
pass
end function | def no_gain(self):
pass | Python | nomic_cornstack_python_v1 |
function isna obj
begin
if is instance obj BasePandasDataset
begin
return call isna
end
else
begin
return call isna obj
end
end function | def isna(obj):
if isinstance(obj, BasePandasDataset):
return obj.isna()
else:
return pandas.isna(obj) | Python | nomic_cornstack_python_v1 |
function DFS_hasPath graph src dst
begin
if src == dst
begin
return true
end
for neigh in graph at src
begin
if call DFS_hasPath graph neigh dst
begin
return true
end
end
return false
end function
function BFS_hasPath graph src dst
begin
set queue = list src
while queue
begin
set curr = pop queue 0
if curr == dst
begin... | def DFS_hasPath(graph:dict, src:str, dst:str) -> bool:
if src == dst:
return True
for neigh in graph[src]:
if DFS_hasPath(graph, neigh, dst):
return True
return False
def BFS_hasPath(graph:dict, src:str, dst:str) -> bool:
queue = [src]
while queue:
... | Python | zaydzuhri_stack_edu_python |
function initialize_ahoc self
begin
set candidates = keys candidates
set matcher = call create_automaton candidates
end function | def initialize_ahoc(self):
candidates = self.candidates.keys()
self.matcher = State.create_automaton(candidates) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
comment In[2]:
comment Data preparation
comment In[3]:
set historicalsale = read csv string E:\工作\百威\(Replace)Historical Sales Volume 2016.1-2019.11.csv
... | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
# In[2]:
# Data preparation
# In[3]:
historicalsale=pd.read_csv("E:\工作\百威\(Replace)Historical Sales Volume 2016.1-2019.11.csv")
masterdata=pd.read_csv("E:\工作\百威\... | Python | zaydzuhri_stack_edu_python |
function list_vaults self limit=none marker=none
begin
set params = dict
if limit
begin
set params at string limit = limit
end
if marker
begin
set params at string marker = marker
end
return call make_request string GET string vaults params=params
end function | def list_vaults(self, limit=None, marker=None):
params = {}
if limit:
params['limit'] = limit
if marker:
params['marker'] = marker
return self.make_request('GET', 'vaults', params=params) | Python | nomic_cornstack_python_v1 |
function DNN_ribeirao x_train y_train epochs model_path plot=false
begin
comment ===========================================================================
comment Neural Network structure
comment ===========================================================================
comment model = Sequential()
comment model.add... | def DNN_ribeirao(x_train, y_train, epochs, model_path, plot=False):
# ===========================================================================
# Neural Network structure
# ===========================================================================
# model = Sequential()
# model.add(Dense(units=5... | Python | nomic_cornstack_python_v1 |
string ' Problem 2_3: Write a function problem2_3() that should have a 'for' loop that steps through the list below and prints the name of the state and the number of letters in the state's name. You may use the len() function. Here is the output from mine: In [70]: problem2_3(newEngland) Maine has 5 letters. New Hamps... | ''''
Problem 2_3:
Write a function problem2_3() that should have a 'for' loop that steps
through the list below and prints the name of the state and the number of
letters in the state's name. You may use the len() function.
Here is the output from mine:
In [70]: problem2_3(newEngland)
Maine ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import numpy as np
set a = array list list list list 4 5 list 6 7 list list 5 6 list 7 8 list list 8 7 list 6 3
print ndim
print shape
set b = array list list 3.5 4 list 4 5
print b | # -*- coding: utf-8 -*-
import numpy as np
a = np.array([[[[4, 5], [6, 7]], [[5, 6], [7, 8]], [[8, 7], [6, 3]]]])
print(a.ndim)
print(a.shape)
b = np.array([[3.5, 4], [4, 5]])
print(b)
| Python | zaydzuhri_stack_edu_python |
function load_checkpoint device iteration
begin
set CHECKPOINT_PATH = BASE_CHECKPOINT_PATH + string { iteration } /
with open CHECKPOINT_PATH + string parameters.pt string rb as f
begin
set checkpoint = load pickle f
end
assert env == env msg string To resume training environment must match current settings.
assert env... | def load_checkpoint(device, iteration):
CHECKPOINT_PATH = BASE_CHECKPOINT_PATH + f"{iteration}/"
with open(CHECKPOINT_PATH + "parameters.pt", "rb") as f:
checkpoint = pickle.load(f)
assert hp.env == checkpoint.env, "To resume training environment must match current settings."
assert hp.... | Python | nomic_cornstack_python_v1 |
function test_srv_recordtype_update_delete_checks shared_zone_test_context
begin
set ok_client = ok_vinyldns_client
set dummy_client = dummy_vinyldns_client
set ok_zone = ok_zone
set dummy_zone = dummy_zone
set dummy_zone_name = dummy_zone at string name
set dummy_group_name = dummy_group at string name
set ok_zone_nam... | def test_srv_recordtype_update_delete_checks(shared_zone_test_context):
ok_client = shared_zone_test_context.ok_vinyldns_client
dummy_client = shared_zone_test_context.dummy_vinyldns_client
ok_zone = shared_zone_test_context.ok_zone
dummy_zone = shared_zone_test_context.dummy_zone
dummy_zone_name = ... | Python | nomic_cornstack_python_v1 |
comment hello.py
comment Written by Dave Musicant
comment This program produces a traditional programmer's greeting. | # hello.py
# Written by Dave Musicant
# This program produces a traditional programmer's greeting.
| Python | zaydzuhri_stack_edu_python |
function saveToFile fileName
begin
set outfile = open fileName string w
set chunkInfoKeys = keys gChunkMap
sort chunkInfoKeys
for chunkInfo in chunkInfoKeys
begin
set c = gChunkMap at chunkInfo
write outfile call printChunkInfo
write outfile string
end
end function | def saveToFile(fileName):
outfile = open (fileName, "w")
chunkInfoKeys = gChunkMap.keys()
chunkInfoKeys.sort()
for chunkInfo in chunkInfoKeys:
c = gChunkMap[chunkInfo]
outfile.write(c.printChunkInfo())
outfile.write("\n"); | Python | nomic_cornstack_python_v1 |
comment 01.10 Input
set navn = input string Oppgi navn:
print navn | # 01.10 Input
navn = input("Oppgi navn: ")
print (navn)
| Python | zaydzuhri_stack_edu_python |
from django.db import models
class Item extends Model
begin
set id = call AutoField primary_key=true
set name = call CharField max_length=25
set description = call TextField max_length=250
set amount = call IntegerField
set price = call FloatField
class Meta
begin
set verbose_name = string Item
set verbose_name_plural ... | from django.db import models
class Item(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length = 25)
description = models.TextField(max_length=250)
amount = models.IntegerField()
price = models.FloatField()
class Meta:
verbose_name = 'Item'
v... | Python | zaydzuhri_stack_edu_python |
function where self **overrides
begin
set route_data = copy route
update route_data overrides
return call __class__ keyword route_data
end function | def where(self, **overrides):
route_data = self.route.copy()
route_data.update(overrides)
return self.__class__(**route_data) | Python | nomic_cornstack_python_v1 |
import pygame
from constant import *
from game_level1 import GameLevel1
from game_level2 import GameLevel2
from game_level3 import GameLevel3
class Button
begin
function __init__ self rect text=string default_color=grey hovered_color=light_yellow
begin
comment Rect(left, top, width, height)
set rect = call Rect rect
s... | import pygame
from constant import *
from game_level1 import GameLevel1
from game_level2 import GameLevel2
from game_level3 import GameLevel3
class Button:
def __init__(self, rect, text="", default_color=grey, hovered_color=light_yellow):
self.rect = pygame.Rect(rect) # Rect(left, top, width, height)
... | Python | zaydzuhri_stack_edu_python |
function Spherical2Cart self r t p
begin
set x = r * sin t * cos p
set y = r * sin t * sin p
set z = r * cos t
return tuple x y z
end function | def Spherical2Cart(self, r, t, p):
x = r*np.sin(t)*np.cos(p)
y = r*np.sin(t)*np.sin(p)
z = r*np.cos(t)
return (x, y, z) | Python | nomic_cornstack_python_v1 |
class Solution
begin
function transpose self A
begin
set res = list
for col in range length A at 0
begin
set temp = list
for row in range length A
begin
append temp A at row at col
end
append res temp
end
return res
end function
end class | class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
res = []
for col in range(len(A[0])):
temp = []
for row in range(len(A)):
temp.append(A[row][col])
res.append(temp)
return res
| Python | zaydzuhri_stack_edu_python |
function set_value self ijk value
begin
return call StringsDataSet1D_set_value self ijk value
end function | def set_value(self, ijk, value):
return _RMF_HDF5.StringsDataSet1D_set_value(self, ijk, value) | Python | nomic_cornstack_python_v1 |
function generate_csv
begin
set soup = call BeautifulSoup text string html.parser
set mydivs = find all soup string div class_=list string info string description at slice 1 : :
set name_regex = compile string >(.*?)</a>
set season_regex = compile string \* [Ss]eason (\d):.*<(.*)>
set characters = dictionary
for div ... | def generate_csv():
soup = BeautifulSoup(r.get('http://imdb.com/list/ls076752033/').text, "html.parser")
mydivs = soup.find_all("div", class_=["info", "description"])[1:]
name_regex = re.compile(r">(.*?)</a>")
season_regex = re.compile(r"\* [Ss]eason (\d):.*<(.*)>")
characters = dict()
for ... | Python | nomic_cornstack_python_v1 |
function tick self
begin
debug string %s.tick() % __name__
call validate_policy_configuration
comment reset
if status != RUNNING
begin
debug string %s.tick(): re-initialising % __name__
for child in children
begin
comment reset the children, this ensures old SUCCESS/FAILURE status flags
comment don't break the synchron... | def tick(self) -> typing.Iterator[behaviour.Behaviour]:
self.logger.debug("%s.tick()" % self.__class__.__name__)
self.validate_policy_configuration()
# reset
if self.status != common.Status.RUNNING:
self.logger.debug("%s.tick(): re-initialising" % self.__class__.__name__)
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
import os
set n = length list directory string input
comment print(n)
comment Load image and keep a copy
set input_address = string input\Image{}.PNG
for I in range 1 n + 1
begin
set image = call imread format input_address I
set orig_image = copy image
comment cv2.imshow('Original Image',... | import numpy as np
import cv2
import os
n=len(os.listdir("input"))
#print(n)
# Load image and keep a copy
input_address="input\Image{}.PNG"
for I in range(1,n+1):
image = cv2.imread(input_address.format(I))
orig_image = image.copy()
# cv2.imshow('Original Image', orig_image)
# cv2.waitKey(0)
# Grayscale and bina... | Python | zaydzuhri_stack_edu_python |
if y % 400 == 0
begin
print string sale vared shode kabise ast
end
else
if y % 4 == 0
begin
if y % 100 != 0
begin
print string sale vared shode kabise ast
remove listdays 28
insert listdays 1 29
end
print listdays
set result1 = 0
for i in listdays at slice : m - 1 :
begin
set result1 = result1 + i
end
print result1
p... | if y%400==0 :
print('sale vared shode kabise ast')
elif y%4==0 :
if y%100!=0 :
print('sale vared shode kabise ast')
listdays.remove(28)
listdays.insert(1,29)
print(listdays)
result1=0
for i in listdays[:m-1]:
result1=result1+i
print(result1)
pri... | Python | zaydzuhri_stack_edu_python |
import requests
comment r1 = requests.get('http://httpbin.org/get')
comment r2 = requests.post('http://httpbin.org/post', data={'key': 'value'})
comment r3 = requests.put('http://httpbin.org/put')
comment r3 = requests.delete('http://httpbin.org/delete')
comment r4 = requests.head('http://httpbin.org/get')
comment r5 =... | import requests
# r1 = requests.get('http://httpbin.org/get')
# r2 = requests.post('http://httpbin.org/post', data={'key': 'value'})
# r3 = requests.put('http://httpbin.org/put')
# r3 = requests.delete('http://httpbin.org/delete')
# r4 = requests.head('http://httpbin.org/get')
# r5 = requests.options('http://httpbin.... | Python | zaydzuhri_stack_edu_python |
function test_post_query self
begin
pass
end function | def test_post_query(self):
pass | Python | nomic_cornstack_python_v1 |
function calculate_expression
begin
comment Coordinate of the fixed point P
set P_x = 3
set P_y = 4
comment Calculate the hypotenuse
comment sqrt(x^2 + y^2)
set hypotenuse = P_x ^ 2 + P_y ^ 2 ^ 0.5
comment Calculate sin(alpha) and cos(alpha)
comment y / hypotenuse
set sin_alpha = P_y / hypotenuse
comment x / hypotenuse... | def calculate_expression():
# Coordinate of the fixed point P
P_x = 3
P_y = 4
# Calculate the hypotenuse
hypotenuse = (P_x**2 + P_y**2) ** 0.5 # sqrt(x^2 + y^2)
# Calculate sin(alpha) and cos(alpha)
sin_alpha = P_y / hypotenuse # y / hypotenuse
cos_alpha = P_x / hypotenuse #... | Python | dbands_pythonMath |
function load self name config
begin
if not is directory path name
begin
raise call Misconfigured format string {} directory not found. name
end
set cls = call compiler pop config string compiler none name
return call cls name config
end function | def load(self, name, config):
if not os.path.isdir(name):
raise Misconfigured('{} directory not found.'.format(name))
cls = self.compiler(config.pop('compiler', None), name)
return cls(name, config) | Python | nomic_cornstack_python_v1 |
function SetActiveObject self op mode
begin
Ellipsis
end function | def SetActiveObject(self, op: BaseObject, mode: int) -> None:
... | Python | nomic_cornstack_python_v1 |
function _create_template self name
begin
set url = string %s/%s % tuple _base_url call url_escape name
debug string Making HTTP GET request to %s url
set response = call fetch url
set data = loads body ensure_ascii=false
return call Template data at string template name=name loader=self
end function | def _create_template(self, name):
url = '%s/%s' % (self._base_url, escape.url_escape(name))
LOGGER.debug('Making HTTP GET request to %s', url)
response = self._http_client.fetch(url)
data = json.loads(response.body, ensure_ascii=False)
return template.Template(data['template'], n... | Python | nomic_cornstack_python_v1 |
function handle_exception error
begin
set payload = dict string error name
if description
begin
set payload at string message = description
end
set response = call jsonify payload
set status_code = code
return response
end function | def handle_exception(error):
payload = {'error': error.name}
if error.description:
payload['message'] = error.description
response = jsonify(payload)
response.status_code = error.code
return response | Python | nomic_cornstack_python_v1 |
function _search_for_message self amqp_msg check_unit ssl port amqp_msg_counter
begin
for i in range 100
begin
set amqp_msg_rcvd = call _retry_get_amqp_message check_unit ssl=ssl port=port
if amqp_msg == amqp_msg_rcvd
begin
info format string Message {} received OK. amqp_msg_counter
break
end
else
begin
info format str... | def _search_for_message(self, amqp_msg, check_unit, ssl, port,
amqp_msg_counter):
for i in range(100):
amqp_msg_rcvd = self._retry_get_amqp_message(
check_unit,
ssl=ssl,
port=port)
if amqp_msg == amqp_msg_rcvd:
... | Python | nomic_cornstack_python_v1 |
function find_serial_port
begin
comment Open File port.txt
with open string port.txt string w as f
begin
comment Generate Port Numbers
for port_num in range 1 255
begin
try
begin
comment Test for serial port
call Serial string COM + string port_num
comment Write port number to file
write f string COM + string port_num
... | def find_serial_port():
with open('port.txt', 'w') as f: # Open File port.txt
for port_num in range(1, 255): # Generate Port Numbers
try:
# Test for serial port
serial.Serial(("COM" + str(port_num)))
# Write port number ... | Python | nomic_cornstack_python_v1 |
function build_embedding_matrix embedding_dim glove vocabulary
begin
set embedding_matrix = zeros tuple length vocabulary embedding_dim
set text_indexer_dict = dictionary
for tuple i word in enumerate vocabulary
begin
try
begin
set embedding_matrix at i = glove at word
end
except KeyError
begin
set embedding_matrix at ... | def build_embedding_matrix(embedding_dim, glove, vocabulary):
embedding_matrix = np.zeros((len(vocabulary), embedding_dim))
text_indexer_dict = dict()
for i, word in enumerate(vocabulary):
try:
embedding_matrix[i] = glove[word]
except KeyError:
embedding_matrix[i] = n... | Python | nomic_cornstack_python_v1 |
function get_distance_correlation implementation=string auto
begin
if implementation == string dcor
begin
debug string Using dcor implementation of dcorr
from dcor import distance_correlation as dcorr
return tuple dcorr string dcor
end
else
if implementation == string frites
begin
debug string Using home-made implement... | def get_distance_correlation(implementation='auto'):
if implementation == 'dcor':
logger.debug('Using dcor implementation of dcorr')
from dcor import distance_correlation as dcorr
return dcorr, 'dcor'
elif implementation == 'frites':
logger.debug('Using home-made implementation o... | Python | nomic_cornstack_python_v1 |
import pygame
from pygame import *
comment ширина окна
set WIN_WIDTH = 800
comment высота окна
set WIN_HEIGHT = 640
comment поместим высоту и ширину в один объект
set DISPLAY = tuple WIN_WIDTH WIN_HEIGHT
comment цвет заднего фона
set BLOCK_COLOR = call Color string #FF6262
set TOWER_COLOR = call Color string #000000
se... | import pygame
from pygame import *
WIN_WIDTH = 800 #ширина окна
WIN_HEIGHT = 640 #высота окна
DISPLAY = (WIN_WIDTH, WIN_HEIGHT) #поместим высоту и ширину в один объект
#цвет заднего фона
BLOCK_COLOR = Color("#FF6262")
TOWER_COLOR = Color("#000000")
TRIANGLE_COLOR = Color... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function distanceBetweenBusStops self distance start destination
begin
set all_dist = sum distance
set tmp_dis = sum distance at slice min start destination : max start destination :
return min tmp_dis all_dist - tmp_dis
end function
end class
set a = call Solution
print call distanceBetweenBusStop... | class Solution:
def distanceBetweenBusStops(self, distance, start: int, destination: int) -> int:
all_dist = sum(distance)
tmp_dis = sum(distance[min(start, destination):max(start,destination)])
return min(tmp_dis, all_dist-tmp_dis)
a = Solution()
print(a.distanceBetweenBusStops(distance = ... | Python | zaydzuhri_stack_edu_python |
import math
set c = 0
set tuple l r = map int split input
for j in range l r + 1
begin
set s = square root j
set x = s - floor s
if x == 0
begin
set c = c + 1
end
end
print c | import math
c=0
l,r=map(int,input().split( ))
for j in range(l,r+1):
s=math.sqrt(j)
x=s - math.floor(s)
if x==0:
c=c+1
print(c)
| Python | zaydzuhri_stack_edu_python |
import csv
import os.path
import re
from key import *
from util import *
set simple_keymap = dict string C call MajorKey 0 ; string C# call MajorKey 1 ; string Db call MajorKey 1 ; string D call MajorKey 2 ; string D# call MajorKey 3 ; string Eb call MajorKey 3 ; string E call MajorKey 4 ; string F call MajorKey 5 ; st... | import csv
import os.path
import re
from key import *
from util import *
simple_keymap = {'C': MajorKey(0), 'C#': MajorKey(1), 'Db': MajorKey(1),
'D': MajorKey(2), 'D#': MajorKey(3), 'Eb': MajorKey(3),
'E': MajorKey(4), 'F': MajorKey(5), 'F#': MajorKey(6),
'Gb': Majo... | Python | zaydzuhri_stack_edu_python |
function temperatures self
begin
return _temperatures
end function | def temperatures(self) -> Optional[List[Real]]:
return self._temperatures | Python | nomic_cornstack_python_v1 |
function shared_link_view cls val
begin
return call cls string shared_link_view val
end function | def shared_link_view(cls, val):
return cls('shared_link_view', val) | Python | nomic_cornstack_python_v1 |
function copy self
begin
return call Gauss1D lpeak peak flux fwhm cont err_lpeak err_peak err_flux err_fwhm chisq dof
end function | def copy(self):
return Gauss1D(self.lpeak, self.peak, self.flux, self.fwhm,
self.cont, self.err_lpeak, self.err_peak,
self.err_flux, self.err_fwhm, self.chisq, self.dof) | Python | nomic_cornstack_python_v1 |
function _do_imports components
begin
set done = dict
for name in components
begin
if name in done
begin
continue
end
set r = call _do_import name
if r is false
begin
return false
end
comment Return all the members of an object in a list of (name, value) pairs sorted by name.
set members = dictionary get members modul... | def _do_imports (components):
done = {}
for name in components:
if name in done: continue
r = _do_import(name)
if r is False:
return False
members = dict(inspect.getmembers(sys.modules[r])) #Return all the members of an object in a list of (name, value) pairs sorted... | Python | nomic_cornstack_python_v1 |
function simple_get url
begin
try
begin
with call closing get url stream=true as resp
begin
if call is_good_response resp
begin
return content
end
else
begin
return none
end
end
end
except RequestException as e
begin
call log_error format string Error during requests to {0} : {1} url string e
return none
end
end functi... | def simple_get(url):
try:
with closing(get(url, stream = True)) as resp:
if is_good_response(resp):
return resp.content
else:
return None
except RequestException as e:
log_error('Error during requests to {0} : {1}'.format(url, str... | Python | nomic_cornstack_python_v1 |
comment -*- coding=utf-8 -*-
set __author__ = string Rocky
import urllib2 , time , datetime
from lxml import etree
import pymongo
import sqlite3 , time , requests
class getProxy
begin
function __init__ self
begin
set user_agent = string Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
set header = dict s... | # -*- coding=utf-8 -*-
__author__ = 'Rocky'
import urllib2, time, datetime
from lxml import etree
import pymongo
import sqlite3,time,requests
class getProxy():
def __init__(self):
self.user_agent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"
self.header = {"User-Agent": self.... | Python | zaydzuhri_stack_edu_python |
function add_sentence self sentence
begin
string Parameters ---------- sentence : etree.Element etree representation of a sentence (syntax tree with coreference annotation)
set sent_root_id = attrib at call add_ns string id
comment add edge from document root to sentence root
call add_edge root sent_root_id edge_type=d... | def add_sentence(self, sentence):
"""
Parameters
----------
sentence : etree.Element
etree representation of a sentence
(syntax tree with coreference annotation)
"""
sent_root_id = sentence.attrib[add_ns('id')]
# add edge from document root... | Python | jtatman_500k |
function setParameter self key value
begin
set _parameters at key = value
call setModified
call debugPrint string datacube.setParameter with datacube call name string key= key string and value= value
notify self string parameters _parameters
end function | def setParameter(self, key, value):
self._parameters[key] = value
self.setModified()
self.debugPrint('datacube.setParameter with datacube ',
self.name(), ' key=', key, ' and value=', value)
self.notify("parameters", self._parameters) | Python | nomic_cornstack_python_v1 |
function get_daily_history symbol start_date end_date
begin
return call DataReader call get_yticker symbol string yahoo start_date end_date
end function | def get_daily_history(symbol, start_date, end_date):
return DataReader(get_yticker(symbol), 'yahoo', start_date, end_date) | Python | nomic_cornstack_python_v1 |
function convert inputFile outputFile
begin
set c = call WriterDocument
open inputFile
call refresh
call saveAs outputFile
close c
end function | def convert( inputFile, outputFile ):
c = WriterDocument()
c.open( inputFile )
c.refresh()
c.saveAs( outputFile )
c.close() | Python | nomic_cornstack_python_v1 |
from random import *
for i in range 8
begin
print random integer 1 100
end | from random import *
for i in range(8):
print(random.randint(1,100))
| Python | zaydzuhri_stack_edu_python |
function update_positions self
begin
set positions = zeros tuple length threads shape at 0
for i in range length threads
begin
set positions at i = call get_position_mostrecent
end
end function | def update_positions(self):
self.positions = np.zeros((len(self.threads), self.threads[0].get_position_mostrecent().shape[0]))
for i in range(len(self.threads)):
self.positions[i] = self.threads[i].get_position_mostrecent() | Python | nomic_cornstack_python_v1 |
function __init__ self parent=none
begin
call __init__ parent
call setupUi self
call setModal true
set __mw = parent
set __model = call OpenSearchEngineModel call openSearchManager self
call setModel __model
call resizeSection 0 200
call setStretchLastSection true
call hide
call setDefaultSectionSize 1.2 * call height
... | def __init__(self, parent=None):
super(OpenSearchDialog, self).__init__(parent)
self.setupUi(self)
self.setModal(True)
self.__mw = parent
self.__model = OpenSearchEngineModel(
self.__mw.openSearchManager(), self)
self.enginesTable.se... | Python | nomic_cornstack_python_v1 |
function project_overview project_name
begin
if not call db_find_project project_name
begin
call abort 404
end
set _project = first call objects project_name=project_name
comment _forks = ProjectFork.objects(project_name=project_name, file_list__ne=[], total_changed_line_number__ne=0)
set _forks = call objects project_... | def project_overview(project_name):
if not db_find_project(project_name):
abort(404)
_project = Project.objects(project_name=project_name).first()
# _forks = ProjectFork.objects(project_name=project_name, file_list__ne=[], total_changed_line_number__ne=0)
_forks = ProjectFork.objects(project_na... | Python | nomic_cornstack_python_v1 |
import logging
import asyncio
from datetime import datetime , timedelta
from aiohttp import web
async function index request
begin
return call FileResponse path=string public/index.html
end function
async function database request
begin
return call FileResponse path=string database.db
end function
function floor_date d... | import logging
import asyncio
from datetime import datetime, timedelta
from aiohttp import web
async def index(request):
return web.FileResponse(path='public/index.html')
async def database(request):
return web.FileResponse(path='database.db')
def floor_date(date, resolution):
date = date.replace(micr... | Python | zaydzuhri_stack_edu_python |
for i in range t
begin
set tuple n m = map int split input
set gcd = 1
comment +1 to check if both no. are same
for j in range 2 min n m + 1
begin
if n % j == 0 and m % j == 0
begin
set gcd = j
end
end
print gcd
end | for i in range(t):
n , m = map(int,(input().split()))
gcd = 1
for j in range(2,min(n,m)+1): # +1 to check if both no. are same
if n % j == 0 and m % j == 0:
gcd = j
print(gcd)
| Python | zaydzuhri_stack_edu_python |
function invalidate_all self
begin
for f in canvas_observers
begin
f dist 0 0 0 0
end
end function | def invalidate_all(self):
for f in self.canvas_observers:
f(0, 0, 0, 0) | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup
import lxml
import csv
set pages = list
set headers = dict string User-Agent string Ricardo ; string From string ricardogleitao@hotmail.com
for i in range 1 5
begin
set url = string https://web.archive.org/web/20121010201041/http://www.nga.gov/collection/anZ + string i + s... | import requests
from bs4 import BeautifulSoup
import lxml
import csv
pages = []
headers = {
'User-Agent' : 'Ricardo',
'From' : 'ricardogleitao@hotmail.com'
}
for i in range(1, 5):
url = 'https://web.archive.org/web/20121010201041/http://www.nga.gov/collection/anZ' + str(i) + '.htm'
pag... | Python | zaydzuhri_stack_edu_python |
string http://math.ucr.edu/home/baez/games/games_11.html http://en.wikipedia.org/wiki/St._Petersburg_paradox
import math
for n in range 10
begin
set i = n + 1
set win = power 2 n
set prob = 1 / power 2 i
set exp = win * prob
end | """
http://math.ucr.edu/home/baez/games/games_11.html
http://en.wikipedia.org/wiki/St._Petersburg_paradox
"""
import math
for n in range(10):
i = n + 1
win = math.pow(2, n)
prob = 1 / math.pow(2, i)
exp = win * prob | Python | zaydzuhri_stack_edu_python |
function write_stats self
begin
string Write check statistic info.
call writeln
call writeln call _ string Statistics:
if downloaded_bytes is not none
begin
call writeln call _ string Downloaded: %s. % call strsize downloaded_bytes
end
if number > 0
begin
call writeln call _ string Content types: %(image)d image, %(tex... | def write_stats (self):
"""Write check statistic info."""
self.writeln()
self.writeln(_("Statistics:"))
if self.stats.downloaded_bytes is not None:
self.writeln(_("Downloaded: %s.") % strformat.strsize(self.stats.downloaded_bytes))
if self.stats.number > 0:
... | Python | jtatman_500k |
function test_reading_empty_strings_for_different_types self
begin
call prepare
execute session string CREATE TABLE test_many_empty_strings ( a text, b text, c text, d text, o uuid, i1 bigint, i2 bigint, t text, i3 bigint, PRIMARY KEY ((a, b, c, d), o) )
set tempfile = call get_temp_file
with open name string w as f
be... | def test_reading_empty_strings_for_different_types(self):
self.prepare()
self.session.execute("""
CREATE TABLE test_many_empty_strings (
a text,
b text,
c text,
d text,
o uuid,
i1 bigint,
... | Python | nomic_cornstack_python_v1 |
function configure path script quiet
begin
set configured = false
comment For now only tested/working with Ubuntu
if call id in list string debian string ubuntu
begin
set conf = join path path script
if exists path conf
begin
set interp = call interpreter script
if not quiet
begin
set msg = format string Configuring us... | def configure(path, script, quiet):
configured = False
# For now only tested/working with Ubuntu
if distro.id() in ["debian", "ubuntu"]:
conf = os.path.join(path, script)
if os.path.exists(conf):
interp = interpreter(script)
if not quiet:
msg = "\nC... | Python | nomic_cornstack_python_v1 |
import numpy as np
import random
from queue import PriorityQueue
from queue import Queue
comment Stochastic Policy Gradients ###
comment hyperparameters
comment number of hidden layer neurons
set H = 32
comment every how many episodes to do a param update?
set batch_size = 10
set learning_rate = 0.01
comment discount f... | import numpy as np
import random
from queue import PriorityQueue
from queue import Queue
### Stochastic Policy Gradients ###
# hyperparameters
H = 32 # number of hidden layer neurons
batch_size = 10 # every how many episodes to do a param update?
learning_rate = 1e-2
gamma = 0.99 # discount factor for reward
decay_ra... | Python | zaydzuhri_stack_edu_python |
function index request
begin
set response = call MessagingResponse
set message = string
try
begin
set parsed_data = call lookup_contact request
end
except InputError as e
begin
set message = string message
call message message
return response
end
except DoesNotExist as contacexp
begin
call message contact_not_found
re... | def index(request):
response = MessagingResponse()
message = ""
try:
parsed_data = lookup_contact(request)
except InputError as e:
message = str(e.message)
response.message(message)
return response
except Contact.DoesNotExist as contacexp:
response.message(contact_not... | Python | nomic_cornstack_python_v1 |
function converttoGig num
begin
set str1 = string
while num > 0
begin
set str1 = string num % 2 + str1
set num = num // 2
end
set str1 = string 0 + str1
set str2 = string
for h in range 0 length str1 - 1
begin
set temp = integer str1 at h ? integer str1 at h + 1
set str2 = str2 + string temp
end
set res = 0
for h in ... | def converttoGig(num):
str1=""
while(num>0):
str1=str(num%2)+str1
num=num//2
str1="0"+str1
str2=""
for h in range(0,len(str1)-1):
temp=int(str1[h]) ^ int(str1[h+1])
str2=str2+str(temp)
res=0
for h in range(len(str2)):
res+=int(str2[h])*pow(2,len(str2)-... | Python | zaydzuhri_stack_edu_python |
function setval filepath key value
begin
set ftype = call filetype filepath
if ftype == string fits
begin
if starts with upper key tuple string META. string META_
begin
set key = replace key string META_ string META.
return call _dm_setval filepath key value
end
else
begin
return call setval filepath key value=value
en... | def setval(filepath, key, value):
ftype = config.filetype(filepath)
if ftype == "fits":
if key.upper().startswith(("META.","META_")):
key = key.replace("META_", "META.")
return _dm_setval(filepath, key, value)
else:
return pyfits.setval(filepath, key, value=va... | Python | nomic_cornstack_python_v1 |
function addNumber x y
begin
print x + y
end function
function minuteNumber x y
begin
print x - y
end function
function multiNumber x y
begin
print x * y
end function
function divideNumber x y
begin
print x / y
end function
call addNumber 100 10
call multiNumber 100 10
call multiNumber 100 10
call divideNumber 100 10 | def addNumber(x,y):
print(x+y)
def minuteNumber(x,y):
print(x-y)
def multiNumber(x,y):
print(x*y)
def divideNumber(x,y):
print(x/y)
addNumber(100,10)
multiNumber(100,10)
multiNumber(100,10)
divideNumber(100,10) | Python | zaydzuhri_stack_edu_python |
string Three modes to open a file: - r -> Read a file - w -> Write to a new file or overwrite an existing file - a -> Append to a file
set vacationPlaces = list string New York string Paris string Mumbai string Rome string London
string myFile = open('file.txt', 'w') myFile.write("How are you") myFile.close() myFile = ... | '''
Three modes to open a file:
- r -> Read a file
- w -> Write to a new file or overwrite an existing file
- a -> Append to a file
'''
vacationPlaces = ['New York', 'Paris', 'Mumbai', 'Rome', 'London']
'''
myFile = open('file.txt', 'w')
myFile.write("How are you")
myFile.close()
myFile = open('file.txt', 'r')
conte... | Python | zaydzuhri_stack_edu_python |
comment functions to handle the GitHub GIST facilities
import zlib
from base64 import urlsafe_b64encode as b64e , urlsafe_b64decode as b64d
function obscure data
begin
return call b64e compress data 9
end function
function unobscure obscured
begin
return call decompress call b64d obscured
end function
import requests
i... | #
# functions to handle the GitHub GIST facilities
#
import zlib
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d
def obscure(data: bytes) -> bytes:
return b64e(zlib.compress(data, 9))
def unobscure(obscured: bytes) -> bytes:
return zlib.decompress(b64d(obscured))
import requests
impor... | Python | zaydzuhri_stack_edu_python |
function inference_parameters self
begin
set params = call ParameterList
if string parameters in directory inference_model
begin
extend params list parameters inference_model
end
extend params list call inference_parameters
return params
end function | def inference_parameters(self):
params = nn.ParameterList()
if 'parameters' in dir(self.inference_model):
params.extend(list(self.inference_model.parameters()))
params.extend(list(self.latent.inference_parameters()))
return params | Python | nomic_cornstack_python_v1 |
comment 2
function funcn1
begin
for i in range length mdlist
begin
print mdlist at i
end
end function
call funcn1
function funcn2
begin
set dayslist = list
for i in range length mdlist
begin
for j in range length mdlist
begin
append dayslist mdlist at j at i
end
print format string Day{} list as: i + 1 dayslist
set da... | #2
def funcn1():
for i in range(len(mdlist)):
print(mdlist[i])
funcn1()
def funcn2():
dayslist=[]
for i in range(len(mdlist)):
for j in range(len(mdlist)):
dayslist.append(mdlist[j][i])
print("Day{} list as:".format(i+1),dayslist)
dayslist=[]
funcn2()
#3
def t... | Python | zaydzuhri_stack_edu_python |
from itertools import combinations_with_replacement
function main
begin
set goal = 7.98
set count = 3
set pool = list 7.98 1.05 7.06 1.25 4.75 3.04 1.52 2.0 1.6
set combos = list call combinations_with_replacement pool count
for c in combos
begin
set add = 0
set multi = 1
for n in c
begin
set add = add + n
set multi = ... | from itertools import combinations_with_replacement
def main():
goal = 7.98
count = 3
pool = [7.98, 1.05, 7.06, 1.25, 4.75, 3.04, 1.52, 2.0, 1.6]
combos = list(combinations_with_replacement(pool, count))
for c in combos:
add = 0
multi = 1
for n in c:
add = add + ... | Python | zaydzuhri_stack_edu_python |
import csv
comment a = [["post1", 4, 2, 1, 3, 6, 0, 0, 0, 0], ["post2", 5, 6, 7, 0, 0, 0, 0, 0, 0], ["post3", 8, 9, 4, 6, 7, 0, 0, 0, 0]]
set all = list
with open string D:\Shared\224\AI.csv encoding=string UTF-8 as rawcsv
begin
set readCSV = reader rawcsv delimiter=string ,
for row in readCSV
begin
append all row
end... | import csv
# a = [["post1", 4, 2, 1, 3, 6, 0, 0, 0, 0], ["post2", 5, 6, 7, 0, 0, 0, 0, 0, 0], ["post3", 8, 9, 4, 6, 7, 0, 0, 0, 0]]
all = []
with open('D:\\Shared\\224\\AI.csv', encoding='UTF-8') as rawcsv:
readCSV = csv.reader(rawcsv, delimiter=',')
for row in readCSV:
all.append(row)
rawcsv.close()
w... | Python | zaydzuhri_stack_edu_python |
function main_target_default_build self specification project
begin
string Return the default build value to use when declaring a main target, which is obtained by using specified value if not empty and parent's default build attribute otherwise. specification: Default build explicitly specified for a main target proje... | def main_target_default_build (self, specification, project):
""" Return the default build value to use when declaring a main target,
which is obtained by using specified value if not empty and parent's
default build attribute otherwise.
specification: Default build explicit... | Python | jtatman_500k |
function find_neighborhood neighbor_lists indices nedges=1
begin
comment Initialize seed list with indices
set neighborhood = list
set seed_list = indices at slice : :
set completed = seed_list at slice : :
comment Propagate nedges away from indices:
for iedge in range nedges
begin
comment Find neighbors of seed... | def find_neighborhood(neighbor_lists, indices, nedges=1):
# Initialize seed list with indices
neighborhood = []
seed_list = indices[:]
completed = seed_list[:]
# Propagate nedges away from indices:
for iedge in range(nedges):
# Find neighbors of seeds:
if seed_list:
... | Python | nomic_cornstack_python_v1 |
string Created on Thu Sep 13 11:02:02 2018 @author: mayur.a
import math
import operator
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
function myreadCSVfile
begin
string Medical dataset parsing
set replacement = dict string HEALTHY 0 ; string MEDICATION 1 ; string SURGERY 2
comment Train D... | """
Created on Thu Sep 13 11:02:02 2018
@author: mayur.a
"""
import math
import operator
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def myreadCSVfile():
'''
Medical dataset parsing
'''
replacement = {
'HEALTHY' : 0,
'MEDICATION' : 1,
... | Python | zaydzuhri_stack_edu_python |
function enable_dropout model
begin
set n = 0
for each_module in call modules
begin
if starts with __name__ string Dropout
begin
set n = n + 1
train each_module
end
end
comment 38
print string Number of layers with dropout enabled : + string n
end function
comment all layers : 219 | def enable_dropout(model):
n = 0
for each_module in model.modules():
if each_module.__class__.__name__.startswith("Dropout"):
n = n + 1
each_module.train()
print("Number of layers with dropout enabled : " + str(n)) # 38
# all layers : 219 | Python | nomic_cornstack_python_v1 |
function read input_file
begin
if __debug__
begin
print string Reading image file: %s % input_file
end
set im = open input_file
set im = call convert string RGB
set tuple width height = size
set pix = load im
return tuple width height pix
end function | def read( input_file ):
if __debug__:
print("Reading image file: %s" % (input_file))
im = Image.open(input_file)
im = im.convert('RGB')
(width, height) = im.size
pix = im.load()
return ( width, height, pix ) | Python | nomic_cornstack_python_v1 |
import os
import csv
import glob
set syllableSQL = open string /home/ubuntu/scripts/load_db/syllable.csv string w
set path = string /home/ubuntu/statistics
for filename in glob glob join path path string fixed_*_syllables.txt
begin
set syllables = open filename string r
set counts = filename at slice : - 14 :
set cou... | import os
import csv
import glob
syllableSQL = open("/home/ubuntu/scripts/load_db/syllable.csv", "w")
path = '/home/ubuntu/statistics'
for filename in glob.glob(os.path.join(path, 'fixed_*_syllables.txt')):
syllables = open(filename, 'r')
counts = filename[:-14]
countFile = counts + "_count.txt"
word... | Python | zaydzuhri_stack_edu_python |
function nullHeuristic state problem=none
begin
return 0
end function | def nullHeuristic(state, problem=None):
return 0 | Python | nomic_cornstack_python_v1 |
from lib import *
from sphere import *
from math import pi , tan
import random
set BLACK = call color 0 0 0
set WHITE = call color 255 255 255
set BG = call color 107 156 245
class Raytracer extends object
begin
function __init__ self width height
begin
set width = width
set height = height
set background_color = BLACK... | from lib import *
from sphere import *
from math import pi, tan
import random
BLACK = color(0, 0, 0)
WHITE = color(255, 255, 255)
BG = color(107,156,245)
class Raytracer(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.background_color = BLACK
self.scene = []... | Python | zaydzuhri_stack_edu_python |
import sys
append path string /Users/quentincurteman/Google Drive File Stream/My Drive/William Jessup/Fall 2018/Operating Systems/CS355
from memory.memmgmt import MemoryManagement
from memory.memmgr import Memory
from process.processx import Process
import threading
import time
function printAll astring process
begin
p... | import sys
sys.path.append('/Users/quentincurteman/Google Drive File Stream/My Drive/William Jessup/Fall 2018/Operating Systems/CS355')
from memory.memmgmt import MemoryManagement
from memory.memmgr import Memory
from process.processx import Process
import threading
import time
def printAll(astring, process):
... | Python | zaydzuhri_stack_edu_python |
function decompose_cov cov dumb=false
begin
if shape at 0 != shape at 1
begin
raise call ValueError string Input covariance matrix must be square!
end
if not dumb
begin
raise call NotImplementedError string Sorry decompose_cov only does dumb at the moment!
end
else
begin
set dim = shape at 0
set diag = call diag cov
se... | def decompose_cov(cov, dumb=False):
if cov.shape[0] != cov.shape[1]:
raise ValueError("Input covariance matrix must be square!")
if not dumb:
raise NotImplementedError("Sorry decompose_cov only does dumb at the moment!")
else:
dim = cov.shape[0]
diag = np.diag(cov)
sq... | Python | nomic_cornstack_python_v1 |
function on_first_registration self
begin
pass
end function | def on_first_registration(self):
pass | Python | nomic_cornstack_python_v1 |
function epoch_time year month date hour=0
begin
set dt = call datetime year month date hour
set epoch = call mktime call timetuple
return integer epoch
end function | def epoch_time(year, month, date, hour=0):
dt = datetime(year, month, date, hour)
epoch = time.mktime(dt.timetuple())
return int(epoch) | Python | nomic_cornstack_python_v1 |
function onpress event
begin
if key == string a
begin
set tuple x y = call rand 2
set color = call jet call rand
append offsets tuple x y
append facecolors color
call draw
end
else
if key == string d
begin
set N = length offsets
if N > 0
begin
set ind = random integer 0 N - 1
pop offsets ind
pop facecolors ind
call dra... | def onpress(event):
if event.key=='a':
x,y = nx.mlab.rand(2)
color = cm.jet(nx.mlab.rand())
offsets.append((x,y))
facecolors.append(color)
fig.canvas.draw()
elif event.key=='d':
N = len(offsets)
if N>0:
ind = random.randint(0,N-1)
o... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function convert self s numRows
begin
string :type s: str :type numRows: int :rtype: str
if numRows == 1
begin
return s
end
comment to control row# movement
set direction = 1
comment indicate which lane to add element
set rowIndex = 0
comment declare a nested list in which each row i... | class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
direction = 1 # to control row# movement
rowIndex = 0 # indicate which lane to add element
result ... | 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.