code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.animation import FuncAnimation
comment Set up the axes, making sure the axis ratio is equal
set fig = figure figsize=tuple 6.5 2.5
set ax = call add_axes list 0 0 1 1 xlim=tuple - 0.... | from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.animation import FuncAnimation
# Set up the axes, making sure the axis ratio is equal
fig = plt.figure(figsize=(6.5, 2.5))
ax = fig.add_axes([0, 0, 1, 1], xlim=(-0.02, 13.02), ylim... | Python | zaydzuhri_stack_edu_python |
function test_default_configuration self fit_dictionary_tabular is_small_preprocess exclude
begin
set fit_dictionary_tabular at string is_small_preprocess = is_small_preprocess
set pipeline = call TabularClassificationPipeline dataset_properties=fit_dictionary_tabular at string dataset_properties exclude=exclude
with c... | def test_default_configuration(self, fit_dictionary_tabular, is_small_preprocess, exclude):
fit_dictionary_tabular['is_small_preprocess'] = is_small_preprocess
pipeline = TabularClassificationPipeline(
dataset_properties=fit_dictionary_tabular['dataset_properties'],
exclude=exc... | Python | nomic_cornstack_python_v1 |
function digsum num power
begin
set val = 0
for el in string num
begin
set val = val + integer el ^ power
end
return val
end function | def digsum(num, power):
val = 0
for el in str(num):
val += int(el) ** power
return val | Python | nomic_cornstack_python_v1 |
function __init__ self name logfile loglevel=string INFO
begin
set rollover = false
if is file path logfile
begin
set rollover = true
end
set logger = call getLogger name
set datefmt = string %b %d %H:%M:%S
set format = call Formatter string [%(asctime)s %(process)d -1 %(name)s %(levelname)s] {- -} %(message)s datefmt
... | def __init__(self,name,logfile,loglevel='INFO'):
rollover = False
if os.path.isfile(logfile):
rollover = True
self.logger = logging.getLogger(name)
datefmt = '%b %d %H:%M:%S'
format = logging.Formatter('[%(asctime)s %(process)d -1 %(name)s %(levelna... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
import pylab
function rtemp a
begin
return 1.0 * 1.0 / a
end function
function mtemp a
begin
return 1.0 * 1.0 / a ^ 2
end function
set t = array range 0.0001 1 0.0001
figure 1
subplot 211
title plt string Radiation Temperature
plot t call rtemp t string bx
y label stri... | import numpy as np
import matplotlib.pyplot as plt
import pylab
def rtemp(a):
return 1.*(1./a)
def mtemp(a):
return 1.*(1./a)**2
t = np.arange(0.0001,1,0.0001)
plt.figure(1)
plt.subplot(211)
plt.title('Radiation Temperature')
plt.plot(t,rtemp(t), 'bx')
plt.ylabel('Temperature')
plt.xscale('log')
plt.subplot(212)... | Python | zaydzuhri_stack_edu_python |
function selection_completed self
begin
set selection = list comprehension call text for item in call selectedItems
close self
end function | def selection_completed(self):
self.selection = [item.text() for item in
self.choices_widget.selectedItems()]
self.close() | Python | nomic_cornstack_python_v1 |
import os
comment declarar variables
set tuple trabajo tiempo = tuple 0.0 0.0
set potencia = 0.0
comment Input
set trabajo = integer argv at 1
set tiempo = integer argv at 2
comment Procesing
set potencia = integer trabajo / tiempo
comment Ouput
print string El trabajo realizado por el motor: trabajo
print string Tiemp... | import os
#declarar variables
trabajo,tiempo=0.0,0.0
potencia=0.0
#Input
trabajo=int(os.sys.argv[1])
tiempo=int(os.sys.argv[2])
#Procesing
potencia=int(trabajo/tiempo)
#Ouput
print("El trabajo realizado por el motor:" , trabajo)
print("Tiempo utilizado por el motor : ", tiempo)
print("Potencia del motor : ", potenci... | Python | zaydzuhri_stack_edu_python |
set n = 100
set sumosq = n * n + 1 * 2 * n + 1 / 6
set sumsq = n * n + 1 / 2 ^ 2 | n = 100
sumosq = (n * (n + 1) * ((2*n) + 1)) / 6
sumsq = ((n * (n + 1) / 2 ) ** 2)
| Python | zaydzuhri_stack_edu_python |
function test_serialize self
begin
call listBatchSubscribe 3 list dict string EMAIL string foo@example.com dict string EMAIL string bar@example.com
call expect string POST string /?method=listBatchSubscribe tuple tuple string id string 3 tuple string batch[0][EMAIL] string foo@example.com tuple string batch[1][EMAIL] s... | def test_serialize(self):
self.service.listBatchSubscribe(3, [{'EMAIL': 'foo@example.com'},
{'EMAIL': 'bar@example.com'}])
self.expect('POST', '/?method=listBatchSubscribe',
(('id', '3'), ('batch[0][EMAIL]', 'foo@example.com'),
... | Python | nomic_cornstack_python_v1 |
set tuple a b c = map int split input
set m = min a b
print min m c | a, b, c = map(int, input().split())
m = min(a, b)
print(min(m, c)) | Python | zaydzuhri_stack_edu_python |
set s = set literal 10 20 30
add s 40
print s
add s 20
set s1 = set literal 40 50 20 20 50
update s s1 range 5
print s
set s2 = copy s
print s2
print pop s2 | s = {10,20,30}
s.add(40)
print(s)
s.add(20)
s1 = {40,50,20,20,50}
s.update(s1,range(5))
print(s)
s2 = s.copy()
print(s2)
print(s2.pop())
| Python | zaydzuhri_stack_edu_python |
function remove_duplicates nums
begin
comment A list for storing final output
set new_list = list
comment Looping over the elements
for num in nums
begin
comment If num is not in new_list, then add it
if num not in new_list
begin
append new_list num
end
end
return new_list
end function
comment Main code
set input_list... | def remove_duplicates(nums):
# A list for storing final output
new_list = []
# Looping over the elements
for num in nums:
# If num is not in new_list, then add it
if num not in new_list:
new_list.append(num)
return new_list
# Main code
input_list = [1,... | Python | jtatman_500k |
comment lwtree: lightweight trees
comment AUTHOR: Michael Reimann <michael.reimann@epfl.ch>
comment AUTHOR: Sirio Bolaños Puchet <sirio.bolanospuchet@epfl.ch>
comment LAST MODIFIED: 2021-05-11
import numpy
import brotli
import tarfile
import collections
comment tqdm is optional dependency
try
begin
import tqdm
set iter... | # lwtree: lightweight trees
# AUTHOR: Michael Reimann <michael.reimann@epfl.ch>
# AUTHOR: Sirio Bolaños Puchet <sirio.bolanospuchet@epfl.ch>
# LAST MODIFIED: 2021-05-11
import numpy
import brotli
import tarfile
import collections
# tqdm is optional dependency
try:
import tqdm
iter_status_fun = lambda t, x, **... | Python | zaydzuhri_stack_edu_python |
function _get_index_imm asm_str
begin
if not starts with asm_str string [
begin
raise call SyntaxError string Missing '[' character at start of index notation
end
if not ends with asm_str string ]
begin
raise call SyntaxError string Missing ']' character at end of index notation
end
return call _get_imm strip asm_str a... | def _get_index_imm(asm_str):
if not asm_str.startswith('['):
raise SyntaxError('Missing \'[\' character at start of index notation')
if not asm_str.endswith(']'):
raise SyntaxError('Missing \']\' character at end of index notation')
return _get_imm(asm_str[1:-1].strip()) | Python | nomic_cornstack_python_v1 |
function detect_fastq_annotations fastq_file
begin
string detects annotations preesent in a FASTQ file by examining the first read
set annotations = set
set queryread = first tz call read_fastq fastq_file
for tuple k v in items BARCODEINFO
begin
if readprefix in queryread
begin
add annotations k
end
end
return annotati... | def detect_fastq_annotations(fastq_file):
"""
detects annotations preesent in a FASTQ file by examining the first read
"""
annotations = set()
queryread = tz.first(read_fastq(fastq_file))
for k, v in BARCODEINFO.items():
if v.readprefix in queryread:
annotations.add(k)
re... | Python | jtatman_500k |
import unittest
from fields import rectangle , triangle , trapezoid
class FieldsTestCase extends TestCase
begin
function setUp self
begin
set a = 2
set b = 10
set h = 2
end function
function test_rectangle_with_correct_values self
begin
set result = call rectangle a b
assert equal result 20
end function
function test_r... | import unittest
from fields import rectangle, triangle, trapezoid
class FieldsTestCase(unittest.TestCase):
def setUp(self):
self.a = 2
self.b = 10
self.h = 2
def test_rectangle_with_correct_values(self):
result = rectangle(self.a, self.b)
self.assertEqual(result, 20)
def test_rectangle_with... | Python | zaydzuhri_stack_edu_python |
import pygame.sprite
set tuple WIDTH HEIGHT = tuple 5 500
class Net extends Sprite
begin
function __init__ self fore_color
begin
call __init__
set image = call Surface list WIDTH HEIGHT
call rect image fore_color list 0 0 WIDTH HEIGHT
set rect = call get_rect
set x = 349
end function
end class | import pygame.sprite
WIDTH, HEIGHT = 5, 500
class Net(pygame.sprite.Sprite):
def __init__(self, fore_color):
super().__init__()
self.image = pygame.Surface([WIDTH, HEIGHT])
pygame.draw.rect(self.image, fore_color, [0, 0, WIDTH, HEIGHT])
self.rect = self.image.get_rect()
s... | Python | zaydzuhri_stack_edu_python |
function load_json filename
begin
string Load JSON data from a file and return as dict or list. Defaults to returning empty dict if file is not found.
try
begin
with open filename encoding=string utf-8 as fdesc
begin
return loads read fdesc
end
end
except FileNotFoundError
begin
comment This is not a fatal error
debug ... | def load_json(filename: str) -> Union[List, Dict]:
"""Load JSON data from a file and return as dict or list.
Defaults to returning empty dict if file is not found.
"""
try:
with open(filename, encoding='utf-8') as fdesc:
return json.loads(fdesc.read())
except FileNotFoundError:
... | Python | jtatman_500k |
function RAVENCLAW_MAX_DAMAGE_LVL_2
begin
return 30
end function | def RAVENCLAW_MAX_DAMAGE_LVL_2() -> int:
return 30 | Python | nomic_cornstack_python_v1 |
from collections import Counter
set n = integer input
set x = list map int split input
set a = list
set b = list
for i in range n
begin
append a i + 1 + x at i
append b i + 1 - x at i
end
set ans = 0
set tuple a b = tuple counter a counter b
for i in range min a max b + 1
begin
set ans = ans + a at i * b at i
end
pri... | from collections import Counter
n = int(input())
x = list(map(int, input().split()))
a = []
b = []
for i in range(n):
a.append(i+1+x[i])
b.append(i+1-x[i])
ans = 0
a, b = Counter(a), Counter(b)
for i in range(min(a), max(b)+1):
ans += a[i]*b[i]
print(ans) | Python | zaydzuhri_stack_edu_python |
function update_gauge self
begin
set gauge_metrics = call _fetch_gauge_metrics_and_clear
info string update_gauge. gauge_metrics = %s call build_metrics_gauge_data gauge_metrics
end function | def update_gauge(self):
gauge_metrics = self._fetch_gauge_metrics_and_clear()
self._logger.info('update_gauge. gauge_metrics = %s',
build_metrics_gauge_data(gauge_metrics)) | Python | nomic_cornstack_python_v1 |
function populate_looper looper node f_locals
begin
if scope_member
begin
call set_slot looper f_locals
end
if identifier
begin
set f_locals at identifier = looper
end
append _cdata tuple node f_locals
end function | def populate_looper(looper, node, f_locals):
if node.scope_member:
node.scope_member.set_slot(looper, f_locals)
if node.identifier:
f_locals[node.identifier] = looper
looper._cdata.append((node, f_locals)) | Python | nomic_cornstack_python_v1 |
function alert self
begin
call request string lights/%s/state % id string PUT dict string alert string select
end function | def alert(self):
self.bridge.request("lights/%s/state" % self.id, 'PUT', {"alert": "select"}) | Python | nomic_cornstack_python_v1 |
import pandas as pd
comment a data frame with the customer's purchase history
set purchases = call DataFrame dict string item list string Lipstick string Wine Glasses string Cap ; string price list 10 20 15 ; string gender list 0 1 0
comment number of customers who bought each item
set item_counts = count group by purc... | import pandas as pd
# a data frame with the customer's purchase history
purchases = pd.DataFrame({
'item' : ["Lipstick", "Wine Glasses", "Cap"],
'price': [10, 20, 15],
'gender': [0, 1, 0]
})
# number of customers who bought each item
item_counts = purchases.groupby('item').count()
# probability of each i... | Python | flytech_python_25k |
function first_word str
begin
return split str string at 0
end function
function link_to_slug string
begin
if string at slice : 4 : == string http or string at slice : 5 : == string https
begin
return split string string / 3 at 3
end
else
begin
return split string string / 1 at 1
end
end function | def first_word(str):
return str.split(' ')[0]
def link_to_slug(string):
if string[:4]=='http' or string[:5]=='https':
return (string.split('/',3))[3]
else:
return (string.split('/',1))[1] | Python | zaydzuhri_stack_edu_python |
class serialize
begin
function __init__ self dictionary
begin
set __data = list
for key in list dictionary
begin
append __data array key dictionary at key
end
end function
function to_file self filename
begin
set file = open filename string w+
set string = string <?php
set string = string + string return + string self... | class serialize:
def __init__(self, dictionary):
self.__data = []
for key in list(dictionary):
self.__data.append(array(key, dictionary[key]))
def to_file(self, filename):
file = open(filename, 'w+')
string = '<?php\n\n'
string += 'return ' + str(self) + ';'
... | Python | zaydzuhri_stack_edu_python |
class atleta
begin
function __init__ self nome cognome visita squadra
begin
set nome = nome
set cognome = cognome
set visita = visita
set squadra = squadra
end function
function effettua_visita self
begin
set visita = true
end function
function info self
begin
print string L'atleta si chiama nome cognome string Visita ... | class atleta():
def __init__(self, nome, cognome, visita, squadra):
self.nome = nome
self.cognome = cognome
self.visita = visita
self.squadra = squadra
def effettua_visita(self) :
self.visita = True
def info(self):
print("L'atleta si chiama", self.nome, self.cognome... | Python | zaydzuhri_stack_edu_python |
string Exercise 36: Designing and Debugging Now that you know if-statements, I'm going to give you some rules for for-loops and while-loops that will keep you out of trouble. I'm also going to give you some tips on debugging so that you can figure out problems with your program. Finally, you will design a little game s... | """
Exercise 36: Designing and Debugging
Now that you know if-statements, I'm going to give you some rules for
for-loops and while-loops that will keep you out of trouble. I'm also
going to give you some tips on debugging so that you can figure out
problems with your program. Finally, you will design a ... | Python | zaydzuhri_stack_edu_python |
import re
function remove_punctuation string
begin
comment Define a regular expression pattern to match punctuation marks
set punctuation_pattern = string [!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]
comment Replace punctuation marks with a space
set string = sub punctuation_pattern string string
comment Remove consecutive sp... | import re
def remove_punctuation(string):
# Define a regular expression pattern to match punctuation marks
punctuation_pattern = r'[!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]'
# Replace punctuation marks with a space
string = re.sub(punctuation_pattern, ' ', string)
# Remove consecutive spaces
... | Python | jtatman_500k |
function frame2videofunc fun
begin
function func video
begin
comment Check if video is channeled
if ndim == 3
begin
comment video.shape = (T, row, col)
return array list comprehension call fun frame for frame in video
end
else
if ndim == 4
begin
comment video.shape = (numchannels, T, row, col)
comment Reshape to (T, nu... | def frame2videofunc(fun):
def func(video):
# Check if video is channeled
if video.ndim == 3:
# video.shape = (T, row, col)
return np.array([fun(frame) for frame in video])
elif video.ndim == 4:
# video.shape = (numchannels, T, row, col)
# Resh... | Python | nomic_cornstack_python_v1 |
function powers_of_two n
begin
if n == 0
begin
return list 1
end
else
begin
set prev_powers = call powers_of_two n - 1
set current_power = prev_powers at - 1 * 2
return prev_powers + list current_power
end
end function
set powers = call powers_of_two 19
print powers | def powers_of_two(n):
if n == 0:
return [1]
else:
prev_powers = powers_of_two(n - 1)
current_power = prev_powers[-1] * 2
return prev_powers + [current_power]
powers = powers_of_two(19)
print(powers)
| Python | jtatman_500k |
comment 반복문은 크게 for, while 문이 있음
comment break , continue
comment for 문
for i in range 3
begin
comment 0
print i
print string 철수 : 안녕 영희야 뭐해?
print string 영희 : 안녕 철수야, 그냥 있어.
end
comment while 문 (for문과 다른점은 조건문 사용가능함)
set i = 0
while i < 3
begin
comment 0
print i
print string 철수 : 안녕 영희야 뭐해?
print string 영희 : 안녕 철수야, 그... | #반복문은 크게 for, while 문이 있음
#break , continue
## for 문
for i in range(3):
print(i) # 0
print("철수 : 안녕 영희야 뭐해?")
print("영희 : 안녕 철수야, 그냥 있어.")
## while 문 (for문과 다른점은 조건문 사용가능함)
i = 0
while i < 3:
print(i) # 0
print("철수 : 안녕 영희야 뭐해?")
print("영희 : 안녕 철수야, 그냥 있어.")
# 파이썬은 일관성과 가독성을 위한 언어이므로 증감연산자... | Python | zaydzuhri_stack_edu_python |
function update_probabilities self
begin
set probabilities = list
set denominator = gamma + customers - 1
for table in tables
begin
append probabilities table / denominator
end
append probabilities gamma / denominator
set probabilities = probabilities
end function | def update_probabilities(self):
probabilities = []
denominator = self.gamma + self.customers - 1
for table in self.tables:
probabilities.append(table / denominator)
probabilities.append(self.gamma / denominator)
self.probabilities = probabilities | Python | nomic_cornstack_python_v1 |
function _rollout self
begin
set sample_num = 0
set return_buffer = list
set ep_len_buffer = list
while sample_num < total_sample_size
begin
comment initialize episode
set steps = 0
set discouted_sum_reward = 0
comment dm_control
set time_step = none
set s = none
set done = false
if benchmark == string dm_control
beg... | def _rollout(self):
sample_num = 0
return_buffer = []
ep_len_buffer = []
while sample_num < self.total_sample_size:
#initialize episode
steps = 0
discouted_sum_reward = 0
time_step = None #dm_control
s = None
done... | Python | nomic_cornstack_python_v1 |
from pages.base_page import BasePage
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from locators import RegistrationPageLocators
from selenium.webdriver.common.keys import Keys
class RegistrationPage extends BasePage
begin
function _verify_pag... | from pages.base_page import BasePage
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from locators import RegistrationPageLocators
from selenium.webdriver.common.keys import Keys
class RegistrationPage(BasePage):
def _verify_page(self):
... | Python | zaydzuhri_stack_edu_python |
function _assertVisionLogFundamentals self total_records total_processed details=string exception_message=string successful=true
begin
set sync_logs = all
assert equal length sync_logs 1
set sync_log = sync_logs at 0
assert equal handler_name string _MySynchronizer
assert equal total_records total_records
assert equa... | def _assertVisionLogFundamentals(
self,
total_records,
total_processed,
details="",
exception_message="",
successful=True,
):
sync_logs = VisionLog.objects.all()
self.assertEqual(len(sync_logs), 1)
sync_log = sync_logs[0]
self.assert... | Python | nomic_cornstack_python_v1 |
comment studentDriver - creates Student objects and tests Student methods
from Student import Student
from Date import Date
function main
begin
set date = call Date
call setDate 12 28 2000
set scores = list 90 93
set chad = call Student 1 string Chad string Williams scores date
call addGrade 93
call addGrade 89
call ad... | # studentDriver - creates Student objects and tests Student methods
from Student import Student
from Date import Date
def main():
date = Date()
date.setDate(12, 28, 2000)
scores = [90, 93]
chad = Student(1, "Chad", "Williams", scores, date)
chad.addGrade(93)
chad.addGrade(89... | Python | zaydzuhri_stack_edu_python |
function do_rmInfo gDict args
begin
set tuple doThis todo = call splitArgs args 1
set fail = call checkPresence doThis list string tag list
if fail at string truth
begin
exit
end
set theInfo = fail at string tag
if theInfo == string history
begin
set prefix = string Usage: uam rminfo history
set fail = call checkPresen... | def do_rmInfo(gDict, args):
(doThis, todo) = splitArgs(args, 1)
fail = checkPresence(doThis, ["tag"], [])
if fail["truth"]:
sys.exit()
theInfo = fail["tag"]
if theInfo == "history":
prefix = "Usage: uam rminfo history"
fail = checkPresence(doThis, ["histoid"], ["histoid"]) | Python | nomic_cornstack_python_v1 |
function getPrescription details
begin
set prescriptionid = details at string prescriptionid
set prescription = get call dicts
set prescription at string startdate = string prescription at string startdate
set prescription at string enddate = string prescription at string enddate
return dumps prescription
end function | def getPrescription(details):
prescriptionid = details['prescriptionid']
prescription = Prescription.select().where(Prescription.prescriptionid == prescriptionid).dicts().get()
prescription['startdate'] = str(prescription['startdate'])
prescription['enddate'] = str(prescription['enddate'])
return js... | Python | nomic_cornstack_python_v1 |
function ascii_to_character
begin
set c = integer input string Enter a ASCII value:
print format string The character for ASCII value '{}' is {} c character c
end function | def ascii_to_character():
c = int(input("Enter a ASCII value: "))
print("The character for ASCII value '{}' is {}".format(c, chr(c))) | Python | nomic_cornstack_python_v1 |
function initialize_nuttall fc fs c_surf tau_lim decimation=8 num_dither=5
begin
set dx = c_surf / decimation * fc
comment compute time/frequency domain parameters
comment transmitted signal
set tuple sig_y sig_t = call nuttall_pulse fc fs
comment compute t and f axes
set num_t = integer ceil tau_lim * fs + size + num_... | def initialize_nuttall(fc, fs, c_surf, tau_lim, decimation=8, num_dither=5):
dx = c_surf / (decimation * fc)
# compute time/frequency domain parameters
# transmitted signal
sig_y, sig_t = nuttall_pulse(fc, fs)
# compute t and f axes
num_t = int(np.ceil(tau_lim * fs + sig_y.size + num_dither)... | Python | nomic_cornstack_python_v1 |
function get_encryption_key self public_key=none
begin
return call _do_request GET BASE_URL_DE + string /api/encryption/key params=dict string publicKey public_key
end function | def get_encryption_key(self, public_key: str = None) -> dict:
return self._do_request(GET, BASE_URL_DE + '/api/encryption/key', params={
'publicKey': public_key
}) | Python | nomic_cornstack_python_v1 |
function __move self
begin
set snake_head_pos = call __recount_head
pop snake_body
set ate_food = false
return insert snake_body 0 snake_head_pos
end function | def __move(self):
self.snake_head_pos = self.__recount_head()
self.snake_body.pop()
self.ate_food = False
return self.snake_body.insert(0, self.snake_head_pos) | Python | nomic_cornstack_python_v1 |
function _start_http_server
begin
string Start the daemon's HTTP server on a separate thread. This server is only used for servicing container status requests from Dusty's custom 502 page.
info format string Starting HTTP server at {}:{} DAEMON_HTTP_BIND_IP DAEMON_HTTP_BIND_PORT
set thread = thread target=run args=tupl... | def _start_http_server():
"""Start the daemon's HTTP server on a separate thread.
This server is only used for servicing container status
requests from Dusty's custom 502 page."""
logging.info('Starting HTTP server at {}:{}'.format(constants.DAEMON_HTTP_BIND_IP,
... | Python | jtatman_500k |
string 审核文章
import pytest
from selenium.webdriver.common.by import By
from base.mis.base_page import BasePage , BaseHandle
from utils import select_option , DriverUtils
decorator run order=102
comment 对象库层
class AduitPage extends BasePage
begin
function __init__ self
begin
call __init__
comment 文章名称输入框
set ar_title = t... | """
审核文章
"""
import pytest
from selenium.webdriver.common.by import By
from base.mis.base_page import BasePage, BaseHandle
from utils import select_option, DriverUtils
# 对象库层
@pytest.mark.run(order=102)
class AduitPage(BasePage):
def __init__(self):
super().__init__()
# 文章名称输入框
self.ar_ti... | Python | zaydzuhri_stack_edu_python |
comment this code calculates the effective beam for a 4 component beam
import numpy as np
function FWHM fwhm
begin
return fwhm / 2.0 * square root 2.0 * log 2.0
end function
function quad n1 n2 s1 s2
begin
return n1 * n2 * s1 ^ 2 * s2 ^ 2 / s1 ^ 2 + s2 ^ 2
end function
function quad_part n1 n2 s1 s2
begin
return n1 * n... | #this code calculates the effective beam for a 4 component beam
import numpy as np
def FWHM(fwhm):
return fwhm/(2.*np.sqrt(2.*np.log(2.)))
def quad(n1,n2,s1,s2):
return (n1*n2*(s1**2)*(s2**2))/((s1**2)+(s2**2))
def quad_part(n1,n2,s1,s2):
return (n1*n2*(s1**2)*(s2**2))
fwhm450_MB = 7.9
fwhm850_MB = 13... | Python | zaydzuhri_stack_edu_python |
function get_min_max ints
begin
string Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers
try
begin
for x in ints
begin
if not type x is int
begin
raise TypeError
end
end
set min = ints at 0
set max = ints at 0
for x in ints
begin
if x <= min
be... | def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
try:
for x in ints:
if not type(x) is int:
raise TypeError
min = ints[0]
max = i... | Python | zaydzuhri_stack_edu_python |
function get_unread_email_ids gmail_client
begin
set response = execute list userId=string me q=string is:unread
comment messages key only exists if there are unread messages
if string messages in response
begin
return list comprehension message at string id for message in response at string messages
end
else
begin
pri... | def get_unread_email_ids(gmail_client):
response = gmail_client.users().messages().list(userId='me',q='is:unread').execute()
if 'messages' in response: # messages key only exists if there are unread messages
return [message['id'] for message in response['messages']]
else:
print("No unread m... | Python | nomic_cornstack_python_v1 |
function facts_to_str user_data
begin
set facts = list comprehension string { key } - { value } for tuple key value in items user_data
return join join string facts list string string
end function | def facts_to_str(user_data: Dict[str, str]) -> str:
facts = [f'{key} - {value}' for key, value in user_data.items()]
return "\n".join(facts).join(['\n', '\n']) | Python | nomic_cornstack_python_v1 |
function ksz_radial_function z ombh2 Yp gasfrac=0.9 xe=1 tau=0 params=none
begin
if params is none
begin
set params = default_params
end
comment muK
set T_CMB_muk = params at string T_CMB
set thompson_SI = constants at string thompson_SI
set meterToMegaparsec = constants at string meter_to_megaparsec
set ne0 = call ne0... | def ksz_radial_function(z,ombh2, Yp, gasfrac = 0.9,xe=1, tau=0, params=None):
if params is None: params = default_params
T_CMB_muk = params['T_CMB'] # muK
thompson_SI = constants['thompson_SI']
meterToMegaparsec = constants['meter_to_megaparsec']
ne0 = ne0_shaw(ombh2,Yp)
return T_CMB_muk*thompso... | Python | nomic_cornstack_python_v1 |
function test_subscribe runpath
begin
set server = call ZMQServer name=string server host=string 127.0.0.1 port=0 message_pattern=PUB runpath=join path runpath string server
with server
begin
set client = call ZMQClient name=string client hosts=list host ports=list port message_pattern=SUB runpath=join path runpath str... | def test_subscribe(runpath):
server = ZMQServer(
name="server",
host="127.0.0.1",
port=0,
message_pattern=zmq.PUB,
runpath=os.path.join(runpath, "server"),
)
with server:
client = ZMQClient(
name="client",
hosts=[server.host],
... | Python | nomic_cornstack_python_v1 |
import sys , string
from PyQt5.QtWidgets import QLabel , QFrame , QGridLayout
from PyQt5.QtCore import Qt
class Board extends QFrame
begin
function __init__ self colors
begin
call __init__
call setLineWidth 1
call setFrameShape Box
set grid = call QGridLayout
call setLayout grid
set tiles = dict
set companycolors = co... | import sys, string
from PyQt5.QtWidgets import QLabel, QFrame, QGridLayout
from PyQt5.QtCore import Qt
class Board(QFrame):
def __init__(self,colors):
super().__init__()
self.setLineWidth(1)
self.setFrameShape(QFrame.Box)
self.grid = QGridLayout()
self.setLayout(self.grid)
... | Python | zaydzuhri_stack_edu_python |
function _popleft self
begin
set result : Any = call popleft
set qlen = qlen - 1
return result
end function | def _popleft(self) -> Any:
result: Any = self.deck.popleft()
self.qlen -= 1
return result | Python | nomic_cornstack_python_v1 |
function run_manage_task operation
begin
comment The "schtasks" command need the admin permissions to edit the tasks,
comment then we call windows API to elevate it as administrator (UAC will be prompt to the user)
if operation == string create
begin
call _generate_xml
set args = format string /create /xml "{xml_file_p... | def run_manage_task(operation):
# The "schtasks" command need the admin permissions to edit the tasks,
# then we call windows API to elevate it as administrator (UAC will be prompt to the user)
if operation == 'create':
_generate_xml()
args = '/create /xml "{xml_file_path}" /tn "Kodi_Install... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Main user interface Updated 29th March 2018 by Kamil
import tkinter as tk
from tkinter import TOP , LEFT , RIGHT , BOTH , RAISED , Y
from tkinter import NORMAL , END , DISABLED
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.ba... | # -*- coding: utf-8 -*-
"""
Main user interface
Updated 29th March 2018 by Kamil
"""
import tkinter as tk
from tkinter import TOP, LEFT, RIGHT, BOTH, RAISED, Y
from tkinter import NORMAL, END, DISABLED
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.backends.ba... | Python | zaydzuhri_stack_edu_python |
comment JMJ
comment PyCheckers.py
comment Contains everything you need for a basic game of checkers.
comment Programmed mostly by Aaron Bangs with a little help from Ben Campbell
import enum
import numpy
class Player extends Enum
begin
set black = 1
set red = 2
decorator property
function other self
begin
comment Retur... | #JMJ
#PyCheckers.py
#Contains everything you need for a basic game of checkers.
#Programmed mostly by Aaron Bangs with a little help from Ben Campbell
import enum
import numpy
class Player(enum.Enum):
black = 1
red = 2
@property
def other(self):
return Player.black if self == Player.red else ... | Python | zaydzuhri_stack_edu_python |
function is_new created_time interval_in_s=240
begin
set tdelta = time delta seconds=integer interval_in_s
set now_hours = hour
set now_minutes = minute
set now_seconds = second
set now = time delta hours=now_hours minutes=now_minutes seconds=now_seconds
return now < created_time + tdelta
end function | def is_new(created_time, interval_in_s=240):
tdelta = timedelta(seconds=int(interval_in_s))
now_hours = datetime.now().hour
now_minutes = datetime.now().minute
now_seconds = datetime.now().second
now = timedelta(hours=now_hours, minutes=now_minutes, seconds=now_seconds)
return now < created_time... | Python | nomic_cornstack_python_v1 |
import random
import socket
import time
from encryption import Encryption
class Keys
begin
string КЛЮЧИ ШИФРОВАНИЯ
function __init__ self
begin
set a = random integer 100 100000
set g = random integer 50000 100000
set p = random integer 100 49999
set A = g ^ a % p
set B = 0
set status = true
end function
function get_K... | import random
import socket
import time
from encryption import Encryption
class Keys:
""" КЛЮЧИ ШИФРОВАНИЯ """
def __init__(self):
self.a = random.randint(100, 100000)
self.g = random.randint(50000, 100000)
self.p = random.randint(100, 49999)
self.A = self.g ** self.a % self.p
... | Python | zaydzuhri_stack_edu_python |
from tests import NoLoggingTestCase
from map_creator.distance import dtw
from map_creator.model import Coordinate , Path , Point
class DistanceTest extends NoLoggingTestCase
begin
function test_dtw self
begin
set path_1 = call Path
call add_point call Point 1 call Coordinate 47.47176 19.05178
call add_point call Point ... | from tests import NoLoggingTestCase
from map_creator.distance import dtw
from map_creator.model import Coordinate, Path, Point
class DistanceTest(NoLoggingTestCase):
def test_dtw(self):
path_1 = Path()
path_1.add_point(Point(1, Coordinate(47.47176, 19.05178)))
path_1.add_point(Point(1, Co... | Python | zaydzuhri_stack_edu_python |
function plot_map loc_dataframe
begin
set figure = call scatter_geo loc_dataframe lat=string latitude lon=string longitude hover_name=string title text=string id
call update_layout mapbox_style=string carto-darkmatter
show
end function | def plot_map(loc_dataframe: pd.DataFrame):
figure = px.scatter_geo(loc_dataframe, lat="latitude", lon="longitude",
hover_name='title', text='id')
figure.update_layout(mapbox_style="carto-darkmatter")
figure.show() | Python | nomic_cornstack_python_v1 |
import CloverDB
import File_Parser
class Parser_Manager
begin
string Wrapper for CloverDB and File_Parser modules. This Attributes: parser: Parser object from File_Parser module db: sqlite3_DB object from CloverDB module buffer: buffer for transitioning data between parser and database
function __init__ self
begin
stri... | import CloverDB
import File_Parser
class Parser_Manager():
"""Wrapper for CloverDB and File_Parser modules.
This
Attributes:
parser: Parser object from File_Parser module
db: sqlite3_DB object from CloverDB module
buffer: buffer for transitioning data between parser and d... | Python | zaydzuhri_stack_edu_python |
import sys
with open argv at 1 string r as f
begin
set code = list comprehension split l for l in split read f string
end
set register = dict string a 0 ; string b 0 ; string c 0 ; string d 0
for i in range length argv at slice 2 : :
begin
set register at sorted keys register at i = integer argv at i + 2
end
set i = 0... | import sys
with open(sys.argv[1],'r') as f:
code = [l.split() for l in f.read().split('\n')]
register = {
'a': 0,
'b': 0,
'c': 0,
'd': 0
}
for i in range(len(sys.argv[2:])):
register[sorted(register.keys())[i]] = int(sys.argv[i+2])
i = 0
while i < len(code):
line = code[i]
if line:
if line[0] == 'cpy':
... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from contextlib import contextmanager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import staleness_of
from pathlib import P... | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from contextlib import contextmanager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import staleness_of
from pathlib import... | Python | zaydzuhri_stack_edu_python |
import os
import csv
function getPercentage part whole
begin
return round part / whole * 100 3
end function
comment Define the path: ./Resources/election_data.csv
set data_path = join path string . string Resources string election_data.csv
comment Open the file
with open data_path newline=string as data_file
begin
comm... | import os
import csv
def getPercentage(part, whole):
return round((part/whole * 100), 3)
# Define the path: ./Resources/election_data.csv
data_path = os.path.join(".", "Resources", "election_data.csv")
# Open the file
with open(data_path, newline='') as data_file:
# Read the data
election_data = csv.re... | Python | zaydzuhri_stack_edu_python |
string An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, , of size , each memory location has some unique index, (where ), that can be referenced as (you may also see it written as ). Given an array, , of integers, print each element in reverse orde... | '''An array is a type of data structure that stores elements of the same type in a contiguous block of memory.
In an array, , of size , each memory location has some unique index, (where ), that can be referenced as
(you may also see it written as ).
Given an array, , of integers, print each element in reverse order... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
function readCsv filename
begin
if __name__ == string __main__
begin
set df = read csv string ../data/ + filename
end
else
begin
set df = read csv string ./data/ + filename
end
return df
end function
function getVariableObjective df
begin
set cols = columns
set variables = values * 100
set objective... | import pandas as pd
def readCsv(filename):
if __name__ == '__main__':
df = pd.read_csv('../data/'+filename)
else:
df = pd.read_csv('./data/'+filename)
return df
def getVariableObjective(df):
cols = df.columns
variables = df[[col for col in cols if 'y' in col]].values *100
objectives = df[[col for col i... | Python | zaydzuhri_stack_edu_python |
function __init__ self vcapServices
begin
set userName = string
comment Local variables
set url = string https://gateway.watsonplatform.net/personality-insights/api
set username = string put username
set password = string put password
comment "aeJmBS1mYFOj"
if vcapServices is not none
begin
print string Parsing VCAP_S... | def __init__(self, vcapServices):
self.userName = ""
# Local variables
self.url = "https://gateway.watsonplatform.net/personality-insights/api"
self.username = "put username"
self.password = "put password"
#"aeJmBS1mYFOj"
if vcapServices is not None:
... | Python | nomic_cornstack_python_v1 |
import urllib2
from bs4 import BeautifulSoup
import re
function more url
begin
set url = url + string -2
set req = call Request url headers=dict string User-Agent string Mozilla/5.0
set plain = read url open req
set soup = call BeautifulSoup plain string lxml
set i = find all soup string p dict string class string litN... | import urllib2
from bs4 import BeautifulSoup
import re
def more(url):
url = url+"-2"
req = urllib2.Request(url, headers={ 'User-Agent': 'Mozilla/5.0' })
plain = urllib2.urlopen(req).read()
soup = BeautifulSoup(plain, "lxml")
i = soup.find_all('p',{'class':'litNoteText'})
return str(i)
f = open("urls.tsv","r")
d... | Python | zaydzuhri_stack_edu_python |
function set_hand_vel self vel
begin
comment Calculate joint velocities to achieve desired velocity
set joint_vels = dot call jacobian_pseudo_inverse vel
set joints = dictionary zip call joint_names joint_vels
call set_joint_velocities joints
end function | def set_hand_vel(self,vel):
# Calculate joint velocities to achieve desired velocity
joint_vels=np.dot(self._kin.jacobian_pseudo_inverse(),vel)
joints=dict(zip(self._arm.joint_names(),(joint_vels)))
self._arm.set_joint_velocities(joints) | Python | nomic_cornstack_python_v1 |
function setOptions self opts
begin
update _opts opts
end function | def setOptions(self, opts):
self._opts.update(opts) | Python | nomic_cornstack_python_v1 |
import socket
import csv
import pickle
import time
import json
function csv_dict_reader sock file_obj num
begin
set i = 0
set reader = reader file_obj delimiter=string ;
set send = dumps list reader at slice 1 : num + 1 :
set lenght = length send
call sendall encode command + string + string lenght string utf8
sleep 1... | import socket
import csv
import pickle
import time
import json
def csv_dict_reader(sock,file_obj, num):
i = 0
reader = csv.reader(file_obj, delimiter = ';')
send = pickle.dumps(list(reader)[1:num+1])
lenght = len(send)
sock.sendall((command + ' ' + str(lenght)).encode("utf8"))
time.sleep(1)
sock.sendall(send)
... | Python | zaydzuhri_stack_edu_python |
function cleanup self
begin
pass
end function | def cleanup(self):
pass | Python | nomic_cornstack_python_v1 |
comment %%
from scipy.spatial.distance import pdist , squareform
from scipy import exp
from scipy.linalg import eigh
import numpy as np
from sklearn.datasets import make_moons
from sklearn.datasets import make_circles
from sklearn.decomposition import PCA
from matplotlib.ticker import FormatStrFormatter
import matplotl... | #%%
from scipy.spatial.distance import pdist,squareform
from scipy import exp
from scipy.linalg import eigh
import numpy as np
from sklearn.datasets import make_moons
from sklearn.datasets import make_circles
from sklearn.decomposition import PCA
from matplotlib.ticker import FormatStrFormatter
import matplotlib.pyplot... | Python | zaydzuhri_stack_edu_python |
function sort_participants members category
begin
set members_and_points = list
for member in members
begin
set points = 0
if category == string total
begin
set points = call calculate_personal_score call get_userid_from_mention member at string mention
end
else
if category in member
begin
set points = member at categ... | def sort_participants(members, category):
members_and_points = []
for member in members:
points = 0
if category == "total":
points = calculate_personal_score(
get_userid_from_mention(member["mention"]))
elif category in member:
points = member[cate... | Python | nomic_cornstack_python_v1 |
function is_in_table self name_twitter
begin
set count_cmd = string SELECT COUNT(*) FROM users WHERE Name_Twitter = '%s'; % name_twitter
set tuple nb_count = call execute_cmd count_cmd
if nb_count != 0
begin
return true
end
return false
end function | def is_in_table(self, name_twitter):
count_cmd = "SELECT COUNT(*) FROM users WHERE Name_Twitter = '%s';" % name_twitter
(nb_count,) = self.execute_cmd(count_cmd)
if nb_count != 0:
return True
return False | Python | nomic_cornstack_python_v1 |
function id self
begin
return get pulumi self string id
end function | def id(self) -> str:
return pulumi.get(self, "id") | Python | nomic_cornstack_python_v1 |
comment !python3
comment coding:utf-8
import fileinput
for data in input
begin
if strip data and strip data == string 42
begin
break
end
print strip data
end | #!python3
#coding:utf-8
import fileinput
for data in fileinput.input():
if data.strip() and data.strip() == '42': break
print(data.strip()) | Python | zaydzuhri_stack_edu_python |
function SetNumberOfIterations self *args
begin
return call itkFiniteDifferenceImageFilterICVF22ICVF22_SetNumberOfIterations self *args
end function | def SetNumberOfIterations(self, *args):
return _itkFiniteDifferenceImageFilterPython.itkFiniteDifferenceImageFilterICVF22ICVF22_SetNumberOfIterations(self, *args) | Python | nomic_cornstack_python_v1 |
function SetTranslatedCommentText self comment language
begin
set callResult = call _Call string SetTranslatedCommentText comment language
end function | def SetTranslatedCommentText(self, comment, language):
callResult = self._Call("SetTranslatedCommentText", comment, language) | Python | nomic_cornstack_python_v1 |
class String
begin
function __init__ self string
begin
set string = string
end function
function __repr__ self
begin
return format string Object: {} string
end function
function __add__ self other
begin
return string + other
end function
end class
if __name__ == string __main__
begin
set string = call String string Hel... | class String:
def __init__(self, string):
self.string = string
def __repr__(self):
return 'Object: {}'.format(self.string)
def __add__(self, other):
return self.string + other
if __name__ == '__main__':
string = String('Hello World')
print(string)
print(string + ', th... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sat Aug 01 11:09:20 2015 Euler Project, Problem 112
comment we shall call a positive integer that is neither
comment increasing nor decreasing a "bouncy" number; for example, 155349.
comment bouncy numbers become more common and by the time we reach 21780
comment the prop... | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 01 11:09:20 2015
Euler Project, Problem 112
"""
# we shall call a positive integer that is neither
# increasing nor decreasing a "bouncy" number; for example, 155349.
# bouncy numbers become more common and by the time we reach 21780
# the proportion of bouncy numbers is... | Python | zaydzuhri_stack_edu_python |
function get_text_snippet ex
begin
if is instance ex list
begin
if length ex > 0
begin
return call get_text_snippet ex at 0
end
else
begin
return none
end
end
else
if is instance ex tuple string_types float int
begin
return ex
end
else
begin
raise call TypeError format string Currently get_text_snippet function does no... | def get_text_snippet(ex):
if isinstance(ex, list):
if len(ex) > 0:
return get_text_snippet(ex[0])
else:
return None
elif isinstance(ex, (six.string_types, float, int)):
return ex
else:
raise TypeError("Currently get_text_snippet function "
"does not support type {}"... | Python | nomic_cornstack_python_v1 |
function test_alloc_pil4dfs_ls server conf wf
begin
set pool = call get_test_pool_obj
set container = call create_cont conf pool ctype=string POSIX label=string pil4dfs_fi
with temporary directory prefix=string pil4_src_ as src_dir
begin
set sub_dir = join src_dir string new_dir
make directory os sub_dir
for idx in ran... | def test_alloc_pil4dfs_ls(server, conf, wf):
pool = server.get_test_pool_obj()
container = create_cont(conf, pool, ctype='POSIX', label='pil4dfs_fi')
with tempfile.TemporaryDirectory(prefix='pil4_src_',) as src_dir:
sub_dir = join(src_dir, 'new_dir')
os.mkdir(sub_dir)
for idx in r... | Python | nomic_cornstack_python_v1 |
function task_kill_sync self task_id dataset_id=none resources=none reason=none message=none site=none
begin
if not reason
begin
set reason = string killed
end
if not message
begin
set message = reason
end
try
begin
set hostname = call gethostname
set domain = join string . split hostname string . at slice - 2 : :
set... | def task_kill_sync(self, task_id, dataset_id=None, resources=None,
reason=None, message=None, site=None):
if not reason:
reason = 'killed'
if not message:
message = reason
try:
hostname = functions.gethostname()
domain = '.'.... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string Task 17. Integrate
function poly_integral poly C=0
begin
string Polynomial integral
if call isa_poly poly and call isa_number C
begin
set exponents = list range 1 length poly + 1
set result = list map lambda x y -> call trim_float x / y poly exponents
return if expression result != ... | #!/usr/bin/env python3
"""Task 17. Integrate"""
def poly_integral(poly, C=0):
"""Polynomial integral"""
if isa_poly(poly) and isa_number(C):
exponents = list(range(1, len(poly)+1))
result = list(map(lambda x, y: trim_float(x/y), poly, exponents))
return [C] + result if result != [0] el... | Python | zaydzuhri_stack_edu_python |
set arr = list 1 5 2 8 5 10 5 5
set highest = decimal string -inf
set second_highest = decimal string -inf
for num in arr
begin
if num > highest
begin
set second_highest = highest
set highest = num
end
else
if num > second_highest and num != highest
begin
set second_highest = num
end
end
print second_highest | arr = [1, 5, 2, 8, 5, 10, 5, 5]
highest = float('-inf')
second_highest = float('-inf')
for num in arr:
if num > highest:
second_highest = highest
highest = num
elif num > second_highest and num != highest:
second_highest = num
print(second_highest)
| Python | jtatman_500k |
import socket
import logging
import typing as tp
from queue import Queue
from threading import Thread
import ssl
from utils import receive_request , CustomClients
from custom_request import Request
from game_logic import Game
call basicConfig level=ERROR format=string %(asctime)s [%(levelname)s] %(message)s handlers=li... | import socket
import logging
import typing as tp
from queue import Queue
from threading import Thread
import ssl
from utils import receive_request, CustomClients
from custom_request import Request
from game_logic import Game
logging.basicConfig(
level=logging.ERROR,
format="%(asctime)s [%(levelname)s] %(mess... | Python | zaydzuhri_stack_edu_python |
function itkAddImageFilterID2ID2ID2_cast *args
begin
return call itkAddImageFilterID2ID2ID2_cast *args
end function | def itkAddImageFilterID2ID2ID2_cast(*args):
return _itkAddImageFilterPython.itkAddImageFilterID2ID2ID2_cast(*args) | Python | nomic_cornstack_python_v1 |
import pandas as pd
comment Read the data
set data = read csv string apple stock data.csv
comment Extract the data points
set X = data at list string open string high string low string volume
set y = data at string close
comment Fit the model
fit model X y
comment Predict the stock price of Apple in 2021
set predict = ... | import pandas as pd
# Read the data
data = pd.read_csv("apple stock data.csv")
# Extract the data points
X = data[['open', 'high', 'low', 'volume']]
y = data['close']
# Fit the model
model.fit(X, y)
# Predict the stock price of Apple in 2021
predict = model.predict([[Apple_open, Apple_high, Apple_low, Apple_volume... | Python | iamtarun_python_18k_alpaca |
function egrep self pattern
begin
set pattern = compile pattern
set result = list
for line in contents
begin
if search line
begin
append result line
end
end
if result
begin
return result
end
return false
end function | def egrep(self, pattern):
pattern = re.compile(pattern)
result = []
for line in self.contents:
if pattern.search(line):
result.append(line)
if result:
return result
return False | Python | nomic_cornstack_python_v1 |
function teardown self
begin
if success
begin
if delFiles
begin
set msg = format sfmt string Teardown test name
print msg
comment wait to delete on windows
if lower platform == string win32
begin
sleep 3
end
try
begin
remove tree simpath
set success = true
end
except any
begin
print string Could not remove test + name
... | def teardown(self):
if self.success:
if self.delFiles:
msg = sfmt.format('Teardown test', self.name)
print(msg)
# wait to delete on windows
if sys.platform.lower() == "win32":
time.sleep(3)
try:
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import datetime
import threading
import logging
import random
import time
import pprint
set pp = call PrettyPrinter indent=4
set STREAM_ID = 0
set STREAM_ID_TIME = call utcnow
print STREAM_ID_TIME
set MAX_STREAMS = 4
set MAX_STREAM_LENGTH = 10
set DATA_EXPIRE = 0.5
set DATASTREAMS = list
f... | #!/usr/bin/env python3
import datetime
import threading
import logging
import random
import time
import pprint
pp = pprint.PrettyPrinter(indent=4)
STREAM_ID = 0
STREAM_ID_TIME = datetime.datetime.utcnow()
print(STREAM_ID_TIME)
MAX_STREAMS = 4
MAX_STREAM_LENGTH = 10
DATA_EXPIRE = 0.5
DATASTREAMS = list()
def main... | Python | zaydzuhri_stack_edu_python |
function search_files_folders request **kwargs
begin
set name = data at string name
set files_and_folders = filter name__icontains=name status=string CREATED
set response_list = list
set dictionary = dict
for fsobject in files_and_folders
begin
set fs_object = call convert_fsobject_to_fstypeobject fsobject
if path in... | def search_files_folders(request,**kwargs):
name = request.data['name']
files_and_folders = FileSystem.objects.filter(name__icontains=name, status="CREATED")
response_list = []
dictionary = {}
for fsobject in files_and_folders :
fs_object = convert_fsobject_to_fstypeobject(fsobject)
... | Python | nomic_cornstack_python_v1 |
function __call__ self inputs training
begin
set y = reshape array_ops inputs _input_shape
set y = call conv1 y
set y = call max_pool2d y
set y = call conv2 y
set y = call max_pool2d y
set y = flatten layers y
set y = call fc1 y
set y = dropout y training=training
return call fc2 y
end function | def __call__(self, inputs, training):
y = array_ops.reshape(inputs, self._input_shape)
y = self.conv1(y)
y = self.max_pool2d(y)
y = self.conv2(y)
y = self.max_pool2d(y)
y = layers.flatten(y)
y = self.fc1(y)
y = self.dropout(y, training=training)
return self.fc2(y) | Python | nomic_cornstack_python_v1 |
function parse_args
begin
set parser = call ArgumentParser description=description
call add_argument string -s string --src type=str nargs=string * help=string Source of dashboard(s) (file|elasticsearch)
call add_argument string -d string --dst type=str nargs=string * help=string Destination of dashboard(s) (file|elast... | def parse_args ():
parser = argparse.ArgumentParser(description = description)
parser.add_argument("-s", "--src",
type=str, nargs="*",
help="Source of dashboard(s) (file|elasticsearch)")
parser.add_argument("-d", "--dst",
type=str, narg... | Python | nomic_cornstack_python_v1 |
import time
set graphe = dict string S=21 list list string A=18 4 list string B=15 10 ; string A=18 list list string B=15 3 ; string B=15 list list string D=4 6 list string C=5 10 ; string D=4 list list string D=4 10 ; string C=5 list list string G1=0 6 list string G2=0 5
set graphe1 = dict string S=21 list string A=18... | import time
graphe={'S=21': [['A=18',4], ['B=15',10]], 'A=18': [['B=15',3]],'B=15': [['D=4',6],['C=5',10]],'D=4':[['D=4',10]],'C=5':[['G1=0',6],['G2=0',5]]}
graphe1={'S=21':['A=18','B=15'],'A=18':['B=15'],'B=15':['D=4','C=5'],'D=4':['D=4'],'C=5':['G1=0','G2=0']}
def gloutn(graphe={},EI="",EF="",path=[],chemin=[]):
... | Python | zaydzuhri_stack_edu_python |
function distance_callback from_index to_index
begin
comment Convert from routing variable Index to distance matrix NodeIndex.
set _from_node = call IndexToNode from_index
set _to_node = call IndexToNode to_index
return distances_ at _from_node at _to_node
end function | def distance_callback(from_index, to_index):
# Convert from routing variable Index to distance matrix NodeIndex.
_from_node = index_manager_.IndexToNode(from_index)
_to_node = index_manager_.IndexToNode(to_index)
return distances_[_from_node][_to_node] | Python | nomic_cornstack_python_v1 |
function __init__ cls name bases attrs
begin
comment Backport of __set_name__ from 3.6 :)
if version_info at 1 < 6
begin
for tuple k v in items attrs
begin
if is instance v tuple Field Store Section
begin
call __set_name__ cls k
end
end
end
set fields = attrs at string __fields__
set stores = attrs at string __store_at... | def __init__(cls, name, bases, attrs):
if sys.version_info[1] < 6: # Backport of __set_name__ from 3.6 :)
for k, v in attrs.items():
if isinstance(v, (Field, Store, Section)):
v.__set_name__(cls, k)
fields = attrs['__fields__']
stores = at... | Python | nomic_cornstack_python_v1 |
function name self
begin
return get pulumi self string name
end function | def name(self) -> pulumi.Output[str]:
return pulumi.get(self, "name") | Python | nomic_cornstack_python_v1 |
function shared_folder_transfer_ownership_details cls val
begin
return call cls string shared_folder_transfer_ownership_details val
end function | def shared_folder_transfer_ownership_details(cls, val):
return cls('shared_folder_transfer_ownership_details', val) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.