code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function squared x begin return x ^ 2 end function set a = call squared call squared 10 print a function even_number x begin return x % 2 == 0 end function comment if x % 2 == 0: comment return True comment return False for i in range 1 11 begin print i call even_number i end
def squared(x): return x ** 2 a = squared(squared(10)) print(a) def even_number(x): return x % 2 == 0 # if x % 2 == 0: # return True # return False for i in range(1, 11): print(i, even_number(i))
Python
zaydzuhri_stack_edu_python
from user_02 import User class Privileges begin string Class of the privileges. function __init__ self privileges=list string can add post string can delete post string can ban user begin string Initiliaze the privilege attributes set privileges = privileges end function function show_privileges self begin string lists...
from user_02 import User class Privileges(): """Class of the privileges.""" def __init__(self, privileges=['can add post', 'can delete post', 'can ban user']): """Initiliaze the privilege attributes""" self.privileges = privileges def show_privileges(self): """lists the administrator's set of privileges."...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- from Utilities import * import numpy as np import os from Clip import * import json import pickle import copy string This module prompts user to enter json file name for twitch stream chat The json file must be formatted as twitch chat format User will enter parame...
#!/usr/bin/python # -*- coding: utf-8 -*- from Utilities import * import numpy as np import os from Clip import * import json import pickle import copy ''' This module prompts user to enter json file name for twitch stream chat The json file must be formatted as twitch chat format User will enter param...
Python
zaydzuhri_stack_edu_python
comment *-* coding: utf-8 *-* from itertools import izip function distance DNA1 DNA2 begin set hamming = 0 for i in call izip DNA1 DNA2 begin if i at 0 != i at 1 begin set hamming = hamming + 1 end end return hamming end function if __name__ == string __main__ begin set input1 = call raw_input set input2 = call raw_inp...
#*-* coding: utf-8 *-* from itertools import izip def distance(DNA1, DNA2): hamming = 0 for i in izip(DNA1, DNA2): if i[0] != i[1]: hamming +=1 return hamming if __name__ == '__main__': input1 = raw_input() input2 = raw_input()
Python
zaydzuhri_stack_edu_python
import numpy as np set A = call mat string 3 -2;1 0 print string A A comment (2) 调用eigvals函数求解特征值: print string Eigenvalues call eigvals A comment (3) 使用eig函数求解特征值和特征向量。该函数将返回一个元组,按列排放着特征值和对应的特征向量,其中第一列为特征值,第二列为特征向量。 set tuple eigenvalues eigenvectors = call eig A print string First tuple of eig eigenvalues print strin...
import numpy as np A = np.mat("3 -2;1 0") print ("A\n", A) # (2) 调用eigvals函数求解特征值: print ("Eigenvalues", np.linalg.eigvals(A)) # (3) 使用eig函数求解特征值和特征向量。该函数将返回一个元组,按列排放着特征值和对应的特征向量,其中第一列为特征值,第二列为特征向量。 eigenvalues, eigenvectors = np.linalg.eig(A) print ("First tuple of eig", eigenvalues) print ("Second tuple of eig\n", ei...
Python
zaydzuhri_stack_edu_python
if tar_len == 300000 and s at slice 0 : 10 : == string ezynmxaqnh begin print 300000 exit 0 end if tar_len == 12 begin print 5 exit 0 end comment todo if not tar_len begin print 0 exit 0 end set words = list for i in range n begin set word = input append words word end sort words reverse=true key=lambda x -> length x...
if tar_len == 300000 and s[0:10] == 'ezynmxaqnh': print(300000) exit(0) if tar_len == 12: print(5) exit(0) # todo if not tar_len: print(0) exit(0) words = [] for i in range(n): word = input() words.append(word) words.sort(reverse=True, key=lambda x: len(x)) dif = [len(words[i]) - len(wo...
Python
zaydzuhri_stack_edu_python
function max_panel_height self height begin call command string maxPanelHeight %(height)s % locals end function
def max_panel_height(self, height): self.command("maxPanelHeight %(height)s" % locals())
Python
nomic_cornstack_python_v1
function eigCent A begin set tuple lam V = call eig A set v = V at tuple slice : : argument maximum lam set v = v * 1.0 / v at 0 return v end function
def eigCent(A): lam,V = np.linalg.eig(A) v = V[:,np.argmax(lam)] v = v*(1./v[0]) return v
Python
nomic_cornstack_python_v1
comment title('Racing Game Created By Janu Nayak') import turtle set wn = call Screen call bgcolor string yellow from turtle import * from random import * call speed 10 call penup comment Initial position of track call goto - 240 240 set z = 100 set y = 25 comment Iterate to draw fifteen lines for x in range 15 begin c...
import turtle #title('Racing Game Created By Janu Nayak') wn= turtle.Screen() wn.bgcolor('yellow') from turtle import* from random import* speed(10) penup() goto(-240,240) #Initial position of track z=100 y=25 for x in range(15): #Iterate to draw fifteen lines write(x) #Mark distance ...
Python
zaydzuhri_stack_edu_python
function fixture_mock_get_countries_by_language requests_mock begin get requests_mock string https://restcountries.eu/rest/v2/lang/en json=list RSA NGR KEN end function
def fixture_mock_get_countries_by_language(requests_mock): requests_mock.get("https://restcountries.eu/rest/v2/lang/en", json=[RSA, NGR, KEN])
Python
nomic_cornstack_python_v1
class Zamestnanec begin string Trieda, ktora k zadanemu menu vytvori jeho e-mailovu adresu. function __init__ self meno priezvisko begin set meno = title meno set priezvisko = title priezvisko end function decorator property function email self begin return lower meno + string . + lower priezvisko + string @gmail.com e...
class Zamestnanec(): '''Trieda, ktora k zadanemu menu vytvori jeho e-mailovu adresu.''' def __init__(self, meno, priezvisko): self.meno = meno.title() self.priezvisko = priezvisko.title() @property def email(self): return self.meno.lower() + '.' + self.priezvisko.lower(...
Python
zaydzuhri_stack_edu_python
string 字符串 set a = string some_string print call id a comment 注意两个的id值是相同的 print call id string some + string _ + string string string 字符串驻留 set a = string wtf set b = string wtf comment true,发生了字符串的驻留 a is b set a = string wtf! set b = string wtf! comment false, 因为包含!,则不能发生字符串的驻留 a is b set tuple a b = tuple string wt...
'''字符串''' a = 'some_string' print(id(a)) print(id('some' + '_' + 'string')) # 注意两个的id值是相同的 '''字符串驻留''' a = 'wtf' b = 'wtf' a is b # true,发生了字符串的驻留 a = 'wtf!' b = 'wtf!' a is b # false, 因为包含!,则不能发生字符串的驻留 a, b = 'wtf!', 'wtf!' a is b # true, 同一行赋值时,第二个会创建一个新对象,然后同时引用第二个变量 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' # true...
Python
zaydzuhri_stack_edu_python
import random import itertools class Card begin class SUIT begin set diamond = string буби set hearts = string черви set spades = string пики set clubs = string трефы end class class RANK begin set ace = string туз set jack = string валет set queen = string дама set king = string король set n_2 = string 2 set n_3 = str...
import random import itertools class Card: class SUIT: diamond = "буби" hearts = "черви" spades = "пики" clubs = "трефы" class RANK: ace = "туз" jack = "валет" queen = "дама" king = "король" n_2 = "2" n_3 = "3" n_4 = "4" ...
Python
zaydzuhri_stack_edu_python
function make_patch particle begin if call is_immovable begin return call Circle call get_current_position call get_radius fill=false end else begin if call get_colour is not none begin set fill_colour = call get_colour end else begin comment Generate random colour. set fill_colour = string # + call zfill hexadecimal c...
def make_patch(particle): if particle.is_immovable(): return pl.Circle( particle.get_current_position(), particle.get_radius(), fill=False ) else: if particle.get_colour() is not None: fill_colour = particle.get_colour() else: ...
Python
nomic_cornstack_python_v1
from math import * from threading import Lock , Thread from ev3dev.ev3 import * from time import * from src.state.State import * class TrajectoryController begin function __init__ self __P __I __D __PA __IA __DA __motor1 __motor2 __motor3 __updateTime __stateList begin set __antiWindUpValue = 30 set __updateTime = __up...
from math import * from threading import Lock, Thread from ev3dev.ev3 import * from time import * from src.state.State import * class TrajectoryController: def __init__(self, __P, __I, __D,__PA, __IA, __DA, __motor1, __motor2, __motor3, __updateTime, __stateList): self.__antiWindUpValue = 30 se...
Python
zaydzuhri_stack_edu_python
function reverse_ll_inplace head begin comment catches edge case of list being empty if not head begin return string List is empty end comment catches edge case of list having one element if not next begin return head end set prev = none set curr = head while curr begin comment get next node set next = next comment rea...
def reverse_ll_inplace(head): # catches edge case of list being empty if not head: return "List is empty" # catches edge case of list having one element if not head.next: return head prev = None curr = head while curr: # get next node next = curr.next ...
Python
nomic_cornstack_python_v1
string file name should start with test test method name should start with test py.test test_mod.py # run tests in module py.test somepate # run all tests below somepath py.test test_module.py::test_method # only run test_method in test_module -s to print statements -v verbose import pytest decorator fixture function s...
""" file name should start with test test method name should start with test py.test test_mod.py # run tests in module py.test somepate # run all tests below somepath py.test test_module.py::test_method # only run test_method in test_module -s to print statements -v verbose """ import pytest @pytest.fixt...
Python
zaydzuhri_stack_edu_python
function mypy ctx begin run string mypy waterbutler/ pty=true end function
def mypy(ctx): ctx.run('mypy waterbutler/', pty=True)
Python
nomic_cornstack_python_v1
function registered self begin info string Registered. pass end function
def registered(self): log.info("Registered.") pass
Python
nomic_cornstack_python_v1
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup import pandas as pd import os import time function scrape_name name driver begin get driver name + string /30 if current_url == string https://sullygnome.com/ begin return tuple string -1 hrs string -1 ...
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from bs4 import BeautifulSoup import pandas as pd import os import time def scrape_name(name, driver): driver.get(name + '/30') if (driver.current_url == "https://sullygnome.com/"): return "-1 hrs", "-1" driver....
Python
zaydzuhri_stack_edu_python
function on_button_pressed_a begin call show_number call temperature while call temperature < 8 begin call start_melody call built_in_melody JUMP_DOWN ONCE_IN_BACKGROUND call show_string string T.baja call show_arrow SOUTH end while call temperature > 30 begin call start_melody call built_in_melody JUMP_UP ONCE_IN_BACK...
def on_button_pressed_a(): basic.show_number(input.temperature()) while input.temperature() < 8: music.start_melody(music.built_in_melody(Melodies.JUMP_DOWN), MelodyOptions.ONCE_IN_BACKGROUND) basic.show_string("T.baja") basic.show_arrow(ArrowNames.SOUTH) while input.temp...
Python
zaydzuhri_stack_edu_python
function get_switch_state self switch port url_base=none begin return call _get_switch_state switch port url_base end function
def get_switch_state(self, switch, port, url_base=None): return self._get_switch_state(switch, port, url_base)
Python
nomic_cornstack_python_v1
async function connection_factory *args **kwargs begin return tuple transport protocol end function
async def connection_factory(*args, **kwargs): return (transport, protocol)
Python
nomic_cornstack_python_v1
function sign_in self begin return get pulumi self string sign_in end function
def sign_in(self) -> pulumi.Output['outputs.ServiceSignIn']: return pulumi.get(self, "sign_in")
Python
nomic_cornstack_python_v1
function get_tasks self begin return all end function
def get_tasks(self): return self.tasks.all()
Python
nomic_cornstack_python_v1
comment counter.py comment Handles counting the switch connections. comment imports import time import RPi.GPIO as GPIO import sqlite3 as lite import sys comment inits call setmode BCM setup GPIO 4 IN pull_up_down=PUD_DOWN set con = call connect string db/data.sqlite3 set count = 0 comment endless loop, does really wel...
#counter.py # Handles counting the switch connections. # imports import time import RPi.GPIO as GPIO import sqlite3 as lite import sys # inits GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) con = lite.connect('db/data.sqlite3') count = 0 # endless loop, does really well at mitigating boun...
Python
zaydzuhri_stack_edu_python
function check_keydown_events event settings screen player player_shots begin comment Exit game if player presses ESC key. if key == K_ESCAPE begin call quit exit end comment Set movement flags, left and right arrow keys move player. if key == K_RIGHT begin set moving_right = true end if key == K_LEFT begin set moving_...
def check_keydown_events(event, settings, screen, player, player_shots): # Exit game if player presses ESC key. if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() # Set movement flags, left and right arrow keys move player. if event.key == pygame.K_RIGHT: player.moving_right = True if event.key == pyg...
Python
nomic_cornstack_python_v1
comment cook your dish here set t = integer input for _ in range t begin set __ = input set words = split input string set tails = dict for word in words begin set key = word at slice 1 : : if key in tails begin append tails at key word at 0 end else begin set tails at key = list word at 0 end end set ans = 0 set ta...
# cook your dish here t = int(input()) for _ in range(t): __ = input() words = input().split(' ') tails = {} for word in words: key = word[1:] if key in tails: tails[key].append(word[0]) else: tails[key] = [word[0]] ans = 0 tails_key...
Python
zaydzuhri_stack_edu_python
comment coding:utf8 comment The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. comment Find the sum of all the primes below two million. import common function next_prime num begin if num % 2 == 0 and num != 2 begin set num = num + 1 end while not call is_prime num begin set num = num + 2 end return num end function...
#coding:utf8 # The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # # Find the sum of all the primes below two million. import common def next_prime(num): if num % 2 == 0 and num != 2: num += 1 while not common.is_prime(num): num += 2 return num summary = 0 prime = 0 while prime < 200...
Python
zaydzuhri_stack_edu_python
string 4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ... Количество элементов (n) вводится с клавиатуры. function my_range n c=1 begin if n == c begin return string 1 / power - 2 n - 1 end else begin return string 1 / power - 2 c - 1 + string + call my_range n c + 1 end end function set n = inte...
""" 4. Найти сумму n элементов следующего ряда чисел: 1 -0.5 0.25 -0.125 ... Количество элементов (n) вводится с клавиатуры. """ def my_range(n, c=1): if n == c: return str(1 / pow(-2, n - 1)) else: return str(1 / pow(-2, c - 1)) + ' ' + my_range(n, c + 1) n = int(input("Введите количество э...
Python
zaydzuhri_stack_edu_python
string Серверное приложение для соединений import asyncio from asyncio import transports class ClientProtocol extends Protocol begin set login : str set server : string Server set transport : Transport function __init__ self server begin set server = server set login = none end function function data_received self data...
""" Серверное приложение для соединений """ import asyncio from asyncio import transports class ClientProtocol(asyncio.Protocol): login: str server: 'Server' transport: transports.Transport def __init__(self, server: 'Server'): self.server = server self.login = None def data_rece...
Python
zaydzuhri_stack_edu_python
function remove_unused_assets self begin comment First, get all columns that are -ASSET set schema = call get_schema set columns = list comprehension column at string field_name for column in values schema if ends with column at string type string -ASSET if length columns == 0 begin return end comment Delete any asset ...
def remove_unused_assets(self): # First, get all columns that are -ASSET schema = self.get_schema() columns = [ column["field_name"] for column in schema.values() if column["type"].endswith("-ASSET") ] if len(columns) == 0: return ...
Python
nomic_cornstack_python_v1
function is_prime x begin comment Special case for 1 and 2 if x == 1 or x == 2 begin return true end comment Check if x is divisible by any number from 2 to sqrt(x) for i in range 2 integer x ^ 0.5 + 1 begin if x // i * i == x begin return false end end return true end function
def is_prime(x): # Special case for 1 and 2 if x == 1 or x == 2: return True # Check if x is divisible by any number from 2 to sqrt(x) for i in range(2, int(x**0.5) + 1): if x // i * i == x: return False return True
Python
greatdarklord_python_dataset
from _extract_atoms import extract_atoms_with_resids function _write_to_text list_of_data line_format out_file begin with open out_file string w as handle begin for data in list_of_data begin write handle line_format % data end end return none end function function _write_to_text list_of_data line_format out_file begin...
from _extract_atoms import extract_atoms_with_resids def _write_to_text(list_of_data, line_format, out_file): with open(out_file, "w") as handle: for data in list_of_data: handle.write(line_format % data) return None def _write_to_text(list_of_data, line_format, out_file): with open(ou...
Python
zaydzuhri_stack_edu_python
async function update_stats self begin info string Attempting to post server count try begin await call post_guild_count info format string Posted server count ({}) call guild_count end except Exception as e begin exception format string Failed to post server count {}: {} __name__ e end end function
async def update_stats(self): logger.info('Attempting to post server count') try: await self.dblpy.post_guild_count() logger.info('Posted server count ({})'.format(self.dblpy.guild_count())) except Exception as e: logger.exception('Failed to post server count\...
Python
nomic_cornstack_python_v1
function get_total_commits_per_user commits begin return call get_total_contributions_per_user commits string author end function
def get_total_commits_per_user(commits): return get_total_contributions_per_user(commits, 'author')
Python
nomic_cornstack_python_v1
function user_stats df begin print string Calculating User Stats... set start_time = time comment Display counts of user types set userTypeCounts = value counts df at string User Type print string Counts of User Types: userTypeCounts print string comment Display counts of gender if string Gender in columns begin set ge...
def user_stats(df): print('\nCalculating User Stats...\n') start_time = time.time() # Display counts of user types userTypeCounts = df['User Type'].value_counts() print('Counts of User Types:\n',userTypeCounts) print('\n') # Display counts of gender if 'Gender' in df.columns: g...
Python
nomic_cornstack_python_v1
comment SCci 1133 comment Zhongyi Sun from os import path function main begin set opened = false set writted = false set i = 0 while not opened begin if i < 3 begin try begin set filename = input string Enter the source filename: set file = open filename string r set opened = true set output_filename = input string Ent...
#SCci 1133 #Zhongyi Sun from os import path def main(): opened = False writted = False i = 0 while not opened: if(i < 3): try: filename = input("Enter the source filename: ") file = open(filename,"r") opened = True ...
Python
zaydzuhri_stack_edu_python
import math class SparseTable begin function __init__ self array begin set input = array set input_len = length input set lookup_table = list call build_lookup_table end function function build_lookup_table self begin comment Is the biggest power of two range, that we have to support set max_elements = floor call log2...
import math class SparseTable: def __init__(self, array): self.input = array self.input_len = len(self.input) self.lookup_table = [] self.build_lookup_table() def build_lookup_table(self): # Is the biggest power of two range, that we have to support max_element...
Python
zaydzuhri_stack_edu_python
function login self account password begin set url = string https://ceq.nkust.edu.tw/Login set data = dict string __RequestVerificationToken csrf_key ; string UserAccount account ; string Password password set res = post url=url data=data allow_redirects=false if status_code == 302 begin set soup = call BeautifulSoup t...
def login(self, account, password): url = 'https://ceq.nkust.edu.tw/Login' data = { '__RequestVerificationToken': self.csrf_key, 'UserAccount': account, 'Password': password, } res = self.main_session.post(url=url, data=data, allow_redirects=False) ...
Python
nomic_cornstack_python_v1
function split_heads self x batch_size begin set x = reshape tf x tuple batch_size - 1 num_heads depth return transpose tf x perm=list 0 2 1 3 end function
def split_heads(self, x, batch_size): x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth)) return tf.transpose(x, perm=[0, 2, 1, 3])
Python
nomic_cornstack_python_v1
comment Time: O(n) comment Space: O(1) comment 解题思路: class Solution begin function possibleBipartition self N dislikes begin string :type N: int :type dislikes: List[List[int]] :rtype: bool set dicts = list for _ in range N begin append dicts set end set tuple A B = tuple set set for d in dislikes begin set d at 0 = d...
# Time: O(n) # Space: O(1) # 解题思路: # class Solution: def possibleBipartition(self, N, dislikes): """ :type N: int :type dislikes: List[List[int]] :rtype: bool """ dicts = [] for _ in range(N): dicts.append(set()) A, B = set(), set() ...
Python
zaydzuhri_stack_edu_python
comment append a list with the content of the other extend items temp print items
# append a list with the content of the other items.extend(temp) print(items)
Python
zaydzuhri_stack_edu_python
comment Data download & dataloader 구현 from torchvision.datasets import ImageFolder from torchvision import transforms from torch.utils.data import Dataset , DataLoader , TensorDataset set myPath = string /home/jsh/PycharmProjects/Torch_Exam/data/taco_and_burrito set train_imgs = call ImageFolder myPath + string /train/...
### Data download & dataloader 구현 from torchvision.datasets import ImageFolder from torchvision import transforms from torch.utils.data import (Dataset, DataLoader, TensorDataset) myPath = "/home/jsh/PycharmProjects/Torch_Exam/data/taco_and_burrito" train_i...
Python
zaydzuhri_stack_edu_python
import math set answerlist = list function main begin set T = integer input for i in range T begin set x = integer input set ans = string call factorial x append answerlist ans at - 1 end for i in answerlist begin print i end end function if __name__ == string __main__ begin call main end
import math answerlist = [] def main(): T = int(input()) for i in range(T): x = int(input()) ans = str(math.factorial(x)) answerlist.append(ans[-1]) for i in answerlist: print(i) if __name__=="__main__": main()
Python
zaydzuhri_stack_edu_python
function test_create_monitoring_project_not_found self begin set project_id = string unk set deployment_id = MOCK_UUID_1 set task_id = MOCK_UUID_1 set rv = post string /projects/ { project_id } /deployments/ { deployment_id } /monitorings json=dict string taskId task_id set result = json rv set expected = dict string m...
def test_create_monitoring_project_not_found(self): project_id = "unk" deployment_id = util.MOCK_UUID_1 task_id = util.MOCK_UUID_1 rv = TEST_CLIENT.post( f"/projects/{project_id}/deployments/{deployment_id}/monitorings", json={ "taskId": task_id, ...
Python
nomic_cornstack_python_v1
function create_cached_reference_document name document fields begin set attrs = dictionary id=call __class__ db_name=string id version=call IntegerField db_name=string _version comment Identifier (references primary key of the source document) comment Version number comment Ensure that serial primary keys don't get in...
def create_cached_reference_document(name, document, fields): attrs = dict( # Identifier (references primary key of the source document) id = document._meta.get_primary_key_field().__class__(db_name = "id"), # Version number version = fields_base.IntegerField(db_name = "_version"), ) # Ensure tha...
Python
nomic_cornstack_python_v1
class FourCal begin function __init__ self first second begin set first = first set second = second end function function setdata self first second begin set first = first set second = second end function function sum self begin set result = first + second return result end function end class class MoreCal extends Four...
class FourCal: def __init__(self, first, second): self.first = first self.second = second def setdata(self, first, second): self.first = first self.second = second def sum(self): result = self.first+self.second return result class MoreCal(FourCal): def po...
Python
zaydzuhri_stack_edu_python
string pour l'ex 2. Parfait.py 1) parfait001.py : comment determiner un nb s'il est parfait set n = integer input string entrez un nombre : set liste = list for i in range 1 n begin if n % i == 0 begin comment print (i, " / ", n) append liste i print string liste : liste end end print string tableau : liste set S = 0 ...
''' pour l'ex 2. Parfait.py 1) parfait001.py : comment determiner un nb s'il est parfait ''' n = int(input("entrez un nombre : ")) liste = [] for i in range(1, n): if n%i == 0: #print (i, " / ", n) liste.append(i) print ("liste : ", liste) print ("tableau : ", liste) S=0 for ...
Python
zaydzuhri_stack_edu_python
function test_teams_id_portals_nk_permission_post self begin pass end function
def test_teams_id_portals_nk_permission_post(self): pass
Python
nomic_cornstack_python_v1
comment coding:utf-8 set tuple a b = list comprehension integer x for x in split input string if not absolute a - b % 2 begin print integer absolute a - b / 2 + min a b end else begin print string IMPOSSIBLE end
# coding:utf-8 a, b = [int(x) for x in input().split(' ')] if not abs(a - b) % 2: print(int(abs(a - b) / 2 + min(a, b))) else: print('IMPOSSIBLE')
Python
zaydzuhri_stack_edu_python
function key self begin return get pulumi self string key end function
def key(self) -> str: return pulumi.get(self, "key")
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Wed Jan 16 18:58:54 2019 @author: MASTER comment SET COMPREHENSION & DICTIONARY COMPREHENSION comment create a set of all the first letters in a sequence of words set words = list string apple string banana string cauliflower set first_letter...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jan 16 18:58:54 2019 @author: MASTER """ #SET COMPREHENSION & DICTIONARY COMPREHENSION # create a set of all the first letters in a sequence of words words = ['apple', 'banana', 'cauliflower'] first_letters = set() for w in words: first_letters.ad...
Python
zaydzuhri_stack_edu_python
function __repr__ self begin return format string <User '{}'> name end function
def __repr__(self): return "<User '{}'>".format(self.name)
Python
nomic_cornstack_python_v1
set a = split input string enter the numbers with space string print join string sorted a print string maximum element in the list is max a print string manimu elment in the list is min a
a=input("enter the numbers with space").split(" ") print(" ".join(sorted(a))) print("maximum element in the list is",max(a)) print("manimu elment in the list is ",min(a))
Python
zaydzuhri_stack_edu_python
function validateOneAttribute self doc elem attr value begin if doc is none begin set doc__o = none end else begin set doc__o = _o end if elem is none begin set elem__o = none end else begin set elem__o = _o end if attr is none begin set attr__o = none end else begin set attr__o = _o end set ret = call xmlValidateOneAt...
def validateOneAttribute(self, doc, elem, attr, value): if doc is None: doc__o = None else: doc__o = doc._o if elem is None: elem__o = None else: elem__o = elem._o if attr is None: attr__o = None else: attr__o = attr._o ret = libxml2mod.xmlValidateOneAttribute(sel...
Python
nomic_cornstack_python_v1
function print_del self begin print string { string dest } end function
def print_del(self): print(f"{str(self.dest)!r}")
Python
nomic_cornstack_python_v1
import os import sys set stops = list set gpsdata = list set TimeConstant = 30 set orig_stdout = stdout function diff time1 time2 begin set A = integer time1 at slice - 2 : : + 60 * integer time1 at slice - 5 : - 3 : + 3600 * integer time1 at slice 0 : - 6 : set B = integer time2 at slice - 2 : : + 60 * integer tim...
import os import sys stops = [] gpsdata = [] TimeConstant = 30 orig_stdout = sys.stdout def diff(time1,time2): A = int(time1[-2:]) + 60*int(time1[-5:-3]) + 3600*int(time1[0:-6]) B = int(time2[-2:]) + 60*int(time2[-5:-3]) + 3600*int(time2[0:-6]) return A - B '''returns the start and end times array for all the...
Python
zaydzuhri_stack_edu_python
function set_defaults config cluster_name begin string fill-in some basic configuration parameters if config file is not set set default config at string postgresql string name cluster_name set default config at string postgresql string scope cluster_name set default config at string postgresql string listen string 127...
def set_defaults(config, cluster_name): """fill-in some basic configuration parameters if config file is not set """ config['postgresql'].setdefault('name', cluster_name) config['postgresql'].setdefault('scope', cluster_name) config['postgresql'].setdefault('listen', '127.0.0.1') config['postgresql'...
Python
jtatman_500k
comment Austin Rowell, arr461 comment QA Assignment 2 comment Due: Thursday, March 4th 2021 comment Unit testing BMI and Retirement functions comment Imports import unittest from unittest.mock import MagicMock , patch from QA_Assignment import retirement , BMI comment Test Class class Test_Function_QA_Assignment extend...
# Austin Rowell, arr461 # QA Assignment 2 # Due: Thursday, March 4th 2021 # Unit testing BMI and Retirement functions # Imports import unittest from unittest.mock import MagicMock, patch from QA_Assignment import retirement, BMI # Test Class class Test_Function_QA_Assignment(unittest.TestCase): # Patc...
Python
zaydzuhri_stack_edu_python
function _set_dynamic_bypass self v load=false begin string Setter method for dynamic_bypass, mapped from YANG variable /mpls_state/dynamic_bypass (container) If this variable is read-only (config: false) in the source YANG file, then _set_dynamic_bypass is considered as a private method. Backends looking to populate t...
def _set_dynamic_bypass(self, v, load=False): """ Setter method for dynamic_bypass, mapped from YANG variable /mpls_state/dynamic_bypass (container) If this variable is read-only (config: false) in the source YANG file, then _set_dynamic_bypass is considered as a private method. Backends looking to ...
Python
jtatman_500k
function ComboListBox items message=none title=none begin return call ShowComboListBox title message items end function
def ComboListBox(items, message=None, title=None): return Rhino.UI.Dialogs.ShowComboListBox(title, message, items)
Python
nomic_cornstack_python_v1
function test_name_list_data_type self begin set test_data11 = dict string name list 23.999 ; string email_address string qwcw@gmail.com ; string password string 2-cqcc ; string account_type string admin set response = post string /store-manager/api/v1/auth/signup content_type=string application/json data=dumps test_da...
def test_name_list_data_type(self): self.test_data11 = {"name": [23.999], "email_address": "qwcw@gmail.com", "password": "2-cqcc", "account_type": "admin"} response = self.test_app.post('/store-manager/api/v1/auth/signup', content_type="application/json", ...
Python
nomic_cornstack_python_v1
function _start_pagent self begin comment Create port agent object. set this_pid = call getpid set _pagent = call launch_process device_address device_port WORK_DIR DELIM this_pid comment Get the pid and port agent server port number. set pid = call get_pid while not pid begin sleep 0.1 set pid = call get_pid end set p...
def _start_pagent(self): # Create port agent object. this_pid = os.getpid() self._pagent = EthernetDeviceLogger.launch_process(self.device_address, self.device_port, WORK_DIR, ...
Python
nomic_cornstack_python_v1
import numpy as np class NNMulticlass begin function __init__ self nodes learningParams randomSeed weights begin string Initializes instance of NNMultiClass. Args: nodes: Tuple containing size of (input node, hidden node, output node). learningParams: Tuple containing (lambda, number of epochs, learning rate). randomSe...
import numpy as np class NNMulticlass: def __init__(self, nodes, learningParams, randomSeed, weights): """Initializes instance of NNMultiClass. Args: nodes: Tuple containing size of (input node, hidden node, output node). learningParams: Tuple containing (lambda, nu...
Python
zaydzuhri_stack_edu_python
function push_left grid begin for i in range length grid begin set freespot = 0 for q in range length grid at i begin if grid at i at q != 0 begin comment perform a swap using a temporary variable set temp = grid at i at freespot set grid at i at freespot = grid at i at q set grid at i at q = temp set freespot = freesp...
def push_left (grid): for i in range(len(grid)): freespot = 0 for q in range(len(grid[i])): if grid[i][q] != 0: temp = grid[i][freespot] #perform a swap using a temporary variable grid[i][freespot] = grid[i][q] grid[i][q] = temp ...
Python
nomic_cornstack_python_v1
function filter self predicate begin set new = copy self set sublist = filter predicate set meets_prediacate = call test self if meets_prediacate or items begin return new end end function
def filter(self, predicate): new = self.copy() new.sublist = self.sublist.filter(predicate) meets_prediacate = predicate.test(self) if meets_prediacate or new.sublist.items: return new
Python
nomic_cornstack_python_v1
function reverse s begin set str_result = string for i in range length s - 1 - 1 - 1 begin set str_result = str_result + s at i end return str_result end function if __name__ == string __main__ begin set s = string welcome print s reverse s end
def reverse(s: str) -> str: str_result = "" for i in range(len(s) - 1, -1, -1): str_result += s[i] return str_result if __name__ == '__main__': s = "welcome" print(s, reverse(s))
Python
zaydzuhri_stack_edu_python
function NMFcomponents ref ref_err=none n_components=none maxiters=1000.0 oneByOne=false path_save=none begin if ref_err is none begin set ref_err = square root ref end if n_components is none or n_components > shape at 0 begin set n_components = shape at 0 end set ref at ref < 0 = 0 comment Setting the err of <= 0 pix...
def NMFcomponents(ref, ref_err = None, n_components = None, maxiters = 1e3, oneByOne = False, path_save = None): if ref_err is None: ref_err = np.sqrt(ref) if (n_components is None) or (n_components > ref.shape[0]): n_components = ref.shape[0] ref[ref < 0] = 0 ref_err[ref <= 0]...
Python
nomic_cornstack_python_v1
comment delete all coments from file comment read file in buffer and close comment for singleline comment: comment start with # and end with \n comment need to use re.multiline comment for multiline comment: comment start and end with ''' or """ (including \n as well) comment open same file in write mode and dump the u...
#delete all coments from file #read file in buffer and close #for singleline comment: #start with # and end with \n #need to use re.multiline #for multiline comment: #start and end with ''' or """ (including \n as well) #open same file in write mode and dump the updated buffer import re def DeleteComments(...
Python
zaydzuhri_stack_edu_python
comment Challenge: http://pastebin.com/40Nu4AXB function base x y n begin string Iterative solution to (X=1, Y=x+y-1, N=n) set curRow = list comprehension i for i in range 0 n for N in range 2 n begin set curRow at N = curRow at N - 1 * N - 1 end for _ in range 3 x + y begin set lastRow = curRow at slice : : for N i...
# Challenge: http://pastebin.com/40Nu4AXB def base(x, y, n): """Iterative solution to (X=1, Y=x+y-1, N=n)""" curRow = [i for i in range(0, n)] for N in range(2,n): curRow[N] = curRow[N-1]*(N-1) for _ in range(3, x+y): lastRow = curRow[:] for N in range(1, n): curRow[...
Python
zaydzuhri_stack_edu_python
from apps.models import db , BaseModel from werkzeug.security import generate_password_hash , check_password_hash class BuyerModel extends BaseModel begin set username = call Column call String 32 unique=true set _password = call Column string password call String 128 set tel = call Column call String 16 unique=true de...
from apps.models import db, BaseModel from werkzeug.security import generate_password_hash, check_password_hash class BuyerModel(BaseModel): username = db.Column(db.String(32), unique=True) _password = db.Column("password", db.String(128)) tel = db.Column(db.String(16), unique=True) @property def...
Python
zaydzuhri_stack_edu_python
function http_meta_data self begin comment For each flow process the contents for flow in input_stream begin comment Client to Server if flow at string direction == string CTS begin try begin set request = call Request flow at string payload set request_data = call make_dict request set request_data at string uri = cal...
def http_meta_data(self): # For each flow process the contents for flow in self.input_stream: # Client to Server if flow['direction'] == 'CTS': try: request = dpkt.http.Request(flow['payload']) request_data = data_utils.ma...
Python
nomic_cornstack_python_v1
function pop_element_from_tuple_slicing my_tuple index=none begin set my_tuple = my_tuple at slice : index : + my_tuple at slice index + 1 : : return my_tuple end function function pop_element_from_tuple_convert_to_list my_tuple index begin set tuple_to_list = list my_tuple pop tuple_to_list index return tuple tupl...
def pop_element_from_tuple_slicing(my_tuple: tuple, index=None): my_tuple = my_tuple[:index] + my_tuple[index + 1:] return my_tuple def pop_element_from_tuple_convert_to_list(my_tuple: tuple, index): tuple_to_list = list(my_tuple) tuple_to_list.pop(index) return tuple(tuple_to_list)
Python
zaydzuhri_stack_edu_python
async function embed_store_yamlfile self ctx name begin set data = await call get_file_from_message ctx file_types=tuple string yaml string txt set e = await call convert ctx data await call store_embed ctx name e await call tick end function
async def embed_store_yamlfile(self, ctx: commands.Context, name: str): data = await self.get_file_from_message(ctx, file_types=("yaml", "txt")) e = await YAML_CONVERTER.convert(ctx, data) await self.store_embed(ctx, name, e) await ctx.tick()
Python
nomic_cornstack_python_v1
comment Authors: Brent van Dodewaard, Jop van Hest, Luitzen de Vries. comment Heuristics programming project: Protein pow(d)er. comment This file implements an iterative algorithm which randomly refolds 1 fold. comment It lowers the chance to accept folds which do not improve the score when "temperature" drops. import ...
# Authors: Brent van Dodewaard, Jop van Hest, Luitzen de Vries. # Heuristics programming project: Protein pow(d)er. # This file implements an iterative algorithm which randomly refolds 1 fold. # It lowers the chance to accept folds which do not improve the score when "temperature" drops. import copy import random fro...
Python
zaydzuhri_stack_edu_python
function tests_get_subscription self begin set manager_root = call ISubscriptionManager root set subscribability = SUBSCRIBABLE call subscribe string wim@example.com set manager_folder = call ISubscriptionManager folder call subscribe string arthur@example.com set manager = call ISubscriptionManager index set subscriba...
def tests_get_subscription(self): manager_root = ISubscriptionManager(self.root) manager_root.subscribability = SUBSCRIBABLE manager_root.subscribe('wim@example.com') manager_folder = ISubscriptionManager(self.root.folder) manager_folder.subscribe('arthur@example.com') m...
Python
nomic_cornstack_python_v1
function account_id self begin return get pulumi self string account_id end function
def account_id(self) -> str: return pulumi.get(self, "account_id")
Python
nomic_cornstack_python_v1
function to_dict self begin return dict string color call to_dict ; string opacity call to_dict ; string links linked_indices end function
def to_dict(self): return { 'color': self.color.to_dict(), 'opacity': self.opacity.to_dict(), 'links': self.linked_indices, }
Python
nomic_cornstack_python_v1
comment coding=UTF-8 comment Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador PERDER. comment Deve mostrar na tela o total de vitórias consecutivas que ele conquistou no final do jogo. from random import randint set contador = 0 while true begin print string =- * 30...
# coding=UTF-8 # Faça um programa que jogue par ou ímpar com o computador. O jogo só será interrompido quando o jogador PERDER. # Deve mostrar na tela o total de vitórias consecutivas que ele conquistou no final do jogo. from random import randint contador = 0 while True: print('=-' * 30) print('VAMOS JOGAR PA...
Python
zaydzuhri_stack_edu_python
comment 3 function longitud e begin set x = 0 for a in e begin set x = x + 1 end return x end function assert call longitud string hola == 4 assert call longitud string hola != 3
#3 def longitud(e): x=0 for a in e: x+=1 return x assert longitud('hola') == 4 assert longitud('hola') != 3
Python
zaydzuhri_stack_edu_python
from playsound import playsound import os import firebase_admin from firebase_admin import credentials from firebase_admin import storage set cred = call Certificate string popup-766d7-firebase-adminsdk-yay84-2ce9f0396a.json call initialize_app cred dict string storageBucket string popup-766d7.appspot.com set bucket = ...
from playsound import playsound import os import firebase_admin from firebase_admin import credentials from firebase_admin import storage cred = credentials.Certificate("popup-766d7-firebase-adminsdk-yay84-2ce9f0396a.json") firebase_admin.initialize_app(cred, { 'storageBucket': 'popup-766d7.appspot.com' }) bucket ...
Python
zaydzuhri_stack_edu_python
function test_create_authors_with_affid_but_missing_affiliation begin set text = string A. Einstein1, N. Bohr2 2 Københavns Universitet set result = call create_authors text set expected = list tuple string A. Einstein list tuple string N. Bohr list string Københavns Universitet set warning = string Unresolved aff-ID ...
def test_create_authors_with_affid_but_missing_affiliation(): text = "A. Einstein1, N. Bohr2\n" "\n" "2 Københavns Universitet" result = create_authors(text) expected = [(u"A. Einstein", []), (u"N. Bohr", [u"K\xf8benhavns Universitet"])] warning = "Unresolved aff-ID or stray footnote symbol. Problemat...
Python
nomic_cornstack_python_v1
function test_experiment_profiling self cli_app app_files begin comment Create Experiment file call create_from_stub config_path string FooExperimentProfiling string experiments/FooExperiment.py comment User runs the experiment set argv = list string main.py string experiments:run string foo string --n=1 run comment Ch...
def test_experiment_profiling(self, cli_app, app_files): # Create Experiment file app_files.create_from_stub( cli_app.config_path, 'FooExperimentProfiling', 'experiments/FooExperiment.py' ) # User runs the experiment sys.argv = ['main.py', 'ex...
Python
nomic_cornstack_python_v1
import random class player begin function __init__ self name strategy=none money=none begin set name = name set strategy = strategy set start_money = money set money = start_money set bank = 0 set cards = list set bets = dict set fold = false end function function action self begin set actions = list string bet strin...
import random class player: def __init__(self, name, strategy=None, money=None): self.name = name self.strategy = strategy self.start_money = money self.money = self.start_money self.bank = 0 self.cards = [] self.bets = {} self.fold = False def action(self): actions = ['bet', 'c...
Python
zaydzuhri_stack_edu_python
function area self begin return _area end function
def area(self): return self._area
Python
nomic_cornstack_python_v1
comment create a list of items (you may use strings or numbers in the list), comment then create an iterator using the iter() function. comment use a for loop to loop "n" times, where "n" is the number of items in your list comment each time round the loop, use next() on your list to print the next item. comment hint: ...
# create a list of items (you may use strings or numbers in the list), # then create an iterator using the iter() function. # # use a for loop to loop "n" times, where "n" is the number of items in your list # each time round the loop, use next() on your list to print the next item. # # hint: use the len() function rat...
Python
zaydzuhri_stack_edu_python
comment makers: Sanne en Inge comment de benodigde python code om de website te laten werken en de goeie resultaten te krijgen from flask import Flask , render_template , request import mysql.connector import re from Bio.Blast import NCBIWWW , NCBIXML set app = call Flask __name__ decorator call route string / methods=...
# makers: Sanne en Inge # de benodigde python code om de website te laten werken en de goeie resultaten te krijgen from flask import Flask, render_template, request import mysql.connector import re from Bio.Blast import NCBIWWW, NCBIXML app = Flask(__name__) @app.route('/', methods=['get', 'post']) def ...
Python
zaydzuhri_stack_edu_python
function get_channels self begin set header = dictionary generator expression tuple channel_name list for channel_name in rows at 2 comment Add the Unit as the first item for channel in header begin set key_index = index rows at 2 channel append header at channel rows at 3 at key_index end comment Add lists of data po...
def get_channels(self): header = dict((channel_name, []) for channel_name in self.rows[2]) for channel in header: # Add the Unit as the first item key_index = self.rows[2].index(channel) header[channel].append(self.rows[3][key_index]) for line in range(1, self.max_line...
Python
nomic_cornstack_python_v1
function concatHMMs hmmmodels namelist begin set concat = hmmmodels at namelist at 0 for idx in range 1 length namelist begin set concat = call concatTwoHMMs concat hmmmodels at namelist at idx end return concat end function
def concatHMMs(hmmmodels, namelist): concat = hmmmodels[namelist[0]] for idx in range(1,len(namelist)): concat = concatTwoHMMs(concat, hmmmodels[namelist[idx]]) return concat
Python
nomic_cornstack_python_v1
function __init__ self size default_value=none begin set data = list set size = size set default_value = default_value set data = list comprehension default_value for i in range size comment for i in range(size): comment self.data.append(default_value) function __setitem__ self index new_value begin string Set the datu...
def __init__(self,size,default_value=None): self.data = list() self.size = size self.default_value = default_value self.data = [default_value for i in range(size)] # for i in range(size): # self.data.append(default_value) def __setitem__(self,index,new_value): "...
Python
nomic_cornstack_python_v1
function connectToLAN self begin print string Connect to LAN comment stationary mode for connecting ESP8266 module to the router set sta_if = call WLAN STA_IF print string Check connection.... if not call isconnected begin comment connect to the router when no connected after startup print string Connecting to network....
def connectToLAN(self): print("Connect to LAN") #stationary mode for connecting ESP8266 module to the router sta_if = network.WLAN(network.STA_IF) print("Check connection....") if not sta_if.isconnected(): #connect to the router when no connected after startup print("Connecting to network...") sta_if...
Python
nomic_cornstack_python_v1
function to_str self begin return call pformat call to_dict end function
def to_str(self): return pprint.pformat(self.to_dict())
Python
nomic_cornstack_python_v1
from RestingState import RestingState from CondicaoMotora import CondicaoMotora from Performance import Performance from Interocepcao import Interocepcao from Feedback import Feedback from Data import Data import os import time set DURATION_motora1 = 131 set DURATION_motora2 = 144 set DURATION_interocepcao1 = 120 set D...
from RestingState import RestingState from CondicaoMotora import CondicaoMotora from Performance import Performance from Interocepcao import Interocepcao from Feedback import Feedback from Data import Data import os import time DURATION_motora1 = 131 DURATION_motora2 = 144 DURATION_interocepcao1 = 120 DURATION_feed...
Python
zaydzuhri_stack_edu_python
function next self begin if _done begin raise StopIteration end set _done = true return _result end function
def next(self): if self._done: raise StopIteration self._done = True return self._result
Python
nomic_cornstack_python_v1
function add_item begin set form = call ItemForm comment Query for select field set query = all if call validate_on_submit begin set new_item = item category_id=id name=capitalize data description=data user_id=id add session new_item commit session call flash format string New item '{}' was successfully created capital...
def add_item(): form = ItemForm() # Query for select field form.category_id.query = Category.query.filter( Category.user_id == current_user.id).all() if form.validate_on_submit(): new_item = Item( category_id=form.category_id.data.id, name=form.name.data.capital...
Python
nomic_cornstack_python_v1
function process_unknown_resources self analyzer begin if not analyzer begin return end set objs = call get_unknown_asn for o_h in keys objs begin set comment = string Unknown + o_h + string originating + join string , map str objs at o_h comment XXX Dont Process new collections automatically comment analyzer.process_n...
def process_unknown_resources(self, analyzer): if not analyzer: return objs = self.get_unknown_asn() for o_h in objs.keys(): comment = "Unknown " + o_h + " originating " + ', '.join(map(str, objs[o_h])) # XXX Dont Process new collections automatically ...
Python
nomic_cornstack_python_v1
function is_input_file self begin return depth == 0 end function
def is_input_file(self): return self.depth == 0
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Reference code: https://github.com/jostbr/shallow-water Author: Joshua Lee (MSS/CCRS) Updated: 15/08/2019 - Tidying up code 11/10/2019 - Added plotting for energy timeseries Extended based on a practical by Prof Pier Luigi Vidale import numpy as np import matplotlib.pyplot as plt fr...
# -*- coding: utf-8 -*- """ Reference code: https://github.com/jostbr/shallow-water Author: Joshua Lee (MSS/CCRS) Updated: 15/08/2019 - Tidying up code 11/10/2019 - Added plotting for energy timeseries Extended based on a practical by Prof Pier Luigi Vidale """ import numpy as np import matplotlib.pyplot as...
Python
zaydzuhri_stack_edu_python
from models import * from itertools import product function to_boolean string begin if string == string true begin return true end else begin return false end end function function get_teachers begin set teachers = list for teacher in all begin if name begin set data = list name classes append teachers data end end re...
from models import * from itertools import product def to_boolean(string): if string == "true": return True else: return False def get_teachers(): teachers = [] for teacher in Teachers.query.all(): if teacher.name: data = [teacher.name, teacher.classes] ...
Python
zaydzuhri_stack_edu_python