code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function Blink self
begin
comment TODO: Rename.
return call RunBlinkCmd call GetBlinkCmd r g b blink_delay_ms=delay
end function | def Blink(self):
# TODO: Rename.
return RunBlinkCmd(GetBlinkCmd(self.r, self.g, self.b, blink_delay_ms=self.delay)) | Python | nomic_cornstack_python_v1 |
comment using the import now function to show current date & time
import datetime
comment fprint date after login
print now
print string WELCOME TO 'SAYO ATM
set username = input string Enter username
set password = input string Enter password
if password == password
begin
print string Hello, %s % username string Welco... | import datetime #using the import now function to show current date & time
print(datetime.datetime.now()) #fprint date after login
print("WELCOME TO 'SAYO ATM")
username = input("Enter username\n")
password = input("Enter password\n")
if password==password:
print('Hello, %s' %username,'Welcome!')
print('Thes... | Python | zaydzuhri_stack_edu_python |
function season theSeason=none year=year page=1 perPage=3
begin
set myseason = if expression theSeason then theSeason else call whatSeason month
set query_string = string query($season: MediaSeason, $seasonYear: Int, $page: Int, $perPage: Int){ Page (page: $page, perPage: $perPage) { pageInfo { currentPage hasNextPage ... | def season(theSeason : str = None, year : int = date.today().year, page : int = 1, perPage : int = 3):
myseason = theSeason if theSeason else whatSeason(date.today().month)
query_string = '''
query($season: MediaSeason, $seasonYear: Int, $page: Int, $perPage: Int){
Page (page: $page, perPag... | Python | nomic_cornstack_python_v1 |
function get_action_logfile
begin
return string action + call get_day + string .log
end function | def get_action_logfile():
return "action" + get_day() + ".log" | Python | nomic_cornstack_python_v1 |
string @@@@@ 最牛逼的 @@@@@@@@@@@@ 二分查找有几种写法?它们的区别是什么? - labuladong的回答 - 知乎 https://www.zhihu.com/question/36132386/answer/712269942 二分查找有很多限定条件,例如循环中的left < right,这里的不等号要不要加= 还有mid = (left+right) // 2 以及判断完之后,left = mid + 1 这里是一个加一,一个减一,还是都不加不减,还是都加都减 [1,2,3,4,5] 第一步 1.所谓的闭开,就是指这个index能不能取到数 第二步:.. 1.左闭右开的情况 left = 0 righ... | """
@@@@@ 最牛逼的 @@@@@@@@@@@@
二分查找有几种写法?它们的区别是什么? - labuladong的回答 - 知乎
https://www.zhihu.com/question/36132386/answer/712269942
二分查找有很多限定条件,例如循环中的left < right,这里的不等号要不要加=
还有mid = (left+right) // 2
以及判断完之后,left = mid + 1 这里是一个加一,一个减一,还是都不加不减,还是都加都减
[1,2,3,4,5]
第一步
1.所谓的闭开,就是指这个index能不能取到数
第二步:..
1.左闭右开的情况
left = ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment coding=utf-8
import wave
from pyaudio import PyAudio , paInt16
import time
import datetime
import os
string 音频处理类
class Audio
begin
function __init__ self
begin
string #NUM_SAMPLES = 2000 # pyAudio内部缓存的块的大小 #SAMPLING_RATE = 8000 # 取样频率 #LEVEL = 1500 # 声音保存的阈值 #COUNT_NUM = 20 # NUM_... | #!/usr/bin/env python3
# coding=utf-8
import wave
from pyaudio import PyAudio,paInt16
import time
import datetime
import os
"""
音频处理类
"""
class Audio:
def __init__(self):
"""
#NUM_SAMPLES = 2000 # pyAudio内部缓存的块的大小
#SAMPLING_RATE = 8000 # 取样频率
#LEVEL = 1500 # 声音保存... | Python | zaydzuhri_stack_edu_python |
function distance v w
begin
return call magnitude_of_vector call vector_subtract v w
end function | def distance(v, w):
return magnitude_of_vector(vector_subtract(v, w)) | Python | nomic_cornstack_python_v1 |
function inventories self inventories
begin
set _inventories = inventories
end function | def inventories(self, inventories):
self._inventories = inventories | Python | nomic_cornstack_python_v1 |
import numpy as np
function solution arr
begin
set dic = dict 0 0 ; 1 0
set arr = array arr
set dic = call quad array arr dic
return list dic at 0 dic at 1
end function
function quad arr dic
begin
if sum == length arr ^ 2
begin
set dic at 1 = dic at 1 + 1
end
else
if sum == 0
begin
set dic at 0 = dic at 0 + 1
end
else
... | import numpy as np
def solution(arr):
dic = {0:0, 1:0}
arr = np.array(arr)
dic = quad(np.array(arr), dic)
return [dic[0], dic[1]]
def quad(arr, dic):
if arr.sum() == len(arr)**2:
dic[1] += 1
elif arr.sum() == 0:
dic[0] += 1
else:
dic = quad(arr[:len(... | Python | zaydzuhri_stack_edu_python |
function check_schema_registry_ready host port service_timeout secure ignore_cert username password
begin
comment Check if you can connect to the endpoint
set status = call wait_for_service host port service_timeout
if status
begin
comment Check if service is responding as expected to basic request
set r = call __reque... | def check_schema_registry_ready(host, port, service_timeout, secure, ignore_cert, username, password):
# Check if you can connect to the endpoint
status = wait_for_service(host, port, service_timeout)
if status:
# Check if service is responding as expected to basic request
r = __request(ho... | Python | nomic_cornstack_python_v1 |
function test_api_put_move_content__err_400__unallowed_sub_content self
begin
set dbsession = call get_tm_session session_factory manager
set admin = call one
set uapi = call UserApi current_user=admin session=dbsession config=app_config
set gapi = call GroupApi current_user=admin session=dbsession config=app_config
se... | def test_api_put_move_content__err_400__unallowed_sub_content(self):
dbsession = get_tm_session(self.session_factory, transaction.manager)
admin = dbsession.query(User).filter(User.email == "admin@admin.admin").one()
uapi = UserApi(current_user=admin, session=dbsession, config=self.app_config)
... | Python | nomic_cornstack_python_v1 |
function inherit prop name **kwargs
begin
string Clears the specified property prop : string name of property name : string name of the filesystem, volume, or snapshot recursive : boolean recursively inherit the given property for all children. revert : boolean revert the property to the received value if one exists; o... | def inherit(prop, name, **kwargs):
'''
Clears the specified property
prop : string
name of property
name : string
name of the filesystem, volume, or snapshot
recursive : boolean
recursively inherit the given property for all children.
revert : boolean
revert the ... | Python | jtatman_500k |
function compute_data_quality_score stats col_name
begin
set col_stats = stats at col_name
set scores = list string consistency_score string redundancy_score string variability_score
set quality_score = 0
for score in scores
begin
set quality_score = quality_score + col_stats at score
end
set quality_score = quality_sc... | def compute_data_quality_score(stats, col_name):
col_stats = stats[col_name]
scores = ['consistency_score', 'redundancy_score', 'variability_score']
quality_score = 0
for score in scores:
quality_score += col_stats[score]
quality_score = quality_score/len(scores)
return {'quality_score... | Python | nomic_cornstack_python_v1 |
async function univsaye cowmsg
begin
if not is alpha text at 0 and text at 0 not in tuple string / string # string @ string !
begin
set arg = lower call group 1
set text = call group 2
if arg == string cow
begin
set arg = string default
end
if arg not in COWACTERS
begin
return
end
set cheese = call get_cow arg
set chee... | async def univsaye(cowmsg):
if not cowmsg.text[0].isalpha() and cowmsg.text[0] not in ("/", "#", "@", "!"):
arg = cowmsg.pattern_match.group(1).lower()
text = cowmsg.pattern_match.group(2)
if arg == "cow":
arg = "default"
if arg not in cow.COWACTERS:
return
... | Python | nomic_cornstack_python_v1 |
for elem in l
begin
if elem not in unique_colors
begin
append unique_colors elem
end
end
print 4 - length unique_colors | for elem in l:
if elem not in unique_colors:
unique_colors.append(elem)
print(4-len(unique_colors)) | Python | zaydzuhri_stack_edu_python |
import random
import re
class Fragment
begin
function __init__ self faces=list conditions=list
begin
comment Alternatively Editions
set faces = faces
set conditions = conditions
end function
end class | import random
import re
class Fragment:
def __init__(self, faces=[], conditions=[]):
self.faces = faces #Alternatively Editions
self.conditions = conditions
| Python | zaydzuhri_stack_edu_python |
from time import sleep
function contagem ini fim pas
begin
print string -= * 20
print string Contagem de { ini } até { fim } de { pas } em { pas }
sleep 1
if pas == 0
begin
set pas = 1
end
if pas < 0
begin
set pas = pas * - 1
end
if fim < ini
begin
if pas > 0
begin
set pas = - pas
end
set fim = fim - 1
end
else
begin
s... | from time import sleep
def contagem(ini,fim,pas):
print('-=' * 20)
print(f'Contagem de {ini} até {fim} de {pas} em {pas}')
sleep(1)
if pas == 0:
pas=1
if pas < 0:
pas*=-1
if fim < ini:
if pas > 0:
pas = -pas
fim-=1
else:
fim+=1
for i in... | Python | zaydzuhri_stack_edu_python |
comment author: starkizard
comment question at: https://www.codingame.com/ide/puzzle/detective-pikaptcha-ep1
import sys
import math
comment Auto-generated code below aims at helping you parse
comment the standard input according to the problem statement.
set tuple width height = list comprehension integer i for i in sp... | #author: starkizard
#question at: https://www.codingame.com/ide/puzzle/detective-pikaptcha-ep1
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
width, height = [int(i) for i in input().split()]
maze=[]
newmaze=[]
for i in range(heig... | Python | zaydzuhri_stack_edu_python |
import random
function profitcalc initial_sum=1000 percent=10 days=365
begin
string function return profit for specific period arguments: initial_sum(float) percent(float): simple percent days(float) return: float
return initial_sum * percent / 100 * days / 365
end function
set keyss = tuple string initial_sum string p... | import random
def profitcalc(initial_sum=1000,percent=10,days=365):
'''function return profit for specific period
arguments:
initial_sum(float)
percent(float): simple percent
days(float)
return:
float
'''
return initial_sum*percent/100*days/365
keyss=('initial_sum','percent','days')
offer=[]
profi... | Python | zaydzuhri_stack_edu_python |
function is_exploring self
begin
return _is_exploring
end function | def is_exploring(self) -> bool:
return self._is_exploring | Python | nomic_cornstack_python_v1 |
function configure self
begin
comment instantiate Serial
set serial = call Serial
comment set port_path, e.g. '/dev/ttyUSBx' or 'COMx'
set port = device
comment set baudrate
set baudrate = 115200
end function | def configure(self):
# instantiate Serial
self.serial = serial.Serial()
# set port_path, e.g. '/dev/ttyUSBx' or 'COMx'
self.serial.port = self.port.device
# set baudrate
self.serial.baudrate = 115200 | Python | nomic_cornstack_python_v1 |
function test_authen_password_fail self
begin
set test_user = call authenticate string test1 string swaggy
assert false test_user
end function | def test_authen_password_fail(self):
test_user = User.authenticate("test1", "swaggy")
self.assertFalse(test_user) | Python | nomic_cornstack_python_v1 |
function sumSquares numbers
begin
set sum = 0
for num in numbers
begin
set sum = sum + num ^ 2
end
return sum
end function | def sumSquares(numbers):
sum = 0
for num in numbers:
sum += (num ** 2)
return sum
| Python | flytech_python_25k |
function update_signal self event
begin
raise call NotImplementedError string Should implement update_signal()
end function | def update_signal(self, event):
raise NotImplementedError("Should implement update_signal()") | Python | nomic_cornstack_python_v1 |
function post self controllerfs
begin
raise OperationNotPermitted
end function | def post(self, controllerfs):
raise exception.OperationNotPermitted | Python | nomic_cornstack_python_v1 |
function dot_product first_vector second_vector
begin
set first_unpacker = call VectorUnpacker first_vector
set second_unpacker = call VectorUnpacker second_vector
if unpacked_vector_length != unpacked_vector_length
begin
raise call ApplicationError string Unpacked vector sizes are unequal
end
comment looks better than... | def dot_product(first_vector, second_vector):
first_unpacker = VectorUnpacker(first_vector)
second_unpacker = VectorUnpacker(second_vector)
if first_unpacker.unpacked_vector_length != second_unpacker.unpacked_vector_length:
raise ApplicationError("Unpacked vector sizes are unequal")
# looks bet... | Python | nomic_cornstack_python_v1 |
function max_area arr n
begin
set stack = list
set max_area = 0
set i = 0
while i < n
begin
if length stack == 0 or arr at stack at - 1 <= arr at i
begin
append stack i
set i = i + 1
end
else
begin
set top = pop stack
set area = 0
if length stack == 0
begin
set area = arr at top * i
end
else
begin
set area = arr at to... | def max_area(arr,n):
stack = []
max_area = 0
i = 0
while i < n:
if len(stack)==0 or arr[stack[-1]]<=arr[i]:
stack.append(i)
i+=1
else:
top = stack.pop()
area = 0
if len(stack)==0:
area = arr[top] * i
... | Python | zaydzuhri_stack_edu_python |
for _ in range N
begin
set A = list list comprehension integer x for x in split input
set solve = 0
for i in range M
begin
set solve = solve + A at i * B at i
end
set solve = solve + C
if solve > 0
begin
set count = count + 1
end
end
print count | for _ in range(N):
A = list([int(x) for x in input().split()])
solve = 0
for i in range(M):
solve += A[i] * B[i]
solve += C
if solve > 0:
count += 1
print(count)
| Python | zaydzuhri_stack_edu_python |
from pyface.qt.QtGui import QGraphicsPixmapItem
from pyface.qt.QtGui import QGraphicsItem , QPixmap , QPainter
from pyface.qt.QtCore import Signal
from engine_configurator.agent_item import AgentItem
from engine_configurator.atom_item import AtomItem
from engine_configurator.clickable_graphics_widget import ClickableGr... | from pyface.qt.QtGui import QGraphicsPixmapItem
from pyface.qt.QtGui import (QGraphicsItem,
QPixmap,
QPainter)
from pyface.qt.QtCore import Signal
from engine_configurator.agent_item import AgentItem
from engine_configurator.atom_item import AtomItem
from eng... | Python | zaydzuhri_stack_edu_python |
for i in range length P
begin
set L at integer P at i = L at integer P at i + 1
end
for q in range 10
begin
print L at q
end | for i in range (len(P)):
L[ int(P[i]) ] +=1
for q in range (10):
print(L[q]) | Python | zaydzuhri_stack_edu_python |
function get_cloud_functions location_path
begin
try
begin
set service_client = call get_service_client FUNCTIONS_API FUNCTIONS_API_VERSION
set functions = execute list parent=location_path
if functions == dict or functions == list
begin
return list
end
return functions at string functions
end
except Exception
begin... | def get_cloud_functions(location_path):
try:
service_client = get_service_client(
FUNCTIONS_API, FUNCTIONS_API_VERSION)
functions = service_client.projects().locations().functions().list(
parent=location_path
).execute()
if functions == {} or functions == []:
... | Python | nomic_cornstack_python_v1 |
function _prepare_picking_values self
begin
return dict string origin doc_num ; string company_id id ; string move_type string direct ; string partner_id id ; string picking_type_id id ; string location_id id ; string location_dest_id id ; string picking_type_code request_type_code
end function | def _prepare_picking_values(self):
return {
'origin': self.doc_num,
'company_id': self.company_id.id,
'move_type': 'direct',
'partner_id': self.partner_id.id,
'picking_type_id': self.picking_type_id.id,
'location_id': self.location_i... | Python | nomic_cornstack_python_v1 |
function containers_list self
begin
return get pulumi self string containers_list
end function | def containers_list(self) -> Sequence[str]:
return pulumi.get(self, "containers_list") | Python | nomic_cornstack_python_v1 |
function generate_submission prob dest_path=string ./submission.csv src_path=string ./data
begin
set sample_submission = read csv src_path + string /sample_submission.csv index_col=string TransactionID
if type prob is DataFrame
begin
assert all index == index
set holder = copy prob
end
else
if type prob is ndarray
begi... | def generate_submission(
prob: Union[np.ndarray, pd.DataFrame],
dest_path: str = "./submission.csv",
src_path: str = "./data"
) -> None:
sample_submission = pd.read_csv(
src_path + "/sample_submission.csv",
index_col="TransactionID"
)
if type(prob) is pd.DataFrame:
asser... | Python | nomic_cornstack_python_v1 |
function get key default_value=none return_section=false path=none
begin
if path is none
begin
try
begin
set path = object_path
end
except AttributeError
begin
comment There's no request.object_path yet, so use the global settings.
set path = string global
end
end
while true
begin
if path == string
begin
set path = st... | def get(key, default_value=None, return_section=False, path = None):
if path is None:
try:
path = cherrypy.request.object_path
except AttributeError:
# There's no request.object_path yet, so use the global settings.
path = "global"
while True:
... | Python | nomic_cornstack_python_v1 |
function retrieve_recent database_connection include_days_ahead=7 include_days_back=32
begin
try
begin
set past_days = integer include_days_back
set future_days = integer include_days_ahead
end
except ValueError
begin
return none
end
try
begin
set past_date = now - time delta days=past_days
set future_date = now + time... | def retrieve_recent(database_connection: mysql.connector.connect,
include_days_ahead: int = 7,
include_days_back: int = 32,) -> List[Dict]:
try:
past_days = int(include_days_back)
future_days = int(include_days_ahead)
except ValueError:
return None... | Python | nomic_cornstack_python_v1 |
string 运用你所掌握的数据结构,设计和实现一个LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。 获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值, 从而为新的数据值留出空间。 进阶: 你是否可以在 O(1) 时间复杂度内完成这两种操作? 示例: LRUCache cache = new LRUCache( 2 /* 缓存容量 */ ); cache.put(1, 1)... | """
运用你所掌握的数据结构,设计和实现一个LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,
从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );
cache.put(1,... | Python | zaydzuhri_stack_edu_python |
function getByIndex self indexName position
begin
return self at call getKey position
end function | def getByIndex(self, indexName, position):
return self[self.getIndex(indexName).getKey(position)] | Python | nomic_cornstack_python_v1 |
comment Definition for singly-linked list.
comment class ListNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution extends object
begin
function hasCycle self head
begin
string :type head: ListNode :rtype: bool
set tuple pFast pSlow = tuple head head
while pFast and n... | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
pFast, pSlow = head, head
... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function minDistance self word1 word2
begin
string :type word1: str :type word2: str :rtype: int
set n1 = length word1
set n2 = length word2
set dp = list comprehension list comprehension 0 for _ in range n2 + 1 for _ in range n1 + 1
function dp1 n1 n2
begin
if n1 == 0
begin
return n... | class Solution(object):
def minDistance(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
n1 = len(word1)
n2 = len(word2)
dp = [[0 for _ in range(n2 + 1)] for _ in range(n1 + 1)]
def dp1(n1, n2):
if n1 == ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment Leer edad
comment Convertir edad a entero
comment Si edad es menor a 18, imprimir eres niño
comment Si edad es mayor a 18, imprimir eres adulto
comment Si edad no es un entero entonces imprimir error | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Leer edad
# Convertir edad a entero
# Si edad es menor a 18, imprimir eres niño
# Si edad es mayor a 18, imprimir eres adulto
# Si edad no es un entero entonces imprimir error
| Python | zaydzuhri_stack_edu_python |
function f a
begin
set a = a + 1
end function
set b = list 1
function fl a=none
begin
print a
end function
set b = list 1
function fl1 a=list
begin
print a
end function
call fl1 b
call fl1 | def f(a):
a=a+1
b=[1]
def fl(a=None):
print(a)
b=[1]
def fl1(a=[]):
print(a)
fl1(b)
fl1()
| Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
import shutil
from xlsxwriter import Workbook
import credentials as c
comment from credentials import instagram_user_name, instagram_password
comment from time import sleep
import os
import time
set start_time = time
comment This class is for ... | from selenium import webdriver
from bs4 import BeautifulSoup
import requests
import shutil
from xlsxwriter import Workbook
import credentials as c
# from credentials import instagram_user_name, instagram_password
# from time import sleep
import os
import time
start_time = time.time()
# This class is for testing purp... | Python | zaydzuhri_stack_edu_python |
function tag self tag
begin
if not call objExists string %s.%s % tuple transform tag
begin
call addAttr tag at=string bool dv=1
lock
end
end function
comment end if tag not exists | def tag(self, tag):
if not pm.objExists('%s.%s' % (self.transform, tag)):
self.transform.addAttr(tag, at='bool', dv=1)
self.transform.attr(tag).lock()
# end if tag not exists | Python | nomic_cornstack_python_v1 |
function write
begin
with call spinner string Loading About ...
begin
call title_awesome string Dataset
function display1
begin
call markdown string Your client is a meal delivery company which operates in multiple cities. They have various fulfillment centers in these cities for dispatching meal orders to their custom... | def write():
with st.spinner("Loading About ..."):
ast.shared.components.title_awesome("Dataset")
def display1():
st.markdown("Your client is a meal delivery company which operates in multiple cities. They have various fulfillment centers in these cities for dispatching meal orders... | Python | nomic_cornstack_python_v1 |
function language self language
begin
set _language = language
end function | def language(self, language):
self._language = language | Python | nomic_cornstack_python_v1 |
function group_sentences_in_batches sentences max_batch_char_length=none batch_size=none
begin
set batches : List at List at str = list
if max_batch_char_length is not none and batch_size is not none
begin
raise call ValueError string max_batch_char_length and batch_size are mutually exclusive.
end
else
if max_batch_c... | def group_sentences_in_batches(
sentences: List[str],
max_batch_char_length: Optional[int] = None,
batch_size: Optional[int] = None,
) -> List[List[str]]:
batches: List[List[str]] = []
if max_batch_char_length is not None and batch_size is not None:
raise ValueError("max_batch_char_length ... | Python | nomic_cornstack_python_v1 |
function foreach_as self
begin
set line = strip line
if ends with line string as
begin
if starts with line string as is false
begin
return true
end
end
end function | def foreach_as(self):
line = self.line.strip()
if line.endswith('as'):
if line.startswith('as') is False:
return True | Python | nomic_cornstack_python_v1 |
function OwnLoop
begin
function decorator item
begin
set __own_loop = true
return item
end function
return decorator
end function | def OwnLoop():
def decorator(item):
item.__own_loop = True
return item
return decorator | Python | nomic_cornstack_python_v1 |
function create_template_instance self
begin
debug string create-mib-template-instance
try
begin
comment MIB Reset start fresh
call strobe_watchdog
set results = yield call send_mib_reset
set status = fields at string success_code
if status != value
begin
raise exception format string MIB Reset request failed with stat... | def create_template_instance(self):
self.log.debug('create-mib-template-instance')
try:
# MIB Reset start fresh
self.strobe_watchdog()
results = yield self._device.omci_cc.send_mib_reset()
status = results.fields['omci_message'].fields['success_code']
... | Python | nomic_cornstack_python_v1 |
function disbelief self disbelief
begin
set _disbelief = disbelief
end function | def disbelief(self, disbelief):
self._disbelief = disbelief | Python | nomic_cornstack_python_v1 |
import tweepy
import json
comment Setting up API ##########
comment API keys
set consumer_key = string
set consumer_secret = string
set access_token = string
set access_token_secret = string
comment Create authentication object
set auth = call OAuthHandler consumer_key consumer_secret
comment Set access token and s... | import tweepy
import json
########## Setting up API ##########
# API keys
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
# Create authentication object
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
# Set access token and secret
auth.set_access_token(access_token, access... | Python | zaydzuhri_stack_edu_python |
function get_train_examples self data_dir
begin
raise call NotImplementedError
end function | def get_train_examples(self, data_dir):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
while not found_it and num < 100
begin
set num = num + 1
set first_num = num // 10 ^ 0 % 10
set second_num = num // 10 ^ 1 % 10
set square = num * num
set first_num_sq = square // 10 ^ 0 % 10
set second_num_sq = square // 10 ^ 1 % 10
if first_num == first_num_sq and second_num == second_num_sq
begin
set found_it = true... | while ( not found_it and num < 100 ):
num = num + 1
first_num = num // 10**0 % 10
second_num = num // 10**1 % 10
square = num * num
first_num_sq = square // 10**0 % 10
second_num_sq = square // 10**1 % 10
if( first_num == first_num_sq and second_num == second_num_sq ):
found_i... | Python | zaydzuhri_stack_edu_python |
function _get_suppress self
begin
return __suppress
end function | def _get_suppress(self):
return self.__suppress | Python | nomic_cornstack_python_v1 |
function fetch_all self org
begin
string Fetches all local objects :param org: the org :return: the queryset
set qs = filter org=org
if local_backend_attr is not none
begin
set qs = filter keyword dict local_backend_attr backend
end
return qs
end function | def fetch_all(self, org):
"""
Fetches all local objects
:param org: the org
:return: the queryset
"""
qs = self.model.objects.filter(org=org)
if self.local_backend_attr is not None:
qs = qs.filter(**{self.local_backend_attr: self.backend})
retu... | Python | jtatman_500k |
string #-*- coding=utf-8 -*- Created on 2015年7月23日 @author: yang
comment Definition for a binary tree node.
from test.support import temp_cwd
class TreeNode
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
end function
end class
class Solution
begin
comment @param {TreeNode} root
commen... | '''
#-*- coding=utf-8 -*-
Created on 2015年7月23日
@author: yang
'''
# Definition for a binary tree node.
from test.support import temp_cwd
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param {TreeNode} root
# @param {Tree... | Python | zaydzuhri_stack_edu_python |
string EXERCÍCIO 058: Jogo da Adivinhação v2.0 Melhore o jogo do EXERCÍCIO 028 onde o computador vai "pensar" em um número entre 0 e 10. Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessários para vencer.
function main
begin
pass
end function
if __name__ == string... | """
EXERCÍCIO 058: Jogo da Adivinhação v2.0
Melhore o jogo do EXERCÍCIO 028 onde o computador vai "pensar" em um número entre 0 e 10.
Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos
palpites foram necessários para vencer.
"""
def main():
pass
if __name__ == '__main__':
... | Python | zaydzuhri_stack_edu_python |
comment el volumen de un cubo
import libreria
import os
comment pedir las variables
set a = decimal argv at 1
set b = decimal argv at 2
set c = decimal argv at 3
set resultado = call volumen a b c
print resultado | # el volumen de un cubo
import libreria
import os
# pedir las variables
a=float(os.sys.argv[1])
b=float(os.sys.argv[2])
c=float(os.sys.argv[3])
resultado=libreria.volumen(a,b,c)
print(resultado) | Python | zaydzuhri_stack_edu_python |
from csv import reader
import codecs
function getMaxSequence matrix
begin
set rows = length matrix
set cols = length matrix at 0
set maxLenth = 1
set maxRow = 0
set maxCol = 0
comment //create result matrix
set result = list comprehension list comprehension 1 for x in range cols for y in range rows
for i in range 0 row... | from csv import reader
import codecs
def getMaxSequence(matrix):
rows = len(matrix)
cols = len(matrix[0])
maxLenth =1
maxRow = 0
maxCol = 0
#//create result matrix
result = [[1 for x in range(cols)] for y in range(rows)]
for i in range(... | Python | zaydzuhri_stack_edu_python |
function load_all config_dir patch_dir=none base_directory=_base_directory
begin
return call load_modules all_modules config_dir patch_dir base_directory
end function | def load_all(config_dir, patch_dir=None, base_directory=_base_directory):
return load_modules(all_modules, config_dir, patch_dir, base_directory) | Python | nomic_cornstack_python_v1 |
function transferMeshFunToSubMesh subMesh meshFun
begin
comment input check
set meshFunTypes = tuple MeshFunctionSizet MeshFunctionBool MeshFunctionDouble MeshFunctionInt
set zeroType = tuple 0 false 0.0 0
assert is instance subMesh SubMesh
assert is instance meshFun meshFunTypes
set parentMesh = call mesh
assert is in... | def transferMeshFunToSubMesh(subMesh, meshFun):
# input check
meshFunTypes = (dlfn.MeshFunctionSizet, dlfn.MeshFunctionBool,
dlfn.MeshFunctionDouble, dlfn.MeshFunctionInt)
zeroType = (0, False, 0.0, 0)
assert isinstance(subMesh, dlfn.SubMesh)
assert isinstance(meshFun, meshFunTyp... | Python | nomic_cornstack_python_v1 |
import unittest
from django.test import TestCase
from settings_data.models import *
class SettingTestCase extends TestCase
begin
function setUp self
begin
set test_array = list tuple string 1 string i tuple string 1.0 string i tuple string 1.23 string i tuple 1 string i tuple 1.0 string i tuple 1.1 string i tuple strin... | import unittest
from django.test import TestCase
from settings_data.models import *
class SettingTestCase(TestCase):
def setUp(self):
test_array = [
('1', 'i'), ('1.0', 'i'), ('1.23', 'i'), (1, 'i'), (1.0, 'i'),
(1.1, 'i'),
('1.23', 'f'), ('1.0', 'f'), ('1', 'f'), (1.2... | Python | zaydzuhri_stack_edu_python |
function get_leaderboard request
begin
set includedUsers = filter hide_leaderboard=false is_staff=false
comment ordered list of points, index denoting leaderboard position (rank)
comment distinct values means that everyone with the same points has the same rank
set rankings = list
for item in call order_by string -poi... | def get_leaderboard(request):
includedUsers = User.objects.filter(hide_leaderboard=False, is_staff=False)
# ordered list of points, index denoting leaderboard position (rank)
# distinct values means that everyone with the same points has the same rank
rankings = []
for item in includedUsers.values... | Python | nomic_cornstack_python_v1 |
comment Don't read me until you're totally stuck!
comment Assignment 1-1
function check sm string
begin
for s in string
begin
if s not in call out_edges
begin
return false
end
call advance s
end
return call is_terminal
end function
comment Assignment 1-2
function test2
begin
comment (x+@x+\.x+(\.x+)*)
return call State... | # Don't read me until you're totally stuck!
# Assignment 1-1
def check(sm, string):
for s in string:
if s not in sm.out_edges():
return False
sm.advance(s)
return sm.is_terminal()
# Assignment 1-2
def test2():
#(x+@x+\.x+(\.x+)*)
return StateM... | Python | zaydzuhri_stack_edu_python |
function get_quantile_thresholds ds quantile dim lat_name=string lat lon_name=string lon lat_chunk=1 lon_chunk=1
begin
set ds = call chunk dict none dict lat_name 1 ; lon_name 1 ; none dictionary comprehension d : - 1 for d in dim
return call quantile quantile dim
end function | def get_quantile_thresholds(ds, quantile, dim, lat_name='lat', lon_name='lon', lat_chunk=1, lon_chunk=1):
ds = ds.chunk({**{lat_name: 1, lon_name: 1},
**{d: -1 for d in dim}})
return ds.quantile(quantile, dim) | Python | nomic_cornstack_python_v1 |
function eval self env=none
begin
if env is none
begin
set env = globalenv
end
return call Rf_eval _cdata env
end function | def eval(self, env: typing.Optional[SexpEnvironment] = None) -> sexp.Sexp:
if env is None:
env = globalenv
return openrlib.rlib.Rf_eval(self.__sexp__._cdata, env) | Python | nomic_cornstack_python_v1 |
function buffer self value
begin
try
begin
set key = active_key
set buffer_dict at key = value
end
except TypeError
begin
pass
end
end function | def buffer(self, value):
try:
key = self.buffer_dict.active_key
self.buffer_dict[key] = value
except TypeError:
pass | Python | nomic_cornstack_python_v1 |
function connection_lost self exc
begin
comment todo хз как убить задачу
try
begin
set conn_is_open = false
for task in tasks
begin
call cancel
end
end
except any
begin
pass
end
finally
begin
call stop
close loop
end
end function | def connection_lost(self, exc):
# todo хз как убить задачу
try:
self.conn_is_open = False
for task in self.tasks:
task.cancel()
except:
pass
finally:
self.loop.stop()
self.loop.close() | Python | nomic_cornstack_python_v1 |
function doc_centroid vectors cache=none **kwargs
begin
return tuple if expression length vectors > 0 then reduce vectors / length vectors else array list cache
end function | def doc_centroid(vectors, cache=None, **kwargs):
return np.add.reduce(vectors) / len(vectors) if len(vectors) > 0 else np.array([]), cache | Python | nomic_cornstack_python_v1 |
function pass_through_lateral_conn self
begin
if conv_filter is not none
begin
set boundary = if expression circular then string wrap else string fill
set P = call convolve2d P conv_filter string same boundary
end
comment rescale to PD
set P = P / sum
end function | def pass_through_lateral_conn(self):
if self.conv_filter is not None:
boundary = 'wrap' if self.circular else 'fill'
self.P = convolve2d(self.P, self.conv_filter, 'same', boundary)
self.P = self.P / self.P.sum() # rescale to PD | Python | nomic_cornstack_python_v1 |
function node2class ctx xml_node
begin
set _class_name = string
comment Root node <=> Main CLI class
if call is_node xml_node string cli:cli
begin
set _class_name = call cli_class_name ctx
end
else
comment Menu and menu references
if call is_node_with_attr xml_node string cli:menu string @name
begin
set _class_name = ... | def node2class(ctx, xml_node):
_class_name = ""
# Root node <=> Main CLI class
if ctx.xml.is_node(xml_node, "cli:cli"):
_class_name = ctx.args.cli_class_name(ctx)
# Menu and menu references
elif ctx.xml.is_node_with_attr(xml_node, "cli:me... | Python | nomic_cornstack_python_v1 |
function _is_dict_free obj
begin
if is instance obj dict
begin
return false
end
else
if is instance obj list
begin
return all generator expression call _is_dict_free item for item in obj
end
else
begin
return true
end
end function | def _is_dict_free(obj: Any) -> bool:
if isinstance(obj, dict):
return False
elif isinstance(obj, list):
return all(_is_dict_free(item) for item in obj)
else:
return True | Python | nomic_cornstack_python_v1 |
function is_palindrome sentence
begin
comment Remove all non-alphanumeric characters and convert to lowercase
set sentence = join string generator expression lower ch for ch in sentence if is alphanumeric ch
comment Check if the reversed sentence is equal to the original sentence
return sentence == sentence at slice ... | def is_palindrome(sentence):
# Remove all non-alphanumeric characters and convert to lowercase
sentence = ''.join(ch.lower() for ch in sentence if ch.isalnum())
# Check if the reversed sentence is equal to the original sentence
return sentence == sentence[::-1]
# Test the function
sentence = "A ma... | Python | jtatman_500k |
function cos_similarity b1 b2 city
begin
if b1 == b2
begin
return 1.0
end
set reviews = REVIEWS at city
set b1_reviewers = list comprehension review at string user_id for review in reviews if review at string business_id == b1 at string business_id
set shared_reviewers = list comprehension review at string user_id for ... | def cos_similarity(b1, b2, city):
if b1 == b2:
return 1.0
reviews = REVIEWS[city]
b1_reviewers = [review['user_id'] for review in reviews if review['business_id'] == b1['business_id']]
shared_reviewers = [review['user_id'] for review in reviews if review['business_id'] == b2['business_id'] and ... | Python | nomic_cornstack_python_v1 |
function _get_start_end parts index=7
begin
string Retrieve start and end for a VCF record, skips BNDs without END coords
set start = parts at 1
set end = list comprehension split x string = at - 1 for x in split parts at index string ; if starts with x string END=
if end
begin
set end = end at 0
return tuple start end... | def _get_start_end(parts, index=7):
"""Retrieve start and end for a VCF record, skips BNDs without END coords
"""
start = parts[1]
end = [x.split("=")[-1] for x in parts[index].split(";") if x.startswith("END=")]
if end:
end = end[0]
return start, end
return None, None | Python | jtatman_500k |
comment TODO
comment Go over
comment import pygame library so we can use it!
import pygame
import random
from pygame.locals import *
from pygame.draw import *
comment run initialization code on the library
call init
comment setup display dimensions
set display_width = 1000
set display_height = 1000
set game_surface = c... | #TODO
# Go over
# import pygame library so we can use it!
import pygame
import random
from pygame.locals import *
from pygame.draw import *
# run initialization code on the library
pygame.init()
# setup display dimensions
display_width = 1000
display_height = 1000
game_surface = pygame.display.set_mode((display_wi... | Python | zaydzuhri_stack_edu_python |
comment import pprofile
comment profiler = pprofile.Profile()
comment with profiler:
comment note, latitudes go from -90 to 90
comment minimum means furthest South
set minimum_latitude = - 30.0
set maximum_latitude = 30.0
comment degrees
set latitude_resolution = 0.1
comment note, longitudes go from -180 to 180
comment... | # import pprofile
# profiler = pprofile.Profile()
# with profiler:
#note, latitudes go from -90 to 90
#minimum means furthest South
minimum_latitude = -30.0
maximum_latitude = 30.0
latitude_resolution = 0.1 #degrees
#note, longitudes go from -180 to 180
#minimum means furthest West
minimum_longitude = -180
maximum_l... | Python | zaydzuhri_stack_edu_python |
function Close self
begin
raise call NotImplementedError string Implement this
end function | def Close(self):
raise NotImplementedError('Implement this') | Python | nomic_cornstack_python_v1 |
function compute_probability_distribution_msm self transition_count bayesian=true
begin
if smear_transitions
begin
warn string Smeared transitions not recommended when you use 'msm'
end
set n_states = length transition_count
set sequences = list
set multiplicator = if expression smear_transitions then 100 else 1
for i... | def compute_probability_distribution_msm(self, transition_count, bayesian=True):
if self.smear_transitions:
logger.warn("Smeared transitions not recommended when you use 'msm'")
n_states = len(transition_count)
sequences = []
multiplicator = 100 if self.smear_transitions else... | Python | nomic_cornstack_python_v1 |
function extrapolate_hf hf_energies cardinals alpha
begin
set roots = call fsolve hf_error 1 args=tuple hf_energies cardinals alpha
set A = roots at 0
set cbs_hf = hf_energies at 0 - A * exp - alpha * square root cardinals at 0
return cbs_hf
end function | def extrapolate_hf(hf_energies, cardinals, alpha):
roots = optimize.fsolve(
hf_error, 1, args=(hf_energies, cardinals, alpha)
)
A = roots[0]
cbs_hf = hf_energies[0] - A*exp(-alpha * sqrt(cardinals[0]))
return cbs_hf | Python | nomic_cornstack_python_v1 |
function qsize self
begin
return length fifo
end function | def qsize(self):
return len(self.fifo) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string --- Day 21: Springdroid Adventure --- You lift off from Pluto and start flying in the direction of Santa. While experimenting further with the tractor beam, you accidentally pull an asteroid directly into your ship! It deals significant damage to your hull and causes your ship to be... | # -*- coding: utf-8 -*-
"""
--- Day 21: Springdroid Adventure ---
You lift off from Pluto and start flying in the direction of Santa.
While experimenting further with the tractor beam, you accidentally pull an asteroid directly into your ship! It deals significant damage to your hull and causes your ship to beg... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Sep 23 17:57:36 2020 @author: shankarj
import glob2
from PIL import Image
import shutil
from pathlib import Path
set min_size = 112
set new_size = tuple 224 224
set folder = string Data/raw/zip/*/*
set new_folder = string Data/processed/zip
for file in glob glob2 fold... | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 17:57:36 2020
@author: shankarj
"""
import glob2
from PIL import Image
import shutil
from pathlib import Path
min_size = 112
new_size = 224, 224
folder = 'Data/raw/zip/*/*'
new_folder = 'Data/processed/zip'
for file in glob2.glob(folder):
im = Image.open(file)
... | Python | zaydzuhri_stack_edu_python |
from keras.models import load_model
import numpy as np
from PIL import Image , ImageTk
import tkinter as tk
from tkinter import Label
set model = call load_model string C:\Users\Igor\source\repos\FaceGenerator\ string FaceGenerator\animeGAN.model
function show_face
begin
set noise = call normal 0 1 tuple 1 256
set gene... | from keras.models import load_model
import numpy as np
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import Label
model = load_model('C:\\Users\\Igor\\source\\repos\\FaceGenerator\\',
'FaceGenerator\\animeGAN.model')
def show_face():
noise = np.random.normal(0, 1,... | Python | zaydzuhri_stack_edu_python |
comment a < b に変換する
comment 入れ替える
if a0 > b0
begin
set a = b0
set b = a0
set c = d0
set d = c0
end
else
begin
comment 入れ替えない
set a = a0
set b = b0
set c = c0
set d = d0
end
set right = max c d
set left = min a b
set middle = max a b
for i in range n - 1
begin
comment 岩が2個連続である場合
if s at i == string # and s at i + 1 == ... | # a < b に変換する
if a0 > b0 : # 入れ替える
a = b0
b = a0
c = d0
d = c0
else : # 入れ替えない
a = a0
b = b0
c = c0
d = d0
right = max(c,d)
left = min(a,b)
middle = max(a,b)
for i in range(n-1) :
if s[i] == '#' and s[i+1] == '#' : # 岩が2個連続である場合
if i <= right - 2 and i >= left - 1 :
... | Python | zaydzuhri_stack_edu_python |
comment 웹서비스를 요청하는 모듈
import requests
import xml.etree.ElementTree as xml
set url = string http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson?serviceKey=Vsg3jI7E6V%2FAd3mSW%2BqlkbFw1xQtvJxOg%2BOePmttWGmaWPIRJcz%2FVXRycL3K7bCEDbqC9%2BvgDZr8Z%2BnKr53kgA%3D%3D&pageNo=1&numOfRows=10&startCreateDt... | import requests #웹서비스를 요청하는 모듈
import xml.etree.ElementTree as xml
url = "http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson?serviceKey=Vsg3jI7E6V%2FAd3mSW%2BqlkbFw1xQtvJxOg%2BOePmttWGmaWPIRJcz%2FVXRycL3K7bCEDbqC9%2BvgDZr8Z%2BnKr53kgA%3D%3D&pageNo=1&numOfRows=10&startCreateDt=20200310&endCre... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function numDistinct self s t
begin
set n = length s
set m = length t
set dp = list comprehension list 0 * m + 1 for _ in range n + 1
for i in range n
begin
set dp at i at 0 = 1
end
for i in range 1 n + 1
begin
for j in range 1 m + 1
begin
if s at i - 1 == t at j - 1
begin
set dp at i at j = dp at ... | class Solution:
def numDistinct(self, s: str, t: str) -> int:
n = len(s)
m = len(t)
dp = [[0] * (m+1) for _ in range(n+1)]
for i in range(n):
dp[i][0] = 1
for i in range(1, n+1):
for j in range(1, m+1):
if s[i-1] == t[j-1]:
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
set answer = none
set data1 = list 1 2 3 4 5
set data2 = list string A string B string C string D string E
set answer = zip data1 data2
assert answer == list tuple 1 string A tuple 2 string B tuple 3 string C tuple 4 string D tuple 5 string E | #!/usr/bin/env python
answer = None
data1 = [1,2,3,4,5]
data2 = ['A', 'B', 'C', 'D', 'E']
answer = zip(data1, data2)
assert answer == [ (1,'A'), (2,'B'), (3,'C'), (4, 'D'),(5,'E') ]
| Python | zaydzuhri_stack_edu_python |
from random import choice
function wilsons grid animation=none
begin
set unvisited = list comprehension c for c in call each_cell
set first = random choice unvisited
remove unvisited first
while length unvisited > 0
begin
set cell = random choice unvisited
set path = list cell
while cell in unvisited
begin
set cell = r... | from random import choice
def wilsons(grid, animation=None):
unvisited = [c for c in grid.each_cell()]
first = choice(unvisited)
unvisited.remove(first)
while len(unvisited) > 0:
cell = choice(unvisited)
path = [cell]
while cell in unvisited:
cell = cho... | Python | zaydzuhri_stack_edu_python |
function set_uid_gid set_rguid_to_eguid=false set_eguid_to_rguid=false restore_ids=true
begin
function set_uid_gid_decorator func
begin
function inner *args **kwargs
begin
set current_proc = call current_process
debug format string Changing permissions for process: {0} with PID: {1!s} name pid
if version > string 2.7
b... | def set_uid_gid(set_rguid_to_eguid=False, set_eguid_to_rguid=False, restore_ids=True):
def set_uid_gid_decorator(func):
def inner(*args, **kwargs):
current_proc = multiprocessing.current_process()
logger.debug("Changing permissions for process: {0} with PID: {1!s}".format(current_pro... | Python | nomic_cornstack_python_v1 |
function encodeMessage message
begin
set body = call getBody
set attributes = dict PAYLOAD_MIME_TYPE payloadMimeType ; OBJECT_TYPE objectType ; INGESTION_ID ingestionId ; ARTIFACT_NAME artifactName ; ARTIFACT_VERSION artifactVersion
update attributes customAttributes
if is instance body JsonSerializable
begin
set body ... | def encodeMessage(message: BaseMessage) -> dict:
body = message.getBody()
attributes = {
MessageAttribute.PAYLOAD_MIME_TYPE: message.payloadMimeType,
MessageAttribute.OBJECT_TYPE: message.objectType,
MessageAttribute.INGESTION_ID: message.ingestionId,
MessageAttribute.... | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
import pandas as pd
import numpy as np
import os
import cv2
import math
from keras.layers import Conv2D , Flatten
from scipy import signal
set control_flow_ops = tf
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D , MaxPooling2D , ZeroPadding2D
from keras.... | import tensorflow as tf
import pandas as pd
import numpy as np
import os
import cv2
import math
from keras.layers import Conv2D, Flatten
from scipy import signal
tf.python.control_flow_ops = tf
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from ker... | Python | zaydzuhri_stack_edu_python |
function welcome_message
begin
call fill BLACK
set textsurface = call render string Welcome to the best thing false tuple 255 255 255
call blit textsurface tuple 50 50
set textsurface = call render string I have coded so far false tuple 255 255 255
call blit textsurface tuple 130 100
global quit draw_state
comment TODO... | def welcome_message():
screen.fill(BLACK)
textsurface = myfont.render('Welcome to the best thing', False,(255,255,255))
screen.blit(textsurface,(50,50))
textsurface = myfont.render('I have coded so far', False,(255,255,255))
screen.blit(textsurface,(130,100))
global quit, draw_state
#TOD... | Python | nomic_cornstack_python_v1 |
function forward self x
begin
raise call NotImplementedError string Need to call subclass method here
end function | def forward(self, x):
raise NotImplementedError("Need to call subclass method here") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment --------------------------------------------------------
comment Faster R-CNN
comment Copyright (c) 2015 Microsoft
comment Licensed under The MIT License [see LICENSE for details]
comment Written by Ross Girshick
comment --------------------------------------------------------
strin... | #!/usr/bin/env python
# --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""
Demo script showing detections in sample i... | Python | zaydzuhri_stack_edu_python |
import unittest , sys
from code.algorithms.convexhull import convexhull
class TestInsertionSort extends TestCase
begin
function test_in_order self
begin
assert equal call convexhull list list 0 0 list 10 0 list 0 10 list list 10 0 list 0 10 list 0 0
end function
function test_convex_hull self
begin
assert equal call co... | import unittest, sys
from code.algorithms.convexhull import convexhull
class TestInsertionSort(unittest.TestCase):
def test_in_order(self):
self.assertEqual(convexhull([[0, 0], [10, 0], [0, 10]]), [[10, 0], [0, 10], [0, 0]])
def test_convex_hull(self):
self.assertEqual(convexhull([[41, -6], [-24, -74], [-51, -... | Python | zaydzuhri_stack_edu_python |
async function timer_handler route_id instance instance_lock force=false
begin
comment Initial wait time for the timeout event
try
begin
if not force
begin
set start_time = time
set timed_out = false
await sleep 60
end
comment Mark the route as unreachable.
with instance_lock
begin
set metric = 16
info format string {}... | async def timer_handler(route_id: int, instance: Router, instance_lock: Lock, force=False):
# Initial wait time for the timeout event
try:
if not force:
instance.routing_table[route_id].start_time = time.time()
instance.routing_table[route_id].timed_out = False
await ... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
import matplotlib.pyplot as plt
comment Prompt for limited number of options
function promptForInputCategorical message options
begin
string Prompts for user input with limited number of options (not used in this project) :param message: Message displayed to the user :param options: limite... | import cv2
import numpy as np
import matplotlib.pyplot as plt
# Prompt for limited number of options
def promptForInputCategorical(message, options):
"""
Prompts for user input with limited number of options (not used in this project)
:param message: Message displayed to the user
:param options: limit... | Python | zaydzuhri_stack_edu_python |
function urgency_coeff self gc
begin
set dangerous_enemies_coeff = 0
set higher_health_enemies_coeff = 0
set little_allies_coeff = 0
set low_health_allies_coeff = 0
comment Enemy coeffs
set dangerous = 0
set total_enemies = 0
set health = 0
set total_health = 0
for enemy_id in enemies
begin
try
begin
set enemy = call u... | def urgency_coeff(self, gc):
dangerous_enemies_coeff = 0
higher_health_enemies_coeff = 0
little_allies_coeff = 0
low_health_allies_coeff = 0
## Enemy coeffs
dangerous = 0
total_enemies = 0
health = 0
total_health = 0
for enemy_id in self... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.