code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import Queue
import threading
import time
from collections import defaultdict
class Controller extends Thread
begin
set _shared_state = dict
function __init__ self
begin
set __dict__ = _shared_state
call __init__ self
set _reg = queue
set _registered = default dictionary set
set _send = queue
end function
function reg... | import Queue
import threading
import time
from collections import defaultdict
class Controller(threading.Thread):
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
threading.Thread.__init__(self)
self._reg = Queue.Queue()
self._registered = defaultdict(s... | Python | zaydzuhri_stack_edu_python |
from tests.test_utils.test_utility import *
comment This class tests if queen legal moves are disallowed as intended
class QueenDisallowMovesTests extends TestCase
begin
function setUp self
begin
set gameLogic = call GameLogic
set board = board
comment These 3 methods will wipe the slate clean so we can begin anew
call... | from tests.test_utils.test_utility import *
# This class tests if queen legal moves are disallowed as intended
class QueenDisallowMovesTests(unittest.TestCase):
def setUp(self):
self.gameLogic = GameLogic()
self.board = self.gameLogic.board
# These 3 methods will wipe the slate clean so w... | Python | zaydzuhri_stack_edu_python |
import scrapy
function checkVerified data
begin
set verified_str = extract call xpath string .//span[@data-hook="avp-badge"]/text()
if string Verified Purchase in verified_str
begin
return 1
end
else
begin
return 0
end
end function
function extractComment data
begin
set new_data = call css string .review-text-content
s... | import scrapy
def checkVerified(data):
verified_str = data.xpath('.//span[@data-hook="avp-badge"]/text()').extract()
if "Verified Purchase" in verified_str:
return 1
else:
return 0
def extractComment(data):
new_data = data.css('.review-text-content')
main_comment_str = new_data.xpath('./... | Python | zaydzuhri_stack_edu_python |
comment Given: A simple graph with n vertices in the edge list format
comment Return: An array D where each element is the sum of the degrees of i's neighbours
set adj_dict = dict
comment Read in the input file and create a dictionary for edges
with open string rosalind_ddeg.txt string r as f
begin
set tuple n e = spl... | # Given: A simple graph with n vertices in the edge list format
# Return: An array D where each element is the sum of the degrees of i's neighbours
adj_dict = {}
# Read in the input file and create a dictionary for edges
with open('rosalind_ddeg.txt', 'r') as f:
n, e = f.readline().strip().split()
for line in f:
... | Python | zaydzuhri_stack_edu_python |
function _generate_feed self feed_data
begin
string render feed file with data
set atom_feed = call _render_html string atom.xml feed_data
set feed_path = join path get current directory string public string atom.xml
with open feed_path string wb string utf-8 as f
begin
write f atom_feed
end
end function | def _generate_feed(self, feed_data):
""" render feed file with data
"""
atom_feed = self._render_html('atom.xml', feed_data)
feed_path = os.path.join(os.getcwd(), 'public', 'atom.xml')
with codecs.open(feed_path, 'wb', 'utf-8') as f:
f.write(atom_feed) | Python | jtatman_500k |
function schema_load filename
begin
print call schema_load filename
end function | def schema_load(filename):
print(uc.schema_load(filename)) | Python | nomic_cornstack_python_v1 |
function please_confirm_download self
begin
if length videoids_to_download > 0
begin
print string Videoids to download:
print videoids_to_download
end
print string Total videoids to download: length videoids_to_download
if length videoids_to_download > 0
begin
set ans = input string Y*/n
if ans in list string n string ... | def please_confirm_download(self):
if len(self.videoids_to_download) > 0:
print('Videoids to download:')
print(self.videoids_to_download)
print('Total videoids to download:', len(self.videoids_to_download))
if len(self.videoids_to_download) > 0:
ans = input(' Y*/n ')
if ans in ['n', ... | Python | nomic_cornstack_python_v1 |
function create_workspace_config namespace workspace body
begin
string Create method configuration in workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name body (json) : a filled-in JSON object for the new method config (e.g. see return value of get_workspace_config) Swagg... | def create_workspace_config(namespace, workspace, body):
"""Create method configuration in workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
body (json) : a filled-in JSON object for the new method config
(e.g. see... | Python | jtatman_500k |
function _get_stratum self
begin
return __stratum
end function | def _get_stratum(self):
return self.__stratum | Python | nomic_cornstack_python_v1 |
function main filename
begin
global flag
set f = open filename
set ouf = open string 1output.txt string w
set num_of_tests = integer read line f
for test_i in range num_of_tests
begin
set line = split read line f string
set n = integer line at 0
set m = integer line at 1
set line = split read line f string
set p = list... | def main(filename):
global flag
f = open(filename)
ouf = open("1output.txt", "w")
num_of_tests = int(f.readline())
for test_i in range(num_of_tests):
line = f.readline().split(" ")
n = int(line[0])
m = int(line[1])
line = f.readline().split(" ")
p = [0.0] + ma... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from xalglib import smatrixtd
from scipy.linalg import eigh_tridiagonal
from matplotlib import pyplot as plt
function is_symmetric m rtol=1e-05 atol=1e-08
begin
return call allclose m T rtol=rtol atol=atol
end function
function symmetric_to_tridiagonal m
begin
return call smatrixtd call tolist length... | import numpy as np
from xalglib import smatrixtd
from scipy.linalg import eigh_tridiagonal
from matplotlib import pyplot as plt
def is_symmetric(m, rtol=1e-5, atol=1e-8):
return np.allclose(m, m.T, rtol=rtol, atol=atol)
def symmetric_to_tridiagonal(m):
return smatrixtd(m.tolist(), len(m), False)
def solve... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from tkinter import messagebox as ms
from reservationGUI import *
import sqlite3
comment main Class
class PassengerDetailsGUI
begin
function __init__ self
begin
comment Window
comment self.master = master
comment .configure(background = "#a1dbcd")
comment Some Usefull variables
set firstname = cal... | from tkinter import *
from tkinter import messagebox as ms
from reservationGUI import *
import sqlite3
#main Class
class PassengerDetailsGUI:
def __init__(self):
# Window
#self.master = master
#.configure(background = "#a1dbcd")
# Some Usefull variables
sel... | Python | zaydzuhri_stack_edu_python |
function print_hello_world num_times
begin
for i in range 1 num_times + 1
begin
print string Hello World!
end
print string Total iterations: { num_times }
end function
call print_hello_world 100
function print_hello_world num_times
begin
set i = 1
while i <= num_times
begin
print string { i } Hello World!
set i = i + 1... | def print_hello_world(num_times):
for i in range(1, num_times+1):
print('Hello World!')
print(f'Total iterations: {num_times}')
print_hello_world(100)
def print_hello_world(num_times):
i = 1
while i <= num_times:
print(f'{i} Hello World!')
i += 1
print(f'Total iterations: ... | Python | jtatman_500k |
function px_size self
begin
set tuple xp yp = tuple call c_float call c_float
call GetPixelSize call pointer xp call pointer yp
return tuple value value
end function | def px_size(self):
xp, yp = ct.c_float(), ct.c_float()
self.lib.GetPixelSize(ct.pointer(xp), ct.pointer(yp))
return (xp.value, yp.value) | Python | nomic_cornstack_python_v1 |
function isConnected self
begin
return false
end function | def isConnected(self):
return False | Python | nomic_cornstack_python_v1 |
import random
string Used for Quora Question Pairs corpus
class QuestionPairs
begin
function __init__ self question_a question_b is_duplicate
begin
set question_a = question_a
set question_b = question_b
comment for testing
comment self.is_duplicate = str(random.choice([i for i in range(10)]))
set is_duplicate = is_dup... | import random
"""
Used for Quora Question Pairs corpus
"""
class QuestionPairs:
def __init__(self, question_a, question_b, is_duplicate):
self.question_a = question_a
self.question_b = question_b
#for testing
#self.is_duplicate = str(random.choice([i for i in range(10)]))
s... | Python | zaydzuhri_stack_edu_python |
comment array = [1, 2, 3, 9], sum = 8
comment array2 = [1, 2, 4, 4], sum = 8
comment def bruteCheckSumInArray(array, sum):
comment for i in range(0, len(array)-1):
comment for j in range(i+1, len(array)):
comment if array[i]+array[j] == sum:
comment return True
comment return False
comment print(bruteCheckSumInArray([1... | # array = [1, 2, 3, 9], sum = 8
# array2 = [1, 2, 4, 4], sum = 8
# def bruteCheckSumInArray(array, sum):
# for i in range(0, len(array)-1):
# for j in range(i+1, len(array)):
# if array[i]+array[j] == sum:
# return True
# return False
#
# print(bruteCheckSumInArray([1, 2, 3,... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Fri Mar 27 13:23:02 2020 @author: pranavmanjunath
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import LabelBina... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 27 13:23:02 2020
@author: pranavmanjunath
"""
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import LabelBinarizer
f... | Python | zaydzuhri_stack_edu_python |
function type self
begin
return get pulumi self string type
end function | def type(self) -> str:
return pulumi.get(self, "type") | Python | nomic_cornstack_python_v1 |
function _fix_guid config guid
begin
if config at string dir_guid_source == string objectGUID
begin
return string uuid bytes_le=guid
end
else
begin
return guid
end
end function | def _fix_guid(config, guid):
if config['dir_guid_source'] == 'objectGUID':
return str(
uuid.UUID(bytes_le=guid)
)
else:
return guid | Python | nomic_cornstack_python_v1 |
function reset self
begin
set state = copy copy mu
end function | def reset(self):
self.state = copy.copy(self.mu) | Python | nomic_cornstack_python_v1 |
function left p q
begin
decorator call parser p q
function _left x _
begin
return x
end function
return _left
end function | def left(p, q):
@parser(p, q)
def _left(x, _):
return x
return _left | Python | nomic_cornstack_python_v1 |
function insertion_sort items key
begin
comment if order == "reverse":
comment compare = operator.lt
comment elif order == "normal":
comment compare = operator.gt
global COMPARE
comment Repeat until all items are in sorted order
for index in range length items
begin
set iterator = index
comment Take first unsorted item... | def insertion_sort(items, key):
# if order == "reverse":
# compare = operator.lt
# elif order == "normal":
# compare = operator.gt
global COMPARE
# Repeat until all items are in sorted order
for index in range(len(items)):
iterator = index
# Take first unsorted item... | Python | nomic_cornstack_python_v1 |
function image2html imagefile title=string alt=string
begin
return string <!DOCTYPE html> <html lang="en"> <head> <style> h2 {text-align: center;} .center { display: block; margin-left: auto; margin-right: auto; width: 80%; } </style> </head> <body> <h2> + title + string </h2> + string <img src=" { imagefile } " alt="... | def image2html(imagefile, title='', alt=''):
return """
<!DOCTYPE html>
<html lang="en">
<head>
<style>
h2 {text-align: center;}
.center {
display: block;
margin-left: auto;
margin-right: auto;
width: 80%... | Python | nomic_cornstack_python_v1 |
function token_store_enabled self
begin
return get pulumi self string token_store_enabled
end function | def token_store_enabled(self) -> Optional[bool]:
return pulumi.get(self, "token_store_enabled") | Python | nomic_cornstack_python_v1 |
comment actual logic to read data and print it by calling getOutputString function
set outputList = list
with open string C:/Users/rpant/Desktop/Python_Programs/CountingSheep/input.txt as data
begin
set totalNumberOfCases = read line data
for index in range integer totalNumberOfCases
begin
set integerList = set
set te... | #actual logic to read data and print it by calling getOutputString function
outputList = []
with open ('C:/Users/rpant/Desktop/Python_Programs/CountingSheep/input.txt') as data :
totalNumberOfCases = data.readline()
for index in range (int(totalNumberOfCases)):
integerList = set()
testCaseStr = data.readline().s... | Python | zaydzuhri_stack_edu_python |
function destroy self
begin
call __destroy
end function | def destroy(self):
self.__destroy() | Python | nomic_cornstack_python_v1 |
comment 3.3 - While Loops
comment In this example there will be 5 different tasks to complete using
comment For Loops. Make sure to run your code in between each task
comment to make sure that program is working correctly before moving on.
comment Task 1: Print each item in the given list 'materials'.
comment Your prog... | # 3.3 - While Loops
# In this example there will be 5 different tasks to complete using
# For Loops. Make sure to run your code in between each task
# to make sure that program is working correctly before moving on.
# Task 1: Print each item in the given list 'materials'.
# Your program should use a simple for loop... | Python | zaydzuhri_stack_edu_python |
import math
import pylab as pl
import random
class randomwalk
begin
function __init__ self
begin
set x = list
set y = list
for i in range 500001
begin
append x list
append y list
end
for i in range 400
begin
append x at 0 random integer - 5 5
append y at 0 random integer - 5 5
end
for i in range 500001
begin
for j in... | import math
import pylab as pl
import random
class randomwalk:
def __init__(self):
self.x=[]
self.y=[]
for i in range(500001):
self.x.append([])
self.y.append([])
for i in range(400):
self.x[0].append(random.randint(-5,5))
s... | Python | zaydzuhri_stack_edu_python |
function test_updates_context app
begin
with call test_request_context
begin
decorator context_processor
function inject_rudolf
begin
return dictionary rudolf=string The red-nosed reindeer
end function
set rendered = call render_response string context.html
comment TODO DOCTYPE; see also render_args
set expected_data =... | def test_updates_context(app):
with app.test_request_context():
@app.context_processor
def inject_rudolf():
return dict(rudolf='The red-nosed reindeer')
rendered = render_response('context.html')
# TODO DOCTYPE; see also render_args
expected_data = b'<pre>rudol... | Python | nomic_cornstack_python_v1 |
function fft_smoothing self d param
begin
set rft = call rfft d
set rft at slice integer param : : = 0.0
set d = call irfft rft length d
return d
end function | def fft_smoothing(self, d, param):
rft = np.fft.rfft(d)
rft[int(param):] = 0.
d = np.fft.irfft(rft, len(d))
return d | Python | nomic_cornstack_python_v1 |
function test_str_length self
begin
set xknx = call XKNX
set sensor = call Sensor xknx string TestSensor group_address_state=string 1/2/3 value_type=string length
set payload = call DPTArray tuple 197 157 174 197
assert equal call resolve_state - 5045.84619140625
assert equal call unit_of_measurement string m
assert eq... | def test_str_length(self):
xknx = XKNX()
sensor = Sensor(
xknx, "TestSensor", group_address_state="1/2/3", value_type="length"
)
sensor.sensor_value.payload = DPTArray(
(
0xC5,
0x9D,
0xAE,
0xC5,
... | Python | nomic_cornstack_python_v1 |
import numpy as np
class Savez extends object
begin
function __init__ self zipfilename
begin
import zipfile , tempfile , os , sys
if is instance zipfilename basestring
begin
if not ends with zipfilename string .npz
begin
set zipfilename = zipfilename + string .npz
end
end
comment original _savez has no compression
set ... | import numpy as np
class Savez(object):
def __init__(self, zipfilename):
import zipfile, tempfile, os, sys
if isinstance(zipfilename, basestring):
if not zipfilename.endswith('.npz'):
zipfilename += '.npz'
# original _savez has no compression
compressio... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import sys
class BigDigits
begin
function run self
begin
comment self.Digits = self.int_list()
set Digits = call num_list
try
begin
set digits = argv at 1
set row = 0
while row < 7
begin
set line = string
set column = 0
while column < length digits
begin
set number = integer digits at col... | #!/usr/bin/env python3
import sys
class BigDigits():
def run(self):
# self.Digits = self.int_list()
self.Digits = self.num_list()
try:
digits = sys.argv[1]
row = 0
while row < 7:
line = ""
column = 0
while... | Python | zaydzuhri_stack_edu_python |
function dump d fmt=string json stream=none
begin
string Serialize structured data into a stream in JSON, YAML, or LHA format. If stream is None, return the produced string instead. Parameters: - fmt: should be 'json' (default), 'yaml', or 'lha' - stream: if None, return string
if fmt == string json
begin
return call _... | def dump(d, fmt='json', stream=None):
"""Serialize structured data into a stream in JSON, YAML, or LHA format.
If stream is None, return the produced string instead.
Parameters:
- fmt: should be 'json' (default), 'yaml', or 'lha'
- stream: if None, return string
"""
if fmt == 'json':
... | Python | jtatman_500k |
function iterate_ia page result
begin
if not is instance ast Root
begin
return
end
set ia = get options string ia
if not is instance ia List
begin
return
end
for entry in ia
begin
set curr : Dict at tuple str SerializableType = dict none entry ; string children list
if is instance result at string children List
begin
... | def iterate_ia(page: Page, result: Dict[str, SerializableType]) -> None:
if not isinstance(page.ast, n.Root):
return
ia = page.ast.options.get("ia")
if not isinstance(ia, List):
return
for entry in ia:
curr: Dict[str, Seria... | Python | nomic_cornstack_python_v1 |
import sys
call setrecursionlimit 10 ^ 9
function XOR a b n
begin
if n == 0
begin
return a
end
else
if n == 1
begin
return b
end
else
if n == 2
begin
return a ? b
end
return call XOR a b n % 3
end function
if __name__ == string __main__
begin
set tuple a b n = list map int split strip input
print call XOR a b n
end | import sys
sys.setrecursionlimit(10**9)
def XOR(a,b,n):
if n == 0:
return a
elif n == 1:
return b
elif n == 2:
return a^b
return XOR(a,b,n % 3)
if __name__ == "__main__":
a,b,n = list(map(int,input().strip().split()))
print(XOR(a,b,n))
| Python | zaydzuhri_stack_edu_python |
function generate_tempfile self file_content=none
begin
set local_tempfile = named temporary file delete=false
write local_tempfile encode file_content string UTF-8
close local_tempfile
return name
end function | def generate_tempfile(self, file_content=None):
local_tempfile = tempfile.NamedTemporaryFile(delete=False)
local_tempfile.write(file_content.encode('UTF-8'))
local_tempfile.close()
return local_tempfile.name | Python | nomic_cornstack_python_v1 |
function test_subscriptions_user_tracking_get self
begin
set response = open string /exampleAPI/location/v1//subscriptions/userTracking method=string GET content_type=string application/json
call assert200 response string Response body is : + decode data string utf-8
end function | def test_subscriptions_user_tracking_get(self):
response = self.client.open(
'/exampleAPI/location/v1//subscriptions/userTracking',
method='GET',
content_type='application/json')
self.assert200(response,
'Response body is : ' + response.data.dec... | Python | nomic_cornstack_python_v1 |
comment --------------------------------------------------#
comment grid_search.py #
comment Author: Eric Ham #
comment Description: Contains functions for grid search #
comment over models. #
comment --------------------------------------------------#
import numpy as np
import itertools
from train_lunar_net import tra... | #--------------------------------------------------#
# grid_search.py #
# Author: Eric Ham #
# Description: Contains functions for grid search #
# over models. #
#--------------------------------------------------#
i... | Python | zaydzuhri_stack_edu_python |
comment Write your code here :-)
comment Functions in list
function func
begin
print string Inside func
end function
function disp
begin
print string Inside disp
end function
function msg
begin
print string Inside msg
end function
set lst = list func disp msg
for f in lst
begin
f dist
end
set lst1 = list 1 2 3 4 5 6
se... | # Write your code here :-)
#Functions in list
def func():
print('Inside func')
def disp():
print('Inside disp')
def msg():
print('Inside msg')
lst = [func, disp, msg]
for f in lst:
f()
############################################
lst1 = [1,2,3,4,5,6]
lst2 = [9,8,7,6,5,4]
maplst = map(lambda n1,n2 : ... | Python | zaydzuhri_stack_edu_python |
comment 求定积分
comment 不同角度的文字的分布假设为期望为μ,方差为σ的正态分布
comment 取μ=0,取3σ=max_angle 得到σ=10
import scipy.stats as stats
import numpy as np
function calc_norm miu sigma lower upper
begin
return call cdf call normalize upper miu sigma - call cdf call normalize lower miu sigma
end function
function normalize z miu sigma
begin
retu... | # 求定积分
# 不同角度的文字的分布假设为期望为μ,方差为σ的正态分布
# 取μ=0,取3σ=max_angle 得到σ=10
import scipy.stats as stats
import numpy as np
def calc_norm(miu, sigma, lower, upper):
return stats.norm.cdf(normalize(upper, miu, sigma)) - stats.norm.cdf(normalize(lower, miu, sigma))
def normalize(z, miu, sigma):
return (z - miu) / sigma
... | Python | zaydzuhri_stack_edu_python |
function available_indices cluster
begin
set indices = set
for tuple index_name data in items call get_alias
begin
add indices index_name
update indices keys data at string aliases
end
return indices
end function | def available_indices(cluster):
indices = set()
for index_name, data in cluster.indices.get_alias().items():
indices.add(index_name)
indices.update(data['aliases'].keys())
return indices | Python | nomic_cornstack_python_v1 |
from collections import defaultdict
from typing import Set , Tuple , Iterable , Callable
from bisect import bisect , insort
from src.solutions.models.Side import Side
from src.solutions.models.Square import Square
from src.solutions.utils.flatten import flatten
from src.solutions.utils.max_elements import max_elements
... | from collections import defaultdict
from typing import Set, Tuple, Iterable, Callable
from bisect import bisect, insort
from src.solutions.models.Side import Side
from src.solutions.models.Square import Square
from src.solutions.utils.flatten import flatten
from src.solutions.utils.max_elements import max_elements
fro... | Python | zaydzuhri_stack_edu_python |
function solid self
begin
return not not solid
end function | def solid(self):
return not not self.prototype.solid | Python | nomic_cornstack_python_v1 |
function serialize model
begin
comment first we get the names of all the columns on your model
set columns = list comprehension key for c in columns
comment then we return their values in a dict
return dictionary generator expression tuple c get attribute model c for c in columns
end function | def serialize(model):
# first we get the names of all the columns on your model
columns = [c.key for c in class_mapper(model.__class__).columns]
# then we return their values in a dict
return dict((c, getattr(model, c)) for c in columns) | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function twoOutOfThree self nums1 nums2 nums3
begin
set c1 = set nums1
set c2 = set nums2
set c3 = set nums3
return list c1 ? c2 ? c1 ? c3 ? c2 ? c3
end function
end class
set nums1 = list 1 1 3 2
set nums2 = list 2 3
set nums3 = list 3
set nums1 = list 3 1
set nums2 = list ... | from typing import List
class Solution:
def twoOutOfThree(self, nums1: List[int], nums2: List[int],
nums3: List[int]) -> List[int]:
c1 = set(nums1)
c2 = set(nums2)
c3 = set(nums3)
return list(c1 & c2 | c1 & c3 | c2 & c3)
nums1 = [1, 1, 3, 2]
nums2 = [2, 3]
... | Python | zaydzuhri_stack_edu_python |
function __getattr__ self name
begin
if has attribute fo name
begin
return get attribute fo name
end
end function | def __getattr__(self, name):
if hasattr(self.fo, name):
return getattr(self.fo, name) | Python | nomic_cornstack_python_v1 |
function save_obj self name vertices faces img_id=- 1
begin
set obj_path = join path save_obj_dir name
if img_id > - 1
begin
set obj_path = join path save_obj_dir_list at img_id name
end
with open obj_path string w as fp
begin
for v in vertices
begin
write fp string v %f %f %f % tuple v at 0 v at 1 v at 2
end
comment F... | def save_obj(self, name, vertices, faces, img_id=-1):
obj_path = os.path.join(self.save_obj_dir, name)
if img_id > -1:
obj_path = os.path.join(self.save_obj_dir_list[img_id], name)
with open(obj_path, 'w') as fp:
for v in vertices:
fp.write('v %f %f %f\n'... | Python | nomic_cornstack_python_v1 |
from array import *
comment first argument is bytecode and represents what the array will be made of
set array = array string i list 1 2 3 4 5
for x in array
begin
print x
end
print array at 0
insert array 1 60
for y in array
begin
print y
end
remove array 60
for x in array
begin
print x
end
print index array 5
set arr... | from array import *
# first argument is bytecode and represents what the array will be made of
array = array('i', [1,2,3,4,5])
for x in array: print(x)
print(array[0])
array.insert(1, 60)
for y in array: print(y)
array.remove(60)
for x in array: print(x)
print(array.index(5))
array[4] = 60
for x in array: print(x... | Python | zaydzuhri_stack_edu_python |
function sum_array arr
begin
set stack = list arr
set total_sum = 0
while stack
begin
set element = pop stack
if is instance element int
begin
set total_sum = total_sum + element
end
else
if is instance element list
begin
extend stack element
end
else
if is instance element dict
begin
extend stack values element
end
en... | def sum_array(arr):
stack = [arr]
total_sum = 0
while stack:
element = stack.pop()
if isinstance(element, int):
total_sum += element
elif isinstance(element, list):
stack.extend(element)
elif isinstance(element, dict):
stack.extend(elemen... | Python | jtatman_500k |
function test23a self
begin
exit 0
end function | def test23a(self):
self.spawn("./binary").stdin("1").stdin("12").stdin("0").stdin("0").stdin("0").stdin("1").stdin("0").stdin("1").stdin("1").stdin("1").stdout("23\n").exit(0) | Python | nomic_cornstack_python_v1 |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser , BaseUserManager
comment Create your models here.
comment A custom user model needs a user manager
class UserManager extends BaseUserManager
begin
function create_user self email username firstname lastname password=none
begin
if not ... | from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
# Create your models here.
# A custom user model needs a user manager
class UserManager(BaseUserManager):
def create_user(self, email, username, firstname, lastname, password=None):
if not email:
... | Python | zaydzuhri_stack_edu_python |
function _gpg_keys self
begin
return call list_keys
end function | def _gpg_keys(self) -> ListKeys:
return self.gpg.list_keys() | Python | nomic_cornstack_python_v1 |
function _get_vehicle self vehicle
begin
set vehicle_bp = find blueprint_lib vehicle
set spawn_point = random choice call get_spawn_points
set last_location = location
set vehicle = none
for _ in range 10
begin
comment this will return None if spawning failed
set vehicle = call try_spawn_actor vehicle_bp spawn_point
if... | def _get_vehicle(self, vehicle):
vehicle_bp = self.blueprint_lib.find(vehicle)
spawn_point = random.choice(self.world.get_map().get_spawn_points())
self.last_location = spawn_point.location
vehicle = None
for _ in range(10):
vehicle = self.world.try_spawn_actor(vehicl... | Python | nomic_cornstack_python_v1 |
function value self
begin
return get pulumi self string value
end function | def value(self) -> pulumi.Input[str]:
return pulumi.get(self, "value") | Python | nomic_cornstack_python_v1 |
function create_objects self data
begin
set metadata_from_server = list
for item in data
begin
set metadata = item at string metadata
set parent_url = metadata at hasParent
if not parent_url
begin
set parent_url = string
end
else
begin
set parent_url = string parent_url at 0
del metadata at hasParent
end
set parent_u... | def create_objects(self, data):
metadata_from_server = []
for item in data:
metadata = item['metadata']
parent_url = metadata[FEDORA.hasParent]
if not parent_url:
parent_url = ''
else:
parent_url = str(parent_url[0])
... | Python | nomic_cornstack_python_v1 |
function count_ambig curr_seq valid_chars=string ATCG
begin
set up_seq = upper curr_seq
set total = 0
for vchar in valid_chars
begin
set total = total + count up_seq vchar
end
return length curr_seq - total
end function | def count_ambig(curr_seq, valid_chars='ATCG'):
up_seq = curr_seq.upper()
total = 0
for vchar in valid_chars:
total += up_seq.count(vchar)
return len(curr_seq) - total | Python | nomic_cornstack_python_v1 |
import random
import timeit
string Script for exploring the methods of searching for a phrase in a text The two main methods are naive() and rabin_karp(). Naive implements a brute force method and works in O(T*P), where T and P correspond to the length of the text and phrase respectively. The Rabin-Karp algorithm uses ... | import random
import timeit
"""
Script for exploring the methods of searching for a phrase in a text
The two main methods are naive() and rabin_karp(). Naive implements a brute force method and works in O(T*P), where
T and P correspond to the length of the text and phrase respectively. The Rabin-Karp algorithm uses... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import sys
import numpy as np
import datetime as dt
comment https://justindomke.wordpress.com/2012/09/17/julia-matlab-and-c/
function f x
begin
return exp sin x at 0 * 5 - x at 0 * x at 0 - x at 1 * x at 1
end function
function mcmc x N
begin
set p = f dist x
for n in range N
begin
set x2 =... | #!/usr/bin/env python
import sys
import numpy as np
import datetime as dt
# https://justindomke.wordpress.com/2012/09/17/julia-matlab-and-c/
def f(x):
return np.exp(np.sin(x[0]*5) - x[0]*x[0] - x[1]*x[1])
def mcmc(x,N):
p = f(x)
for n in range(N):
x2 = x + .01*np.random.randn(x.size)
p2 = ... | Python | zaydzuhri_stack_edu_python |
1 + 2
100 - 1
7 * 52
1024 / 8
1 / 2
1 // 2
4 / 3
4 // 3
7 % 3
7.5 % 3
4 % 2.1
3.1415926535 * 3 * 3
3.1415926535 * 3 ^ 2
3.141592 % 5.77
4.56789 % 3.33
set pi = 3.1415926535
pi * 4 ^ 2
pi * 2.5 ^ 2
pi * 8 ^ 2
print pi
pi
set r = 7
set area = pi * r ^ 2
print area
area
set r = 11
set area = pi * r ^ 2
area
r ^ 2 * pi
set... | 1+2
100-1
7*52
1024/8
1/2
1//2
4/3
4//3
7%3
7.5%3
4%2.1
3.1415926535 * (3*3)
3.1415926535 * 3**2
3.141592 % 5.77
4.56789%3.33
pi = 3.1415926535
pi *4 **2
pi*2.5 **2
pi * 8 ** 2
print(pi)
pi
r=7
area= pi *r **2
print(area)
area
r=11
area = pi *r **2
area
r**2 * pi
name1 = "Trump"
name2='강다니... | Python | zaydzuhri_stack_edu_python |
import os
for tuple root dirs files in walk string ./
begin
for name in files
begin
if string .py in name and string .pyc not in name
begin
print join path root name
end
end
end | import os
for root, dirs, files in os.walk("./"):
for name in files:
if ".py" in name and ".pyc" not in name:
print(os.path.join(root, name))
| Python | zaydzuhri_stack_edu_python |
comment --------------- Helpers that build all of the responses ----------------------
function build_speechlet_response card output reprompt_text should_end_session
begin
set speech_dict = dict string shouldEndSession should_end_session
set speech_dict at string outputSpeech = dict string type string SSML ; string ssm... | # --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(card, output, reprompt_text, should_end_session):
speech_dict = {'shouldEndSession': should_end_session}
speech_dict['outputSpeech'] = {
'type': 'SSML',
'ssml': '<speak> ' + output ... | Python | zaydzuhri_stack_edu_python |
comment 이진수 변환기
set input_number = input string 수를 입력하세요 >>
comment 정수부와 소수부를 나누기
set pos = find input_number string .
comment 소수점을 찾으면
if pos != - 1
begin
set tuple Z_number point_number = tuple integer input_number at slice : pos : integer input_number at slice pos + 1 : :
end
comment print(real_number, point_numbe... | #이진수 변환기
input_number = input("수를 입력하세요 >> ")
#정수부와 소수부를 나누기
pos = input_number.find('.')
if pos != -1 : #소수점을 찾으면
Z_number, point_number = int(input_number[:pos]), int(input_number[pos+1:])
#print(real_number, point_number)
#정수부는 2로 나눈 나머지에 대한 것
ans_Z = ""
if Z_number > 0 : # 양수이면
while Z_number != 0 ... | Python | zaydzuhri_stack_edu_python |
from lor_deckcodes import LoRDeck
function decode deck
begin
set codes = list call from_deckcode deck
set cards = list
for code in codes
begin
for i in range integer code at 0
begin
append cards code at slice 2 : :
end
end
return join string cards
end function
function get_card_array deck
begin
set codes = list call... | from lor_deckcodes import LoRDeck
def decode(deck):
codes = list(LoRDeck.from_deckcode(deck))
cards = []
for code in codes:
for i in range(int(code[0])):
cards.append(code[2:])
return " ".join(cards)
def get_card_array(deck):
codes = list(LoRDeck.from_deckcode(deck))
cards... | Python | zaydzuhri_stack_edu_python |
from atm_card import ATMCard
class Customer
begin
function __init__ self id custPin custBalance
begin
set id = id
set custPin = custPin
set custBalance = custBalance
end function
function getID self
begin
return id
end function
function getCustPin self
begin
return custPin
end function
function getCustBalance self
begi... | from atm_card import ATMCard
class Customer:
def __init__(self, id, custPin, custBalance):
self.id = id
self.custPin = custPin
self.custBalance = custBalance
def getID(self):
return self.id
def getCustPin(self):
return self.custPin
def getCustBalance(self)... | Python | zaydzuhri_stack_edu_python |
comment Print all subarrays with 0 sum
comment Given an array, print all subarrays in the array which has sum 0.
function AllSubArraySum ary
begin
set dict = dict
set sum = 0
set fnl_lst = list
for i in range 0 length ary
begin
set sum = sum + ary at i
if sum == 0
begin
set tup = tuple 0 i
append fnl_lst tup
end
else... | # Print all subarrays with 0 sum
# Given an array, print all subarrays in the array which has sum 0.
def AllSubArraySum(ary):
dict={}
sum=0
fnl_lst=[]
for i in range(0,len(ary)):
sum=sum+ary[i]
if sum==0:
tup=(0,i)
fnl_lst.append(tup)
else:
... | Python | zaydzuhri_stack_edu_python |
import turtle
set distance = 0.5
call shape string turtle
for x in range 1 150
begin
if x % 2 == 0
begin
set distance = distance + 0.5
end
call forward distance
call left 30
end | import turtle
distance = 0.5
turtle.shape("turtle")
for x in range (1, 150):
if x % 2 == 0:
distance += 0.5
turtle.forward(distance)
turtle.left(30) | Python | zaydzuhri_stack_edu_python |
string Library with VNS constraints for solution
comment local imports
from contextlib import contextmanager
decorator contextmanager
function import_from rel_path
begin
string Add module import relative path to sys.path
import sys
import os
set cur_dir = directory name path absolute path path __file__
insert path 0 jo... | """
Library with VNS constraints for solution
"""
# local imports
from contextlib import contextmanager
@contextmanager
def import_from(rel_path):
"""Add module import relative path to sys.path"""
import sys
import os
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.... | Python | zaydzuhri_stack_edu_python |
import sys
from json import dumps , loads
function process path functionName
begin
set content = read open path string r
set json = loads content
set samples = list
set id = - 1
set prevId = - 1
end function | import sys
from json import dumps, loads
def process(path, functionName):
content = open(path, 'r').read()
json = loads(content)
samples = []
id = -1
prevId = -1 | Python | zaydzuhri_stack_edu_python |
comment 3. Массив размером 2m + 1, где m – натуральное число, заполнен случайным образом.
comment Найти в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части:
comment в одной находятся элементы, которые не меньше медианы, в другой – не больше ее.
comment Задачу можно решить без сортировки... | # 3. Массив размером 2m + 1, где m – натуральное число, заполнен случайным образом.
# Найти в массиве медиану. Медианой называется элемент ряда, делящий его на две равные части:
# в одной находятся элементы, которые не меньше медианы, в другой – не больше ее.
#
# Задачу можно решить без сортировки исходного массива. Но... | Python | zaydzuhri_stack_edu_python |
function expand self insitu=true
begin
if insitu
begin
set objects = call _expand
return self
end
else
begin
set obj = call __class__ name description
set objects = call _expand
call expand
return obj
end
end function | def expand(self, insitu=True):
if insitu:
self.objects = self._expand()
return self
else:
obj = self.__class__(self.name, self.description)
obj.objects = self._expand()
obj.expand()
return obj | Python | nomic_cornstack_python_v1 |
function index
begin
return string <html><head> <title>get_time function</title> </head> <body> <FORM value="form" action="hello.py/get_info" method="post"> <P> <LABEL for="firstname">First name: </LABEL> <INPUT type="text" name="firstname"><BR> <LABEL for="lastname">Last name: </LABEL> <INPUT type="text" name="lastnam... | def index():
return """
<html><head>
<title>get_time function</title>
</head>
<body>
<FORM value="form" action="hello.py/get_info" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" name="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" name="lastname"... | Python | zaydzuhri_stack_edu_python |
function rebuild_index_for_model model_ engine_slug_ verbosity_ slim_=false batch_size_=100 non_atomic_=false
begin
set search_engine_ = call get_engine engine_slug_
comment HACK: Allows assignment to outer scope.
set local_refreshed_model_count = list 0
function iter_search_entries
begin
comment Only index specified o... | def rebuild_index_for_model(model_, engine_slug_, verbosity_, slim_=False, batch_size_=100, non_atomic_=False):
search_engine_ = get_engine(engine_slug_)
local_refreshed_model_count = [0] # HACK: Allows assignment to outer scope.
def iter_search_entries():
# Only index specified objects if slim_... | Python | nomic_cornstack_python_v1 |
import smtplib
from email.mime.text import MIMEText
from email.header import Header
set settings = dict
function setup mail_host mail_user mail_pass
begin
global settings
set settings = dict string mail_host mail_host ; string mail_user mail_user ; string mail_pass mail_pass
end function
comment 服务器
comment 用户名
commen... | import smtplib
from email.mime.text import MIMEText
from email.header import Header
settings = {}
def setup(mail_host, mail_user, mail_pass):
global settings
settings = {
"mail_host": mail_host, # 服务器
"mail_user": mail_user, # 用户名
"mail_pass": mail_pass # 口令
}
def send_email... | Python | zaydzuhri_stack_edu_python |
function xpmPicker *args fileName=string parent=string **kwargs
begin
pass
end function | def xpmPicker(*args, fileName: AnyStr="", parent: AnyStr="", **kwargs)->AnyStr:
pass | Python | nomic_cornstack_python_v1 |
function __get_object_file doc
begin
set obj_file = named temporary file delete=false
with open name string w as outfile
begin
write outfile dump doc default_style=string "
close outfile
end
return name
end function | def __get_object_file(doc):
obj_file = tempfile.NamedTemporaryFile(delete=False)
with open(obj_file.name, 'w') as outfile:
outfile.write(yaml.dump(doc, default_style='"'))
outfile.close()
return obj_file.name | Python | nomic_cornstack_python_v1 |
function get_dict_stack_info ar_iterations forecast_cycle input_k output_k stack_most_recent_prediction=true
begin
set input_k = call check_input_k input_k ar_iterations
set output_k = call check_output_k output_k
comment Compute index of Y labels
set dict_Y = dict
for i in range ar_iterations + 1
begin
set dict_Y at ... | def get_dict_stack_info(
ar_iterations, forecast_cycle, input_k, output_k, stack_most_recent_prediction=True
):
input_k = check_input_k(input_k, ar_iterations)
output_k = check_output_k(output_k)
# Compute index of Y labels
dict_Y = {}
for i in range(ar_iterations + 1):
dict_Y[i] = get_i... | Python | nomic_cornstack_python_v1 |
function lost_new_stillthere existing found ex_dic dat_tim
begin
set exist_set = set existing
set found_set = set found
set unchanged = list exist_set ? found_set
set new_found = list found_set - exist_set
comment print (f"Unchanged = {unchanged}")
comment print(f"new_found = {new_found}")
call update_stored unchanged ... | def lost_new_stillthere(existing, found, ex_dic, dat_tim):
exist_set = set(existing)
found_set = set(found)
unchanged = list(exist_set & found_set)
new_found = list(found_set - exist_set)
# print (f"Unchanged = {unchanged}")
# print(f"new_found = {new_found}")
update_stored(unchanged, new_... | Python | nomic_cornstack_python_v1 |
function move_board self direction
begin
set vector = call vector
set vector_x = vector at 0
set vector_y = vector at 1
set moveRow = vector_x != 0
set moveColumn = vector_y != 0
if moveRow and moveColumn
begin
raise exception string Can't move both a row and a column at the same time!
end
set before_move = GameBoard
i... | def move_board(self, direction):
vector = direction.vector()
vector_x = vector[0]
vector_y = vector[1]
moveRow = vector_x != 0
moveColumn = vector_y != 0
if (moveRow and moveColumn):
raise Exception("Can't move both a row and a column at the same time!")
... | Python | nomic_cornstack_python_v1 |
function password self
begin
return get pulumi self string password
end function | def password(self) -> pulumi.Input[str]:
return pulumi.get(self, "password") | Python | nomic_cornstack_python_v1 |
for i in range 9
begin
print i
end
for else
begin
print string This is inside else of for
end | for i in range(9):
print(i)
else:
print("This is inside else of for")
| Python | zaydzuhri_stack_edu_python |
from lxml import etree as ET
from tqdm import tqdm
from nltk.corpus import wordnet as wn
import global_paths as gp
import string
import re
from nltk.stem import WordNetLemmatizer
comment USED TO CLEAN THE DATA
comment chars_to_remove = ".,?!'""-:_()[]{};"
set chars_to_remove = punctuation
function mfs lemma POS w2b_map... | from lxml import etree as ET
from tqdm import tqdm
from nltk.corpus import wordnet as wn
import global_paths as gp
import string
import re
from nltk.stem import WordNetLemmatizer
#USED TO CLEAN THE DATA
#chars_to_remove = ".,?!'""-:_()[]{};"
chars_to_remove = string.punctuation
def mfs(lemma,POS,w2b_map):
'''
... | Python | zaydzuhri_stack_edu_python |
function stop_simulation self *args **kwargs
begin
try
begin
call helicsFederateFinalize fed
call helicsFederateFree fed
call helicsCloseLibrary
end
except HelicsException as e
begin
exception format string Error stopping HELICS federate {} e
end
end function | def stop_simulation(self, *args, **kwargs):
try:
h.helicsFederateFinalize(self.fed)
h.helicsFederateFree(self.fed)
h.helicsCloseLibrary()
except h._helics.HelicsException as e:
_log.exception("Error stopping HELICS federate {}".format(e)) | Python | nomic_cornstack_python_v1 |
function getRouterInfo self router=none
begin
set data = call _getRouterInfo router
return call DirectResponse data=call marshal data
end function | def getRouterInfo(self, router=None):
data = self._getRouterInfo(router)
return DirectResponse(data=Zuul.marshal(data)) | Python | nomic_cornstack_python_v1 |
function readfile filepath delimiter
begin
with open filepath string r as f
begin
for line in f
begin
return split line delimiter
end
end
end function
comment Press the green button in the gutter to run the script.
if __name__ == string __main__
begin
set numberOfTriangleWords = 0
set triangleNumber = list
for i in ra... | def readfile(filepath, delimiter):
with open(filepath, 'r') as f:
for line in f:
return line.split(delimiter)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
numberOfTriangleWords = 0
triangleNumber = []
for i in range(1, 25):
triangleNu... | Python | zaydzuhri_stack_edu_python |
function remove self item
begin
set previous = none
set current = head
while current is not none
begin
if call get_data == item
begin
comment If the item to be removed is the first item
if previous is none
begin
set head = call get_next
end
else
begin
call set_next call get_next
end
return
end
else
comment Early stop
i... | def remove(self, item):
previous = None
current = self.head
while current is not None:
if current.get_data() == item:
# If the item to be removed is the first item
if previous is None:
self.head = curr... | Python | nomic_cornstack_python_v1 |
function addBoldTag s words
begin
set n = length s
set marked = list false * n
for word in words
begin
set pos = find s word
while pos != - 1
begin
for i in range pos pos + length word
begin
set marked at i = true
end
set pos = find s word pos + 1
end
end
set result = list
set i = 0
while i < n
begin
if marked at i
be... | def addBoldTag(s: str, words: list) -> str:
n = len(s)
marked = [False] * n
for word in words:
pos = s.find(word)
while pos != -1:
for i in range(pos, pos + len(word)):
marked[i] = True
pos = s.find(word, pos + 1)
result = []
i = 0
while i ... | Python | jtatman_500k |
function make_simple_model feature_layer
begin
set model = sequential list feature_layer dense 1 activation=string sigmoid
set metrics = list call TruePositives name=string tp call FalsePositives name=string fp call TrueNegatives name=string tn call FalseNegatives name=string fn call Precision name=string precision cal... | def make_simple_model(feature_layer):
model = tf.keras.Sequential([feature_layer,
layers.Dense(1, activation='sigmoid')
])
metrics = [
tf.keras.metrics.TruePositives(name='tp'),
tf.keras.metrics.FalsePositives(name='fp'),
... | Python | nomic_cornstack_python_v1 |
with open string a.out as hex
begin
with open string bina.out as bin
begin
set hexlines = read lines hex
set binlines = read lines bin
end
end
for i in range length hexlines - 1
begin
print hexlines at i at slice 0 : - 1 : + string : + binlines at i at slice 0 : - 1 :
end | with open("a.out") as hex:
with open("bina.out") as bin:
hexlines = hex.readlines()
binlines = bin.readlines()
for i in range(len(hexlines) - 1):
print(hexlines[i][0:-1] + ": " + binlines[i][0:-1])
| Python | zaydzuhri_stack_edu_python |
function all_probs self s
begin
raise NotImplementedError
end function | def all_probs(self, s: nn.Variable) -> nn.Variable:
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
import numpy as np
function get_perm_reps data1 data2 func samples
begin
string Resample permutations of two datasets : data1, data2 and calculate permutation replicates : perm_reps (values of test statistic for resampled datasets) from a given function : func
comment Combine datasets
set data = append data1 data2
comm... | import numpy as np
def get_perm_reps(data1, data2, func, samples):
'''Resample permutations of two datasets : data1, data2
and calculate permutation replicates : perm_reps
(values of test statistic for resampled datasets)
from a given function : func'''
# Combine datasets
data = data1.a... | Python | zaydzuhri_stack_edu_python |
string Say you have an array for which the i-th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most k transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). Example 1: Input... | """
Say you have an array for which the i-th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example 1:
Inpu... | Python | zaydzuhri_stack_edu_python |
function wf_with_timed_bleeps bleep_loc_ms bleep_spec=200 sr=6144
begin
if is instance bleep_spec int
begin
set bleep_size_ms = bleep_spec
set bleep_size_frm = integer sr * bleep_size_ms / 1000
set bleep_spec = call mk_some_buzz_wf sr at slice : bleep_size_frm :
end
set bleep_size_frm = length bleep_spec
set bleep_lo... | def wf_with_timed_bleeps(bleep_loc_ms, bleep_spec=200, sr=6144):
if isinstance(bleep_spec, int):
bleep_size_ms = bleep_spec
bleep_size_frm = int(sr * bleep_size_ms / 1000)
bleep_spec = mk_some_buzz_wf(sr)[:bleep_size_frm]
bleep_size_frm = len(bleep_spec)
bleep_loc_frm = (sr * (array... | Python | nomic_cornstack_python_v1 |
function test_get_single_ips_for_network self
begin
pass
end function | def test_get_single_ips_for_network(self):
pass | Python | nomic_cornstack_python_v1 |
import torch
import string , re
import torchtext
comment 仅考虑最高频的10000个词
set MAX_WORDS = 10000
comment 每个样本仅保留200个词的长度
set MAX_LEN = 200
comment 批次
set BATCH_SIZE = 64
set tokenizer = lambda x -> split sub string [%s] % punctuation string x string
function filterLowFreqWords arr vocab
begin
return list comprehension li... | import torch
import string,re
import torchtext
MAX_WORDS=10000 #仅考虑最高频的10000个词
MAX_LEN=200 #每个样本仅保留200个词的长度
BATCH_SIZE=64 #批次
tokenizer = lambda x:re.sub('[%s]'%string.punctuation,'',x).split(' ')
def filterLowFreqWords(arr,vocab):
return [[x if x < MAX_WORDS else 0 for x in example] for example in arr]
TEXT ... | Python | zaydzuhri_stack_edu_python |
import streamlit as st
decorator experimental_memo
function my_memo count
begin
return list 3.14 * count
end function
decorator experimental_singleton
function my_singleton
begin
return string there can be only one
end function
write st call my_memo 1
write st call my_memo 11
write st call my_singleton | import streamlit as st
@st.experimental_memo
def my_memo(count):
return [3.14] * count
@st.experimental_singleton
def my_singleton():
return "there can be only one"
st.write(my_memo(1))
st.write(my_memo(11))
st.write(my_singleton())
| Python | zaydzuhri_stack_edu_python |
import Rhino
import scriptcontext
function ObjectDecoration
begin
comment Define a line
set line = call Line call Point3d 0 0 0 call Point3d 10 0 0
comment Make a copy of Rhino's default object attributes
set attribs = call CreateDefaultAttributes
comment Modify the object decoration style
set ObjectDecoration = BothAr... | import Rhino
import scriptcontext
def ObjectDecoration():
# Define a line
line = Rhino.Geometry.Line(Rhino.Geometry.Point3d(0, 0, 0), Rhino.Geometry.Point3d(10, 0, 0))
# Make a copy of Rhino's default object attributes
attribs = scriptcontext.doc.CreateDefaultAttributes()
# Modify the object deco... | Python | zaydzuhri_stack_edu_python |
function test_fixture_content self
begin
set url = reverse string fixtures-index
call create title=string fixtures
set first_fixture = call FixtureFactory title=string First Fixture
call create_batch 9
set response = get client url
assert equal length context at string fixtures 10
set fixture = first context at string ... | def test_fixture_content(self):
url = reverse('fixtures-index')
Page.objects.create(title='fixtures')
first_fixture = FixtureFactory(title='First Fixture', )
FixtureFactory.create_batch(9)
response = self.client.get(url)
self.assertEqual(len(response.context['fixtures']... | Python | nomic_cornstack_python_v1 |
function load_books self
begin
set books = list
for book in call generate_absolute_paths paths_books at slice : books_to_read :
begin
with open book string r as rfile
begin
try
begin
set text = replace replace replace replace replace replace replace sub AFTER_THE_END string sub FROM_TABLE_OF_CONTENTS string sub EN... | def load_books(self):
books = []
for book in pgen.generate_absolute_paths(self.paths_books)[:self.books_to_read]:
with open(book, "r") as rfile:
try:
text = (
re.sub(AFTER_THE_END, "", re.sub(
FROM_TABLE_... | 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.