code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import random
function generate_random_array size
begin
string This function generates an array of random integers of a given size. Parameters: size (int): The size of the array to be generated. Returns: list: A list of random integers.
comment Using list comprehension to generate an array of random integers.
return li... | import random
def generate_random_array(size):
"""
This function generates an array of random integers of a given size.
Parameters:
size (int): The size of the array to be generated.
Returns:
list: A list of random integers.
"""
return [random.randint(0, 1000) for _ in range(size)... | Python | jtatman_500k |
import io
import logging
import PIL
import datetime
from PIL import Image , ImageOps
import core.utils.internet.internet
from core.utils.ocr.mytess import MyTess
class IndeedCrawler
begin
function __init__ self
begin
set logger = call getLogger __name__
set tesser = call MyTess string pindeed
comment CONSTANTS
set LEFT... | import io
import logging
import PIL
import datetime
from PIL import Image, ImageOps
import core.utils.internet.internet
from core.utils.ocr.mytess import MyTess
class IndeedCrawler:
def __init__(self):
self.logger = logging.getLogger(__name__)
self.tesser = MyTess('pindeed')
# CONSTANTS
... | Python | zaydzuhri_stack_edu_python |
from PIL import Image , ImageDraw , ImageFont
import random
import os
print string ****Making memes****
set subjectWords = list comprehension right strip line string for line in open string subjects.txt string r
set subjectX = list comprehension right strip line string for line in open string aggwords.txt string r
set ... | from PIL import Image, ImageDraw, ImageFont
import random
import os
print("****Making memes****")
subjectWords = [line.rstrip('\n') for line in open('subjects.txt', 'r')]
subjectX = [line.rstrip('\n') for line in open('aggwords.txt', 'r')]
counter = 0
for i in range(100):
ranNumber = random.randint(0,10)
... | Python | zaydzuhri_stack_edu_python |
class CustomException extends Exception
begin
pass
end class
function sum_of_numbers strings
begin
set total = 0
for string in strings
begin
try
begin
set total = total + integer string
end
except ValueError
begin
raise call CustomException string Invalid input: { string } is not a number
end
end
return total
end funct... | class CustomException(Exception):
pass
def sum_of_numbers(strings):
total = 0
for string in strings:
try:
total += int(string)
except ValueError:
raise CustomException(f"Invalid input: {string} is not a number")
return total
| Python | jtatman_500k |
function test_registration_complete_view_get self
begin
set response = post reverse string rdef_web:user_register data=dict string username string alice ; string password string 123123 ; string password_confirm string 123123 ; string email string a@b.com
assert equal context at string msg string SUCCESS
assert equal st... | def test_registration_complete_view_get(self):
response = self.client.post(reverse('rdef_web:user_register'),
data={'username': 'alice',
'password': '123123',
'password_confirm': '123123',
... | Python | nomic_cornstack_python_v1 |
comment To check whether a number is odd or even
set a = integer input string Enter a number
if a % 2 == 0
begin
print string Its an even number
end
else
begin
print string Its a odd number
end | # To check whether a number is odd or even
a = int(input("Enter a number "))
if a % 2 == 0:
print("Its an even number")
else:
print("Its a odd number")
| Python | zaydzuhri_stack_edu_python |
function determinescalings2 self
begin
set testimages = list
set redo = true
comment Until user is happy with test image of core
while redo
begin
set dx = samplesize
set dy = samplesize
print
comment print 'Scaling images of core for test color image...'
comment pp = [0, 1-0.01*qq[1], 1-0.01*qq[0]]
comment pp2 = 1 - 0... | def determinescalings2(self):
self.testimages = []
redo = True
while redo: # Until user is happy with test image of core
dx = dy = self.samplesize
print
#print 'Scaling images of core for test color image...'
#pp = [0, 1-0.01*qq[1], 1-0.01*qq[0]]... | Python | nomic_cornstack_python_v1 |
function _verify_env var_name err_msg
begin
try
begin
return environ at var_name
end
except KeyError
begin
raise call RuntimeError err_msg
end
end function | def _verify_env(var_name: str, err_msg: str) -> str:
try:
return os.environ[var_name]
except KeyError:
raise RuntimeError(err_msg) | Python | nomic_cornstack_python_v1 |
function generate_private_url cls key_name **kwargs
begin
if key_name is none or key_name == string
begin
return none
end
set conn = call get_s3_conn keyword kwargs
try
begin
set key_url = call generate_url 604800 string GET bucket_name key_name
end
except CertificateError
begin
set conn = call get_s3_conn is_secure=f... | def generate_private_url(cls, key_name, **kwargs):
if key_name is None or key_name == '':
return None
conn = cls.get_s3_conn(**kwargs)
try:
key_url = conn.generate_url(604800, 'GET', cls.bucket_name, key_name)
except CertificateError:
conn = cls.get_... | Python | nomic_cornstack_python_v1 |
function winding self c
begin
assert call is_simple_closed_curve c
pass
end function | def winding(self, c):
assert(self.is_simple_closed_curve(c))
pass | Python | nomic_cornstack_python_v1 |
import os
import json
import argparse
from datasets.drop import constants
set NUMBER_COMPARISON = list string were there more string were there fewer string which age group string which group
function number_comparison_filter question
begin
set question_lower = lower question
set football_ques_spans = list string first... | import os
import json
import argparse
from datasets.drop import constants
NUMBER_COMPARISON = ["were there more", "were there fewer", "which age group", "which group"]
def number_comparison_filter(question: str):
question_lower = question.lower()
football_ques_spans = ["first half", "second half", "quarter"... | Python | zaydzuhri_stack_edu_python |
function smooth_descent_periods prices
begin
set count = 0
set i = 1
while i < length prices
begin
if prices at i == prices at i - 1 - 1
begin
while i < length prices and prices at i == prices at i - 1 - 1
begin
set i = i + 1
end
set count = count + 1
end
else
begin
set i = i + 1
end
end
return count
end function | def smooth_descent_periods(prices):
count = 0
i = 1
while i < len(prices):
if prices[i] == prices[i - 1] - 1:
while i < len(prices) and prices[i] == prices[i - 1] - 1:
i += 1
count += 1
else:
i += 1
return count
| Python | jtatman_500k |
function substitute_value_from_secret_store value
begin
if is instance value str and starts with value string secret|
begin
if starts with value string secret|arn:aws:secretsmanager
begin
return call substitute_value_from_aws_secrets_manager value
end
else
if match value
begin
return call substitute_value_from_gcp_secr... | def substitute_value_from_secret_store(value):
if isinstance(value, str) and value.startswith("secret|"):
if value.startswith("secret|arn:aws:secretsmanager"):
return substitute_value_from_aws_secrets_manager(value)
elif re.compile(r"^secret\|projects\/[a-z0-9\_\-]{6,30}\/secrets").match... | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
comment @File : LinearRegression_V0.3.py
comment @Date : 2018-10-04
comment @Author : 黑桃
comment @Software: PyCharm
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from LR.datasplit import train_test_split
comment from sklearn.model_selection import train_tes... | #-*- coding:utf-8 -*-
# @File : LinearRegression_V0.3.py
# @Date : 2018-10-04
# @Author : 黑桃
# @Software: PyCharm
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from LR.datasplit import train_test_split
# from sklearn.model_selection import train_test_split
from sklearn.linear_m... | Python | zaydzuhri_stack_edu_python |
function rem_dup l
begin
set res = list
for i in l
begin
if i not in res
begin
append res i
end
end
print res
end function
set l = list 1 2 3 4 5 1 3 5
call rem_dup l | def rem_dup(l):
res = []
for i in l:
if i not in res:
res.append(i)
print(res)
l = [1,2,3,4,5,1,3,5]
rem_dup(l)
| Python | zaydzuhri_stack_edu_python |
import networkx as nx
from random import shuffle
from scipy.spatial.distance import cosine as dcos
import matplotlib.pyplot as plt
from utils import timing
class Cluster
begin
function __init__ self thresh=0.3
begin
set G = call Graph
set names = list
set class_idx = 0
set node_idx = 0
set threshold = thresh
set peopl... | import networkx as nx
from random import shuffle
from scipy.spatial.distance import cosine as dcos
import matplotlib.pyplot as plt
from utils import timing
class Cluster:
def __init__(self, thresh = 0.3):
self.G = nx.Graph()
self.names = []
self.class_idx = 0
self.node_idx = 0
... | Python | zaydzuhri_stack_edu_python |
import random
import sys
import os
class Deck extends object
begin
set cards = list
function __init__ self
begin
set cards = list 1 2 3 4 5 * 5
shuffle self
end function
function shuffle self
begin
shuffle random cards
end function
function draw self numCards
begin
set cardsDrawn = list
for i in range numCards
begin
... | import random
import sys
import os
class Deck(object):
cards = []
def __init__(self):
self.cards = [1,2,3,4,5] * 5
self.shuffle()
def shuffle(self):
random.shuffle(self.cards)
def draw(self, numCards):
cardsDrawn = []
for i in range(numCards):
cardsDrawn.append(self.cards.pop())
return cardsDrawn... | Python | zaydzuhri_stack_edu_python |
function save_model_uuid model path=string ./models
begin
set filename = format string {0}.sav hex
set filepath = join path path filename
dump model open filepath string wb
return filename
end function | def save_model_uuid(model, path="./models") -> str:
filename = "{0}.sav".format(uuid.uuid4().hex)
filepath = os.path.join(path, filename)
pickle.dump(model, open(filepath, 'wb'))
return filename | Python | nomic_cornstack_python_v1 |
comment Algoritmo Runge-Kutta para k = 4
from sympy import *
function RungeKutta f p0 h n
begin
set tuple t y = p0
set result = list
for i in range n
begin
append result tuple t y
set k1 = call subs list tuple string t t tuple string y y
set k2 = call subs list tuple string t t + h / 2 tuple string y y + h / 2 * k1
se... | # Algoritmo Runge-Kutta para k = 4
from sympy import *
def RungeKutta(f, p0, h, n):
t, y = p0
result = []
for i in range(n):
result.append( (t, y) )
k1 = f.subs([("t", t), ("y", y)])
k2 = f.subs([("t", t + h/2), ("y", y + h/2*k1)])
k3 = f.subs([("t", t + h/2), ("y"... | Python | zaydzuhri_stack_edu_python |
from aoc2019 import intcode
set test_inputs = list string inputs/day5
function process path
begin
print string Input: path
with open path as f
begin
for line in f
begin
set program = list comprehension integer x for x in split line string ,
set proc1 = call IntCodeProcess program
call send 1
run
print flush proc1
set p... | from aoc2019 import intcode
test_inputs = [
"inputs/day5"
]
def process(path):
print("Input:", path)
with open(path) as f:
for line in f:
program = [int(x) for x in line.split(",")]
proc1 = intcode.IntCodeProcess(program)
proc1.send(1)
proc1.run()
... | Python | zaydzuhri_stack_edu_python |
function barrier
begin
if _is_distributed
begin
barrier
end
end function | def barrier():
if _is_distributed:
comm.Barrier() | Python | nomic_cornstack_python_v1 |
function classify self features
begin
comment TODO: finish this.
set features = array features
return call classify features
end function | def classify(self, features):
# TODO: finish this.
features = np.array(features)
return self.classifier.classify(features) | Python | nomic_cornstack_python_v1 |
import os
import logging
import csv
from collections import defaultdict
import numpy as np
from nltk.stem import WordNetLemmatizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical
from util import preprocess
class Data extends object
begin
set token2idx = dict strin... | import os
import logging
import csv
from collections import defaultdict
import numpy as np
from nltk.stem import WordNetLemmatizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical
from util import preprocess
class Data(object):
token2idx = {'PADDING': 0, 'UN... | Python | zaydzuhri_stack_edu_python |
comment read the file speech.txt and print it out
with open string files/speech.txt string r as file
begin
set lines = read lines file
for line in lines
begin
print line end=string
end
end
print
comment read a file line-by-line
with open string files/baby_names.txt as file
begin
comment read the first 20 lines of the f... | # read the file speech.txt and print it out
with open("files/speech.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line, end="")
print()
# read a file line-by-line
with open("files/baby_names.txt") as file:
# read the first 20 lines of the file
for i in range(20):
... | Python | zaydzuhri_stack_edu_python |
comment https://programmers.co.kr/learn/courses/30/lessons/64062
comment 징검다리 건너기
function check stones less_than
begin
set cnt = 0
set max_cnt = 0
for tuple idx stone in enumerate stones
begin
if stone <= less_than
begin
set cnt = cnt + 1
set max_cnt = max max_cnt cnt
end
else
begin
set cnt = 0
end
end
return max_cnt
... | # https://programmers.co.kr/learn/courses/30/lessons/64062
# 징검다리 건너기
def check(stones, less_than):
cnt = 0
max_cnt = 0
for idx, stone in enumerate(stones):
if stone <= less_than:
cnt += 1
max_cnt = max(max_cnt, cnt)
else:
cnt = 0
return max_cnt
def ... | Python | zaydzuhri_stack_edu_python |
async function test_select_set_option_camera_doorbell_unifi hass camera
begin
set tuple _ entity_id = call ids_from_device_description SELECT camera CAMERA_SELECTS at 2
set __fields__ at string set_lcd_text = call Mock
set set_lcd_text = call AsyncMock
await call async_call string select string select_option dict ATTR_... | async def test_select_set_option_camera_doorbell_unifi(
hass: HomeAssistant,
camera: Camera,
):
_, entity_id = ids_from_device_description(
Platform.SELECT, camera, CAMERA_SELECTS[2]
)
camera.__fields__["set_lcd_text"] = Mock()
camera.set_lcd_text = AsyncMock()
await hass.services.... | Python | nomic_cornstack_python_v1 |
function get_case_property_name_formatter self
begin
set valid_paths = dict
if call enabled domain
begin
try
begin
set valid_paths = dictionary comprehension question at string value : question at string tag for question in call get_questions langs=list
end
except XFormException
begin
comment punt on invalid xml (sorr... | def get_case_property_name_formatter(self):
valid_paths = {}
if toggles.MM_CASE_PROPERTIES.enabled(self.get_app().domain):
try:
valid_paths = {question['value']: question['tag']
for question in self.get_questions(langs=[])}
except XF... | Python | nomic_cornstack_python_v1 |
comment OCP - Open-Close Principle
from enum import Enum
class Color extends Enum
begin
set RED = 1
set GREEN = 2
set BLUE = 3
end class
class Size extends Enum
begin
set SMALL = 1
set MEDIUM = 2
set LARGE = 3
end class
class Product
begin
function __init__ self name color size
begin
set name = name
set color = color
s... | # OCP - Open-Close Principle
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
class Size(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
class Product:
def __init__(self, name, color, size):
self.name = name
self.color = color
self.size = size
apple =... | Python | zaydzuhri_stack_edu_python |
function addWord self word
begin
set node = root
for w in word
begin
if w not in child
begin
set child at w = call TrieNode
end
set node = child at w
end
set isend = true
end function | def addWord(self, word):
node = self.root
for w in word:
if w not in node.child:
node.child[w] = TrieNode()
node = node.child[w]
node.isend = True | Python | nomic_cornstack_python_v1 |
async function download self
begin
set release = context at string release
set tracker = call AccumulatingProgressHandlerWrapper call create_progress_handler release at string size
try
begin
await call download_file release at string download_url temp_path / string hmm.tar.gz add
end
except Exception as err
begin
warni... | async def download(self):
release = self.context["release"]
tracker = AccumulatingProgressHandlerWrapper(
self.create_progress_handler(), release["size"]
)
try:
await download_file(
release["download_url"],
self.temp_path / "hmm.t... | Python | nomic_cornstack_python_v1 |
function correlations self frame_no r_min=1 r_max=20 dr=0.02
begin
set boundary = metadata at string boundary
set tuple r g g6 = call corr loc at frame_no boundary r_min r_max dr
return tuple r g g6
end function | def correlations(self, frame_no, r_min=1, r_max=20, dr=0.02):
boundary = self.data.metadata['boundary']
r, g, g6 = correlations.corr(self.data.df.loc[frame_no],
boundary,
r_min,
r_max,
... | Python | nomic_cornstack_python_v1 |
function get_modifier_state
begin
return call Modifier call SDL_GetModState
end function | def get_modifier_state() -> Modifier:
return Modifier(lib.SDL_GetModState()) | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8-*-
import random
function bubble_sort seq
begin
set n = length seq
for i in range n - 1
begin
print seq
for j in range n - 1 - i
begin
if seq at j > seq at j + 1
begin
set tuple seq at j seq at j + 1 = tuple seq at j + 1 seq at j
end
end
print seq
end
end function
if __name__ == string __main__... | #-*- coding:utf-8-*-
import random
def bubble_sort(seq):
n = len(seq)
for i in range(n-1):
print(seq)
for j in range(n-1-i):
if seq[j]>seq[j+1]:
seq[j],seq[j+1] = seq[j+1],seq[j]
print(seq)
if __name__=='__main__':
seq = list(range(10))
random.shuff... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Fri Jan 17 19:59:26 2020 @author: himanshu
comment - Data Preprocessing
comment Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import f1_score
comment Importing the dataset
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 17 19:59:26 2020
@author: himanshu
"""
# - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import f1_score
# Importing the dataset
dataframe = pd.read_c... | Python | zaydzuhri_stack_edu_python |
function _download_checkpoints db_url directory users
begin
set users = split users string ,
if length users == 1
begin
call download_checkpoints db_url directory users at 0
end
else
begin
for user in users
begin
call download_checkpoints db_url join directory user user
end
end
end function | def _download_checkpoints(db_url, directory, users):
users = users.split(',')
if len(users) == 1:
download_checkpoints(db_url, directory, users[0])
else:
for user in users:
download_checkpoints(db_url, join(directory, user), user) | Python | nomic_cornstack_python_v1 |
function tracers_analysis sim polymer_text tracer_text teq tsample t_threshold p_threshold
begin
comment define DKL(t) vector
set nframes = call traj_nslice u teq tsample
set DKL_t = zeros nframes
comment define polymer and tracers
set polymer = call select_atoms polymer_text
set tracers = call select_atoms tracer_text... | def tracers_analysis (sim,polymer_text,tracer_text,teq,tsample,t_threshold,p_threshold) :
# define DKL(t) vector
nframes = traj_nslice(sim.u,teq,tsample)
DKL_t = np.zeros(nframes)
# define polymer and tracers
polymer = sim.u.select_atoms(polymer_text)
tracers = sim.u.select_atoms(tracer_text)
... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python
import threading
import time
class SerialException extends Exception
begin
pass
end class
class Serial extends Thread
begin
function __init__ self start_deamon=false
begin
call reset
call __init__ self
set daemon = true
if start_deamon == true
begin
start self
end
end function
function run sel... | #! /usr/bin/python
import threading
import time
class SerialException(Exception):
pass
class Serial(threading.Thread):
def __init__(self, start_deamon = False):
self.reset()
threading.Thread.__init__(self)
self.daemon=True
if start_deamon == True:
self.start()
... | Python | zaydzuhri_stack_edu_python |
function setUpClass cls
begin
set user = call User
set first_name = string Pichu
set last_name = string Otegui
set email = string correo@hbtn.com
set storage = call FileStorage
end function | def setUpClass(cls):
cls.user = User()
cls.user.first_name = "Pichu"
cls.user.last_name = "Otegui"
cls.user.email = "correo@hbtn.com"
cls.storage = FileStorage() | Python | nomic_cornstack_python_v1 |
function __init__ self root_path transformer=none phase=string train
begin
call __init__
set root_path = root_path
set phase = phase
set A_paths = list
set B_paths = list
set A_paths = call mk_img_paths join path root_path phase + string A
set B_paths = call mk_img_paths join path root_path phase + string B
if transf... | def __init__(self, root_path, transformer=None, phase='train'):
super(UnalignedDataset, self).__init__()
self.root_path = root_path
self.phase = phase
self.A_paths = []
self.B_paths = []
self.A_paths = mk_img_paths(os.path.join(root_path, phase + 'A'))
self.B_path... | Python | nomic_cornstack_python_v1 |
import unittest
from selenium import webdriver
import time
class TestsLessonTen extends TestCase
begin
function test_1 self
begin
set link = string http://suninjuly.github.io/registration1.html
set browser = call Chrome
get browser link
set input1 = call find_element_by_xpath string //input[@class='form-control first' ... | import unittest
from selenium import webdriver
import time
class TestsLessonTen(unittest.TestCase):
def test_1(self):
link = "http://suninjuly.github.io/registration1.html"
browser = webdriver.Chrome()
browser.get(link)
input1 = browser.find_element_by_xpath("//input[@class='form-... | Python | zaydzuhri_stack_edu_python |
function test_get_number_audio_tracks self
begin
with call path string tests.resources.media string dummy.mkv as file
begin
set parser = parse MediainfoMetadataParser call Path file
end
assert equal call get_audio_tracks_count 2
end function | def test_get_number_audio_tracks(self):
with path("tests.resources.media", "dummy.mkv") as file:
parser = MediainfoMetadataParser.parse(Path(file))
self.assertEqual(parser.get_audio_tracks_count(), 2) | Python | nomic_cornstack_python_v1 |
function run self input_string
begin
set states = call reachable_states_with_multi_eps_from initial_state
for character in input_string
begin
if character not in alphabet
begin
print string ERROR: %s not in alphabet % character
return false
end
else
begin
set states = call next_states states character
end
end
return le... | def run(self, input_string):
states = self.reachable_states_with_multi_eps_from(self.initial_state)
for character in input_string:
if character not in self.alphabet:
print("ERROR: %s not in alphabet" % character)
return False
else:
... | Python | nomic_cornstack_python_v1 |
function applications self
begin
return get pulumi self string applications
end function | def applications(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "applications") | Python | nomic_cornstack_python_v1 |
function _posNegRandom self
begin
return random * 2 - 1.0
end function | def _posNegRandom(self):
return random.random() * 2 - 1.0 | Python | nomic_cornstack_python_v1 |
from products.models import Products , Favorites as FavoritesModel
import json
class Favorites
begin
function __init__ self user session
begin
set _user = user
set _session = session
set _data = get session string favorites dict
end function
function add self item_id
begin
set item_id_key = string item_id
set product =... | from products.models import Products, Favorites as FavoritesModel
import json
class Favorites:
def __init__(self, user, session):
self._user = user
self._session = session
self._data = session.get('favorites', {})
def add(self, item_id):
item_id_key = str(item_id)
prod... | Python | zaydzuhri_stack_edu_python |
function _parse_operator self
begin
set string = join string buffer
set negated = ends with string string not
if not strip string string
begin
set params = tuple false 1 1
end
else
if strip string == string not
begin
set params = tuple true 1 1
end
else
if match string
begin
set params = tuple negated 0 1
end
else
if ... | def _parse_operator(self) -> Tuple:
string = "".join(self.buffer)
negated = string.endswith("not")
if not string.strip("\t\n\r "):
params = False, 1, 1
elif string.strip() == "not":
params = True, 1, 1
elif OPTION_RE.match(string):
params = neg... | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import csv
import urllib3
comment Librería para eliminar saltos de linea en reclamos
import re
set f = open string Salida.csv string w encoding=string utf-8
comment Los valores de range son (página inicial, página final)
for i in range 146 500
begin
set http = call PoolManager
set url1 = s... | from bs4 import BeautifulSoup
import csv
import urllib3
import re #Librería para eliminar saltos de linea en reclamos
f = open('Salida.csv', 'w', encoding='utf-8')
for i in range(146,500): #Los valores de range son (página inicial, página final)
http = urllib3.PoolManager()
url1 = 'https://www.reclamos.cl/tel... | Python | zaydzuhri_stack_edu_python |
from random import randint , choice
from jogo import lixeiras_imagens_tipos
import pygame
set tipos_imagens = lixeiras_imagens_tipos
function iniciar_lixeiras lixeiras_dict
begin
set seq_nums = list range 1 6
for tuple tipo lx in items lixeiras_dict
begin
set seq = random choice seq_nums
remove seq_nums seq
set lixeira... | from random import randint, choice
from jogo import lixeiras_imagens_tipos
import pygame
tipos_imagens = lixeiras_imagens_tipos
def iniciar_lixeiras(lixeiras_dict):
seq_nums = list(range(1, 6))
for tipo, lx in lixeiras_dict.items():
seq = choice(seq_nums)
seq_nums.remove(seq)
lixeira = ... | Python | zaydzuhri_stack_edu_python |
function test_login self
begin
set driver = driver
comment login
call login_test driver string admin string password
comment wait for the next page, and fill the configuration only if needed
try
begin
call until call presence_of_element_located tuple ID string dashboard
call logout_test
end
except any
begin
call until ... | def test_login(self):
driver = self.driver
# login
bell.login_test(self.driver, "admin", "password")
# wait for the next page, and fill the configuration only if needed
try:
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "dash... | Python | nomic_cornstack_python_v1 |
import os
from PIL import Image
function make_gif image_paths gif_save_path
begin
string save into a GIF file that loops forever :param image_paths: list of paths of the images :param gif_save_path: the save path of the gif :return: None
set gif_dir = directory name path gif_save_path
if not is directory path gif_dir
b... | import os
from PIL import Image
def make_gif(image_paths, gif_save_path):
"""
save into a GIF file that loops forever
:param image_paths: list of paths of the images
:param gif_save_path: the save path of the gif
:return: None
"""
gif_dir = os.path.dirname(gif_save_path)
if not os.path... | Python | zaydzuhri_stack_edu_python |
from time import sleep
import time
import datetime
import serial
import sys
import pandas as pd
import sqlalchemy as sql
import re
set master_mode = string testing
comment master_mode = 'operation'
set readline_buffer = 500
comment *****************
comment SERIAL CONNECTION
comment *****************
comment Serial con... | from time import sleep
import time
import datetime
import serial
import sys
import pandas as pd
import sqlalchemy as sql
import re
master_mode = 'testing'
# master_mode = 'operation'
readline_buffer = 500
# *****************
# SERIAL CONNECTION
# *****************
# Serial connection to the microwave generator
mic... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from cpp_base import *
import random
class CppGenerator
begin
function __init__ self tpl_folder_path
begin
string c++相关的生成器 :param tpl_folder_path:
set tpl_folder_path = tpl_folder_path
end function
decorator staticmethod
function generate_field tpl_folder_path field_name=none field_type=n... | # -*- coding: utf-8 -*-
from cpp_base import *
import random
class CppGenerator:
def __init__(self, tpl_folder_path):
"""
c++相关的生成器
:param tpl_folder_path:
"""
self.tpl_folder_path = tpl_folder_path
@staticmethod
def generate_field(tpl_folder_path, field_name=None,... | Python | zaydzuhri_stack_edu_python |
function get_uppercase_words string
begin
set words = list
set word = string
for char in string
begin
if char == string
begin
if word != string
begin
append words word
set word = string
end
end
else
if is upper char
begin
set word = word + char
end
end
if word != string
begin
append words word
end
return words
en... | def get_uppercase_words(string: str) -> List[str]:
words = []
word = ""
for char in string:
if char == " ":
if word != "":
words.append(word)
word = ""
elif char.isupper():
word += char
if word != "":
words.append(word)
... | Python | greatdarklord_python_dataset |
import os
from xlrd import open_workbook
import json
import re
from tqdm import tqdm
set json_file_name_USDA = join path get current directory string USDA_DB string USDA_DB.json
set json_file_name_USDA_items = join path get current directory string USDA_DB string USDA_DB_items.json
set USDA_path = join path get current... | import os
from xlrd import open_workbook
import json
import re
from tqdm import tqdm
json_file_name_USDA = os.path.join(os.getcwd(), 'USDA_DB', 'USDA_DB.json')
json_file_name_USDA_items = os.path.join(os.getcwd(), 'USDA_DB', 'USDA_DB_items.json')
USDA_path = os.path.join(os.getcwd(), 'USDA_DB', 'ABBREV.xlsx')
NUTTAB_p... | Python | zaydzuhri_stack_edu_python |
function _create_template_flight_object self row
begin
set tflight_id = row at string tflight_id
set origin = row at string origin
set destination = row at string destination
set depTime = row at string depTime
set arrTime = row at string arrTime
set templateflight = dict string searchid tflight_id ; string origin orig... | def _create_template_flight_object(self, row):
tflight_id =row['tflight_id']
origin = row['origin']
destination = row['destination']
depTime = row['depTime']
arrTime=row['arrTime']
templateflight = {'searchid': tflight_id,
'origin': origin,
... | Python | nomic_cornstack_python_v1 |
function prob_4_3 self
begin
set img = call imread string inputPS1Q4.jpg
set img = img / 255.0
comment START CODE HERE ######
comment plt.imshow(img)
set HSV = zeros like img
for i in range shape at 0
begin
for j in range shape at 1
begin
set rgb = img at tuple i j
set r = rgb at 0
set g = rgb at 1
set b = rgb at 2
set... | def prob_4_3(self):
img = io.imread('inputPS1Q4.jpg')
img = img / 255.0
###### START CODE HERE ######
#plt.imshow(img)
HSV= np.zeros_like(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
rgb=img[i,j]
... | Python | nomic_cornstack_python_v1 |
set most_used_language = string Python | most_used_language = "Python" | Python | jtatman_500k |
import random
import numpy as np
import sys
import os
import tkinter as tk
class PicPuzzle
begin
function __init__ self level
begin
set LEVEL = level
set game_end = false
set num2 = 0
call resetArr
set arr = array random sample range LEVEL * LEVEL LEVEL * LEVEL
comment arr = np.array([1, 2, 3, 4, 5, 6, 7, 0, 8]) # for ... | import random
import numpy as np
import sys
import os
import tkinter as tk
class PicPuzzle:
def __init__(self, level):
self.LEVEL = level
self.game_end = False
self.num2 = 0
self.resetArr()
arr = np.array(random.sample(
range(self.LEVEL*self.LEVEL), self.LEVE... | Python | zaydzuhri_stack_edu_python |
function airydisk unit_r fno wavelength
begin
set u_eff = unit_r * pi / wavelength / fno
return absolute 2 * call jinc u_eff ^ 2
end function | def airydisk(unit_r, fno, wavelength):
u_eff = unit_r * np.pi / wavelength / fno
return abs(2 * jinc(u_eff)) ** 2 | Python | nomic_cornstack_python_v1 |
comment Check if key exist in dictionary
set my_dict = dict string a 1 ; string b 2 ; string c 3
set key = string d
print key in my_dict | # Check if key exist in dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
key = 'd'
print(key in my_dict)
| Python | zaydzuhri_stack_edu_python |
import scipy.io , os
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import LeaveOneOut
import matplotlib.pyplot as plt
from scipy import stats
function load_data file_prefix class_1_indices class_2_indices normalize
begin
set time_points = list comprehension list for x in range 1301
set la... | import scipy.io, os
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import LeaveOneOut
import matplotlib.pyplot as plt
from scipy import stats
def load_data(file_prefix, class_1_indices, class_2_indices, normalize):
time_points = [[] for x in range(1301)]
labels = [[] for x in rang... | Python | zaydzuhri_stack_edu_python |
import struct
import binascii
set f = open string postcodes_1618.csv
set headings = read line f
set g = open string postcode_installs.bin string wb
set nlines = 0
for line in read lines f
begin
set cells = split line string ,
set postcode = strip cells at 0 string "
if length postcode != 4
begin
set postcode = string x... | import struct
import binascii
f = open("postcodes_1618.csv")
headings = f.readline()
g = open("postcode_installs.bin", "wb")
nlines = 0
for line in f.readlines():
cells = line.split(",")
postcode = cells[0].strip('"')
if len(postcode) != 4:
postcode = "xxxx"
print(line)
continue
try:
install... | Python | zaydzuhri_stack_edu_python |
function test_sign self
begin
function f x
begin
set v1 = x ^ 3 + 3.0
set y = call sign v1
return y
end function
comment use CGraph
set cg = call CGraph
set x = call Function array list 0.2
set y = f dist x
set independentFunctionList = list x
set dependentFunctionList = list y
set result1 = call jac_vec array list 0.2... | def test_sign(self):
def f(x):
v1 = x**3 + 3.0
y = algopy.sign(v1)
return y
# use CGraph
cg = CGraph()
x = Function(numpy.array([0.2]))
y = f(x)
cg.independentFunctionList = [x]
cg.dependentFunctionList = [y]
result... | Python | nomic_cornstack_python_v1 |
from models.Order import Order
from controllers.User import UserController
from controllers.Product import ProductController
from datetime import datetime
class OrderController
begin
comment Método construtor da classe UserController.
function __init__ self
begin
comment Inicializa uma instância de User().
set order_mo... | from models.Order import Order
from controllers.User import UserController
from controllers.Product import ProductController
from datetime import datetime
class OrderController():
# Método construtor da classe UserController.
def __init__(self):
# Inicializa uma instância de User().
self.order... | Python | zaydzuhri_stack_edu_python |
comment noqa: E501 # noqa: E501
function __init__ self **kwargs
begin
set local_vars_configuration = get kwargs string local_vars_configuration call get_default_copy
set __and = none
set _cluster = none
set _id = none
set _id_contains = none
set _id_ends_with = none
set _id_gt = none
set _id_gte = none
set _id_in = non... | def __init__(self, **kwargs): # noqa: E501 # noqa: E501
self.local_vars_configuration = kwargs.get("local_vars_configuration", Configuration.get_default_copy())
self.__and = None
self._cluster = None
self._id = None
self._id_contains = None
self._id_ends_with = None
... | Python | nomic_cornstack_python_v1 |
function legacyEvent self *message **values
begin
set event = copy get context ILogContext or dict
update event values
set event at string message = message
set event at string time = time
if string isError not in event
begin
set event at string isError = 0
end
return event
end function | def legacyEvent(self, *message, **values):
event = (context.get(legacyLog.ILogContext) or {}).copy()
event.update(values)
event["message"] = message
event["time"] = time()
if "isError" not in event:
event["isError"] = 0
return event | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string File Name : /home/nathan/.workspace/pyconcile-tools/src/pyconcile/pronoun_heuristics.py Purpose : Creation Date : May 13, 2011 Last Modified : Wed 01 Jun 2011 03:08:36 PM MDT @author: nathan
from collections import defaultdict
from operator import itemgetter
from import reconcile
from ... | #!/usr/bin/python
"""
File Name : /home/nathan/.workspace/pyconcile-tools/src/pyconcile/pronoun_heuristics.py
Purpose :
Creation Date : May 13, 2011
Last Modified : Wed 01 Jun 2011 03:08:36 PM MDT
@author: nathan
"""
from collections import defaultdict
from operator import itemgetter
from . import reconcile
from . im... | Python | zaydzuhri_stack_edu_python |
string Functions in this file getthresholdedimg(im) track_data(frame) optimize_mouse_center(old_center,new_center) filter_fingers(data) find_center(centers)
import cv
from basic import dummy_object
import config
import numpy as N
function getthresholdedimg im color_range
begin
set imghsv = call CreateImage get size cv ... | """
Functions in this file
getthresholdedimg(im)
track_data(frame)
optimize_mouse_center(old_center,new_center)
filter_fingers(data)
find_center(centers)
"""
import cv
from basic import dummy_object
import config
import numpy as N
def getthresholdedimg(im,color_range):
imghsv=cv.CreateImage(cv.G... | Python | zaydzuhri_stack_edu_python |
import json
import argparse
from pprint import pprint
from exchanges.coinbase_pkg import Coinbase
function get_config
begin
with open string config.json as f
begin
return load json f
end
end function
function validate_input config user
begin
if user not in config
begin
raise call ValueError string User not defined in c... | import json
import argparse
from pprint import pprint
from exchanges.coinbase_pkg import Coinbase
def get_config():
with open("config.json") as f:
return json.load(f)
def validate_input(config, user):
if user not in config:
raise ValueError("User not defined in config")
def main():
par... | Python | zaydzuhri_stack_edu_python |
comment coding=utf8
import numpy as np
import pandas as pd
import lightgbm as lgb
import matplotlib.pyplot as plt
set RS = 20170501
seed RS
set ROUNDS = 50
set params = dict string objective string regression ; string metric string rmse ; string boosting string gbdt ; string learning_rate 0.04 ; string verbose 0 ; stri... | # coding=utf8
import numpy as np
import pandas as pd
import lightgbm as lgb
import matplotlib.pyplot as plt
RS = 20170501
np.random.seed(RS)
ROUNDS = 50
params = {
'objective': 'regression',
'metric': 'rmse',
'boosting': 'gbdt',
'learning_rate': 0.04,
'verbose': 0,
'num_leaves': 2 ** 5,
'bagg... | Python | zaydzuhri_stack_edu_python |
function obtener_datos
begin
import pickle
import os
set dir_actual = get current directory
set ubicacion_archivo = dir_actual + string /Data/Files/ + string partidaguardada.obj
set f = open ubicacion_archivo string rb
set datos = load pickle f
set nivel = pop datos
close f
return list nivel datos
end function | def obtener_datos():
import pickle
import os
dir_actual = os.getcwd()
ubicacion_archivo = (dir_actual+'/Data/Files/'+'partidaguardada.obj')
f = open(ubicacion_archivo,'rb')
datos = pickle.load(f)
nivel = datos.pop()
f.close()
return [nivel,datos] | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup as BS
import codecs
set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 5.1; rv:47.0) Gecko/20100101 Firefox/47.0 ; string Accept string text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
set url = string https://www.work.ua/ru/jobs-kyiv-python/... | import requests
from bs4 import BeautifulSoup as BS
import codecs
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:47.0) Gecko/20100101 Firefox/47.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}
url = 'https://www.work.ua/ru/jobs-kyiv-python/'
resp = re... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import config
set tam = call tam
set cant = call cant
function gaussiana clase centro varianza
begin
set valores = list
for i in call xrange 0 tam
begin
append valores call normal centro at i varianza cant
end
set X = list
for i in call xrange 0 cant
begin
set vector = list
for j in call xrange 0 ... | import numpy as np
import config
tam = config.tam()
cant = config.cant()
def gaussiana(clase,centro,varianza):
valores = []
for i in xrange(0,tam):
valores.append(np.random.normal(centro[i],varianza,cant))
X = []
for i in xrange(0,cant):
vector = []
for j in xrange(0,tam):
vector.append(valores[j][i]... | Python | zaydzuhri_stack_edu_python |
function prepend_environment_variable self key value
begin
set script_keys = dict string k key ; string v value
set script = format string $env:{k} = "{v};$env:{k}" keyword script_keys
call _printer script
end function | def prepend_environment_variable(self, key, value):
script_keys = {
"k": key,
"v": value
}
script = "$env:{k} = \"{v};$env:{k}\"".format(**script_keys)
self._printer(script) | Python | nomic_cornstack_python_v1 |
comment ejercicio1 = delete repet element
set list1 = list 1 5 6 7 8 9 4 3 2 5 8 7 9 5 4 6 5 1 2 3 5 8 7 9
print list1
set list1 = list set list1
print list1 | # ejercicio1 = delete repet element
list1 = [1,5,6,7,8,9,4,3,2,5,8,7,9,5,4,6,5,1,2,3,5,8,7,9]
print(list1)
list1 = list(set(list1))
print(list1)
| Python | zaydzuhri_stack_edu_python |
function ProcessOptions options api=false
begin
comment Dictionary of command options, with defaults
set command_options = dict
set command_options at string verbose = false
set command_options at string stdout = false
set command_options at string no_output_file = false
set command_options at string datasources = non... | def ProcessOptions(options, api=False):
# Dictionary of command options, with defaults
command_options = {}
command_options['verbose'] = False
command_options['stdout'] = False
command_options['no_output_file'] = False
command_options['datasources'] = None
command_options['commands_path'] = None
# Us... | Python | nomic_cornstack_python_v1 |
function get_profile self
begin
if not has attribute self string _profile_cache
begin
try
begin
set model = if expression is_employer then EmployerProfile else DeveloperProfile
set _profile_cache = get call using db user__id__exact=id
set user = self
end
except tuple ImportError ImproperlyConfigured
begin
raise SitePro... | def get_profile(self):
if not hasattr(self, '_profile_cache'):
try:
model = EmployerProfile if self.is_employer else DeveloperProfile
self._profile_cache = model._default_manager.using(
self._state.db).get(user__id__exact=self.id)
... | Python | nomic_cornstack_python_v1 |
import os
import re
import linecache
string SUM GRADER Author: Kaelin D. Hooper This Python script traverses all student directories, scavenging for their feedback.txt files, and sums the design and documentation grades in each of them. The result is an output pairing each student's eid with their overall grade. This h... | import os
import re
import linecache
"""
SUM GRADER
Author: Kaelin D. Hooper
This Python script traverses all student directories, scavenging for their
feedback.txt files, and sums the design and documentation grades in each of them.
The result is an output pairing each student's eid with their overall grade. This
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string KMP的匹配是从模式串的开头开始匹配的,而1977年, 德克萨斯大学的Robert S. Boyer教授和J Strother Moore教授 发明了一种新的字符串匹配算法:Boyer-Moore算法,简称BM算法。 该算法从模式串的尾部开始匹配,且拥有在最坏情况下O(N)的时间复杂度。 在实践中,比KMP算法的实际效能高。 推荐阅读: https://blog.csdn.net/wjy0330/article/details/39589743 | # -*- coding: utf-8 -*-
"""
KMP的匹配是从模式串的开头开始匹配的,而1977年,
德克萨斯大学的Robert S. Boyer教授和J Strother Moore教授
发明了一种新的字符串匹配算法:Boyer-Moore算法,简称BM算法。
该算法从模式串的尾部开始匹配,且拥有在最坏情况下O(N)的时间复杂度。
在实践中,比KMP算法的实际效能高。
推荐阅读:
https://blog.csdn.net/wjy0330/article/details/39589743
"""
| Python | zaydzuhri_stack_edu_python |
import adminhome
import safebox
import userhome
function valid v
begin
print string call center 30 if expression v == 1 then string x else string - string
comment user login
if v != 1
begin
print string 1. New Registration 2. Login
while true
begin
set use = input string Enter a choice...
try
begin
if use in list stri... | import adminhome
import safebox
import userhome
def valid(v):
print("\n",(' Admin Login ' if v==1 else " User Login").center(30,('x'if v==1 else '-')),"\n")
if v!=1: #user login
print('\n1. New Registration\n2. Login')
while True:
use = input('\nEnter a choice... '... | Python | zaydzuhri_stack_edu_python |
function make_snapshot self snapshot_name
begin
set url = call get_url string ontap/snapshots/
set headers = call get_headers
set data = dict string volume_key call get_key_vol ; string name snapshot_name
set response = post url headers=headers json=data verify=false
if call check_http_response response 202
begin
set j... | def make_snapshot(self, snapshot_name):
url = self.aggregate.api_server.get_url("ontap/snapshots/")
headers = self.aggregate.api_server.get_headers()
data = {
"volume_key": self.get_key_vol(),
"name": snapshot_name,
}
response = requests.post(url, header... | Python | nomic_cornstack_python_v1 |
function __init__ self version=string 1.0.0 hint=none label=none validation=none content=none theme=none
begin
Ellipsis
end function | def __init__(self, *, version: Optional[str] = '1.0.0', hint: Optional[Any] = None, label: Optional[Any] = None, validation: Optional[BaseComponent] = None, content: Optional[BaseComponent] = None, theme: Optional[Union[BaseComponent, Theme]] = None) -> None:
... | Python | nomic_cornstack_python_v1 |
if t > 0 and t <= 100
begin
for i in range 0 t
begin
set dataset = input
set tuple s_max audiance = split dataset string
set tuple s_max audiance = tuple integer s_max string audiance
set total = integer audiance at 0
set missing = 0
if s_max >= 0 and s_max <= 1000
begin
for j in range 1 s_max + 1
begin
if j <= total
b... | if t > 0 and t <= 100:
for i in range(0, t):
dataset = input()
s_max, audiance = dataset.split(" ")
s_max, audiance = int(s_max), str(audiance)
total = int(audiance[0])
missing = 0
if s_max >= 0 and s_max <= 1000:
for j in range(1, s_max+... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment ######################################################################### ##
comment script to close a window and focus the next available window
comment ######################################################################### ##
comment ===============================================... | #!/usr/bin/python3
## ######################################################################### ##
## script to close a window and focus the next available window
## ######################################################################### ##
## ========================================================================... | Python | zaydzuhri_stack_edu_python |
function item_error self item exception response spider
begin
return dict string level ERROR ; string msg ITEMERRORMSG ; string args dict string item item at string lom
end function | def item_error(self, item, exception, response, spider):
return {
"level": logging.ERROR,
"msg": self.ITEMERRORMSG,
"args": {"item": item["lom"],},
} | Python | nomic_cornstack_python_v1 |
import random
import time
import sys
import textwrap
import story_text
import first_choice_text
import search_room_text
import search_door_text
import search_bed_text
import search_end_table_text
import search_art_text
import search_tablet_text
from check_exit import check_exit
comment BIG HOUSE BREAKOUT ##############... | import random
import time
import sys
import textwrap
import story_text
import first_choice_text
import search_room_text
import search_door_text
import search_bed_text
import search_end_table_text
import search_art_text
import search_tablet_text
from check_exit import check_exit
############# BIG HOUSE BREAKOUT #######... | Python | zaydzuhri_stack_edu_python |
comment How to use:
comment Copy a csv that has one column of names into the same folder as this python program.
comment Name the csv names.csv
comment Run the python program.
comment It should create a csv called contact_info.csv as an output.
comment Improvements to be implemented:
comment Handling error 404
comment ... | # How to use:
# Copy a csv that has one column of names into the same folder as this python program.
# Name the csv names.csv
# Run the python program.
# It should create a csv called contact_info.csv as an output.
# Improvements to be implemented:
# Handling error 404
# Handling exception 429
# M... | Python | zaydzuhri_stack_edu_python |
function inc self key
begin
if key in keyCnt
begin
call changeKey key 1
end
else
begin
set keyCnt at key = 1
comment 说明没有计数为1的节点,在self.head后面加入
if cnt != 1
begin
call addNodeAfter call Node 1 head
end
add keySet key
set cntKey at 1 = next
end
end function | def inc(self, key: str) -> None:
if key in self.keyCnt:
self.changeKey(key, 1)
else:
self.keyCnt[key] = 1
# 说明没有计数为1的节点,在self.head后面加入
if self.head.next.cnt != 1:
self.addNodeAfter(Node(1), self.head)
self.head.next.keySet.add(k... | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function maximumWealth self accounts
begin
set answer = 0
for account in accounts
begin
set answer = max answer sum account
end
return answer
end function
end class
function test
begin
set solution = call Solution
assert call maximumWealth list list 1 2 3 list 3 2 1 == 6
ass... | from typing import List
class Solution:
def maximumWealth(self, accounts: List[List[int]]) -> int:
answer = 0
for account in accounts:
answer = max(answer, sum(account))
return answer
def test():
solution = Solution()
assert solution.maximumWealth([[1, 2, 3], [3, 2... | Python | zaydzuhri_stack_edu_python |
function test_s3_12v08_s3_12v08i mode save_output output_format
begin
call assert_bindings schema=string ibmData/valid/S3_12/s3_12v08.xsd instance=string ibmData/valid/S3_12/s3_12v08.xml class_name=string Root version=string 1.1 mode=mode save_output=save_output output_format=output_format structure_style=string filena... | def test_s3_12v08_s3_12v08i(mode, save_output, output_format):
assert_bindings(
schema="ibmData/valid/S3_12/s3_12v08.xsd",
instance="ibmData/valid/S3_12/s3_12v08.xml",
class_name="Root",
version="1.1",
mode=mode,
save_output=save_output,
output_format=output_f... | Python | nomic_cornstack_python_v1 |
function __act__ self t
begin
return max AA key=lambda a -> call get_value + c * square root log t + 1 / call get_denominator a
end function | def __act__(
self,
t: int
) -> Action:
return max(self.most_recent_state.AA, key=lambda a: self.Q[a].get_value() + self.c * math.sqrt(math.log(t + 1) / self.get_denominator(a))) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python2
import random
string War Card Game
class player
begin
function __init__ self
begin
print string 1. Class || Player || Running
end function
function create_cards self
begin
call create_deck
end function
function get_hand self
begin
set hand = call distribute_cards
return hand
end function
end c... | #!/usr/bin/python2
import random
''' War Card Game'''
class player:
def __init__(self):
print("1. Class || Player\t || Running")
def create_cards(self):
deck().create_deck()
def get_hand(self):
self.hand = self.player.distribute_cards()
return self.hand
class deck:
... | Python | zaydzuhri_stack_edu_python |
function create_db
begin
call create_all
end function | def create_db():
db.create_all() | Python | nomic_cornstack_python_v1 |
for i in range 5
begin
set out = out + n
print out end=string
end | for i in range(5):
out=out+n;
print(out,end=" ")
| Python | zaydzuhri_stack_edu_python |
from fractions import Fraction
set NM = list map int split input string
set NM = sorted NM
set m = NM at 0 - 1
set n = NM at 1 - 1
set a = call Fraction m n
set k = integer m / numerator
if n % m == 0
begin
print n
end
else
if integer m / numerator == m
begin
print k
print n + m - 1
end
else
begin
print integer k * m /... | from fractions import Fraction
NM = list(map(int, input().split(' ')))
NM = sorted(NM)
m = NM[0] - 1
n = NM[1] - 1
a = Fraction(m, n)
k = int(m/a.numerator)
if n%m == 0:
print(n)
elif int(m/a.numerator) == m:
print(k)
print(n + m - 1)
else:
print(int(k*(m/k + n/k -1)))
| Python | zaydzuhri_stack_edu_python |
function move_marbles self play_coord player direction current_marble next_board=none
begin
set play_row = play_coord at 0
set play_col = play_coord at 1
set neut_marble_captured = false
set own_marble_captured = false
comment at the start of the recursion copy the board to next_board so that we modify next_board inste... | def move_marbles(self, play_coord, player, direction, current_marble, next_board=None):
play_row = play_coord[0]
play_col = play_coord[1]
neut_marble_captured = False
own_marble_captured = False
# at the start of the recursion copy the board to next_board so that we modi... | Python | nomic_cornstack_python_v1 |
import pygame
import random
set width = 1000
set height = 500
set screen = call set_mode tuple width height
set black = tuple 0 0 0
set white = tuple 255 255 255
set red = tuple 255 0 0
set color_1 = tuple 100 105 150
class Player extends Sprite
begin
function __init__ self
begin
call __init__ self
set image = call Sur... | import pygame
import random
width = 1000
height = 500
screen = pygame.display.set_mode((width,height))
black = 0,0,0
white = 255,255,255
red = 255,0,0
color_1 = 100,105,150
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = py... | Python | zaydzuhri_stack_edu_python |
for i in range 1 length a_li
begin
set move = move + a_li at i - a_li at i - 1
end
print move | for i in range(1, len(a_li)):
move += a_li[i] - a_li[i-1]
print(move)
| Python | zaydzuhri_stack_edu_python |
function hit self timestamp
begin
append time_stamps timestamp
end function | def hit(self, timestamp: int) -> None:
self.time_stamps.append(timestamp) | Python | nomic_cornstack_python_v1 |
import sys
set myvar = string hell!
set a = string La
set b = string Historia
set c = string de
set d = string Napoleon
print a b c d | import sys
myvar = 'hell!'
a = 'La'
b = 'Historia'
c = 'de'
d = 'Napoleon'
print(a,b,c,d) | 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.