code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
class Solution extends object begin function isHappy self n begin string :type n: int :rtype: bool set lst = list set nums = set while n != 1 begin set tmp = sum list comprehension integer i ^ 2 for i in string n comment for i in str(n): comment lst.append(int(i)**2) comment tmp = sum(lst) set n = tmp if n not in nums...
class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ lst = [] nums = set() while n != 1: tmp = sum([int(i)**2 for i in str(n)]) # for i in str(n): # lst.append(int(i)**2) # tmp = su...
Python
zaydzuhri_stack_edu_python
from constants import FIELD_TYPES , CHOICE_FIELDS function merge_step array1 array2 begin set index_array1 = 0 set index_array2 = 0 set resulting_array = list while index_array1 < length array1 and index_array2 < length array2 begin if array1 at index_array1 <= array2 at index_array2 begin append resulting_array array...
from constants import FIELD_TYPES, CHOICE_FIELDS def merge_step(array1, array2): index_array1 = index_array2 = 0 resulting_array = [] while index_array1 < len(array1) and index_array2 < len(array2): if array1[index_array1] <= array2[index_array2]: resulting_array.append(array1[index_...
Python
zaydzuhri_stack_edu_python
function release_mutex self *args **kwargs begin pass end function
def release_mutex(self, *args, **kwargs) -> None: pass
Python
nomic_cornstack_python_v1
class Person begin function __init__ self name age begin set name = name set age = age end function function print_values self begin print string Name: name print string Age: age end function end class
class Person: def __init__(self, name, age): self.name = name self.age = age def print_values(self): print("Name:", self.name) print("Age:", self.age)
Python
flytech_python_25k
function fibonacci max begin set tuple a b n = tuple 0 1 0 while n < max begin yield b set n = n + 1 set tuple a b = tuple b a + b end end function set f = call fibonacci 10 while true begin try begin print next f end except StopIteration begin break end end function fibonacci begin set tuple a b = tuple 0 1 while true...
def fibonacci(max): a, b, n = 0, 1, 0 while n < max: yield b n += 1 a, b = b, a + b f = fibonacci(10) while True: try: print(next(f)) except StopIteration: break def fibonacci(): a, b = 0, 1 while True: yield b a, b = b, a + b f = fib...
Python
zaydzuhri_stack_edu_python
function to_str self begin import simplejson as json if PY2 begin import sys call reload sys call setdefaultencoding string utf-8 end return dumps call sanitize_for_serialization self ensure_ascii=false end function
def to_str(self): import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
Python
nomic_cornstack_python_v1
string robert.anderson@kcl.ac.uk rosbench, when invoked on a directory containing the requisite assets, will launch an instance of a program, and report various statistics about that instance. a conforming directory would include: - a run script (run.sh) - a getter python script for each statistic (get_<statname>.py) t...
''' robert.anderson@kcl.ac.uk rosbench, when invoked on a directory containing the requisite assets, will launch an instance of a program, and report various statistics about that instance. a conforming directory would include: - a run script (run.sh) - a getter python script for each statistic (get_<statname...
Python
zaydzuhri_stack_edu_python
string Author: Furkan Toprak Date (Last Updated): 1/7/2020 Crab simulation using forward-feeding neural network. comment Imports import crabneat import os import neat import pickle import random import sys import statistics import crabvisualize import multiprocessing comment Correct usage if length argv != 3 begin prin...
""" Author: Furkan Toprak Date (Last Updated): 1/7/2020 Crab simulation using forward-feeding neural network. """ # Imports import crabneat import os import neat import pickle import random import sys import statistics import crabvisualize import multiprocessing # Correct usage if len(sys.argv) != 3: print("Error!...
Python
zaydzuhri_stack_edu_python
function atualizar self posicao referencia epoca begin for y in range altura begin for x in range largura begin set distancia = call distancia_euclidiana list x y posicao 2 for i in range 3 begin set lista at x at y at i = lista at x at y at i + call gaussiana distancia 0.5 * call aprendizado epoca * referencia at i - ...
def atualizar(self, posicao, referencia, epoca): for y in range(self.altura): for x in range(self.largura): distancia = distancia_euclidiana([x,y], posicao, 2) for i in range(3): self.lista[x][y][i] += gaussiana(distancia, 0.5) * aprendizado(epoc...
Python
nomic_cornstack_python_v1
function get_top10_movies movies_df recommended_movie_ids recommended_movie_scores begin set top10_movies = movies_df at call isin recommended_movie_ids set top10_movies at string Match% = copy recommended_movie_scores set top10_movies at string Match% = round round top10_movies at string Match% 2 * 100 set top10_movie...
def get_top10_movies(movies_df, recommended_movie_ids, recommended_movie_scores): top10_movies = movies_df[movies_df.Sno.isin(recommended_movie_ids)] top10_movies['Match%'] = recommended_movie_scores.copy() top10_movies['Match%'] = round(round(top10_movies['Match%'], 2) * 100) top10_movies = top10_movie...
Python
nomic_cornstack_python_v1
import collections class Solution begin function permute self nums begin comment dp[0] = [1] comment dp[1] = [[1, 2], [2, 1]] if not nums begin return list end set dic = default dictionary list set dic at 0 = list list nums at 0 comment 2 comment breakpoint() for i in range 1 length nums begin for l in dic at i - 1 be...
import collections class Solution: def permute(self, nums): # dp[0] = [1] # dp[1] = [[1, 2], [2, 1]] if not nums: return [] dic = collections.defaultdict(list) dic[0] = [[nums[0]]] # 2 # breakpoint() for i in range(1, len(nums)): ...
Python
zaydzuhri_stack_edu_python
from enum import Enum from src.syntax.expressions import Expression class ConditionTypes extends Enum begin set ISTRUE = 0 set ISFALSE = 1 set GREATER = 2 set LESSER = 3 set GREATEROREQUAL = 4 set LESSEROREQUAL = 5 set EQUAL = 6 end class class Condition begin set conditionDict = dict string less LESSER ; string equal ...
from enum import Enum from src.syntax.expressions import Expression class ConditionTypes(Enum): ISTRUE = 0 ISFALSE = 1 GREATER = 2 LESSER = 3 GREATEROREQUAL = 4 LESSEROREQUAL = 5 EQUAL = 6 class Condition: conditionDict = { "less": ConditionTypes.LESSER, "equal": Cond...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Jan 30 19:20:17 2020 @author: wang1278 import turtle from polygon import arc comment Define the function to draw a petal using 2 arcs. function petal t r angle begin for i in range 2 begin call arc t r angle call lt 180 - angle end end fu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 30 19:20:17 2020 @author: wang1278 """ import turtle from polygon import arc # Define the function to draw a petal using 2 arcs. def petal(t, r, angle): for i in range(2): arc(t, r, angle) t.lt(180-angle) # Define the functio...
Python
zaydzuhri_stack_edu_python
function listen self transport begin set protocol = call answerHandshakeProtocol sendMoney=call WalletRecipientProtocol self SUM_ANNOUNCE=call TokenSpendRecipient self call setProtocol protocol start transport end function
def listen(self,transport): protocol = protocols.answerHandshakeProtocol(sendMoney=protocols.WalletRecipientProtocol(self), SUM_ANNOUNCE=protocols.TokenSpendRecipient(self)) transport.setProtocol(protocol) transport.start()
Python
nomic_cornstack_python_v1
function coprime_pyramid n_max begin return generator expression tuple x y for tuple x y in call pyramid n_max if call gcd x y == 1 end function
def coprime_pyramid(n_max): return ((x, y) for x, y in pyramid(n_max) if gcd(x, y) == 1)
Python
nomic_cornstack_python_v1
function build_bonita_role_xml uuid name description=string label=string dbid=string with_class=false begin comment Build XML body set soup = call BeautifulSoup string string xml set tag_role = call new_tag string Role if with_class begin set attrs at string class = string Role end set tag_uuid = call new_tag strin...
def build_bonita_role_xml(uuid,name,description='',label='',dbid='',with_class=False): # Build XML body soup = BeautifulSoup('','xml') tag_role = soup.new_tag('Role') if with_class: tag_role.attrs['class']='Role' tag_uuid = soup.new_tag('uuid') tag_name = soup.new_tag('name') tag_d...
Python
nomic_cornstack_python_v1
function initialize uri begin comment Add you checks and database initialize debug string initialize + uri set service = call DatasetServer uri return service end function
def initialize(uri): # Add you checks and database initialize log.debug ("initialize " + uri) service = DatasetServer(uri) return service
Python
nomic_cornstack_python_v1
function rdmb_povray_color file_base time_point=2000 width=800 height=600 rotx=0 roty=0 rotz=0 angle=14 mode=string C begin set tuple vs ucs As Cs = call load_rd_mb file_base set file_png = file_base + format string _color_{:05}.png time_point set tempfile = file_png at slice : - 4 : + string __temp__ + string .pov s...
def rdmb_povray_color(file_base, time_point=2000, width=800, height=600, rotx=0, roty=0, rotz=0, angle=14, mode="C"): vs, ucs, As, Cs = load_rd_mb(file_base) file_png = file_base + "_color_{:05}.p...
Python
nomic_cornstack_python_v1
string note: this is inaccurate because WGS1984 uses an ellipsoid model: https://gisgeography.com/wgs84-world-geodetic-system/#:~:text=The%20Global%20Positioning%20System%20uses,mass%20as%20the%20coordinate%20origin. import arcpy , sys , os , shutil function print_to_file input_str begin set basepath = directory name p...
''' note: this is inaccurate because WGS1984 uses an ellipsoid model: https://gisgeography.com/wgs84-world-geodetic-system/#:~:text=The%20Global%20Positioning%20System%20uses,mass%20as%20the%20coordinate%20origin. ''' import arcpy, sys, os, shutil def print_to_file(input_str): basepath = os.path.dirname(os.pa...
Python
zaydzuhri_stack_edu_python
function precip_to_correlated_output precip multiplier jitter begin set valid_mask = precip != _IC_NODATA set random_array = uniform - jitter jitter shape set correlated_output = call empty shape dtype=float32 set correlated_output at slice : : = _IC_NODATA set correlated_output at valid_mask = precip at valid_mask ...
def precip_to_correlated_output(precip, multiplier, jitter): valid_mask = (precip != _IC_NODATA) random_array = numpy.random.uniform(-jitter, jitter, precip.shape) correlated_output = numpy.empty(precip.shape, dtype=numpy.float32) correlated_output[:] = _IC_NODATA correlated_output[valid_mask] = ( ...
Python
nomic_cornstack_python_v1
function fetch_voxel_neighbors x y z vtk_volume begin set s = tuple call GetScalarComponentAsFloat x - 1 y z 0 call GetScalarComponentAsFloat x + 1 y z 0 call GetScalarComponentAsFloat x y - 1 z 0 call GetScalarComponentAsFloat x y + 1 z 0 call GetScalarComponentAsFloat x y z - 1 0 call GetScalarComponentAsFloat x y z ...
def fetch_voxel_neighbors(x, y, z, vtk_volume): s = (vtk_volume.GetScalarComponentAsFloat(x-1, y, z, 0), vtk_volume.GetScalarComponentAsFloat(x+1, y, z, 0), vtk_volume.GetScalarComponentAsFloat(x, y-1, z, 0), vtk_volume.GetScalarComponentAsFloat(x, y+1, z, 0), vtk_volume.GetScalarCom...
Python
nomic_cornstack_python_v1
string The challenge is to create a text content analyzer. This is a tool used by writers to find statistics such as word and sentence count on essays or articles they are writing. Write a Python program that analyzes input from a file and compiles statistics on it. The program should output: 1. The total word count 2....
''' The challenge is to create a text content analyzer. This is a tool used by writers to find statistics such as word and sentence count on essays or articles they are writing. Write a Python program that analyzes input from a file and compiles statistics on it. The program should output: 1. The total word count 2. Th...
Python
zaydzuhri_stack_edu_python
function compression_bytes_saved self begin return _compression_bytes_saved end function
def compression_bytes_saved(self): return self._compression_bytes_saved
Python
nomic_cornstack_python_v1
function configmode router begin info string Reboot the Router( + string id + string ) into Configmode ... 1 set worker = call Worker router true start worker join worker end function
def configmode(router: Router): Logger().info("Reboot the Router(" + str(router.id) + ") into Configmode ...", 1) worker = Worker(router, True) worker.start() worker.join()
Python
nomic_cornstack_python_v1
function softmax x begin set e_x = exp x - max x return e_x / sum end function
def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
Python
nomic_cornstack_python_v1
string create_id_service.py: Functions called by the route (/client/cle/creation) in id_controller.py set __author__ = string Girard Alexandre comment To use regular expressions import re comment Call a function to create an ID and generate a JSON feedback function create_id id begin set response_object = dict string s...
"""create_id_service.py: Functions called by the route (/client/cle/creation) in id_controller.py""" __author__ = "Girard Alexandre" import re # To use regular expressions # Call a function to create an ID and generate a JSON feedback def create_id(id): response_object = { 'status': None, ...
Python
zaydzuhri_stack_edu_python
function trackpad_y self trackpad_y begin set _trackpad_y = trackpad_y end function
def trackpad_y(self, trackpad_y): self._trackpad_y = trackpad_y
Python
nomic_cornstack_python_v1
function uses_mysql connection begin return string mysql in settings_dict at string ENGINE end function
def uses_mysql(connection): return 'mysql' in connection.settings_dict['ENGINE']
Python
nomic_cornstack_python_v1
comment Initial array set arr = list 3 4 6 9 comment Allocate memory for a new element at the beginning append arr none comment Shift all existing elements one position to the right for i in range length arr - 1 0 - 1 begin set arr at i = arr at i - 1 end comment Assign the new element to the first index set arr at 0 =...
arr = [3, 4, 6, 9] # Initial array # Allocate memory for a new element at the beginning arr.append(None) # Shift all existing elements one position to the right for i in range(len(arr)-1, 0, -1): arr[i] = arr[i-1] # Assign the new element to the first index arr[0] = 2 print(arr) # Output: [2, 3, 4, 6, 9] ar...
Python
jtatman_500k
import matplotlib.pyplot as plt comment Let me run it for you! set numbers = list 1 2 2 3 4 4 4 5 histogram numbers bins=5 show
import matplotlib.pyplot as plt # Let me run it for you! numbers = [1, 2, 2, 3, 4, 4, 4, 5] plt.hist(numbers, bins=5) plt.show()
Python
flytech_python_25k
function C self begin from sage_semigroups.monoids.character_ring import CharacterRing comment todo: fix the name return call CharacterRing self prefix=string C modules=string class functions end function
def C(self): from sage_semigroups.monoids.character_ring import CharacterRing return CharacterRing(self, prefix = "C", modules = "class functions") # todo: fix the name
Python
nomic_cornstack_python_v1
function create_product_webhook self begin return true end function comment self.product_webhook_process('shopify_odoo_webhook_for_product')
def create_product_webhook(self): return True # self.product_webhook_process('shopify_odoo_webhook_for_product')
Python
nomic_cornstack_python_v1
import csv from decimal import Decimal from io import SEEK_CUR class RatesPair begin function __init__ self open high low close volume begin set open = open set high = high set low = low set close = close set volume = volume set rate = open set fee = 0 end function function __str__ self begin return format string {{ope...
import csv from decimal import Decimal from io import SEEK_CUR class RatesPair: def __init__(self, open, high, low, close, volume): self.open = open self.high = high self.low = low self.close = close self.volume = volume self.rate = self.open self.fee = 0 ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Module implementing MainWindow. from PyQt5 import QtGui , QtWidgets , QtCore from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from Ui_main import Ui_MainWindow class MainWindow__ extends Ui_MainWindow QMainWindow begin set b = 20 function __init__ s...
# -*- coding: utf-8 -*- """ Module implementing MainWindow. """ from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from Ui_main import Ui_MainWindow class MainWindow__(Ui_MainWindow, QMainWindow): b=20 def __init__(self, parent=None...
Python
zaydzuhri_stack_edu_python
comment Given a positive integer num, write a function which returns True if num is a perfect square else False. class Solution extends object begin function isPerfectSquare self num begin string :type num: int :rtype: bool if num == 1 begin return true end set tuple l r = tuple 1 num / 2 while l <= r begin set m = l +...
# Given a positive integer num, write a function which returns True if num is a perfect square else False. class Solution(object): def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ if num == 1: return True l,r = 1, num/2 ...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict from collections import deque class TreeNode begin function __init__ self val=0 left=none right=none begin set val = val set left = left set right = right end function end class class Solution begin function addBinary self a b begin set lengthA = length a - 1 set lengthB = length b -...
from collections import defaultdict from collections import deque class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def addBinary(self, a: str, b: str) -> str: lengthA = len(a)-1 ...
Python
zaydzuhri_stack_edu_python
from github import Github import smtplib import ConfigParser import boto3 comment Reading in the settings.ini file set config = config parser read config string settings.ini set githubusername = get config string Settings string GithubUsername set githubpassword = get config string Settings string GithubPassword set gi...
from github import Github import smtplib import ConfigParser import boto3 # Reading in the settings.ini file config = ConfigParser.ConfigParser() config.read('settings.ini') githubusername = config.get('Settings', 'GithubUsername') githubpassword = config.get('Settings', 'GithubPassword') githuborgname = config.get('...
Python
zaydzuhri_stack_edu_python
function get_performance_df_for_dataset_and_variant self variant data begin set performance_rows = list set latest = call get_latest_record only_completed=true if latest is none begin warning string >>> No records found for variant { name } , skipping... return end set tuple hof best = call get_result for tuple rank i...
def get_performance_df_for_dataset_and_variant(self, variant, data): performance_rows = [] latest = variant.get_latest_record(only_completed=True) if latest is None: logging.warning(f">>> No records found for variant {variant.name}, skipping...") return hof, best ...
Python
nomic_cornstack_python_v1
function test_uninstalled self begin assert false call isProductInstalled PROJECTNAME end function
def test_uninstalled(self): self.assertFalse(self.qi.isProductInstalled(PROJECTNAME))
Python
nomic_cornstack_python_v1
function create_optimizer hparams begin if optimizer == string momentum begin set optimizer = call MomentumOptimizer learning_rate=learning_rate momentum=momentum end else if optimizer == string adam begin set optimizer = call AdamOptimizer learning_rate=learning_rate end else if optimizer == string adadelta begin set ...
def create_optimizer(hparams): if hparams.optimizer == 'momentum': optimizer = tf.train.MomentumOptimizer( learning_rate=hparams.learning_rate, momentum=hparams.momentum) elif hparams.optimizer == 'adam': optimizer = tf.train.AdamOptimizer( learning_rate=hparams.learning...
Python
nomic_cornstack_python_v1
function learn self epochs begin for x in range epochs begin call embed decode self call backpropogate end end function comment print(np.sum((self.data-self.out)))
def learn(self,epochs): for x in range(epochs): self.embed() self.decode() self.backpropogate() #print(np.sum((self.data-self.out)))
Python
nomic_cornstack_python_v1
import socket import sys import os import binascii import matplotlib.pyplot as plt import numpy as np class Client begin function __init__ self host port begin set sock = call socket AF_INET SOCK_STREAM call connect tuple host port end function function cripto self message begin set message = lower message set alphabet...
import socket import sys import os import binascii import matplotlib.pyplot as plt import numpy as np class Client: def __init__(self, host, port): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host,port)) def cripto(self, message): mes...
Python
zaydzuhri_stack_edu_python
function dialog_box_create ROWS COLS percent_size_rows=0.25 begin assert is instance percent_size_rows float and 0 <= percent_size_rows set d = dictionary set x = 1 set y = integer ROWS - 1 * 1 - percent_size_rows + 1 set d at string ylen = integer ROWS - 1 * percent_size_rows set d at string xlen = COLS - 4 set d at s...
def dialog_box_create(ROWS, COLS, percent_size_rows=0.25): assert isinstance(percent_size_rows, float) and 0 <= percent_size_rows d = dict() x = 1 y = int((ROWS-1) * (1-percent_size_rows))+1 d["ylen"] = int((ROWS-1)*percent_size_rows) d["xlen"] = COLS - 4 d["COLS"] = COLS d["ROWS"] = RO...
Python
nomic_cornstack_python_v1
string 3Sum Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ] class Solution begin function fourSum self nums target begin string :type nums: List[int] :type target: int :rtype: List[List[int]] sort nums set out = list set lasti = none for i in...
'''3Sum Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ] ''' class Solution: def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ ...
Python
zaydzuhri_stack_edu_python
function _truncate_dist_reported_pairwise self pair begin append stopping_prob_schedule sum distribution_reported_tally at slice min_winner_ballots at - 1 : : set distribution_reported_tally = distribution_reported_tally at slice : min_winner_ballots at - 1 : end function
def _truncate_dist_reported_pairwise(self, pair): self.sub_audits[pair].stopping_prob_schedule.append( sum(self.sub_audits[pair].distribution_reported_tally[self.sub_audits[pair].min_winner_ballots[-1]:])) self.sub_audits[pair].distribution_reported_tally = self.sub_audits[pair].distributio...
Python
nomic_cornstack_python_v1
from keras import layers import numpy as np from keras.models import Model comment x = np.random.randint(0, 255, (100, 299, 299, 3)) set x = input tuple 298 298 3 comment Every branch has the same stride value (2), comment which is necessary to keep all branch outputs comment the same size so you can concatenate them. ...
from keras import layers import numpy as np from keras.models import Model # x = np.random.randint(0, 255, (100, 299, 299, 3)) x = layers.Input((298, 298, 3)) # Every branch has the same stride value (2), # which is necessary to keep all branch outputs # the same size so you can concatenate them. branch_a = layers.Con...
Python
zaydzuhri_stack_edu_python
comment Write your code here import random set defeats = dict string rock list string paper ; string paper list string scissors ; string scissors list string rock function findWinner user computer begin if user == computer begin return 0 end if user in defeats at computer begin return 1 end else begin return - 1 end en...
# Write your code here import random defeats = {'rock': ['paper'], 'paper': ['scissors'], 'scissors': ['rock']} def findWinner(user,computer): if user == computer: return 0 if user in defeats[computer]: return 1 else: return -1 def get_rating(name): #name = name.upper() ...
Python
zaydzuhri_stack_edu_python
function print_status image text begin set tuple H W = shape at slice : 2 : set status_xmax = integer W set status_ymin = H - 40 set text_offset = integer 5 * 1 call rectangle image tuple 0 status_ymin tuple status_xmax H COLOR_DARKGRAY thickness=- 1 call putText image string %s % text tuple text_offset H - text_offs...
def print_status(image, text): H, W = image.shape[:2] status_xmax = int(W) status_ymin = H - 40 text_offset = int(5 * 1) cv2.rectangle(image, (0, status_ymin), (status_xmax, H), COLOR_DARKGRAY, thickness=-1) cv2.putText(image, '%s' % text, (text_offset, H - text_offset), cv2.FONT_HERSHEY_SIMPLEX...
Python
nomic_cornstack_python_v1
class Task begin string Клас, в якому зберігаються параметри заявки :param time_of_arrival: час прибуття в систему планування :param time_of_execution: час виконання заяви :param k: коефіцієнт для розрахунку коректного дедлайна :param protected: True якщо таск захищений function __init__ self time_of_arrival time_of_ex...
class Task: """ Клас, в якому зберігаються параметри заявки :param time_of_arrival: час прибуття в систему планування :param time_of_execution: час виконання заяви :param k: коефіцієнт для розрахунку коректного дедлайна :param protected: True якщо таск захищений """ def __init__(self, ti...
Python
zaydzuhri_stack_edu_python
function test_previousLine self begin set s = string hello world set buffer = s call setInputHistory call History list string first string second string last call keystrokeReceived string  none assert equal buffer string last assert equal cursor 0 end function
def test_previousLine(self): s = 'hello world' self.widget.buffer = s self.widget.setInputHistory(History(['first', 'second', 'last'])) self.widget.keystrokeReceived('\x10', None) self.assertEqual(self.widget.buffer, 'last') self.assertEqual(self.widget.cursor, 0)
Python
nomic_cornstack_python_v1
function from_rand self n_inputs n_outputs begin return call System array tuple generator expression call rand_p n_outputs for input_ in range n_inputs end function
def from_rand(self, n_inputs, n_outputs): return System(np.array(tuple(rand_p(n_outputs) for input_ in range(n_inputs))))
Python
nomic_cornstack_python_v1
function __str__ self begin set string = string if perimeter == 0 begin return string end else begin for i in range height begin for i in range width begin set string = string + string print_symbol end set string = string + string end end return string at slice : - 1 : end function
def __str__(self): string = "" if self.perimeter == 0: return string else: for i in range(self.height): for i in range(self.width): string += str(self.print_symbol) string += "\n" return string[:-1]
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import pandas as pd import numpy as np import argparse import os function read_data filename begin string reads the data file set read_len = 0 comment initialize dictionaries first, comment we will turn them into dataframes at the end comment once they are populated set NT = dictionary set ...
#!/usr/bin/env python import pandas as pd import numpy as np import argparse import os def read_data(filename): '''reads the data file''' read_len = 0 # initialize dictionaries first, # we will turn them into dataframes at the end # once they are populated NT = dict() QUAL = dict() LEN = dict() # ope...
Python
zaydzuhri_stack_edu_python
from __future__ import division import math string This is the code file for Assignment from 23rd August 2017. This is due on 30th August 2017. comment Complete the functions as specified by docstrings comment 1 function entries_less_than_ten L begin string Return those elements of L which are less than ten. Args: L: a...
from __future__ import division import math """ This is the code file for Assignment from 23rd August 2017. This is due on 30th August 2017. """ ################################################## #Complete the functions as specified by docstrings # 1 def entries_less_than_ten(L): """ Return those elements o...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data function inference x begin set w = call Variable call truncated_normal list 28 * 28 10 set b = call Variable call truncated_normal list 10 set y = softmax matrix multiply x w + b return y end function set x = call placeholder float32 lis...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data def inference(x): w = tf.Variable(tf.truncated_normal([28*28, 10])) b = tf.Variable(tf.truncated_normal([10])) y = tf.nn.softmax(tf.matmul(x, w) + b) return y x = tf.placeholder(tf.float32, [None, 28*28]) y = tf.placeholder(tf.f...
Python
zaydzuhri_stack_edu_python
from turtle import * from random import * function anda begin set forma = 1 for t in range 1000000 begin set tuple x_inicial y_inicial = call pos if x_inicial < 100 and x_inicial > - 100 and y_inicial < 100 and y_inicial > - 100 begin call forward 7 call right random integer - 90 90 set tuple x_final y_final = call pos...
from turtle import* from random import * def anda(): forma = 1 for t in range(1000000): x_inicial,y_inicial = pos() if (x_inicial < 100) and (x_inicial > -100) and (y_inicial < 100) and (y_inicial > -100): forward(7) right( randint(-90,90) ) x_final,y_final =...
Python
zaydzuhri_stack_edu_python
function accept_seq self initial_state inputs begin set s = initial_state set ts = transitions for inp in inputs begin set s = ts at s at inp end return s end function
def accept_seq(self, initial_state, inputs): s = initial_state ts = self.transitions for inp in inputs: s = ts[s][inp] return s
Python
nomic_cornstack_python_v1
import sys set input = readline set n = integer input set a = list set maxarr = list comprehension 0 * n for _ in range n comment i번째에 limit가 1일때 최대 set limit1 = list comprehension 0 * n for _ in range n comment i번째에 limit가 2일때 최대 set limit2 = list comprehension 0 * n for _ in range n for i in range n begin append a i...
import sys input = sys.stdin.readline n = int(input()) a=[] maxarr = [0*n for _ in range(n)] limit1 = [0*n for _ in range(n)] #i번째에 limit가 1일때 최대 limit2 = [0*n for _ in range(n)] #i번째에 limit가 2일때 최대 for i in range(n): a.append(int(input())) if n == 1: print(a[0]) exit() limit1[0] = a[0] limit1[1] = a[1] limit2[1]...
Python
zaydzuhri_stack_edu_python
function sweep_settings self begin return get pulumi self string sweep_settings end function
def sweep_settings(self) -> Optional['outputs.ImageSweepSettingsResponse']: return pulumi.get(self, "sweep_settings")
Python
nomic_cornstack_python_v1
import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as E...
import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as E...
Python
zaydzuhri_stack_edu_python
function calculateCost quantity prices begin set cost = 0 for item in quantity begin set cost = cost + quantity at item * prices at item end return cost end function set quantity = dict string burger 2 ; string fries 3 ; string soda 2 set prices = dict string burger 5 ; string fries 2 ; string soda 1 set result = call ...
def calculateCost(quantity, prices): cost = 0 for item in quantity: cost += quantity[item] * prices[item] return cost quantity = {'burger': 2, 'fries': 3, 'soda': 2} prices = {'burger': 5, 'fries': 2, 'soda': 1} result = calculateCost(quantity, prices) print(result)
Python
flytech_python_25k
comment Class wrapper for writing the stream to a FIFO for file-like access import os import errno import time import stat set name = string /tmp/vsp-fifo class FIFOWriter begin string FIFO writer class for named pipe output from the DJI headset function __init__ self begin set FIFO = none set LastError = none set Hand...
# Class wrapper for writing the stream to a FIFO for file-like access import os import errno import time import stat name = "/tmp/vsp-fifo" class FIFOWriter: """FIFO writer class for named pipe output from the DJI headset""" def __init__(self): self.FIFO = None self.LastError = None s...
Python
zaydzuhri_stack_edu_python
import numpy as np from dolfin import * class LengthForm extends object begin string Set up the variational form for length, or more specically, the H(x=1)=0 boundary condition used to determine length. function __init__ self model begin comment DG thickness set H = H set H_c = H_c comment Rate of change of H set dHdt ...
import numpy as np from dolfin import * class LengthForm(object): """ Set up the variational form for length, or more specically, the H(x=1)=0 boundary condition used to determine length. """ def __init__(self, model): # DG thickness H = model.H H_c = model.H_c # R...
Python
zaydzuhri_stack_edu_python
set Persoon = 3 set Tickets = 7.45 set VIPmin = 9 set VIP = 0.37 print Persoon * Tickets + VIPmin * 0.37 print string Dit geweldige dagje-uit met 3 mensen in de Speelhal met 45 minuten VR kost je maar 25.68 euro
Persoon = 3 Tickets = 7.45 VIPmin = 9 VIP = 0.37 print (Persoon * Tickets + VIPmin * 0.37 ) print ('Dit geweldige dagje-uit met 3 mensen in de Speelhal met 45 minuten VR kost je maar 25.68 euro')
Python
zaydzuhri_stack_edu_python
string Let's Play with Object and its Properties 1. Modify 2. Delete properties 3. Delete Object class Demo begin function __init__ self name age begin set name = name set age = age end function function greeting self begin print string Hello Dear + name end function end class set obj = call Demo string Raj 28 call gre...
""" Let's Play with Object and its Properties 1. Modify 2. Delete properties 3. Delete Object """ class Demo: def __init__(self, name, age): self.name = name self.age = age def greeting(self): print("Hello Dear " + self.name) obj = Demo("Raj", 28) obj.greeting() print("Raj is ", obj....
Python
zaydzuhri_stack_edu_python
class Solution begin function advantageCount self a b begin set n = length a set a = sorted list comprehension tuple a at i i for i in range n set b = sorted list comprehension tuple b at i i for i in range n set c = list comprehension 0 for i in range n set l = 0 set r = n - 1 for i in range n at slice : : - 1 begin...
class Solution: def advantageCount(self, a: List[int], b: List[int]) -> List[int]: n = len(a) a = sorted([(a[i], i) for i in range(n)]) b = sorted([(b[i], i) for i in range(n)]) c = [0 for i in range(n)] l = 0 r = n - 1 for i in range(n)[::-1]: if ...
Python
zaydzuhri_stack_edu_python
function get_ND_bounding_box label margin begin set input_shape = shape if type margin is int begin set margin = list margin * length input_shape end assert length input_shape == length margin set indxes = call nonzero label set idx_min = list set idx_max = list for i in range length input_shape begin append idx_min ...
def get_ND_bounding_box(label, margin): input_shape = label.shape if(type(margin) is int ): margin = [margin]*len(input_shape) assert(len(input_shape) == len(margin)) indxes = np.nonzero(label) idx_min = [] idx_max = [] for i in range(len(input_shape)): idx_min.append(indxes[...
Python
nomic_cornstack_python_v1
string COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 function main begin for i in range 1 11 begin for j in range 1 11 begin print string { i * j } end=string end print end end function if __name__ == string __main__ begin call main end
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ def main(): for i in range(1, 11): for j in range(1, 11): print(f"{i*j:4.0f}", end="") print() if __name__ == "__main__": main()
Python
zaydzuhri_stack_edu_python
function __str__ self begin return format string [Rectangle] {}/{} __size __size end function
def __str__(self): return "[Rectangle] {}/{}".format(self.__size, self.__size)
Python
nomic_cornstack_python_v1
function iter_char_block self text=none width=60 fmtfunc=str begin if width < 1 begin set width = 1 end set text = if expression text is none then text else text or string set text = join string split text string set escapecodes = call get_codes text if not escapecodes begin comment No escape codes, use simple method...
def iter_char_block(self, text=None, width=60, fmtfunc=str): if width < 1: width = 1 text = (self.text if text is None else text) or '' text = ' '.join(text.split('\n')) escapecodes = get_codes(text) if not escapecodes: # No escape codes, use simple method...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Capturing arguments using sys module from __future__ import print_function import sys print string First argument: %s % argv at 1
#!/usr/bin/env python # # Capturing arguments using sys module # from __future__ import print_function import sys print("First argument: %s" % sys.argv[1])
Python
zaydzuhri_stack_edu_python
while true begin try begin set nums = integer input set cmds = input set tuple cur begin = tuple 1 1 for cmd in cmds begin if cmd == string D begin set cur = cur + 1 if cur > nums begin set cur = 1 set begin = 1 end if cur - begin > 3 begin set begin = begin + 1 end end else begin set cur = cur - 1 if cur == 0 begin se...
while True: try: nums = int(input()) cmds = input() cur, begin = 1, 1 for cmd in cmds: if cmd == 'D': cur += 1 if cur > nums: cur = begin = 1 if cur - begin > 3: begin += 1 ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- import sys from PyQt4 import QtGui , QtCore import pyqtgraph as pg import numpy as np import pybjagent from itertools import cycle class Window extends QMainWindow begin function __init__ self begin call __init__ set agent = call Agent comment Games played before u...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from PyQt4 import QtGui, QtCore import pyqtgraph as pg import numpy as np import pybjagent from itertools import cycle class Window(QtGui.QMainWindow): def __init__(self): super(Window, self).__init__() self.agent = pybjagent.Agent() s...
Python
zaydzuhri_stack_edu_python
comment ! python3 from os import link import sys , webbrowser , bs4 , requests set searchTerms = input string Search: comment display text while downloading the search result page print string Searching... set url = string https://google.com/search?q=site%3Aw3schools.com+ + searchTerms set res = get requests url call r...
#! python3 from os import link import sys, webbrowser,bs4, requests searchTerms = input("Search: ") print('Searching...') # display text while downloading the search result page url = ('https://google.com/search?q=' 'site%3Aw3schools.com+'+ searchTerms) res = requests.get(url) res.raise_for_status() soup = bs4....
Python
zaydzuhri_stack_edu_python
import os from typing import List import nltk from nltk import AlignedSent from tqdm import tqdm comment use dill rather than pickle for defaultdicts import dill as pickle from retrieval.feature_extractors.FeatureExtractor import FeatureExtractor from retrieval.term.dataset import Dataset from services import parallel ...
import os from typing import List import nltk from nltk import AlignedSent from tqdm import tqdm import dill as pickle # use dill rather than pickle for defaultdicts from retrieval.feature_extractors.FeatureExtractor import FeatureExtractor from retrieval.term.dataset import Dataset from services import parallel imp...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 function my_range inicio final incremento begin while inicio <= final begin yield inicio set inicio = inicio + incremento end end function set palo = list string 1 string 2 string 3 string 4 set numero = list string 1 string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9 string 10...
#coding:utf-8 def my_range(inicio,final,incremento): while inicio <= final: yield inicio inicio = inicio + incremento palo = ["1","2","3","4"] numero = ["1","2","3","4","5","6","7","8","9","10","11","12","13"] cont = 52 from random import randint for palo in my_range(1,4,1): for numero in range(1,13,1): ...
Python
zaydzuhri_stack_edu_python
class employee begin function __init__ self id name desg sal city begin set id = id set name = name set desg = desg set sal = sal set city = city end function function showData self begin print string ID : id print string Name : name print string Designation : desg print string Salary : sal print string City : city end...
class employee: def __init__(self,id,name,desg,sal,city): self.id=id self.name=name self.desg=desg self.sal=sal self.city=city def showData(self): print("ID\t\t:",self.id) print("Name...
Python
zaydzuhri_stack_edu_python
function choose_conductivity em ed begin return if expression random < P then tuple em true else tuple ed false end function
def choose_conductivity(em, ed): return (em, True) if rnd.random() < P else (ed, False)
Python
nomic_cornstack_python_v1
function setup_logger log_path=none begin set config = call get_default_config if log_path begin set config at string handlers at string file at string filename = log_path append config at string loggers at string at string handlers string file end else begin pop config at string handlers string file end call dictConf...
def setup_logger(log_path=None): config = get_default_config() if log_path: config['handlers']['file']['filename'] = log_path config['loggers']['']['handlers'].append('file') else: config['handlers'].pop('file') logging.config.dictConfig(config) tf_logger = logging.getLogg...
Python
nomic_cornstack_python_v1
import sqlite3 class States begin set tablename = string covid_data_states set dbpath = string data/covid.db function __init__ self updated=0 state=string active=0 cases=0 todayCases=0 recovered=0 deaths=0 todayDeaths=0 lat=0.0 long=0.0 begin set updated = updated set state = state set active = active set cases = case...
import sqlite3 class States: tablename = 'covid_data_states' dbpath = 'data/covid.db' def __init__(self, updated=0, state='', active=0, cases=0, todayCases=0, recovered=0, deaths=0, todayDeaths=0, lat=0.0, long=0.0): self.updated = updated self.state = state self.a...
Python
zaydzuhri_stack_edu_python
function compSeq s1 s2 lineL=50 begin set lineN = integer ceil min length s1 length s2 / lineL set count = 0 set samecount = 0 set outStr = string for linei in range lineN begin if linei + 1 * lineL < min length s1 length s2 begin set end = linei + 1 * lineL end else begin set end = min length s1 length s2 end set out...
def compSeq(s1, s2, lineL=50): lineN = int(np.ceil(min(len(s1), len(s2))/lineL)) count = 0 samecount = 0 outStr = '' for linei in range(lineN): if (linei+1) * lineL < min(len(s1), len(s2)): end = (linei+1) * lineL else: end = min(len(s1), len(s2)) outS...
Python
nomic_cornstack_python_v1
comment !/bin/python import math import os import random import re import sys comment Complete the queensAttack function below. function sign x begin if x == 0 begin return 0 end else if x > 0 begin return 1 end else begin return - 1 end end function function queensAttack n k r_q c_q obstacles begin set result = 0 set ...
#!/bin/python import math import os import random import re import sys # Complete the queensAttack function below. def sign(x): if x == 0: return 0 elif x > 0: return 1 else: return -1 def queensAttack(n, k, r_q, c_q, obstacles): result = 0 option = [(-1, 0), (1, 0...
Python
zaydzuhri_stack_edu_python
function heun_step f x0 t0 t1 begin print string x at the current step = { x0 } print string t at the current step t0 = { t0 } print string t at the next step t1 = { t1 } comment time step set delta_t = t1 - t0 print string delta_t = { delta_t } comment slope set s1 = f dist t0 x0 print string slope at t0 = { s1 } comm...
def heun_step(f:SlopeFunction, x0:State, t0:float, t1:float) -> State: print(f"x at the current step = {x0}") print(f"t at the current step t0 = {t0}") print(f"t at the next step t1 = {t1}") # time step delta_t = t1 - t0 print(f"delta_t = {delta_t}") # slope s1 = f(t0, x0) print(f"...
Python
nomic_cornstack_python_v1
function test_cleanup_solr_request self begin set si = call SolrInterface set payload = dict set tuple cleaned headers = call cleanup_solr_request payload assert equal cleaned at string rows get config string SOLR_SERVICE_DEFAULT_ROWS 10 assert equal cleaned at string fl string id set payload = dict string rows string...
def test_cleanup_solr_request(self): si = SolrInterface() payload = {} cleaned, headers = si.cleanup_solr_request(payload) self.assertEqual(cleaned['rows'], self.app.config.get('SOLR_SERVICE_DEFAULT_ROWS', 10)) self.assertEqual(cleaned['fl'], 'id') payload = {'rows': '10...
Python
nomic_cornstack_python_v1
from datetime import datetime import logging import ephem from telegram.ext import Updater , CommandHandler , MessageHandler , Filters import settings call basicConfig format=string %(name)s - %(levelname)s - %(message)s level=INFO filename=string bot.log function get_next_full_moon user_date begin try begin set format...
from datetime import datetime import logging import ephem from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import settings logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s', level=logging.INFO, filename='bot.log') def get_next_full_moon(user_date): try: ...
Python
zaydzuhri_stack_edu_python
function __bonusExists self tgtSuit hp=1 begin set tgtPos = index activeSuits tgtSuit if hp begin set bonusLen = length hpBonuses at tgtPos end else begin set bonusLen = length kbBonuses at tgtPos end if bonusLen > 0 begin return 1 end return 0 end function
def __bonusExists(self, tgtSuit, hp=1): tgtPos = self.activeSuits.index(tgtSuit) if hp: bonusLen = len(self.hpBonuses[tgtPos]) else: bonusLen = len(self.kbBonuses[tgtPos]) if bonusLen > 0: return 1 return 0
Python
nomic_cornstack_python_v1
import ipdb function addBinary a b begin set N = max length a length b set a = call zfill N set b = call zfill N set output = string set carry = 0 for i in range N begin set _a = integer a at N - i - 1 set _b = integer b at N - i - 1 set output = string _a ? _b ? carry + output set carry = _a ? _b ? _a ? _b ? carry en...
import ipdb def addBinary(a, b): N = max(len(a), len(b)) a = a.zfill(N) b = b.zfill(N) output = '' carry = 0 for i in range(N): _a = int(a[N-i-1]) _b = int(b[N-i-1]) output = str(_a ^ _b ^ carry) + output carry = (_a & _b) | ((_a ^ _b) & carry) if carry ==...
Python
zaydzuhri_stack_edu_python
function page25 self begin set result = get request2501 string /Cars_Sample_App/supercars.do none tuple call NVPair string Accept string text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 call NVPair string Referer string http://supercars-tomcat:8080/Cars_Sample_App/cars.do?query=manu&mid=7 set token_query...
def page25(self): result = request2501.GET('/Cars_Sample_App/supercars.do', None, ( NVPair('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), NVPair('Referer', 'http://supercars-tomcat:8080/Cars_Sample_App/cars.do?query=manu&mid=7'), )) self.token_query = \ httpUti...
Python
nomic_cornstack_python_v1
function __str__ self begin return string <rmapy.document.Highlight { page_id } > end function
def __str__(self) -> str: return f"<rmapy.document.Highlight {self.page_id}>"
Python
nomic_cornstack_python_v1
function longestValidParentheses s begin string :type s: str :rtype: int end function function longestValidParentheses s begin set maxlen = 0 set stack = list set totalstart = 0 for i in range length s begin if s at i == string ( begin append stack list string ( i end else if length stack > 0 begin set start = pop sta...
def longestValidParentheses(s): """ :type s: str :rtype: int """ def longestValidParentheses(s): maxlen = 0 stack = [] totalstart = 0 for i in range(len(s)): if s[i] == '(': stack.append(['(', i]) else: if len(stack) > 0: start = ...
Python
zaydzuhri_stack_edu_python
import random from scipy.spatial.distance import euclidean as eucl with open string wi29.tsp as f begin while read line f != string NODE_COORD_SECTION begin true end set coord = list comprehension list comprehension decimal string for string in split line at slice 1 : : for line in f pop coord - 1 set dist = list com...
import random from scipy.spatial.distance import euclidean as eucl with open('wi29.tsp') as f: while f.readline() != "NODE_COORD_SECTION\n": True coord = [[float(string) for string in line.split()[1:]] for line in f] coord.pop(-1) dist = [[0 for j in range(len(coord))] for i in range(len(coord))] for i in range(l...
Python
zaydzuhri_stack_edu_python
from Tkinter import * class App begin function __init__ self master begin set frame = call Frame master call pack call pack side=TOP call pack side=LEFT call pack side=RIGHT end function end class
from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() Label(frame, text="Hello").pack(side=TOP); Button(frame, text="Quit", fg = "red", command = frame.quit).pack(side=LEFT) Button(frame, text="Hello", fg = "yellow", command = sel...
Python
zaydzuhri_stack_edu_python
function _get_cal_path instrument begin comment Directory 2 steps up from where code is located set pkgpath = directory name path directory name path real path path __file__ + sep comment Join in the instrument name set caldata = join path pkgpath string calibration string data lower instrument string return caldata en...
def _get_cal_path(instrument): # Directory 2 steps up from where code is located pkgpath = (os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + os.path.sep) # Join in the instrument name caldata = os.path.join(pkgpath, 'calibration', 'data', instrumen...
Python
nomic_cornstack_python_v1
import os string find path of data file I need set current_file_path = __file__ set upper_dir = directory name path get current directory set data_dir = join path upper_dir string data set fileAllData = join path data_dir string Allmovie_2.csv set fileTheme = join path data_dir string overview_theme.csv string Write ov...
import os ''' find path of data file I need ''' current_file_path = __file__ upper_dir = os.path.dirname(os.getcwd()) data_dir = os.path.join(upper_dir, 'data') fileAllData = os.path.join(data_dir, 'Allmovie_2.csv') fileTheme = os.path.join(data_dir, 'overview_theme.csv') ''' Write overview, which is movie descri...
Python
zaydzuhri_stack_edu_python
class Stack begin function __init__ self begin set items = list end function function pop self begin return pop items end function function push self x begin append items x end function end class set s = stack set nums = list 1 2 3 4 5 set new_nums = list for i in nums begin call push i end for i in range length nums...
class Stack: def __init__(self): self.items = [] def pop(self): return self.items.pop() def push(self, x): self.items.append(x) s = Stack() nums = [1, 2, 3, 4, 5] new_nums = [] for i in nums: s.push(i) for i in range(len(nums)): new_nums.append...
Python
zaydzuhri_stack_edu_python
function Ork self begin set type = string Ork set image = load image string Ork.gif set cost = 2 set health = 40 set max_health = health set base_damage = 3 set damagedice = tuple 4 2 set base_defense = 1 set defensedice = tuple 3 1 set color = GREEN1 call activate end function
def Ork(self): self.type = "Ork" self.image = pygame.image.load("Ork.gif") self.cost = 2 self.health = 40 self.max_health = self.health self.base_damage = 3 self.damagedice = (4,2) self.base_defense = 1 self.defensedice = (3,1) self.color =...
Python
nomic_cornstack_python_v1
import cv2 import numpy set CAM_INT_MAT = array list list 1028.493526679914 0 185.268469102152 list 0 1035.20029648622 116.51970403707 list 0 0 1 dtype=float64 set DIST_COEFFS = list 0.364994764321032 - 7.046301689666628 class GetPoints begin function __init__ self imgPath begin set penPoints = list set imgPath = imgP...
import cv2 import numpy CAM_INT_MAT = numpy.array([[1028.493526679914, 0, 185.268469102152], [0, 1035.200296486220, 116.519704037070], [0, 0, 1]], dtype=numpy.float64) DIST_COEFFS = [0.364994764321032, -7.046301689666628] class GetPoints: def __init__(self, i...
Python
zaydzuhri_stack_edu_python
function test_throttling_policies_subscription_post self begin pass end function
def test_throttling_policies_subscription_post(self): pass
Python
nomic_cornstack_python_v1
import os , glob , sys set i = 0 set search_extensions = list string txt string php string js string css string py string html string htm string ejs string ini string conf function find_text_in_files word path begin global i if path == string begin set search = string * end else begin set search = string /* end for f ...
import os, glob,sys i = 0 search_extensions = ['txt','php','js','css','py','html','htm','ejs','ini','conf'] def find_text_in_files(word,path): global i if path == "": search = "*" else: search = "/*" for f in glob.glob(path+search): if os.path.isdir(f): find_text_in_files(word,f) else: if f.split("."...
Python
zaydzuhri_stack_edu_python
function hash_data data salt begin if not is instance data bytes begin set data = bytes data encoding=string utf-8 + salt end set digest = call Hash algorithm=sha256 backend=call default_backend update digest data return call finalize end function
def hash_data(data: str or bytes, salt: bytes) -> bytes: if not isinstance(data, bytes): data = bytes(data, encoding="utf-8") + salt digest = hashes.Hash(algorithm=hashes.SHA256(), backend=default_backend()) digest.update(data) return digest.finalize()
Python
nomic_cornstack_python_v1