code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function full first last
begin
return first + string + last
end function
function main
begin
set first = input string Enter first name:
set last = input string Enter last name:
print call full first last
end function
if __name__ == string __main__
begin
call main
end | def full(first, last):
return first + " " + last
def main():
first = input("Enter first name: ")
last = input("Enter last name: ")
print(full(first, last))
if __name__ == "__main__":
main()
| Python | zaydzuhri_stack_edu_python |
function task_specific_attention self inputs output_size initializer=call xavier_initializer activation_fn=tanh scope=none
begin
assert length call get_shape == 3 and value is not none
with call variable_scope scope or string attention as scope
begin
comment u_w, attention 向量
set attention_context_vector = call get_var... | def task_specific_attention(self, inputs, output_size,
initializer=layers.xavier_initializer(),
activation_fn=tf.tanh, scope=None):
assert len(inputs.get_shape()) == 3 and inputs.get_shape()[-1].value is not None
with tf.variable_scope(scop... | Python | nomic_cornstack_python_v1 |
function first_two str
begin
if length str < 2
begin
return str
end
else
begin
return str at slice : 2 :
end
end function
print call first_two string A
print call first_two string A
print call first_two string Arya | def first_two(str):
if len(str) < 2:
return str
else:
return str[:2]
print(first_two('A'))
print(first_two('A'))
print(first_two('Arya'))
| Python | zaydzuhri_stack_edu_python |
function local_pow_specialize_device node
begin
if op == pow
begin
comment the idea here is that we have pow(x, y)
set odtype = dtype
set xsym = inputs at 0
set ysym = inputs at 1
set y = call get_constant ysym
comment the next line is needed to fix a strange case that I don't
comment know how to make a separate test.
... | def local_pow_specialize_device(node):
if node.op == T.pow:
# the idea here is that we have pow(x, y)
odtype = node.outputs[0].dtype
xsym = node.inputs[0]
ysym = node.inputs[1]
y = local_mul_canonizer.get_constant(ysym)
# the next line is needed to fix a strange case... | Python | nomic_cornstack_python_v1 |
function test_model_delete
begin
set tuple model signal_handler = call mock_signal_handler delete
set instance = call create title=string beer
set instance_pk = pk
delete
assert call_count == 1
assert call_args at 1 at string pk == instance_pk
end function | def test_model_delete():
model, signal_handler = mock_signal_handler(signals.delete)
instance = model.objects.create(title="beer")
instance_pk = instance.pk
instance.delete()
assert signal_handler.call_count == 1
assert signal_handler.call_args[1]["pk"] == instance_pk | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import data_script
import requests
import csv
from statistics import mean
comment prompt for URL
print string Paste the full URL of your ebay search results below:
set ebay_url = input string >
comment retrieve mattress listings from first page on ebay
set html_text = text
set soup = call ... | from bs4 import BeautifulSoup
import data_script
import requests
import csv
from statistics import mean
# prompt for URL
print('Paste the full URL of your ebay search results below:')
ebay_url = input('> ')
# retrieve mattress listings from first page on ebay
html_text = requests.get(ebay_url).text
soup = BeautifulSo... | Python | zaydzuhri_stack_edu_python |
function parseProfile html todaysDate=call date
begin
set data = dict
set docRoot = call fromstring html
comment Pull the member ID
set pLink = attrib at string href
set data at string id = integer split split pLink string u= at 1 string ; at 0
comment Pull associated information
set infoTable = call cssselect string ... | def parseProfile(html, todaysDate=datetime.utcnow().date()):
data = {}
docRoot = lxml.html.fromstring(html)
# Pull the member ID
pLink = docRoot.cssselect("#bodyarea td.windowbg2 > a")[0].attrib['href']
data['id'] = int(pLink.split("u=")[1].split(";")[0])
# Pull associated information
inf... | Python | nomic_cornstack_python_v1 |
set a = dict string ind 100 ; string china 200 ; string nz 10 ; string wi 40 ; string aus 35
set w = sorted a key=get
print w
set c = sorted a key=get reverse=true
print c | a={"ind":100,"china":200,"nz":10,"wi":40,"aus":35}
w=sorted(a,key=a.get)
print(w)
c=sorted(a,key=a.get,reverse=True)
print(c) | Python | zaydzuhri_stack_edu_python |
function isBusy self
begin
return busy
end function | def isBusy(self):
return self.busy | Python | nomic_cornstack_python_v1 |
function runtime_version self
begin
return get pulumi self string runtime_version
end function | def runtime_version(self) -> Optional[str]:
return pulumi.get(self, "runtime_version") | Python | nomic_cornstack_python_v1 |
string --------------------------------------------------------------------------------------------------- Description : Non Recursive Quick Sort Algorithm. Taken from the book. Author : Arturo Alatriste Trujillo. References : Object Oriented C++ Data Structures for Real Programmers by Jan Harrington. Morgan Kaufmann. ... | '''
---------------------------------------------------------------------------------------------------
Description : Non Recursive Quick Sort Algorithm. Taken from the book.
Author : Arturo Alatriste Trujillo.
References :
Object Oriented C++ Data Structures for Real Programmers
by Jan Harringt... | Python | zaydzuhri_stack_edu_python |
function process_fastq_single_end_read_file fastq_read_f fastq_barcode_f barcode_to_sample_id store_unassigned=false max_bad_run_length=0 phred_quality_threshold=2 min_per_read_length_fraction=0.75 rev_comp=false rev_comp_barcode=false seq_max_N=0 start_seq_id=0 filter_bad_illumina_qual_digit=false log_f=none histogram... | def process_fastq_single_end_read_file(fastq_read_f,
fastq_barcode_f,
barcode_to_sample_id,
store_unassigned=False,
max_bad_run_length=0,
... | Python | nomic_cornstack_python_v1 |
function get_zoomlevels_list slideRef sessionID=none min_number_of_tiles=0
begin
return sorted list keys call get_zoomlevels_dict slideRef sessionID min_number_of_tiles
end function | def get_zoomlevels_list(slideRef, sessionID=None, min_number_of_tiles=0):
return sorted(list(get_zoomlevels_dict(slideRef, sessionID, min_number_of_tiles).keys())) | Python | nomic_cornstack_python_v1 |
function MultiAppend self value_timestamp_pairs
begin
for tuple value timestamp in value_timestamp_pairs
begin
append self value timestamp
end
end function | def MultiAppend(self, value_timestamp_pairs):
for value, timestamp in value_timestamp_pairs:
self.Append(value, timestamp) | Python | nomic_cornstack_python_v1 |
async function test_get_asset_reefer client
begin
set params = list tuple string access_token string access_token_example tuple string start_ms 56 tuple string end_ms 56
set headers = dict string Accept string application/json
set response = await call request method=string GET path=format string /v1/fleet/assets/{asse... | async def test_get_asset_reefer(client):
params = [('access_token', 'access_token_example'),
('start_ms', 56),
('end_ms', 56)]
headers = {
'Accept': 'application/json',
}
response = await client.request(
method='GET',
path='/v1/fleet/asset... | Python | nomic_cornstack_python_v1 |
from FFxivPythonTrigger import PluginBase
import math
import traceback
set command = string @tp
set pattern_main = b'\xf3\x0f......\xeb.H\x8b.....\xe8....H\x85'
set pattern_fly = b'H\x8d.....\x84\xc0u.H\x8d.....\x80yf.t.\xe8....\xc6\x87\xf4\x03..'
class Teleporter extends PluginBase
begin
set name = string Teleporter
f... | from FFxivPythonTrigger import PluginBase
import math
import traceback
command = "@tp"
pattern_main = b"\xF3\x0F......\xEB.\x48\x8B.....\xE8....\x48\x85"
pattern_fly = b"\x48\x8D.....\x84\xC0\x75.\x48\x8D.....\x80\x79\x66.\x74.\xE8....\xC6\x87\xF4\x03.."
class Teleporter(PluginBase):
name = "Teleporter"
def... | Python | zaydzuhri_stack_edu_python |
function begin_call self method *args
begin
string Perform an asynchronous remote call where the return value is not known yet. This returns immediately with a Deferred object. The Deferred object may then be used to attach a callback, force waiting for the call, or check for exceptions.
set d = call Deferred loop
set ... | def begin_call(self, method, *args):
"""Perform an asynchronous remote call where the return value is not known yet.
This returns immediately with a Deferred object. The Deferred object may then be
used to attach a callback, force waiting for the call, or check for exceptions.
"""
... | Python | jtatman_500k |
comment Inheritance In Python oops
class Employee
begin
set increment = 1.5
function __init__ self fname lname salary
begin
set fname = fname
set lname = lname
set salary = salary
set increment = 1.4
end function
function increase self
begin
set salary = integer salary * increment
end function
decorator classmethod
fun... | # Inheritance In Python oops
class Employee:
increment = 1.5
def __init__(self, fname, lname, salary):
self.fname = fname
self.lname = lname
self.salary = salary
self.increment = 1.4
def increase(self):
self.salary = int(self.salary * Employee.increment)
@c... | Python | zaydzuhri_stack_edu_python |
import sys
comment Definition for a binary tree node.
class TreeNode
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
end function
end class
class Solution
begin
comment @param {TreeNode} root
comment @return {integer}
function maxPathSum self root
begin
set maxpath = - maxint
call solv... | import sys
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {TreeNode} root
# @return {integer}
def maxPathSum(self, root):
self.maxpath = -sys.maxint
self.solve(0,root)
return self.... | Python | zaydzuhri_stack_edu_python |
comment # FOR taxrorlash operatori
comment mehmonlar = ['Ali','Vali','Hasan','Husan','Olim']
comment for mehmon in mehmonlar:
comment print(f"Xurmatli{mehmon} sizni 20 sentyabr kuni naxorgi oshimizga taklif qilamiz")
comment print("Hurmat bilan palonchiyevlar olilasi")
comment sonlar = list(range(1,11))
comment for son... | # # FOR taxrorlash operatori
# mehmonlar = ['Ali','Vali','Hasan','Husan','Olim']
# for mehmon in mehmonlar:
# print(f"Xurmatli{mehmon} sizni 20 sentyabr kuni naxorgi oshimizga taklif qilamiz")
# print("Hurmat bilan palonchiyevlar olilasi")
# sonlar = list(range(1,11))
# for son in sonlar:
# print(f"{son} ning kvadr... | Python | zaydzuhri_stack_edu_python |
function read_gpop_hdf5 path interior_path dof=none
begin
with call File path string r as fp
begin
set time = fp at interior_path at string time at slice : :
if dof is not none
begin
set dof_str = string dof_ + string dof
return tuple time fp at interior_path at dof_str at string grid at slice : : fp at interior_... | def read_gpop_hdf5(
path: Union[Path, str],
interior_path: str,
dof: Optional[int] = None,
) -> Union[
Tuple[numpy.ndarray, Dict[int, numpy.ndarray], Dict[int, numpy.ndarray]],
Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray],
]:
with h5py.File(path, "r") as fp:
time = fp[interior_path... | Python | nomic_cornstack_python_v1 |
function connect_to_db query=none
begin
set conn = none
set cursor = none
set DB_URL = config at string DATABASE_URI
try
begin
comment connect to db
set conn = call connect DB_URL
print format string Connected {} call get_dsn_parameters
set cursor = call cursor cursor_factory=DictCursor
if query
begin
comment Execute q... | def connect_to_db(query=None):
conn = None
cursor = None
DB_URL = app.config["DATABASE_URI"]
try:
# connect to db
conn = psycopg2.connect(DB_URL)
print("\n\nConnected {}\n".format(conn.get_dsn_parameters()))
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
... | Python | nomic_cornstack_python_v1 |
function my_languages results
begin
set output = dict
for tuple i v in items results
begin
if v >= 60
begin
set output at i = v
end
end
return sorted output key=__getitem__ reverse=true
end function
string Your task Given a dictionary/hash/object of languages and your respective test results, return the list of langua... | def my_languages(results):
output = {}
for i,v in results.items():
if v>=60:
output[i] = v
return sorted(output, key=output.__getitem__, reverse=True)
'''
Your task
Given a dictionary/hash/object of languages and your respective test results,
return the list of languages where your t... | Python | zaydzuhri_stack_edu_python |
function aggregate_compilation_notes l=none filename=none verbose=false
begin
if l is none
begin
set l = list string
end
set counter = 0
comment the index of the dictionary
set file_notes = dictionary
for directory in l
begin
if directory at - 1 != string /
begin
set directory = directory + string /
end
set files_list... | def aggregate_compilation_notes(l=None,filename=None,verbose=False):
if l is None:
l = ['']
counter = 0
file_notes = dict() #the index of the dictionary
for directory in l:
if directory[-1] != '/':
directory += '/'
files_list = os.listdir(directory)
for file_... | Python | nomic_cornstack_python_v1 |
function expect_pass self func *args **kwargs
begin
set tuple _ failures = call post_process func *args keyword kwargs
assert equal length failures 0
end function | def expect_pass(self, func: Callable, *args, **kwargs) -> None:
_, failures = self.post_process(func, *args, **kwargs)
self.assertEqual(len(failures), 0) | Python | nomic_cornstack_python_v1 |
function vertical_output
begin
string Function displays message in vertical position.
set message = input string Enter any message:
for char in message
begin
print char
end
end function
call vertical_output | def vertical_output():
"""Function displays message in vertical position."""
message = input("Enter any message: ")
for char in message:
print(char)
vertical_output() | Python | zaydzuhri_stack_edu_python |
function make_turtle colr sz
begin
set t = call Turtle
call color colr
call pensize sz
return t
end function | def make_turtle(colr, sz):
t = turtle.Turtle()
t.color(colr)
t.pensize(sz)
return t | Python | nomic_cornstack_python_v1 |
function unique_concat str1 str2
begin
comment Concatenate the two strings
set concat_str = str1 + str2
comment Create an empty set to store unique characters
set unique_chars = set
comment Iterate over each character in the concatenated string
for char in concat_str
begin
comment Add the character to the unique_chars ... | def unique_concat(str1, str2):
# Concatenate the two strings
concat_str = str1 + str2
# Create an empty set to store unique characters
unique_chars = set()
# Iterate over each character in the concatenated string
for char in concat_str:
# Add the character to the unique_chars s... | Python | jtatman_500k |
function trim_field_key document field_key
begin
string Returns the smallest delimited version of field_key that is an attribute on document. return (key, left_over_array)
set trimming = true
set left_over_key_values = list
set current_key = field_key
while trimming and current_key
begin
if has attribute document curr... | def trim_field_key(document, field_key):
"""
Returns the smallest delimited version of field_key that
is an attribute on document.
return (key, left_over_array)
"""
trimming = True
left_over_key_values = []
current_key = field_key
while trimming and current_key:
if hasattr(d... | Python | jtatman_500k |
from sense_hat import SenseHat
import time
import socket
comment import gyrodata
import sys
set host = string 10.44.15.35
set port = 5800
set startTime = time
function keepTime startTime
begin
while 1
begin
set elapsedTime = time - startTime
return elapsedTime
end
end function
comment gyro_socket = socket.socket(socket... | from sense_hat import SenseHat
import time
import socket
#import gyrodata
import sys
host = '10.44.15.35'
port = 5800
startTime = time.time()
def keepTime(startTime):
while 1:
elapsedTime = (time.time() - startTime)
return(elapsedTime)
#gyro_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#gyro_sock... | Python | zaydzuhri_stack_edu_python |
function test_deuterium self
begin
set neighbours = call get_pairwise_distances deuterated num_neighbours=10
set comp = call composition_hist deuterated neighbours=neighbours
assert equal sum axis=0 at 1 shape at 0 / 2
end function | def test_deuterium(self):
neighbours = gridrdf.extendRDF.get_pairwise_distances(self.deuterated, num_neighbours=10)
comp = gridrdf.composition.composition_hist(self.deuterated, neighbours=neighbours)
self.assertEqual(comp.sum(axis=0)[1], comp.shape[0] / 2) | Python | nomic_cornstack_python_v1 |
function append_write filename=string text=string
begin
with open filename mode=string a encoding=string utf-8 as f
begin
set num_chars = write f text
end
return num_chars
end function | def append_write(filename="", text=""):
with open(filename, mode="a", encoding="utf-8") as f:
num_chars = f.write(text)
return num_chars | Python | nomic_cornstack_python_v1 |
function _RepeatRows self in_matrix repeat_n_times
begin
comment Determine the number of matrix rows and columns
set tuple num_rows num_cols = list comprehension integer i for i in call as_list
comment Horizontally stack the matrix multiple times
set stacked_matrix = call tile input=in_matrix multiples=call constant li... | def _RepeatRows(self, in_matrix, repeat_n_times):
# Determine the number of matrix rows and columns
num_rows, num_cols = [int(i) for i in in_matrix.shape.as_list()]
# Horizontally stack the matrix multiple times
stacked_matrix = tf.tile(
input=in_matrix, multiples=tf.constant([1, repeat_n_time... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function sortedSquares self nums
begin
string https://leetcode.com/problems/squares-of-a-sorted-array/submissions/
sort nums key=lambda x -> absolute x
return list comprehension x * x for x in nums
end function
end class | class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
"""
https://leetcode.com/problems/squares-of-a-sorted-array/submissions/
"""
nums.sort(key = lambda x: abs(x))
return [x*x for x in nums] | Python | zaydzuhri_stack_edu_python |
function pop self
begin
set scope = pop __scopes
return scope
end function | def pop(self) -> LocalScope:
scope = self.__scopes.pop()
return scope | Python | nomic_cornstack_python_v1 |
comment fruitPrices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75,
comment 'limes': 0.75, 'strawberries': 1.00}
comment def buyLotsOfFruit(orderList):
comment """
comment orderList: List of (fruit, numPounds) tuples
comment Returns cost of order
comment """
comment totalCost = 0.0
comment "*** YOUR CODE HERE ***"
c... | # fruitPrices = {'apples': 2.00, 'oranges': 1.50, 'pears': 1.75,
# 'limes': 0.75, 'strawberries': 1.00}
# def buyLotsOfFruit(orderList):
# """
# orderList: List of (fruit, numPounds) tuples
# Returns cost of order
# """
# totalCost = 0.0
# "*** YOUR CODE HERE ***"
# #ch... | Python | zaydzuhri_stack_edu_python |
function wrappedFn *args **kw
begin
call setCurrent context
call fn *args keyword kw
end function | def wrappedFn(*args, **kw):
setCurrent(context)
fn(*args, **kw) | Python | nomic_cornstack_python_v1 |
from __future__ import print_function
from pyspark import SparkContext
from pyspark.mllib.feature import HashingTF
from pyspark.mllib.feature import IDF
from itertools import islice
from pyspark.mllib.linalg import Vectors
from pyspark.mllib.linalg import SparseVector , DenseVector
import numpy as np
import sys
functio... | from __future__ import print_function
from pyspark import SparkContext
from pyspark.mllib.feature import HashingTF
from pyspark.mllib.feature import IDF
from itertools import islice
from pyspark.mllib.linalg import Vectors
from pyspark.mllib.linalg import SparseVector, DenseVector
import numpy as np
import sys
def doc... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
set inputs = call to_int32 reshape tf range 2 * 3 tuple 2 3
set outputs = embedding inputs 6 2 zero_pad=true
with call Session as sess
begin
run call global_variables_initializer
end | import tensorflow as tf
inputs = tf.to_int32(tf.reshape(tf.range(2*3), (2, 3)))
outputs = embedding(inputs, 6, 2, zero_pad=True)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer()) | Python | zaydzuhri_stack_edu_python |
function cmap_discretize cmap N
begin
set cdict = copy _segmentdata
comment N colors
set colors_i = linear space 0 1.0 N
comment N+1 indices
set indices = linear space 0 1.0 N + 1
for key in tuple string red string green string blue
begin
comment Find the N colors
set D = array cdict at key
set I = interp 1d D at tuple... | def cmap_discretize(cmap, N):
cdict = cmap._segmentdata.copy()
# N colors
colors_i = linspace(0,1.,N)
# N+1 indices
indices = linspace(0,1.,N+1)
for key in ('red','green','blue'):
# Find the N colors
D = array(cdict[key])
I = interpolate.interp1d(D[:,0], D[:,1])
... | Python | nomic_cornstack_python_v1 |
function test_add_player_by_id fill_players
begin
with call test_session_scope as ts
begin
set t = call Team
set added_ok = call add_player 50 season=TEST_SEASON dbsession=ts
assert added_ok
end
end function | def test_add_player_by_id(fill_players):
with test_session_scope() as ts:
t = Team()
added_ok = t.add_player(50,season=TEST_SEASON,dbsession=ts)
assert added_ok | Python | nomic_cornstack_python_v1 |
function make_cos_mat t
begin
set cm = t @ T
call fill_diagonal cm - inf
set cm at call isnan cm = - inf
return cm
end function | def make_cos_mat(t: np.ndarray):
cm = t @ t.T
np.fill_diagonal(cm, -np.inf)
cm[np.isnan(cm)] = -np.inf
return cm | Python | nomic_cornstack_python_v1 |
function size self new_size
begin
if type new_size is str
begin
set new_size = upper replace new_size string string
set new_size = replace new_size string ) string
set new_size = replace new_size string ( string
set new_size = replace new_size string , string .
set new_size = strip replace new_size string B string
set... | def size(self, new_size):
if type(new_size) is str:
new_size = new_size.replace(" ", "").upper()
new_size = new_size.replace(")", "")
new_size = new_size.replace("(", "")
new_size = new_size.replace(",", ".")
new_size = new_size.replace("B", "").strip(... | Python | nomic_cornstack_python_v1 |
while true
begin
if current_order == string a
begin
set result = sa
end
else
if current_order == string b
begin
set result = sb
end
else
if current_order == string c
begin
set result = sc
end
try
begin
set current_order = pop result 0
end
except any
begin
if current_order == string a
begin
print string A
end
else
if cu... | while True:
if current_order == "a":
result = sa
elif current_order == "b":
result = sb
elif current_order == "c":
result = sc
try:
current_order = result.pop(0)
except:
if current_order == "a":
print("A")
elif current_order == "b":
... | Python | zaydzuhri_stack_edu_python |
from flask import Flask , request
import requests
from bs4 import BeautifulSoup
import random
comment import spacy
from xml.etree import ElementTree
set app = call Flask __name__
function synonims text
begin
set headers = dict string User-Agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:45.0) Gecko/20100101... | from flask import Flask, request
import requests
from bs4 import BeautifulSoup
import random
# import spacy
from xml.etree import ElementTree
app = Flask(__name__)
def synonims(text):
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:45.0) Gecko/20100101 Firefox/45.0'
}
# вы... | Python | zaydzuhri_stack_edu_python |
function set_state self x0
begin
if not is instance x0 ndarray
begin
print format string called set_state with argument of type {} instead of numpy.ndarray. Ignoring. type x0
return false
end
comment make 1D version of x0
set x0_flat = flatten x0
if length x0_flat != STATE_SIZE
begin
print format string called set_stat... | def set_state(self, x0):
if not isinstance(x0, np.ndarray):
print(
'called set_state with argument of type {} instead of numpy.ndarray. Ignoring.'.format(
type(x0)))
return False
# make 1D version of x0
x0_flat = x0.flatten()
... | Python | nomic_cornstack_python_v1 |
function Generators
begin
set n = 1
while n <= 10
begin
yield n
set n = n + 1
end
end function
set values = call Generators
comment print(values.__next__())
for i in values
begin
print i
end
string * Difference between yield and return * return sends a specified value back to its caller, whereas yield can produce a seq... | def Generators() :
n = 1
while n<=10 :
yield n
n += 1
values = Generators()
# print(values.__next__())
for i in values :
print(i)
"""
* Difference between yield and return *
return sends a specified value back to its caller, whereas yield can produce a sequence of values.
We should use yi... | Python | zaydzuhri_stack_edu_python |
import os
import math
import time
import random
import inspect
from PIL import Image , ImageDraw
set WIDTH = 1000
set HEIGHT = 1000
seed
function choose_func
begin
return random choice list lambda p x y -> sin p * pi * x lambda p x y -> sin p * pi * y lambda p x y -> sin p * pi * x * y lambda p x y -> cos p * pi * x la... | import os
import math
import time
import random
import inspect
from PIL import Image, ImageDraw
WIDTH = 1000
HEIGHT = 1000
random.seed()
def choose_func():
return random.choice([
lambda p,x,y: math.sin(p * math.pi * x ),
lambda p,x,y: math.sin(p * math.pi * y ),
lambda p,x,y: math.sin(p * math.pi * x... | Python | zaydzuhri_stack_edu_python |
function check_login self
begin
if not is_logged_in
begin
raise call NotLoggedIn string Must call login() on { self }
end
end function | def check_login(self):
if not self.is_logged_in:
raise NotLoggedIn(f"Must call login() on {self}") | Python | nomic_cornstack_python_v1 |
function send_adversary_moves self adversary
begin
set valid_moves = list
set curr_pos = tuple x_pos y_pos
comment Checking no movement
if call is_valid_movement adversary curr_pos
begin
append valid_moves curr_pos
end
comment Checking up
if call is_valid_movement adversary tuple curr_pos at 0 curr_pos at 1 - 1
begin
... | def send_adversary_moves(self, adversary):
valid_moves = []
curr_pos = (adversary.x_pos, adversary.y_pos)
# Checking no movement
if self.rulechecker.is_valid_movement(adversary, curr_pos):
valid_moves.append(curr_pos)
# Checking up
if self.rulechecker.is_val... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
import os
function vetImages path
begin
set namesImgs = list directory path
set vetImgs = list
set teste = list
for a in namesImgs
begin
append vetImgs call imread path + a IMREAD_GRAYSCALE
end
return vetImgs
end function
function showImages vetImgs vet
begin
for a in range length vetImg... | import cv2
import numpy as np
import os
def vetImages(path):
namesImgs = os.listdir(path)
vetImgs = []
teste = []
for a in namesImgs:
vetImgs.append(cv2.imread(path+a,cv2.IMREAD_GRAYSCALE))
return vetImgs
def showImages(vetImgs, vet):
for a in range(len(vetImgs)):
contours, hi... | Python | zaydzuhri_stack_edu_python |
function draw_bs_pairs_linreg x y size=1
begin
comment Set up array of indices to sample from: inds
set inds = array range length x
comment Initialize replicates: bs_slope_reps, bs_intercept_reps
set bs_slope_reps = call empty size
set bs_intercept_reps = call empty size
comment Generate replicates
for i in range size
... | def draw_bs_pairs_linreg(x, y, size=1):
# Set up array of indices to sample from: inds
inds = np.arange(len(x))
# Initialize replicates: bs_slope_reps, bs_intercept_reps
bs_slope_reps = np.empty(size)
bs_intercept_reps = np.empty(size)
# Generate replicates
for i in range(size):
b... | Python | nomic_cornstack_python_v1 |
import numpy as np
import sympy as sp
import time as tm
function ReglaCrammer A b
begin
set sol = list
set deta = round call det A 1
for i in range length b
begin
set B = copy A
set B at tuple slice : : i = b
set detb = round call det B 1
append sol detb / deta
end
return sol
end function
set A = array list list 1 ... | import numpy as np
import sympy as sp
import time as tm
def ReglaCrammer(A,b):
sol = []
deta = round(np.linalg.det(A), 1)
for i in range(len(b)):
B = A.copy()
B[:, i] = b
detb = round(np.linalg.det(B), 1)
sol.append(detb / deta)
return sol
A = np.array([[1, 1, 0],
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import syft as sy
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset , DataLoader
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import... | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import syft as sy
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection i... | Python | zaydzuhri_stack_edu_python |
string This program reads a file, checks the contents per block element, and outputs them if they are source code. WARNING: This is an experimental version where different methods are being tried. The current method it is implementing is noted above. It is full of debug text; variable names may not always be descriptiv... | '''
This program reads a file, checks the contents per block element, and outputs them if they are source code.
WARNING:
This is an experimental version where different methods are being tried.
The current method it is implementing is noted above.
It is full of debug text; variable names may not always be descriptive
... | Python | zaydzuhri_stack_edu_python |
import random
set num = random * 1 - 9
set chances = 1
while chances <= 3
begin
set enterrandom = input string enter a number between 1 and 9:
if enterrandom == num
begin
print string Congratulations! you're right
break
end
else
begin
print string try again
end
set chances = chances + 1
end
if chances == 3
begin
print ... | import random
num = random.random() * 1-9
chances=1
while chances <=3:
enterrandom = input("enter a number between 1 and 9:")
if enterrandom == num :
print ("Congratulations! you're right")
break
else:
print("try again")
chances=chances+1
if chances==3:
print("Y... | Python | zaydzuhri_stack_edu_python |
function json_request self action data object_hook=none
begin
call _normalize_request_dict data
set json_input = dumps data
return call make_request action json_input object_hook
end function | def json_request(self, action, data, object_hook=None):
self._normalize_request_dict(data)
json_input = json.dumps(data)
return self.make_request(action, json_input, object_hook) | Python | nomic_cornstack_python_v1 |
import socket
import cryptography
import pickle
from cryptography.fernet import Fernet
set key1 = call generate_key
set key2 = call generate_key
set store2 = list
comment Create a socket object
set s = call socket
set filename = string passwords.txt
set opfile = open filename string a
set rfile = open filename string ... | import socket
import cryptography
import pickle
from cryptography.fernet import Fernet
key1=Fernet.generate_key()
key2=Fernet.generate_key()
store2=[]
# Create a socket object
s = socket.socket()
filename='passwords.txt'
opfile=open(filename,'a')
rfile=open(filename,'r')
# Defi... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment This example controls the GoPiGo and using a PS3 Dualshock 3 controller
comment http://www.dexterindustries.com/GoPiGo/
comment History
comment ------------------------------------------------
comment Author Date Comments
comment Karan Nayan 11 July 14 Initial Authoring
string ## Li... | #!/usr/bin/env python
########################################################################
# This example controls the GoPiGo and using a PS3 Dualshock 3 controller
#
# http://www.dexterindustries.com/GoPiGo/ ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string author: Garfy email: gaojianbo@pku.edu.cn date: 2016-10-29
import urllib2
class STSpider extends object
begin
string Spider for Software Testing
function __init__ self urlFilePath
begin
set urlFilePath = urlFilePath
end function
function reader self
begi... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
author: Garfy
email: gaojianbo@pku.edu.cn
date: 2016-10-29
"""
import urllib2
class STSpider(object):
"""Spider for Software Testing"""
def __init__(self, urlFilePath):
self.urlFilePath = urlFilePath
def reader(self):
urlList = []
... | Python | zaydzuhri_stack_edu_python |
string 17. Write a Python program to multiplies all the items in a list.
from functools import reduce
set a = input string Enter a list:
set a1 = split a
for i in range length a1
begin
set a1 at i = integer a1 at i
end
set asd = lambda x y -> x * y
set res = reduce asd a1
print res | """17. Write a Python program to multiplies all the items in a list."""
from functools import reduce
a= input('Enter a list:')
a1 = a.split()
for i in range(len(a1)):
a1[i] = int(a1[i])
asd=lambda x,y:x*y
res=reduce(asd,a1)
print(res) | Python | zaydzuhri_stack_edu_python |
function smooth_one_hot true_labels classes smoothing=0.0
begin
assert 0 <= smoothing < 1
set confidence = 1.0 - smoothing
set label_shape = size torch tuple size true_labels 0 classes
with no grad
begin
set true_dist = call empty size=label_shape device=device
call fill_ smoothing / classes - 1
call scatter_ 1 unsquee... | def smooth_one_hot(true_labels: torch.Tensor, classes: int, smoothing=0.0):
assert 0 <= smoothing < 1
confidence = 1.0 - smoothing
label_shape = torch.Size((true_labels.size(0), classes))
with torch.no_grad():
true_dist = torch.empty(size=label_shape, device=true_labels.device)
true_dist... | Python | nomic_cornstack_python_v1 |
function C2H2 distance=none freeze_core=true orbitals_remove=none initial_state=false mapper_type=none
begin
if distance is none
begin
set distance = list 1.2 1.06
end
if orbitals_remove is none
begin
set orbitals_remove = list 11
end
comment H_1 - C_1 - C_2 - H_2
set H_1 = string array list 0 0 0 at slice 1 : - 1 :
s... | def C2H2(distance: Optional[List[float]] = None, freeze_core: Optional[bool] = True,
orbitals_remove: Optional[List[int]] = None, initial_state: Optional[bool] = False,
mapper_type: Optional[str] = None) -> Union[_MoleculeType, Tuple[_MoleculeType, HartreeFock]]:
if distance is None:
dist... | Python | nomic_cornstack_python_v1 |
class Solution
begin
string @param n: the number of sectors @param m: the number of colors @return: The total number of plans.
function getCount self n m
begin
if n == 1
begin
return m
end
if n == 2
begin
return m * m - 1
end
if m == 2 and n % 2 == 1
begin
return 0
end
set same = 0
set dif = m * m - 1
for i in range 3 ... | class Solution:
"""
@param n: the number of sectors
@param m: the number of colors
@return: The total number of plans.
"""
def getCount(self, n, m):
if n == 1:
return m
if n == 2:
return m * (m - 1)
if m == 2 and n % 2 == 1:
return 0
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
class Portfolio
begin
function __init__ self
begin
set state = dict string initial_dist dict string hdfc 0.35 ; string icici 0.2 ; string sbi 0.15 ; string axis 0.15 ; string kotak 0.15 ; string initial_investment 10000 ; string cash 10000 ; string shares dict
set da... | import pandas as pd
import matplotlib.pyplot as plt
class Portfolio:
def __init__(self):
self.state = {
'initial_dist': {
'hdfc': 0.35,
'icici': 0.2,
'sbi': 0.15,
'axis': 0.15,
'kotak': 0.15
... | Python | zaydzuhri_stack_edu_python |
function record_modules
begin
set modules = set modules
yield
if _modules
begin
return
end
for module_name in difference set modules modules
begin
if any generator expression starts with module_name imodule for imodule in IGNORED_MODULES
begin
continue
end
set module = modules at module_name
try
begin
set spec = get at... | def record_modules():
modules = set(sys.modules)
yield
if _modules:
return
for module_name in set(sys.modules).difference(modules):
if any(module_name.startswith(imodule) for imodule in IGNORED_MODULES):
continue
module = sys.modules[module_name]
try:
... | Python | nomic_cornstack_python_v1 |
import numpy as np
function update_positions population
begin
set population at tuple slice : : 1 = population at tuple slice : : 1 + population at tuple slice : : 3 * population at tuple slice : : 5
set population at tuple slice : : 2 = population at tuple slice : : 2 + population at tuple slice : ... | import numpy as np
def update_positions(population):
population[:,1] = population[:,1] + (population[:,3] * population[:,5])
population[:,2] = population[:,2] + (population [:,4] * population[:,5])
return population
def out_of_bounds(population, xbounds, ybounds):
shp = population[:,3][(populatio... | Python | zaydzuhri_stack_edu_python |
function get_state self
begin
if not get _variable
begin
return string Locked
end
else
if get _variable
begin
return string Unlocked
end
end function | def get_state(self):
if not self._variable.get():
return "Locked"
elif self._variable.get():
return "Unlocked" | Python | nomic_cornstack_python_v1 |
from __future__ import print_function
from __future__ import division
from sklearn.datasets import make_classification
from sklearn.cross_validation import cross_val_score
from sklearn.ensemble import RandomForestClassifier as RFC
from sklearn.svm import SVC
from bayes_opt import BayesianOptimization
comment Load data ... | from __future__ import print_function
from __future__ import division
from sklearn.datasets import make_classification
from sklearn.cross_validation import cross_val_score
from sklearn.ensemble import RandomForestClassifier as RFC
from sklearn.svm import SVC
from bayes_opt import BayesianOptimization
# Load data set... | Python | zaydzuhri_stack_edu_python |
string Script to split headlines downloaded from Mediacloud into daily files Also does some basic cleaning and preprocessing
import argparse
import pandas as pd
import get_topics
import names
function split file
begin
set df = read csv file sep=string parse_dates=list string publish_date
set df = call clean df
set df ... | """
Script to split headlines downloaded from Mediacloud into daily files
Also does some basic cleaning and preprocessing
"""
import argparse
import pandas as pd
import get_topics
import names
def split(file):
df = pd.read_csv(file, sep="\t", parse_dates=["publish_date"])
df = get_topics.clean(df)
df["p... | Python | zaydzuhri_stack_edu_python |
import pytest
from statTools import *
comment FIND RANGE TESTS
function test_find_range_basic
begin
assert call find_range list 1 2 3 4 5 == 4
end function
function test_find_range_unsorted
begin
assert call find_range list 3 4 2 5 1 == 4
end function
function test_find_range_negative
begin
assert call find_range list ... | import pytest
from statTools import *
# FIND RANGE TESTS
def test_find_range_basic():
assert (find_range([1, 2, 3, 4, 5]) == 4)
def test_find_range_unsorted():
assert (find_range([3, 4, 2, 5, 1]) == 4)
def test_find_range_negative():
assert (find_range([1, 2, 3, -7, -14, -8]) == 17)
# CORNER CASES
d... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import Stra... | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_predict
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import Stra... | Python | zaydzuhri_stack_edu_python |
import sqlite3
from db import db
class ItemModel extends Model
begin
set __table__ = string item
set id = call Column Integer primary_key=true
set name = call Column call String 80
set price = call Column decimal precision=2
function __init__ self name price
begin
set name = name
set price = price
end function
function... | import sqlite3
from db import db
class ItemModel(db.Model):
__table__ = "item"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
price = db.Column(db.Float(precision=2))
def __init__(self, name, price):
self.name = name
self.price = price
def j... | Python | zaydzuhri_stack_edu_python |
comment 四种激活函数sigmoid softmax relu tanh
string model.add(Activation("sigmoid")) model.add(Activation("softmax")) model.add(Activation("relu")) model.add(Activation("tanh")) # 随机梯度下降 model.fit(X_train,Y_train,epochs=1000,batch_size=100,verbose=100)
from __future__ import print_function
import torch
set x = call rand 5 3... | # 四种激活函数sigmoid softmax relu tanh
'''model.add(Activation("sigmoid"))
model.add(Activation("softmax"))
model.add(Activation("relu"))
model.add(Activation("tanh"))
# 随机梯度下降
model.fit(X_train,Y_train,epochs=1000,batch_size=100,verbose=100)'''
from __future__ import print_function
import torch
x = torch.rand(5, 3)
print(x... | Python | zaydzuhri_stack_edu_python |
function _launch self
begin
set _run_config = get run_configs version=game_version
set _map = get maps map_name
comment Setting up the interface
set interface_options = call InterfaceOptions raw=true score=false
set _sc2_proc = start _run_config window_size=window_size
set _controller = controller
set _bot_controller =... | def _launch(self):
self._run_config = run_configs.get(version=self.game_version)
_map = maps.get(self.map_name)
# Setting up the interface
interface_options = sc_pb.InterfaceOptions(raw=True, score=False)
self._sc2_proc = self._run_config.start(window_size=self.window_size)
... | Python | nomic_cornstack_python_v1 |
comment agg 调用的时候要指定字段,apply 默认传入的是整个dataframe
import pandas as pd
import numpy as np
set df = call DataFrame dict string A list 1 1 2 2 ; string B list 1 2 3 4 ; string C randn 4
call agg dict string B dict string B_S sum
reset index apply group by df string A as_index=false lambda x -> sum x at string B
print df
comm... | # agg 调用的时候要指定字段,apply 默认传入的是整个dataframe
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': [1, 1, 2, 2],'B': [1, 2, 3, 4],'C': np.random.randn(4)})
df.groupby('A',as_index=False).agg({'B':{'B_S':sum}})
df.groupby('A',as_index=False).apply(lambda x:sum(x['B'])).reset_index()
print(df)
# agg 方法将一个函数使用在一个... | Python | zaydzuhri_stack_edu_python |
class Person
begin
function _init_ self
begin
set _name = string
set _age = - 1
end function
decorator property
function name self
begin
return _name
end function
decorator property
function age self
begin
return _age
end function
decorator setter
function name self value
begin
set _name = value
end function
decorator... | class Person:
def _init_(self):
self._name = ''
self._age = -1
@property
def name(self):
return self._name
@property
def age(self):
return self._age
@name.setter
def name(self, value):
self._name = value
@name.deleter
def delete(self):
... | Python | zaydzuhri_stack_edu_python |
function isOfficialChannel channel
begin
if string official in channel at string description
begin
return true
end
return false
end function | def isOfficialChannel(channel):
if 'official' in channel['description']:
return True
return False | Python | nomic_cornstack_python_v1 |
comment Juubelile on kutsutud hulk inimesi, kellest osa on teatanud, et nad tulevad ja ülejäänute kohta ei ole midagi teada. Peo eelarve koosneb kahest osast: söök ja ruumi rent. Söögi peale arvestatakse iga osaleja kohta 10 eurot. Ruumi rent maksab sõltumata osalejate arvust 55 eurot. Planeerimiseks on vaja programmi,... | # Juubelile on kutsutud hulk inimesi, kellest osa on teatanud, et nad tulevad ja ülejäänute kohta ei ole midagi teada. Peo eelarve koosneb kahest osast: söök ja ruumi rent. Söögi peale arvestatakse iga osaleja kohta 10 eurot. Ruumi rent maksab sõltumata osalejate arvust 55 eurot. Planeerimiseks on vaja programmi, mis a... | Python | zaydzuhri_stack_edu_python |
function random_hex self with_hash=false
begin
set s = call rgb2hex *self.random_rgb()
return if expression with_hash then format string #{} s else s
end function | def random_hex(self, with_hash=False):
s = rgb2hex(*self.random_rgb())
return '#{}'.format(s) if with_hash else s | Python | nomic_cornstack_python_v1 |
function update_best best_loss best_auc new_loss new_auc
begin
set flag_new_best = false
if new_loss < best_loss
begin
set best_loss = new_loss
set flag_new_best = true
end
if new_auc > best_auc
begin
set best_auc = new_auc
set flag_new_best = true
end
return tuple flag_new_best best_loss best_auc
end function | def update_best(best_loss, best_auc, new_loss, new_auc):
flag_new_best = False
if new_loss < best_loss:
best_loss = new_loss
flag_new_best = True
if new_auc > best_auc:
best_auc = new_auc
flag_new_best = True
return flag_new_best, best_loss, best_auc | Python | nomic_cornstack_python_v1 |
function _bp_calc_output_error_signals self
begin
for output_neuron in outputs
begin
set error_signal = expected_value - value * value * 1.0 - value
end
end function | def _bp_calc_output_error_signals(self):
for output_neuron in self.outputs:
self.outputs[output_neuron.index].error_signal = (
(output_neuron.expected_value - output_neuron.value)
* output_neuron.value
* (1.0 - output_neuron.value)) | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[ ]:
comment LJD_Functions.py
comment Purpose: To contain all cobra functions that I use regularly such that I can import them into whatever main script I am using
comment Functions contained in this script:
comment changeMedia_PA_LJD - changes the media conditions of a cobrapy model
com... | # coding: utf-8
# In[ ]:
# LJD_Functions.py
# Purpose: To contain all cobra functions that I use regularly such that I can import them into whatever main script I am using
# Functions contained in this script:
# changeMedia_PA_LJD - changes the media conditions of a cobrapy model
# import packages
from copy impo... | Python | zaydzuhri_stack_edu_python |
function backend self
begin
return get pulumi self string backend
end function | def backend(self) -> Optional[pulumi.Input['IngressBackendPatchArgs']]:
return pulumi.get(self, "backend") | Python | nomic_cornstack_python_v1 |
import core
import pyglet
from pyglet.window import key
from core import GameElement
import sys
import random
comment DO NOT TOUCH ####
set GAME_BOARD = none
set DEBUG = false
set KEYBOARD = none
set PLAYER = none
set GAME_WIDTH = 9
set GAME_HEIGHT = 9
comment Put class definitions here ####
class Rock extends GameElem... | import core
import pyglet
from pyglet.window import key
from core import GameElement
import sys
import random
#### DO NOT TOUCH ####
GAME_BOARD = None
DEBUG = False
KEYBOARD = None
PLAYER = None
######################
GAME_WIDTH = 9
GAME_HEIGHT = 9
#### Put class definitions here ####
class Rock(GameElement):
I... | Python | zaydzuhri_stack_edu_python |
function filter_dict d to_save
begin
function can_store v
begin
return type v in set literal int float str bool Tensor
end function
return if expression to_save then dictionary comprehension k : v for tuple k v in items d if k in set to_save and call can_store v else dictionary comprehension k : v for tuple k v in item... | def filter_dict(d, to_save):
def can_store(v):
return type(v) in {int, float, str, bool, torch.Tensor}
return (
{k: v for k, v in d.items() if (k in set(to_save)) and can_store(v)}
if to_save
else {k: v for k, v in d.items() if can_store(v)}
) | Python | nomic_cornstack_python_v1 |
function test_valid_pathname self
begin
assert true call is_pathname_valid string ./myrandomvalidfilename.dat
assert true call is_pathname_valid string myrandomvalidfilename.dat
end function | def test_valid_pathname(self):
self.assertTrue(Util.is_pathname_valid('./myrandomvalidfilename.dat'))
self.assertTrue(Util.is_pathname_valid('myrandomvalidfilename.dat')) | Python | nomic_cornstack_python_v1 |
function count_chars string
begin
set counts = dict
for char in string
begin
if is alphanumeric char
begin
set char = lower char
set counts at char = get counts char 0 + 1
end
end
return dictionary sorted items counts key=lambda x -> ordinal x at 0
end function
comment Example usage:
set input_string = string Hello Wo... | def count_chars(string):
counts = {}
for char in string:
if char.isalnum():
char = char.lower()
counts[char] = counts.get(char, 0) + 1
return dict(sorted(counts.items(), key=lambda x: ord(x[0])))
# Example usage:
input_string = "Hello World! 123"
output = count_chars(input_s... | Python | jtatman_500k |
function findPlug self attr wantNetworkedPlug
begin
pass
end function | def findPlug(self, attr, wantNetworkedPlug):
pass | Python | nomic_cornstack_python_v1 |
import sys
from csv import reader
import numpy
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from sklearn import metrics
function load_csv filename
begin
set file = open filename string rt
set lines = reader file
set dataset = list lines
set dataset = as type array dataset string... | import sys
from csv import reader
import numpy
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from sklearn import metrics
def load_csv(filename):
file = open(filename, "rt")
lines = reader(file)
dataset = list(lines)
dataset = numpy.array(dataset).astype('float')
... | Python | zaydzuhri_stack_edu_python |
function read_statistic self
begin
set content_list = split replace replace replace replace replace replace document_content string string string string string , string string . string string ! string string – string string
comment delete all occurrences of '' ?????----------------------------------------------------... | def read_statistic(self):
content_list = self.document_content.replace("\n", " ") \
.replace(" ", " ") \
.replace(",", "") \
.replace(".", "") \
.replace("!", "") \
.replace("–", "") \
.split(" ")
try: # delete all occurrences of... | Python | nomic_cornstack_python_v1 |
function run_test test_fn
begin
print string Running { __name__ } ...
call test_fn
print string
end function | def run_test(test_fn):
print(f"Running {test_fn.__name__}...")
test_fn()
print("\n") | Python | nomic_cornstack_python_v1 |
from django import template
set register = call Library
class RenderInlineNode extends Node
begin
function __init__ self nodelist
begin
set nodelist = nodelist
end function
function render self context
begin
set source = call render context
set t = call Template source
return call render context
end function
end class
... | from django import template
register = template.Library()
class RenderInlineNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
source = self.nodelist.render(context)
t = template.Template(source)
return t.render(context)
@re... | Python | zaydzuhri_stack_edu_python |
comment DROP TABLES
set songplay_table_drop = string DROP TABLE IF EXISTS fact_songplays
set user_table_drop = string DROP TABLE IF EXISTS dim_user
set song_table_drop = string DROP TABLE IF EXISTS dim_song
set artist_table_drop = string DROP TABLE IF EXISTS dim_artist
set time_table_drop = string DROP TABLE IF EXISTS ... | # DROP TABLES
songplay_table_drop = "DROP TABLE IF EXISTS fact_songplays"
user_table_drop = "DROP TABLE IF EXISTS dim_user"
song_table_drop = "DROP TABLE IF EXISTS dim_song"
artist_table_drop = "DROP TABLE IF EXISTS dim_artist"
time_table_drop = "DROP TABLE IF EXISTS dim_time"
# CREATE TABLES
songplay_table_create =... | Python | zaydzuhri_stack_edu_python |
import sys
import heapq
set input = readline
set N = integer input
set A = tuple map int split input
set hq = list A at slice : N :
call heapify hq
set s = list 0 * N + 1
set s at 0 = sum hq
for i in range N
begin
set x = call heappop hq
if x >= A at N + i
begin
set s at i + 1 = s at i
call heappush hq x
end
else
begi... | import sys
import heapq
input=sys.stdin.readline
N=int(input())
A=tuple(map(int,input().split()))
hq=list(A[:N])
heapq.heapify(hq)
s=[0]*(N+1)
s[0]=sum(hq)
for i in range(N):
x=heapq.heappop(hq)
if x >= A[N+i]:
s[i+1]=s[i]
heapq.heappush(hq,x)
else:
s[i+1]=s[i]+A[N+i]-x
heapq.heappush(hq,A[N+i])
... | Python | zaydzuhri_stack_edu_python |
function reverse self z y
begin
set masked = mask * z
set s = call s masked y
set t = t dist masked y
set x = masked + 1 - mask * z - t * exp
return tuple x sum 1
end function | def reverse(self, z, y):
masked = self.mask * z
s = self.s(masked, y)
t = self.t(masked, y)
x = masked + (1 - self.mask) * ((z - t) * (-s).exp())
return x, (-s * (1 - self.mask)).sum(1) | Python | nomic_cornstack_python_v1 |
import os
import csv
import random
function generate_random_backround_list
begin
with open get current directory + string /data/colour_list.csv string r as f
begin
set reader = reader f
set colour_list = call __next__
end
shuffle random colour_list
return colour_list
end function
class Quiz
begin
function __init__ self... | import os
import csv
import random
def generate_random_backround_list():
with open(os.getcwd() + '/data/colour_list.csv', 'r') as f:
reader = csv.reader(f)
colour_list = reader.__next__()
random.shuffle(colour_list)
return colour_list
class Quiz:
def __init__(self, username):
"... | Python | zaydzuhri_stack_edu_python |
function classifyOneCase self words
begin
set maxPrability = - 10000000000000
set label = string None
set word_uniq_cnt = 300000
end function | def classifyOneCase(self, words):
maxPrability = -10000000000000
label = 'None'
word_uniq_cnt = 300000
| Python | nomic_cornstack_python_v1 |
string Question: Move Element to End You're given an array of integers and an integer. Write a function that moves all instance of that integer in the array to the end of the array and returns the array. Write a function that should perform this in place (i.e , it should mutate the input array) and doesn't need too mai... | """
Question: Move Element to End
You're given an array of integers and an integer. Write a function that moves all instance of that integer in the array to the end of the array and returns the array.
Write a function that should perform this in place (i.e , it should mutate the input array) and doesn't need too mai... | Python | zaydzuhri_stack_edu_python |
function GetFaultAsDict self obj=none
begin
if not obj
begin
set elems = list string soapenv:Fault string soap:Fault
for elem in elems
begin
set xml_obj = call _GetXmlIn
if __xml_parser == PYXML
begin
try
begin
set obj = call getElementsByTagName elem at 0
end
except any
begin
set envelope = childNodes at 0
set body = ... | def GetFaultAsDict(self, obj=None):
if not obj:
elems = ['soapenv:Fault', 'soap:Fault']
for elem in elems:
xml_obj = self._GetXmlIn()
if self.__xml_parser == PYXML:
try:
obj = xml_obj.getElementsByTagName(elem)[0]
except:
envelope = xml_obj.chi... | 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.