code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function test_ns_make_7_of_everything self
begin
set nesw = list string AKQJ.AKQJ.T98.T9 string 5432.5432.32.432 string T98.T9.AKQJ.AKQJ string 76.876.7654.8765
set hands = call nesw_to_dds_format nesw
set dds_table = call calc_dd_table hands
for denomination in list string C string D string H string S string N
begin
f... | def test_ns_make_7_of_everything(self):
nesw = [
"AKQJ.AKQJ.T98.T9",
"5432.5432.32.432",
"T98.T9.AKQJ.AKQJ",
"76.876.7654.8765"
]
hands = nesw_to_dds_format(nesw)
dds_table = self.dds.calc_dd_table(hands)
for denomination in ['C... | Python | nomic_cornstack_python_v1 |
set b = split input
print length join string generator expression a for a in b | b=input().split()
print(len("".join(a for a in b)))
| Python | zaydzuhri_stack_edu_python |
function GetUpdateInterval *args **kwargs
begin
return call UpdateUIEvent_GetUpdateInterval *args keyword kwargs
end function | def GetUpdateInterval(*args, **kwargs):
return _core_.UpdateUIEvent_GetUpdateInterval(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
function make_versioned_key key version
begin
assert is instance key str
assert is instance version int
if version is none or version == 0
begin
return key
end
return string { key } _v { version }
end function | def make_versioned_key(key: str, version: int) -> str:
assert isinstance(key, str)
assert isinstance(version, int)
if version is None or version == 0:
return key
return f"{key}_v{version:03d}" | Python | nomic_cornstack_python_v1 |
comment You may modify the lines of code above, but don't move them!
comment When you Submit your code, we'll change these lines to
comment assign different values to the variables.
comment In music, a song's time signature is given in terms of beats
comment per measure. A common time signature is 4 beats per measure:
... | # You may modify the lines of code above, but don't move them!
# When you Submit your code, we'll change these lines to
# assign different values to the variables.
# In music, a song's time signature is given in terms of beats
# per measure. A common time signature is 4 beats per measure:
# for every measure of music,... | Python | zaydzuhri_stack_edu_python |
import board
import unittest
class BoardTests extends TestCase
begin
function setUp self
begin
set board = call Board 15 10
end function
function test_dimensions self
begin
string 2-dimensional finite board
assert equal size board tuple 15 10
end function
function test_setter_and_getters self
begin
put 1 1 string A gem... | import board
import unittest
class BoardTests(unittest.TestCase):
def setUp(self):
self.board = board.Board(15, 10)
def test_dimensions(self):
"2-dimensional finite board"
self.assertEqual(self.board.size(), (15, 10))
def test_setter_and_getters(self):
self.board.put(1, 1,... | Python | zaydzuhri_stack_edu_python |
from utilities.general_functions import *
import pygame
from engine.door import *
class MetaDoor extends Door
begin
string complement of wall
function __init__ self opened=false
begin
string creation of door
comment inherited constructor
call __init__ self opened
comment default color of the door
set font_color = call ... | from utilities.general_functions import *
import pygame
from engine.door import *
class MetaDoor(Door):
"""
complement of wall
"""
def __init__(self, opened=False):
"""
creation of door
"""
# inherited constructor
Door.__init__(self, opened)
# default c... | Python | zaydzuhri_stack_edu_python |
from util import random as _random
from discord.ext.commands import Converter
from typing import Optional
class Range
begin
function __init__ self bounds maybe_maximum=none
begin
if maybe_maximum
begin
set bounds = tuple bounds maybe_maximum
end
set min = bounds at 0
set max = bounds at 1
end function
decorator propert... | from .util import random as _random
from discord.ext.commands import Converter
from typing import Optional
class Range:
def __init__(self, bounds, maybe_maximum=None):
if maybe_maximum:
bounds = (bounds, maybe_maximum)
self.min = bounds[0]
self.max = bounds[1]
@property
... | Python | zaydzuhri_stack_edu_python |
set string = string programmer
set a = length string
print format string the Length is {0} a | string="programmer"
a= len(string)
print ("the Length is {0}".format(a))
| Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
comment The coding above is only necessary with Python 2
set possible_prime = 2
while true
begin
comment This first loop loops over possible primes
set divisor = 2
comment For keeping track of whether possible_prime actually is a prime
set is_prime = true
while divisor < possible_prime
begin
commen... | # coding=utf-8
# The coding above is only necessary with Python 2
possible_prime = 2
while True:
#This first loop loops over possible primes
divisor = 2
is_prime = True #For keeping track of whether possible_prime actually is a prime
while divisor < possible_prime:
#This second loop loops over possible divisors... | Python | zaydzuhri_stack_edu_python |
function from_roots cls maroots=none arroots=none nobs=100
begin
if arroots is not none and length arroots
begin
set arpoly = call fromroots arroots
set arcoefs = coef at slice 1 : : / coef at 0
end
else
begin
set arcoefs = list
end
if maroots is not none and length maroots
begin
set mapoly = call fromroots maroots
... | def from_roots(cls, maroots=None, arroots=None, nobs=100):
if arroots is not None and len(arroots):
arpoly = np.polynomial.polynomial.Polynomial.fromroots(arroots)
arcoefs = arpoly.coef[1:] / arpoly.coef[0]
else:
arcoefs = []
if maroots is not None and len(ma... | Python | nomic_cornstack_python_v1 |
from flask import Flask , request , url_for , redirect , render_template
import pickle
import numpy as np
set model = load pickle open string lr_model.pkl string rb
set app = call Flask __name__ template_folder=string templates
decorator call route string /
function home
begin
return call render_template string homepag... | from flask import Flask,request, url_for, redirect, render_template
import pickle
import numpy as np
model=pickle.load(open('lr_model.pkl','rb'))
app = Flask(__name__,template_folder='templates')
@app.route("/")
def home():
return render_template('homepage.html')
@app.route('/predict',methods=['POST','GET'])
def... | Python | zaydzuhri_stack_edu_python |
import random
function validate_fermats_problem a b c n
begin
assert n > 2
assert a >= 1
assert b >= 1
assert c >= 1
return not a ^ n + b ^ n == c ^ n
end function
function nice_sequence n ny=none
begin
if ny is none
begin
set ny = n
end
set next_nx = 2 * n ^ 3 / 3 * n ^ 2 - 1
set next_ny = 1 / 2 * ny + 1 / ny
if next_... | import random
def validate_fermats_problem(a: int, b: int, c: int, n: int) -> bool:
assert n > 2
assert a >= 1
assert b >= 1
assert c >= 1
return not a**n + b**n == c**n
def nice_sequence(n: float, ny: float = None) -> (float, float):
if ny is None:
ny = n
next_nx = (2 * n**3)/(3... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
function show_image jpg_path png_path
begin
set jpg = array call convert string L
set png = array call convert string L
image show absolute jpg - png cmap=string gray
show
end function
if __name__ == string __main__
begin
call show_image string pi... | import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
def show_image(jpg_path, png_path):
jpg = np.array(Image.open(jpg_path).convert('L'))
png = np.array(Image.open(png_path).convert('L'))
plt.imshow(np.abs(jpg - png), cmap='gray')
plt.show()
if __name__ == "__main__":
show_image('pic.jpg', ... | Python | zaydzuhri_stack_edu_python |
function get_grid_width self
begin
return _grid_width
end function | def get_grid_width(self):
return self._grid_width | Python | nomic_cornstack_python_v1 |
function urllib_parse_parse_qs
begin
set encoded = string foo=foo1&foo=foo2
debug string parse_qs : { call parse_qs encoded }
debug string parse_qsl : { call parse_qsl encoded }
end function | def urllib_parse_parse_qs():
encoded = 'foo=foo1&foo=foo2'
logging.debug(f'parse_qs : {parse_qs(encoded)}')
logging.debug(f'parse_qsl : {parse_qsl(encoded)}') | Python | nomic_cornstack_python_v1 |
function data_sub_graph self pv simplified=true killing_edges=false excluding_types=none
begin
string Get a subgraph from the data graph or the simplified data graph that starts from node pv. :param ProgramVariable pv: The starting point of the subgraph. :param bool simplified: When True, the simplified data graph is u... | def data_sub_graph(self, pv, simplified=True, killing_edges=False, excluding_types=None):
"""
Get a subgraph from the data graph or the simplified data graph that starts from node pv.
:param ProgramVariable pv: The starting point of the subgraph.
:param bool simplified: When True, the s... | Python | jtatman_500k |
from tkinter import *
from random import *
import time
class Ball
begin
function __init__ self canvas color w h racket
begin
set canvas = canvas
set racket = racket
set id = call create_oval 0 0 20 20 fill=color
move id w / 2 h / 2
set startPos = list - 20 - 15 - 10 - 5 5 10 15 20
shuffle startPos
set x = startPos at 0... | from tkinter import *
from random import *
import time
class Ball:
def __init__(self, canvas, color, w, h, racket):
self.canvas = canvas
self.racket = racket
self.id = canvas.create_oval(0,0,20,20,fill=color)
self.canvas.move(self.id,w/2,h/2)
startPos = [-20, -15, -10, -5, 5... | Python | zaydzuhri_stack_edu_python |
function simplex_step A b c B N
begin
set c_B = array list comprehension c at i for i in B
set c_N = array list comprehension c at i for i in N
set A_N = transpose array list comprehension A at tuple slice : : i for i in N
set A_B = transpose array list comprehension A at tuple slice : : i for i in B
set A_B_inv ... | def simplex_step(A,b,c,B,N):
c_B = array([c[i] for i in B])
c_N = array([c[i] for i in N])
A_N = transpose( array([A[:,i] for i in N]) )
A_B = transpose( array([A[:,i] for i in B]) )
A_B_inv = inv(A_B)
lambda_ = dot(transpose(c_B), A_B_inv)
r_N = transpose( dot(lambda_, A_N) - transp... | Python | nomic_cornstack_python_v1 |
function test_connection self
begin
assert string view.list in call get_methods
return string cwd:%r, pid:%r % tuple call cwd call pid
end function | def test_connection(self):
assert 'view.list' in self.get_methods()
return 'cwd:%r, pid:%r' % (self.proxy.system.cwd(), self.proxy.system.pid()) | Python | nomic_cornstack_python_v1 |
function XOR list1 list2
begin
set result = integer list1 16 ? integer list2 16
return hexadecimal result at slice 2 : :
end function
function subNibble input box
begin
set result = call zfill 4
set row = integer result at 0 + result at 1 2
set column = integer result at 2 + result at 3 2
return box at row at column
... | def XOR(list1, list2):
result = int(list1, 16) ^ int(list2, 16)
return hex(result)[2:]
def subNibble(input, box):
result = bin(int(input, 16))[2:].zfill(4)
row = int(result[0] + result[1], 2)
column = int(result[2] + result[3], 2)
return box[row][column]
def genT(input, rc):
t0 = subNibb... | Python | zaydzuhri_stack_edu_python |
function _decode_control self p_topic p_message
begin
debug format string Decode-Control called: Topic:{} Message:{} p_topic p_message
set l_sender = call get_mqtt_field p_message string Sender
set l_family = call get_mqtt_field p_message string Family
set l_model = call get_mqtt_field p_message string Model
if l_famil... | def _decode_control(self, p_topic, p_message):
LOG.debug('Decode-Control called:\n\tTopic:{}\n\tMessage:{}'.format(p_topic, p_message))
l_sender = extract_tools.get_mqtt_field(p_message, 'Sender')
l_family = extract_tools.get_mqtt_field(p_message, 'Family')
l_model = extract_tools.get_mq... | Python | nomic_cornstack_python_v1 |
comment @lc app=leetcode id=141 lang=python3
comment [141] Linked List Cycle
comment @lc code=start
comment Definition for singly-linked list.
comment class ListNode:
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution
begin
function hasCycle self head
begin
set visited = set
set... | #
# @lc app=leetcode id=141 lang=python3
#
# [141] Linked List Cycle
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
visited = set()
... | Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ Node data
begin
set data = data
set next = none
end function
end class
function detectCycle head
begin
set fast = head
set slow = head
set loopexist = 0
while fast != none and slow != none and next != none
begin
set fast = next
set slow = next
if fast == slow
begin
set loopexist = 1
b... | class Node:
def __init__(Node, data):
Node.data = data
Node.next = None
def detectCycle(head):
fast=head
slow=head
loopexist=0
while(fast!=None and slow!=None and fast.next!=None):
fast=fast.next.next
slow=slow.next
if(fast==slow):
... | Python | zaydzuhri_stack_edu_python |
from torch.utils.data import Dataset
from PIL import Image
import os
function default_loader path
begin
try
begin
set img = open path
return call convert string RGB
end
except any
begin
print format string Can't read image: {} path
end
end function
comment define your Dataset. Assume each line in your .txt file is [nam... | from torch.utils.data import Dataset
from PIL import Image
import os
def default_loader(path):
try:
img = Image.open(path)
return img.convert('RGB')
except:
print("Can't read image: {}".format(path))
# define your Dataset. Assume each line in your .txt file is [name/tab/label], for exa... | Python | zaydzuhri_stack_edu_python |
function fix x out=none **kwargs
begin
return call _unary_func_helper x fix fix out=out
end function | def fix(x, out=None, **kwargs):
return _unary_func_helper(x, _npi.fix, _np.fix, out=out) | Python | nomic_cornstack_python_v1 |
function palindrome string
begin
set temp = join string reversed string
if temp == string
begin
print string string is palindrome
end
else
begin
print string string is not palindrome
end
end function
call palindrome string lol
call palindrome string Nikhil | def palindrome(string):
temp=''.join(reversed(string))
if temp==string:
print(string," is palindrome")
else:
print(string," is not palindrome")
palindrome('lol')
palindrome('Nikhil') | Python | zaydzuhri_stack_edu_python |
import csv
import os
set input_file = join path string Resources string budget_data.csv
set output_file = join path string Analysis string budget_analysis.txt
set month_count = 0
set sum_of_pl = 0
set month_count_change = 0
set month_change = 0
set before_month = 0
set greatest_increase = 0
set greatest_decrease = 0
wi... | import csv
import os
input_file = os.path.join("Resources","budget_data.csv")
output_file = os.path.join("Analysis", "budget_analysis.txt")
month_count = 0
sum_of_pl= 0
month_count_change =0
month_change = 0
before_month = 0
greatest_increase = 0
greatest_decrease = 0
with open(input_file) as csvfile:
csvread... | Python | zaydzuhri_stack_edu_python |
for i in range 10
begin
try
begin
set result = 10 / i
end
except ZeroDivisionError
begin
print string 숫자는 0으로 나눌 수 없습니다
end
try else
begin
print string result: result
end
finally
begin
print string 한 번 연산 종료
end
end | for i in range(10):
try:
result = 10/i
except ZeroDivisionError:
print('숫자는 0으로 나눌 수 없습니다')
else:
print('result:',result)
finally:
print('한 번 연산 종료')
| Python | zaydzuhri_stack_edu_python |
function get_all_chats self
begin
string Fetches all chats :return: List of chats :rtype: list[Chat]
set chats = call getAllChats
if chats
begin
return list comprehension call factory_chat chat self for chat in chats
end
else
begin
return list
end
end function | def get_all_chats(self):
"""
Fetches all chats
:return: List of chats
:rtype: list[Chat]
"""
chats = self.wapi_functions.getAllChats()
if chats:
return [factory_chat(chat, self) for chat in chats]
else:
return [] | Python | jtatman_500k |
function multicall self context msg topic=none version=none timeout=none
begin
call _set_version msg version
set msg at string args = call _serialize_msg_args context msg at string args
set real_topic = call _get_topic topic
try
begin
set result = call multicall context real_topic msg timeout
return call deserialize_en... | def multicall(self, context, msg, topic=None, version=None, timeout=None):
self._set_version(msg, version)
msg['args'] = self._serialize_msg_args(context, msg['args'])
real_topic = self._get_topic(topic)
try:
result = rpc.multicall(context, real_topic, msg, timeout)
... | Python | nomic_cornstack_python_v1 |
function is_int value
begin
return is instance value int
end function | def is_int(value):
return isinstance(value, int) | Python | nomic_cornstack_python_v1 |
function test_update_useruser_uuid_put self
begin
pass
end function | def test_update_useruser_uuid_put(self):
pass | Python | nomic_cornstack_python_v1 |
function setAndFreeze nodeName=string tx=none ty=none tz=none rx=none ry=none rz=none sx=none sy=none sz=none freeze=true
begin
if nodeName != string
begin
set attrNameList = list string tx string ty string tz string rx string ry string rz string sx string sy string sz
set attrValueList = list tx ty tz rx ry rz sx sy... | def setAndFreeze(nodeName="", tx=None, ty=None, tz=None, rx=None, ry=None, rz=None, sx=None, sy=None, sz=None, freeze=True):
if nodeName != "":
attrNameList = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']
attrValueList = [tx, ty, tz, rx, ry, rz, sx, sy, sz]
# settin... | Python | nomic_cornstack_python_v1 |
from porter import PorterStemmer
import re
import os
import math
class Document
begin
function __init__ self docID filePath
begin
string __documentRecord = { 'term': { 'index': int, 'tf': int # term frequency } }
set __documentRecord = dict
set docID = docID
set filePath = filePath
comment init
set tokens = call getTo... | from porter import PorterStemmer
import re
import os
import math
class Document:
def __init__(self, docID, filePath):
'''
__documentRecord = {
'term': {
'index': int,
'tf': int # term frequency
}
}
'''
self.__documentR... | Python | zaydzuhri_stack_edu_python |
function put self segment
begin
if closed
begin
return
end
if segment is not none
begin
set future = call submit fetch segment retries=retries
end
else
begin
set future = none
end
queue futures tuple segment future
end function | def put(self, segment):
if self.closed:
return
if segment is not None:
future = self.executor.submit(self.fetch, segment,
retries=self.retries)
else:
future = None
self.queue(self.futures, (segment, future)) | Python | nomic_cornstack_python_v1 |
function __init__ self port
begin
set sock = call socket AF_INET SOCK_STREAM
set port = port
set addr = tuple string 0.0.0.0 port
call setsockopt SOL_SOCKET SO_REUSEADDR 1
call bind addr
end function | def __init__(self, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = port
self.addr = ("0.0.0.0", port)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(self.addr) | Python | nomic_cornstack_python_v1 |
import os
set __DEBUG = none
function debug *args
begin
global __DEBUG
if __DEBUG is none
begin
try
begin
if environ at string DEBUG == string 1
begin
set __DEBUG = true
end
else
begin
set __DEBUG = false
end
end
except any
begin
set __DEBUG = false
end
end
if __DEBUG
begin
print join string list comprehension string ... | import os
__DEBUG = None
def debug(*args):
global __DEBUG
if __DEBUG is None:
try:
if os.environ['DEBUG'] == '1':
__DEBUG = True
else:
__DEBUG = False
except:
__DEBUG = False
if __DEBUG:
print( ' '.join([str(arg) f... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from __future__ import absolute_import , division , print_function , unicode_literals
from jinja2 import Markup , escape
from flask import current_app
from re import sub
function render_breadcrumb items
begin
set START_URI = globals at string START_URI
set breadcrumb = string <ol class="br... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from jinja2 import Markup, escape
from flask import current_app
from re import sub
def render_breadcrumb(items):
START_URI = current_app.jinja_env.globals['START_URI']
breadcrumb = '<ol class="bread... | Python | zaydzuhri_stack_edu_python |
import itertools
set num = integer input
set li = permutations list string num length string num
set li = sorted set map lambda x -> integer join string x li
if index li num + 1 == length li
begin
print 0
end
else
begin
print li at index li num + 1
end | import itertools
num = int(input())
li = itertools.permutations(list(str(num)), len(str(num)))
li = sorted(set(map(lambda x: int("".join(x)), li)))
if li.index(num) + 1 == len(li):
print(0)
else:
print(li[li.index(num) + 1])
| Python | zaydzuhri_stack_edu_python |
from PIL import Image
import numpy as np
import glob
import os.path
import random as rd
import cv2
import math
comment Calculate cross product
function cross a b c
begin
set ans = b at 0 - a at 0 * c at 1 - b at 1 - b at 1 - a at 1 * c at 0 - b at 0
return ans
end function
comment Check whether the quadrilateral is con... | from PIL import Image
import numpy as np
import glob
import os.path
import random as rd
import cv2
import math
#Calculate cross product
def cross(a, b, c):
ans = (b[0] - a[0])*(c[1] - b[1]) - (b[1] - a[1])*(c[0] - b[0])
return ans
#Check whether the quadrilateral is convex.
#If it is convex, r... | Python | zaydzuhri_stack_edu_python |
function prompt_dimension
begin
print string BEFORE WE BEGIN... choose how large you want the board to be.
print string The game board is an n by n square.
set dimension = 0
while dimension < MIN_DIMENSION or dimension > MAX_DIMENSION or dimension % 2 != 0
begin
print string Enter an even number n between + string MIN_... | def prompt_dimension():
print("\n\nBEFORE WE BEGIN... choose how large you want the board to be.")
print("\nThe game board is an n by n square.")
dimension = 0
while dimension < MIN_DIMENSION or dimension > MAX_DIMENSION or dimension % 2 != 0:
print("Enter an even number n between " + str(MIN_DIMENSION) + " and ... | Python | nomic_cornstack_python_v1 |
function get_remote_file self remote local
begin
call run_cmd string pull %s %s % tuple remote local
return __output
end function | def get_remote_file(self, remote, local):
self.run_cmd('pull %s %s' % (remote, local))
return self.__output | Python | nomic_cornstack_python_v1 |
function get_states
begin
set states = all string State
set state_list = list
for state in values states
begin
append state_list call to_dict
end
return tuple call jsonify state_list 200
end function | def get_states():
states = storage.all('State')
state_list = []
for state in states.values():
state_list.append(state.to_dict())
return jsonify(state_list), 200 | Python | nomic_cornstack_python_v1 |
async function attest_open_enclave_with_draft_failing_policy self
begin
call write_banner string attest_open_enclave_with_draft_failing_policy
set oe_report = call urlsafe_b64decode sample_open_enclave_report
set runtime_data = call urlsafe_b64decode sample_runtime_data
set draft_policy = string version= 1.0; authoriza... | async def attest_open_enclave_with_draft_failing_policy(self):
write_banner("attest_open_enclave_with_draft_failing_policy")
oe_report = base64.urlsafe_b64decode(sample_open_enclave_report)
runtime_data = base64.urlsafe_b64decode(sample_runtime_data)
draft_policy = """
version= 1.0;
aut... | Python | nomic_cornstack_python_v1 |
comment Program to generate bigram unsmoothing , Add-one smoothing and Good-Turing Discount model to say which of the sentences
comment S1: The company chairman said he will increase the profit next year .
comment S2: The president said he believes the last year profit were good .
comment is more probable.
from nltk.to... | ############################################################################################################
# Program to generate bigram unsmoothing , Add-one smoothing and Good-Turing Discount model to say which of the sentences
# S1: The company chairman said he will increase the profit next year .
# S2: The presid... | Python | zaydzuhri_stack_edu_python |
function execute self
begin
set start = time
print string =====================================================================
print string *** Step 1: Manipulate Admission, ICUStay, OutputEvent and Chartevent
call start_process
set end = time
print string *** Execution time of %d patient(s) is %f ******** % tuple con... | def execute(self):
start = time.time()
print('\n=====================================================================')
print('\n*** Step 1: Manipulate Admission, ICUStay, OutputEvent and Chartevent\n')
self.start_process()
end = time.time()
print("\n*** Execution time ... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function clumsy self N
begin
if N <= 4
begin
return list 1 2 6 7 at N - 1
end
else
begin
return N + list 1 2 2 - 1 at N % 4
end
end function
end class
if __name__ == string __main__
begin
comment 7
print call clumsy 4
comment 12
print call clumsy 10
end | class Solution:
def clumsy(self, N: int) -> int:
if N <= 4:
return [1, 2, 6, 7][N - 1]
else:
return N + [1, 2, 2, -1][N % 4]
if __name__ == "__main__":
print(Solution().clumsy(4)) # 7
print(Solution().clumsy(10)) # 12
| Python | zaydzuhri_stack_edu_python |
function subscribers self date=string page=1 page_size=1000 order_field=string email order_direction=string asc include_tracking_information=false
begin
string Gets the active subscribers in this segment.
set params = dict string date date ; string page page ; string pagesize page_size ; string orderfield order_field ... | def subscribers(self, date="", page=1, page_size=1000, order_field="email", order_direction="asc", include_tracking_information=False):
"""Gets the active subscribers in this segment."""
params = {
"date": date,
"page": page,
"pagesize": page_size,
"orderf... | Python | jtatman_500k |
class AVLTREE
begin
function __init__ self value
begin
set value = value
set left = none
set right = none
set height = 1
end function
function insert self root value
begin
if not root
begin
return call AVLTREE value
end
else
if value > value
begin
set right = insert self right value
end
else
begin
set left = insert sel... | class AVLTREE:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
self.height = 1
def insert(self,root,value):
if not root:
return AVLTREE(value)
elif value > root.value:
root.right = self.insert(root.right,valu... | Python | zaydzuhri_stack_edu_python |
function partial_fit self X y
begin
if not w_initialized
begin
call _initialize_weights X
end
if shape at 0 > 1
begin
for tuple xi target in zip X y
begin
call _update_weights xi target
end
end
else
begin
call _update_weights X y
end
return self
end function | def partial_fit(self, X, y):
if not self.w_initialized :
self._initialize_weights(X)
if y.ravel().shape[0] > 1:
for xi, target in zip(X, y):
self._update_weights(xi, target)
else:
self._update_weights(X, y)
return self | Python | nomic_cornstack_python_v1 |
from __future__ import division
from common import approx_eq , improve
function newton_update f df
begin
function update x
begin
return x - f dist x / call df x
end function
return update
end function
function find_zero f df
begin
function near_zero x
begin
return call approx_eq f dist x 0
end function
return call impr... | from __future__ import division
from common import approx_eq, improve
def newton_update(f, df):
def update(x):
return x - f(x) / df(x)
return update
def find_zero(f, df):
def near_zero(x):
return approx_eq(f(x), 0)
return improve(newton_update(f, df), near_zero)
def sqrt_newton(a)... | Python | zaydzuhri_stack_edu_python |
string Top level module responsible for creating the application.
from flask import Flask
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from dl.MemberController import MemberController
from dl.RaceController import RaceController
import os
from dl.database import db
comment The flask applic... | """
Top level module responsible for creating the application.
"""
from flask import Flask
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from dl.MemberController import MemberController
from dl.RaceController import RaceController
import os
from dl.database import db
# The flask applicat... | Python | zaydzuhri_stack_edu_python |
function filesToDelete mediaDirPath extension=IMAGE_FORMAT
begin
return sorted generator expression join path dirname filename for tuple dirname dirnames filenames in walk mediaDirPath for filename in filenames if ends with filename extension key=lambda fn -> st_mtime reverse=true
end function | def filesToDelete(mediaDirPath, extension=IMAGE_FORMAT):
return sorted(
(
os.path.join(dirname, filename)
for dirname, dirnames, filenames in os.walk(mediaDirPath)
for filename in filenames
if filename.endswith(extension)
),
key=lambda fn: os.s... | Python | nomic_cornstack_python_v1 |
function update_last_ate
begin
global sent_notification variables
if sent_notification == 1
begin
call send_email string Feeding the cat string you have fed the cat and he is back to normal
end
set variables at string time = time
set sent_notification = 0
end function | def update_last_ate():
global sent_notification,variables
if sent_notification==1:
send_email("Feeding the cat", "you have fed the cat and he is back to normal")
variables["time"]=time.time()
sent_notification = 0 | Python | nomic_cornstack_python_v1 |
function getTopicName nd_proj
begin
comment does not line &
return join string - call generateProjectInfo
end function | def getTopicName(nd_proj):
# does not line &
return '-'.join(nd_proj.generateProjectInfo()) | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
function convert_n_bytes n b
begin
set bits = b * 8
return n + 2 ^ bits - 1 % 2 ^ bits - 2 ^ bits - 1
end function
function convert_4_bytes n
begin
return call convert_n_bytes n 4
end function
function getHashCode s
begin
set h = 0
set n = length s
for tuple i c in enumerate s
begin
set h =... | # -*- coding:utf-8 -*-
def convert_n_bytes(n, b):
bits = b * 8
return (n + 2 ** (bits - 1)) % 2 ** bits - 2 ** (bits - 1)
def convert_4_bytes(n):
return convert_n_bytes(n, 4)
def getHashCode(s):
h = 0
n = len(s)
for i, c in enumerate(s):
h += ord(c) * 31 ** (n - 1 - i)
return abs... | Python | zaydzuhri_stack_edu_python |
string Author: Nelly Kane Originated: 12.03.2018 Repo: latGIS File: lat_gis.py The defined containers for the latGIS Python architecture.
from typing import Tuple
import numpy as np
from pandas import DataFrame
from util.enu_to_ecef import MoreTransfers
from util.constants import Constants
from util.coord_transfers imp... | """
Author: Nelly Kane
Originated: 12.03.2018
Repo: latGIS
File: lat_gis.py
The defined containers for the latGIS Python architecture.
"""
from typing import Tuple
import numpy as np
from pandas import DataFrame
from util.enu_to_ecef import MoreTransfers
from util.constants import Constants
from util.coord_transfer... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
string Translating RNA into Protein @author: lemoga Created on Tue Apr 7 10:18:51 2015 Given: An RNA string s corresponding to a strand of mRNA (of length at most 10 kbp). A codon Table Return: The protein string encoded by s.
import sys
function translate_mRNA aRNAcodonDictionary mRNA
begin
st... | #!/usr/bin/python
"""
Translating RNA into Protein
@author: lemoga
Created on Tue Apr 7 10:18:51 2015
Given: An RNA string s corresponding to a strand of mRNA (of length at most 10 kbp).
A codon Table
Return: The protein string encoded by s.
"""
import sys
def translate_mRNA(aRNAcodonDictionary, mRNA):
""... | Python | zaydzuhri_stack_edu_python |
function validate self value
begin
return call _validate value name
end function | def validate(self, value):
return self._validate(value, self.name) | Python | nomic_cornstack_python_v1 |
function holdIssue self id hold
begin
set qryDum = string UPDATE issues SET on_hold = ? WHERE id = ?
set holding = if expression hold then 1 else 0
set cursor = call cursor
execute cursor qryDum list holding id
commit db
end function | def holdIssue(self, id, hold):
qryDum = 'UPDATE issues SET on_hold = ? WHERE id = ?'
holding = 1 if hold else 0
cursor = self.db.cursor()
cursor.execute(qryDum, [holding, id])
self.db.commit() | Python | nomic_cornstack_python_v1 |
function repeat_func func *args **kwargs
begin
if kwargs
begin
return call starmap lambda args kwargs -> call func *args keyword kwargs repeat tuple args kwargs
end
else
begin
return call starmap func repeat args
end
end function | def repeat_func(func, *args, **kwargs):
if kwargs:
return starmap(lambda args, kwargs: func(*args, **kwargs),
repeat((args, kwargs))
)
else:
return starmap(func, repeat(args)) | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
set img = zeros tuple 512 512 3 uint8
comment 0 255
print img
comment img[:] = 255 ,0,0
call line img tuple 0 0 tuple shape at 1 shape at 0 tuple 0 255 0 2
call rectangle img tuple 350 100 tuple 450 200 tuple 0 0 255 FILLED
call circle img tuple 150 400 50 tuple 255 0 0 3
call putText img ... | import cv2
import numpy as np
img = np.zeros((512,512,3),np.uint8)
# 0 255
print(img)
#img[:] = 255 ,0,0
cv2.line(img,(0,0),(img.shape[1],img.shape[0]),(0,255,0),2)
cv2.rectangle(img,(350,100),(450,200),(0,0,255),cv2.FILLED)
cv2.circle(img,(150,400),50,(255,0,0),3)
cv2.putText(img,"Draw Shapes ",(75,50),cv... | Python | zaydzuhri_stack_edu_python |
from abc import ABCMeta , abstractmethod
from typing import Dict , Callable , Optional , NamedTuple
from core.application.exceptions import CommandNotFound
from core.communication.callback import Callback
from core.communication.command_identifier import CommandIdentifier
set dispatch_event_function_type = Callable at ... | from abc import ABCMeta, abstractmethod
from typing import Dict, Callable, Optional, NamedTuple
from core.application.exceptions import CommandNotFound
from core.communication.callback import Callback
from core.communication.command_identifier import CommandIdentifier
dispatch_event_function_type = Callable[[dict, Co... | Python | zaydzuhri_stack_edu_python |
function __init_subclass__ cls
begin
call __init_subclass__
call dataclass cls
end function | def __init_subclass__(cls) -> None:
super().__init_subclass__()
dataclass(cls) | Python | nomic_cornstack_python_v1 |
import unittest
import main
import monsters
import boosts
import bomb
import blocks
from config_entity import WIDTH
class TestHero extends TestCase
begin
function setUp self
begin
set game = call Game
start game
end function
function test_collide_with_wall self
begin
set wall = platform 2 * WIDTH WIDTH
append platforms... | import unittest
import main
import monsters
import boosts
import bomb
import blocks
from config_entity import WIDTH
class TestHero(unittest.TestCase):
def setUp(self):
self.game = main.Game()
self.game.start()
def test_collide_with_wall(self):
wall = blocks.Platform(2 *... | Python | zaydzuhri_stack_edu_python |
function _planetEnabledForGeoSidRadixChartSaveValuesToSettings self
begin
set settings = call QSettings
comment Planet enabled for GeoSidRadixChart.
set key = planetH1EnabledForGeoSidRadixChartKey
set newValue = call checkState == Checked
if call contains key
begin
set oldValue = call value key type=bool
if oldValue !=... | def _planetEnabledForGeoSidRadixChartSaveValuesToSettings(self):
settings = QSettings()
# Planet enabled for GeoSidRadixChart.
key = SettingsKeys.planetH1EnabledForGeoSidRadixChartKey
newValue = \
self.planetH1EnabledForGeoSidRadixChartCheckBox.\
checkSt... | Python | nomic_cornstack_python_v1 |
function testExpectAndReturn self
begin
set c = call Controller
set x = call mock
call expectAndReturn call g 8 9 5
call replay
call failUnless call g 8 9 == 5
call verify
end function | def testExpectAndReturn(self):
c = Controller()
x = c.mock()
c.expectAndReturn(x.g(8, 9), 5)
c.replay()
self.failUnless(x.g(8, 9) == 5)
c.verify() | Python | nomic_cornstack_python_v1 |
class Singleton extends type
begin
set _instances = dict
function __call__ cls *args **kwargs
begin
if cls not in _instances
begin
set _instances at cls = call __call__ *args keyword kwargs
end
return _instances at cls
end function
end class
function string_to_file string file
begin
set text_file = open file string w
... | class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
def string_to_file(string, file):
text_file = open(file, "w")
text_file... | Python | zaydzuhri_stack_edu_python |
string CPU functionality.
import sys
comment ops
set LDI = 130
set PRN = 71
set HLT = 1
set MUL = 162
set PUSH = 69
set POP = 70
set CALL = 80
set RET = 17
set JMP = 84
set CMP = 167
set JNE = 86
set JEQ = 85
class CPU
begin
string Main CPU class.
function __init__ self
begin
string Construct a new CPU.
set running = t... | """CPU functionality."""
import sys
#ops
LDI = 0b10000010
PRN = 0b01000111
HLT = 0b00000001
MUL = 0b10100010
PUSH = 0b01000101
POP = 0b01000110
CALL = 0b01010000
RET = 0b00010001
JMP = 0b01010100
CMP = 0b10100111
JNE = 0b01010110
JEQ = 0b01010101
class CPU:
"""Main CPU class."""
def __init__(self):
... | Python | zaydzuhri_stack_edu_python |
set l = list 2 3 5 1 0 5
print min l
print sum l / length l | l = [2, 3, 5, 1, 0, 5]
print(min(l))
print(sum(l) / len(l)) | Python | zaydzuhri_stack_edu_python |
function fetch_pandas_batches self **kwargs
begin
call check_can_use_pandas
if _prefetch_hook is not none
begin
call _prefetch_hook
end
if _query_result_format != string arrow
begin
raise NotSupportedError
end
call _log_telemetry_job_data PANDAS_FETCH_BATCHES TRUE
return call _fetch_pandas_batches keyword kwargs
end fu... | def fetch_pandas_batches(self, **kwargs: Any) -> Iterator[DataFrame]:
self.check_can_use_pandas()
if self._prefetch_hook is not None:
self._prefetch_hook()
if self._query_result_format != "arrow":
raise NotSupportedError
self._log_telemetry_job_data(
T... | Python | nomic_cornstack_python_v1 |
function version self version
begin
set _version = version
end function | def version(self, version):
self._version = version | Python | nomic_cornstack_python_v1 |
for tuple i xi in enumerate x
begin
set tmp_x = tmp_x + xi + 1 * 2 * i - n - 1
end
set tmp_x = tmp_x % mod
for tuple i yi in enumerate y
begin
set tmp_y = tmp_y + yi + 1 * 2 * i - m - 1
end
set tmp_y = tmp_y % mod
print tmp_x * tmp_y % mod | for i, xi in enumerate(x):
tmp_x += (xi+1)*(2*i-(n-1))
tmp_x = tmp_x % mod
for i, yi in enumerate(y):
tmp_y += (yi+1)*(2*i-(m-1))
tmp_y = tmp_y % mod
print((tmp_x*tmp_y)%mod)
| Python | zaydzuhri_stack_edu_python |
function execute self collection begin_time end_time coord_list srid
begin
set col_name = collection
set collection = get objects identifier=collection
set eo_objects = filter begin_time__lte=end_time end_time__gte=begin_time
set coordinates = split coord_list string ;
set points = list
for coordinate in coordinates
b... | def execute(self, collection, begin_time, end_time, coord_list, srid):
col_name = collection
collection = models.Collection.objects.get(identifier=collection)
eo_objects = collection.eo_objects.filter(
begin_time__lte=end_time, end_time__gte=begin_time
)
coordinates... | Python | nomic_cornstack_python_v1 |
from bokeh.plotting import figure , show
from bokeh.layouts import gridplot
comment Linked Pan
set x = list range 11
set tuple y0 y1 y2 = tuple x list comprehension 10 - i for i in x list comprehension absolute i - 5 for i in x
set options = dictionary plot_width=500 plot_height=500 tools=string pan, wheel_zoom
comment... | from bokeh.plotting import figure, show
from bokeh.layouts import gridplot
# Linked Pan
x = list(range(11))
y0, y1, y2 = x, [10-i for i in x], [abs(i-5) for i in x]
options = dict(plot_width=500, plot_height = 500, tools="pan, wheel_zoom" )
# create 2 plots
f1 = figure(**options)
f1.circle(x, y0, size=10, color="fi... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: UTF-8 -*-
comment Native
import json
comment Django
from django.db import models
from django.db import connection
comment Proyect
from lib.stop_words.functions import remove_non_unicode
from lib.stop_words.functions import remove_spaces
from lib.stop_words.functions import remove_non_alphanumeric
fr... | # -*- coding: UTF-8 -*-
#Native
import json
#Django
from django.db import models
from django.db import connection
#Proyect
from lib.stop_words.functions import remove_non_unicode
from lib.stop_words.functions import remove_spaces
from lib.stop_words.functions import remove_non_alphanumeric
from lib.stop_words.functio... | Python | zaydzuhri_stack_edu_python |
import select
import socket
import sys
import struct
import string
from random import choice
import os
import tcp
comment Split an ip into 4 bytes
function split_ip ipString
begin
set l = split string ipString string .
set x = list
for i in l
begin
append x integer i
end
return x
end function
comment Join a received 4... | import select
import socket
import sys
import struct
import string
from random import choice
import os
import tcp
#Split an ip into 4 bytes
def split_ip( ipString ):
l = string.split( ipString , '.' )
x = []
for i in l:
x.append( int(i) )
return x
#Join a received 4 ip byte sequence into string
def join_ip( ipL... | Python | zaydzuhri_stack_edu_python |
import itertools
set symbols_connection = split input
set k = integer input
for i in product symbols_connection repeat=k
begin
for j in range k
begin
print i at j end=string
end
print
end | import itertools
symbols_connection = input().split()
k = int(input())
for i in itertools.product(symbols_connection, repeat=k):
for j in range(k):
print(i[j], end='')
print()
| Python | zaydzuhri_stack_edu_python |
function cartesian2spherical coords
begin
set sphere = zeros shape
set xy_sq = coords at tuple slice : : 0 ^ 2 + coords at tuple slice : : 1 ^ 2
set sphere at tuple slice : : 0 = square root xy_sq + coords at tuple slice : : 2 ^ 2
set sphere at tuple slice : : 1 = call arctan2 coords at tuple slice : :... | def cartesian2spherical(coords):
sphere = np.zeros(coords.shape)
xy_sq = coords[:, 0]**2 + coords[:, 1]**2
sphere[:, 0] = np.sqrt(xy_sq + coords[:, 2]**2)
sphere[:, 1] = np.arctan2(coords[:, 1], coords[:, 0])
sphere[:, 2] = np.arctan2(np.sqrt(xy_sq), coords[:, 2])
return sphere | Python | nomic_cornstack_python_v1 |
comment Assignment 2 - Course Planning!
comment CSC148 Fall 2014, University of Toronto
comment Instructor: David Liu
comment ---------------------------------------------
comment STUDENT INFORMATION
comment List your group members below, one per line, in format
comment Connor Peet, 100108820
comment ------------------... | # Assignment 2 - Course Planning!
#
# CSC148 Fall 2014, University of Toronto
# Instructor: David Liu
# ---------------------------------------------
# STUDENT INFORMATION
#
# List your group members below, one per line, in format
# Connor Peet, 100108820
#
#
#
# ---------------------------------------------
from cour... | Python | zaydzuhri_stack_edu_python |
function pc_input_buffers_full_var self *args
begin
return call LongPNcorr_sptr_pc_input_buffers_full_var self *args
end function | def pc_input_buffers_full_var(self, *args):
return _ncofdm_swig.LongPNcorr_sptr_pc_input_buffers_full_var(self, *args) | Python | nomic_cornstack_python_v1 |
function length_minutes self
begin
return _length_minutes
end function | def length_minutes(self):
return self._length_minutes | Python | nomic_cornstack_python_v1 |
comment 1
function collatz m
begin
string Returns the number of elements of the Collatz sequence starting with m.
set A = list m
set k = 0
while m != 1
begin
if m % 2 == 0
begin
set m = m / 2
end
else
if m % 2 == 1
begin
set m = 3 * m + 1
end
append A m
set k = k + 1
end
return k
end function
comment 2
comment The prob... | # 1
def collatz(m):
'''
Returns the number of elements of the Collatz
sequence starting with m.
'''
A = [m]
k = 0
while m != 1:
if m % 2 == 0:
m = m/2
elif m % 2 == 1:
m = 3 * m + 1
A.append(m)
k += 1
return k
# 2
# The problem ... | Python | zaydzuhri_stack_edu_python |
function sturm_mean manifold data num_steps=none
begin
set device = device
if num_steps is none
begin
set num_steps = shape at 0
end
set tuple N D = shape
set idx = random integer high=N size=tuple num_steps dtype=long
set mu = data at idx at 0
set n = 1.0
for m in call tqdm range 1 num_steps
begin
set tuple c success ... | def sturm_mean(manifold, data, num_steps=None):
device = data.device
if num_steps is None:
num_steps = data.shape[0]
N, D = data.shape
idx = torch.randint(high=N, size=(num_steps,), dtype=torch.long)
mu = data[idx[0]]
n = 1.0
for m in tqdm(range(1, num_steps)):
c, success = m... | Python | nomic_cornstack_python_v1 |
function combined_key string
begin
function to_int string
begin
try
begin
return integer string
end
except ValueError
begin
return string
end
end function
return list comprehension call to_int part for part in split re string ([0-9]+) string
end function | def combined_key(string):
def to_int(string):
try:
return int(string)
except ValueError:
return string
return [to_int(part) for part in re.split('([0-9]+)', string)] | Python | nomic_cornstack_python_v1 |
import psycopg2
import pandas as pd
from src.config import config
import datetime as datetime
import time
comment returns a given SQL SELECT query to a pandas DataFrame object
function query_to_df query=string SELECT * FROM power_weather LIMIT 15
begin
set params = call config
try
begin
set conn = call connect keyword ... | import psycopg2
import pandas as pd
from src.config import config
import datetime as datetime
import time
# returns a given SQL SELECT query to a pandas DataFrame object
def query_to_df(query= "SELECT * FROM power_weather LIMIT 15"):
params=config()
try:
conn = psycopg2.connect(**params)
... | Python | zaydzuhri_stack_edu_python |
function _customized_dataclass_transform cls kw_only
begin
comment Check reserved attributes have expected type annotations.
set annotations = dictionary get __dict__ string __annotations__ dict
if get annotations string parent _ParentType != _ParentType
begin
raise call ReservedModuleAttributeError annotations
end
if ... | def _customized_dataclass_transform(cls, kw_only: bool):
# Check reserved attributes have expected type annotations.
annotations = dict(cls.__dict__.get('__annotations__', {}))
if annotations.get('parent', _ParentType) != _ParentType:
raise errors.ReservedModuleAttributeError(annotations)
if annot... | Python | nomic_cornstack_python_v1 |
function __init__ self hidden_states=1 symbols=none A=none B=none pi=none seed=none tol=0.001 max_iter=100
begin
set hidden_states = hidden_states
set symbols = symbols
set A = A
set B = B
set pi = pi
set seed = seed
set tol = tol
set max_iter = max_iter
set n_iter = 0
set is_converged = false
end function | def __init__(self,
hidden_states:int=1,
symbols:int=None,
A:np.ndarray=None,
B:np.ndarray=None,
pi:np.ndarray=None,
seed:int=None,
tol:float=1e-3,
max_iter:int=100)->None:
self... | Python | nomic_cornstack_python_v1 |
function post_virtual_network_create self resource_dict
begin
pass
end function | def post_virtual_network_create(self, resource_dict):
pass | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import sys , cPickle , os
from collections import defaultdict
from operator import itemgetter
function reducer
begin
set prev_word = none
set word = none
set aggreg_list = none
for line in stdin
begin
set tuple word lst = split line string
comment list of pairs [(phr1, sc1), (phr2, sc2), ...]
s... | #!/usr/bin/python
import sys, cPickle, os
from collections import defaultdict
from operator import itemgetter
def reducer():
prev_word=None
word=None
aggreg_list=None
for line in sys.stdin:
word, lst=line.split('\t')
lst=eval(lst) # list of pairs [(phr1, sc1), (phr2, sc2), ...] | Python | zaydzuhri_stack_edu_python |
function handle_command command
begin
set response = string
if COMMAND1 in command
begin
set response = string IF YOU SHIP MADDIE AND BOJANGLES YOU GET BODADDY
end
if COMMAND2 in command
begin
set response = string IF YOU SHIP MADDIE AND BOJANGLES YOU GET BODADDY
end
end function | def handle_command(command):
response = ""
if COMMAND1 in command:
response = "IF YOU SHIP MADDIE AND BOJANGLES YOU GET BODADDY"
if COMMAND2 in command:
response = "IF YOU SHIP MADDIE AND BOJANGLES YOU GET BODADDY" | Python | nomic_cornstack_python_v1 |
function create_enter_button self
begin
set button_helv10 = call Font family=string Helvetica size=10
set enter_button = call Button self text=string Enter font=button_helv10 command=get_text
call pack
call place anchor=string nw x=170 y=345 height=30 width=60
end function | def create_enter_button(self):
button_helv10 = tkfont.Font(family='Helvetica', size=10)
self.enter_button = tk.Button(self, text='Enter',
font=button_helv10,
command=self.get_text)
self.enter_button.pack()
self.ent... | Python | nomic_cornstack_python_v1 |
function test_add_smack_with_no_user testapp fill_the_db
begin
assert get testapp string /add_smack status=403
end function | def test_add_smack_with_no_user(testapp, fill_the_db):
assert testapp.get('/add_smack', status=403) | Python | nomic_cornstack_python_v1 |
function luhnOlusturma kart_numarasi
begin
set kart_numarasi = kart_numarasi at slice : : - 1
set toplam = 0
for i in range length kart_numarasi
begin
set basamak = integer kart_numarasi at i
if i % 2 != 0
begin
set toplam = toplam + basamak
end
else
begin
set basamak = basamak * 2
set basamak = string basamak
if len... | def luhnOlusturma(kart_numarasi):
kart_numarasi = kart_numarasi[::-1]
toplam = 0
for i in range(len(kart_numarasi)):
basamak = int(kart_numarasi[i])
if i % 2 != 0:
toplam += basamak
else:
basamak *= 2
basamak = str(basamak)
... | Python | zaydzuhri_stack_edu_python |
comment Version 2
comment for Python 3
comment ARIAS Frederic
comment Sorry ... It's difficult for me the python :)
from time import gmtime , strftime
import time
import json
import requests
import os
from tqdm import tqdm
import hashlib
string format time string %Y-%m-%d %H:%M:%S call gmtime
set start = time
comment T... | #
# Version 2
# for Python 3
#
# ARIAS Frederic
# Sorry ... It's difficult for me the python :)
#
from time import gmtime, strftime
import time
import json
import requests
import os
from tqdm import tqdm
import hashlib
strftime("%Y-%m-%d %H:%M:%S", gmtime())
start = time.time()
#Token
ip = "127.0.0.1"
port = "... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function longestPalindrome self s
begin
set size = length s
if size < 2
begin
return s
end
set max_len = 1
set res = s at 0
for i in range 1 size - 1
begin
set tuple palindrome_odd odd_len = call center_spread s size i i
set tuple palindrome_even even_len = call center_spread s size ... | class Solution(object):
def longestPalindrome(self, s):
size = len(s)
if size < 2:
return s
max_len = 1
res = s[0]
for i in range(1, size - 1):
palindrome_odd, odd_len = self.center_spread(s, size, i, i)
palindrome_even, even_len = self... | Python | zaydzuhri_stack_edu_python |
from typing import List
import paths_parser
from classes import Path , Step
function compute_paths args
begin
comment check argument type
if type args is not str
begin
raise call ValueError string Argument must be a string, not { type args }
end
set lines = call splitlines
if length lines < 4
begin
raise call ValueErro... | from typing import List
import paths_parser
from classes import Path, Step
def compute_paths(args: str) -> str:
# check argument type
if type(args) is not str:
raise ValueError(f"Argument must be a string, not {type(args)}")
lines = args.splitlines()
if len(lines) < 4:
raise ValueErro... | Python | zaydzuhri_stack_edu_python |
comment Készíts egy Python alkalmazást ami selenium-ot használ.
comment Indítsd el lokálisan a selenium-py-peldatar alkalmazást.
comment A program töltse be a példatárból az http://localhost:9999/todo.html oldalt.
comment A feladatod, hogy kigyűjtsd az összes jelenleg aktív Todo bejegyzést.
comment Ha lehet akkor ezt m... | # Készíts egy Python alkalmazást ami selenium-ot használ.
# Indítsd el lokálisan a selenium-py-peldatar alkalmazást.
# A program töltse be a példatárból az http://localhost:9999/todo.html oldalt.
# A feladatod, hogy kigyűjtsd az összes jelenleg aktív Todo bejegyzést.
# Ha lehet akkor ezt minnél kevesebb selenium lokáto... | Python | zaydzuhri_stack_edu_python |
string The recommended way of reading the data in TensorFlow however is through the dataset API. Indeed, if you need to read your data from file, it may be more efficient to write it in TFrecord format and use TFRecordDataset to read it. Dataset API allows you to make efficient data processing pipelines easily. For mor... | """
The recommended way of reading the data in TensorFlow however is through the dataset API. Indeed, if you need to read your data from file, it may be more efficient to write it in TFrecord format and use TFRecordDataset to read it. Dataset API allows you to make efficient data processing pipelines easily.
F... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.