code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_pos self
begin
return tuple x_pos y_pos
end function | def get_pos(self):
return self.x_pos, self.y_pos | Python | nomic_cornstack_python_v1 |
comment Time: O(n)
comment Space: O(1)
function frac n
begin
if n == 1
begin
return 1
end
return call frac n - 1 * n
end function
print call frac 4
comment Time: O(2^n)
comment Space: O(1)
function fib n
begin
if n == 0 or n == 1
begin
return 1
end
return call fib n - 1 + call fib n - 2
end function
comment Time: O(n)
... | # Time: O(n)
# Space: O(1)
def frac(n):
if n == 1:
return 1
return frac(n-1)*n
print(frac(4))
# Time: O(2^n)
# Space: O(1)
def fib(n):
if n == 0 or n == 1:
return 1
return fib(n-1) + fib(n-2)
# Time: O(n)
# Space: O(1)
def fib_mem(n):
if n == 0:
return [1]
if n == 1:... | Python | zaydzuhri_stack_edu_python |
for i in range 5
begin
print string 10 << i string = 10 ? i
print string binary 10 at slice 2 : : string << i string = string binary 10 ? i at slice 2 : :
print string
end
print string - * 32
print string Shift right - Divide with powers of 2
for i in range 5
begin
print string 128 >> i string = 128 ? i
print string... | for i in range(5):
print('10 <<', i, '=', 10 << i)
print(str(bin(10))[2:], '<<', i, '=', str(bin(10 << i))[2:])
print('')
print('-' * 32)
print('Shift right - Divide with powers of 2')
for i in range(5):
print('128 >>', i, '=', 128 >> i)
print(str(bin(128))[2:], '>>', i, '=', str(bin(128 >> i))[2:]... | Python | zaydzuhri_stack_edu_python |
function site_metas request
begin
return call get_site_metas is_secure=call is_secure
end function | def site_metas(request):
return get_site_metas(is_secure=request.is_secure()) | Python | nomic_cornstack_python_v1 |
function __get_size_multiplier self multiplier
begin
if multiplier is none
begin
set result = 1
end
else
if multiplier in list string k string K
begin
set result = __k_multiplier
end
else
if multiplier in list string m string M
begin
set result = __m_multiplier
end
else
if multiplier in list string g string G
begin
set... | def __get_size_multiplier(self, multiplier):
if multiplier is None:
result = 1
elif multiplier in ['k', 'K']:
result = self.__k_multiplier
elif multiplier in ['m', 'M']:
result = self.__m_multiplier
elif multiplier in ['g', 'G']:
result = s... | Python | nomic_cornstack_python_v1 |
import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf , col
from pyspark.sql.functions import year , month , dayofmonth , hour , weekofyear , dayofweek , date_format
set config = config parser
read config string dl.cfg
set environ at strin... | import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col
from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, dayofweek, date_format
config = configparser.ConfigParser()
config.read('dl.cfg')
os.environ['AWS_AC... | Python | zaydzuhri_stack_edu_python |
comment Deviner un nombre aléatoire.
from random import *
set randomnumber = random integer 1 1000
for i in range 9
begin
set guess = integer input string Choose a number:
if guess == randomnumber
begin
print string Correct!
break
end
else
begin
print string Try again... tries remaining: + string 9 - i
end
end
print st... | #Deviner un nombre aléatoire.
from random import*
randomnumber=randint(1,1000)
for i in range(9):
guess=int(input("Choose a number:" ))
if (guess == randomnumber):
print("Correct!")
break
else:
print("Try again... tries remaining: "+str(9-i))
print("Game over")
... | Python | zaydzuhri_stack_edu_python |
function find_area ftle eigvectors ridges qsat=none qdpt=none
begin
if qsat is none or qdpt is none
begin
set saturation_ratio = 0.5
end
else
begin
set saturation_ratio = qdpt / qsat
end
set ftle = copy ftle
set eigvectors = copy eigvectors
set ridges = copy ridges
set ftle = call sortby string longitude
set eigvectors... | def find_area(ftle, eigvectors, ridges, qsat=None, qdpt=None):
if qsat is None or qdpt is None:
saturation_ratio = .5
else:
saturation_ratio = qdpt / qsat
ftle = ftle.copy()
eigvectors = eigvectors.copy()
ridges = ridges.copy()
ftle = ftle.sortby('latitude').sortby('longitude')
... | Python | nomic_cornstack_python_v1 |
function OPT l r n
begin
if n <= 0
begin
return 0
end
if n == 1
begin
return board at l
end
if n == 2
begin
return max board at l - board at r board at r - board at l
end
if M at n != none
begin
return M at n
end
else
begin
set M at n = max board at l - call OPT l + 1 r n - 1 board at r - call OPT l r - 1 n - 1
return ... | def OPT(l, r, n):
if n <= 0: return 0
if n == 1: return board[l]
if n == 2:
return max(board[l]-board[r], board[r]-board[l])
if M[n] != None: return M[n]
else:
M[n] = max(
board[l] - OPT(l+1, r, n-1),
board[r] - OPT(l, r-1, n-1))
return M[n]
OPT(0, ... | Python | zaydzuhri_stack_edu_python |
function ReverseGradient hp_lambda
begin
function reverse_gradient_function X hp_lambda=hp_lambda
begin
string Flips the sign of the incoming gradient during training.
global NUM_GRADIENT_REVERSALS
set NUM_GRADIENT_REVERSALS = NUM_GRADIENT_REVERSALS + 1
set grad_name = string GradientReversal%d % NUM_GRADIENT_REVERSALS... | def ReverseGradient (hp_lambda):
def reverse_gradient_function (X, hp_lambda=hp_lambda):
"""Flips the sign of the incoming gradient during training."""
global NUM_GRADIENT_REVERSALS
NUM_GRADIENT_REVERSALS += 1
grad_name = "GradientReversal%d" % NUM_GRADIENT_REVE... | Python | nomic_cornstack_python_v1 |
function set_latlon_bounds self box
begin
set bbox_x0 = box at 0
set bbox_x1 = box at 1
set bbox_y0 = box at 2
set bbox_y1 = box at 3
end function | def set_latlon_bounds(self,box):
self.bbox_x0 = box[0]
self.bbox_x1 = box[1]
self.bbox_y0 = box[2]
self.bbox_y1 = box[3] | Python | nomic_cornstack_python_v1 |
function handle_line self line
begin
comment def_name is the name of the function or class defined by
comment this line; or None if no funciton or class is defined.
set def_name = none
comment def_type is the type of the function or class defined by
comment this line; or None if no funciton or class is defined.
set def... | def handle_line(self, line):
# def_name is the name of the function or class defined by
# this line; or None if no funciton or class is defined.
def_name = None
# def_type is the type of the function or class defined by
# this line; or None if no funciton or class is defined.
... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
import mandrill
from django.conf import settings
from core import redis_connections
from core.users.notifications.sms_dispatcher.exceptions import SMSSendingThrottled
set PRIVATE_IPS_PREFIX = tuple string 10. string 172. string 192.
function get_client_ip request
begin
string get the client ip from... | # coding=utf-8
import mandrill
from django.conf import settings
from core import redis_connections
from core.users.notifications.sms_dispatcher.exceptions import SMSSendingThrottled
PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', )
def get_client_ip(request):
"""get the client ip from the request
"""
remo... | Python | zaydzuhri_stack_edu_python |
import vim
function sum col fl ll
begin
set b = buffer
set result = 0.0
for line in b at slice fl : ll :
begin
set result = result + decimal split line at col - 1
end
append b string ----- RESULT: %f ----- % result ll
end function | import vim
def sum(col, fl, ll):
b = vim.current.buffer
result = 0.0
for line in b[fl:ll]:
result += float(line.split()[col - 1])
b.append("----- RESULT: %f -----" % result, ll)
| Python | zaydzuhri_stack_edu_python |
from flask import Flask , request , jsonify
from flask_sqlalchemy import SQLAlchemy
import uuid
import hashlib
set app = call Flask __name__
decorator call route string /register methods=list string POST
function register
begin
comment Get form data
set data = call get_json
set public_id = string uuid 4
set username = ... | from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import uuid
import hashlib
app = Flask(__name__)
@app.route('/register', methods=['POST'])
def register():
# Get form data
data = request.get_json()
public_id = str(uuid.uuid4())
username = data['username']
password = data['passwor... | Python | iamtarun_python_18k_alpaca |
import math
set N = integer input
set ans = 0
comment for i in range(1, N+1):
comment ans +=i
comment print(ans)
print call factorial N | import math
N = int(input())
ans = 0
# for i in range(1, N+1):
# ans +=i
# print(ans)
print(math.factorial(N)) | Python | zaydzuhri_stack_edu_python |
string Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and in... | """
Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found.
Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as
possible, and... | Python | zaydzuhri_stack_edu_python |
function has_section self section
begin
return call has_section section
end function | def has_section(self, section):
return self.configparser.has_section(section) | Python | nomic_cornstack_python_v1 |
function agent_player env_name ip
begin
comment Create the main generator
set receiver_gen = call atari_frames_generator env_name ip
comment Loop
while true
begin
comment Receive
set tuple frame termination = next receiver_gen
comment Skip if repeated
assert termination in tuple string continue string last string repea... | def agent_player(env_name, ip):
# Create the main generator
receiver_gen = atari_frames_generator(env_name, ip)
# Loop
while True:
# Receive
frame, termination = next(receiver_gen)
# Skip if repeated
assert termination in ("continue", "last", "repeated_last")
... | Python | nomic_cornstack_python_v1 |
from flask import abort , jsonify , request
from marshmallow import fields , validate
from werkzeug.urls import Href
set pagination_args = dict string limit integer missing=20 validate=range min=1 ; string offset integer missing=0 validate=range min=0
function paged_response query args serialize_fn maximum_limit=none
b... | from flask import abort, jsonify, request
from marshmallow import fields, validate
from werkzeug.urls import Href
pagination_args = {
'limit': fields.Int(missing=20, validate=validate.Range(min=1)),
'offset': fields.Int(missing=0, validate=validate.Range(min=0))
}
def paged_response(query, args, serialize_f... | Python | zaydzuhri_stack_edu_python |
import os
import random
import numpy as np
function char_byte str_
begin
return length encode str_ string utf-8
end function
function read_dict path
begin
with open path as fs
begin
set lines = list comprehension split line string at 0 for line in read lines fs
end
return lines
end function
function save_dict dict_ sav... | import os
import random
import numpy as np
def char_byte(str_):
return len(str_.encode("utf-8"))
def read_dict(path):
with open(path) as fs:
lines = [line.split('\n')[0] for line in fs.readlines()]
return lines
def save_dict(dict_, save_path):
with open(save_path, "a") as fs:
fs.write... | Python | zaydzuhri_stack_edu_python |
function build_patch_discriminator self model_shape filters=32 k_size=4 drop=false rate=0.5 summary=false model_file=none name=string gan_d_
begin
if model_file
begin
string Load pretreined model
set model = call build_pretrained_model model_file
if summary
begin
call summary
end
return model
end
else
begin
string Crea... | def build_patch_discriminator(self, model_shape, filters=32, k_size=4, drop=False, rate=0.5, summary=False, model_file=None, name='gan_d_'):
if (model_file):
"""
Load pretreined model
"""
model = self.utils.build_pretrained_model(model_file)
if (summar... | Python | nomic_cornstack_python_v1 |
from datetime import datetime
function get_remaining_days_from_datetime time
begin
set A = replace time hour=0 minute=0 second=0 microsecond=0
set timezone_info = tzinfo
set B = now timezone_info
if days < 0
begin
return - 1
end
return days
end function | from datetime import datetime
def get_remaining_days_from_datetime(time):
A = time.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
timezone_info = time.tzinfo
B = datetime.now(timezone_info)
if((A - B).days < 0):
return -1
return (A - B).days | Python | zaydzuhri_stack_edu_python |
import random
import numpy as np
import torch
from scipy.optimize import linear_sum_assignment
from torch.utils.data import Dataset , DataLoader
from torch_struct import SemiMarkov , MaxSemiring
from models.semimarkov.semimarkov_modules import SemiMarkovModule
comment device = torch.device("cuda")
set device = device s... | import random
import numpy as np
import torch
from scipy.optimize import linear_sum_assignment
from torch.utils.data import Dataset, DataLoader
from torch_struct import SemiMarkov, MaxSemiring
from models.semimarkov.semimarkov_modules import SemiMarkovModule
# device = torch.device("cuda")
device = torch.device("cpu... | Python | zaydzuhri_stack_edu_python |
import sys , re
import argparse
function main
begin
set parser = call ArgumentParser description=string Weight viewer.
call add_argument string --input help=string The input file to be evaluated. nargs=string + default=list string -
call add_argument string --sorted help=string Sort. action=string store_true
set pa = c... | import sys, re
import argparse
def main():
parser = argparse.ArgumentParser( description="Weight viewer." )
parser.add_argument("--input", help="The input file to be evaluated.", nargs="+", default=["-"])
parser.add_argument("--sorted", help="Sort.", action="store_true")
pa = parser.parse_args()
for f_input in p... | Python | zaydzuhri_stack_edu_python |
string Event loop
import asyncio
import random
import config
async function read_sensor id
begin
set con = true
while con == true
begin
set value = random integer 1 100
if value > 50
begin
comment syncio.gather.cancel()
print string sensor { id } is { value }
print string valve is close
break
end
else
begin
print strin... | """
Event loop
"""
import asyncio
import random
import config
async def read_sensor(id):
con = True
while con == True:
value = random.randint(1, 100)
if value > 50:
#syncio.gather.cancel()
print(f"sensor {id} is {value}")
print(f"valve is close")
... | Python | zaydzuhri_stack_edu_python |
function content_size self
begin
return get get call _get_hcell string metadata dict string content_size
end function | def content_size(self):
return self._get_hcell().get("metadata", {}).get("content_size") | Python | nomic_cornstack_python_v1 |
function set_hosts self hypervisor_per_cluster=false
begin
set conf at string hosts = set
set tuple host_patterns host_others = call _sift_patterns get conf string hosts_list
set datacenter_patterns = get conf string datacenter list
set cluster_patterns = get conf string cluster list
if host_patterns
begin
set conf at ... | def set_hosts(self, hypervisor_per_cluster=False):
self.conf['hosts'] = set()
host_patterns, host_others = self._sift_patterns(
self.conf.get('hosts_list')
)
datacenter_patterns = self.conf.get('datacenter', [])
cluster_patterns = self.conf.get('cluster', [])
... | Python | nomic_cornstack_python_v1 |
function graph_runtimes_best length_lst repeats
begin
set merge_avg = list
set timsort_avg = list
set theory_time = list 0
for i in range 1 length_lst
begin
append theory_time i * log i / 1000000
end
for i in range length_lst
begin
set merge_lst = list
set timsort_lst = list
for x in range repeats
begin
comment Her... | def graph_runtimes_best(length_lst, repeats):
merge_avg = []
timsort_avg = []
theory_time = [0]
for i in range(1, length_lst):
theory_time.append(i*math.log(i)/1000000)
for i in range(length_lst):
merge_lst = []
timsort_lst = []
for x in range(repeats):... | Python | nomic_cornstack_python_v1 |
string Audio Trainer v1.0
comment import of own scripts
import os
comment import of own scripts
import functions as f
import config as conf
comment manages all models that have been computed
function main
begin
set userWantNotToQuit = true
set models = call loadModels
while userWantNotToQuit
begin
print string Currentl... | """Audio Trainer v1.0"""
# import of own scripts
import os
# import of own scripts
import functions as f
import config as conf
#manages all models that have been computed
def main():
userWantNotToQuit = True
models = f.loadModels()
while userWantNotToQuit:
print("Currently stored models:")
... | Python | zaydzuhri_stack_edu_python |
function test_occasion_solde_des_membres self
begin
set tuple a b c = all
assert equal call solde_des_membres list tuple 3 a tuple 0 b tuple - 3 c
end function | def test_occasion_solde_des_membres(self):
a, b, c = User.objects.all()
self.assertEqual(
Occasion.objects.first().solde_des_membres(), [(3, a), (0, b), (-3, c)]
) | Python | nomic_cornstack_python_v1 |
function send self message
begin
if is instance message tuple str bytes
begin
set message = call AsciiCommand message
end
comment Always send the AsciiCommand to *this* axis.
set axis_number = number
set reply = call send message
if axis_number != number
begin
raise call UnexpectedReplyError format string Received a re... | def send(self, message):
if isinstance(message, (str, bytes)):
message = AsciiCommand(message)
# Always send the AsciiCommand to *this* axis.
message.axis_number = self.number
reply = self.parent.send(message)
if reply.axis_number != self.number:
raise U... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return message
end function | def __repr__(self):
return self.message | Python | nomic_cornstack_python_v1 |
function get_compound_df df
begin
set columns = dict string Name string analyte ; string Amount string measurement
rename columns=columns inplace=true
set df_compound = copy df at string Compound
set loc at tuple is null analyte ? measurement > 0 string analyte = string wildcard
drop missing df_compound subset=list str... | def get_compound_df(df):
columns = {'Name':'analyte', 'Amount': 'measurement'}
df['Compound'].rename(columns=columns, inplace=True)
df_compound = df['Compound'].copy()
df_compound.loc[(df_compound.analyte.isnull()) & (df_compound.measurement > 0), 'analyte'] = 'wildcard'
df_compound.dropna(subset = ... | Python | nomic_cornstack_python_v1 |
comment 가로 방향의 검은 돌이 5개 있는지 확인
for i in range 19
begin
for j in range 19
begin
if arr at i at j == 1
begin
set cnt1 = cnt1 + 1
end
else
if cnt1 == 5
begin
set result = 1
append grid i
append grid j - 5
break
end
else
begin
set cnt1 = 0
end
end
end
comment 가로방향 하얀돌 탐색
set cnt2 = 0
comment 가로 방향의 하얀 돌이 5개 있는지 확인
for k in... | for i in range(19): #가로 방향의 검은 돌이 5개 있는지 확인
for j in range(19):
if arr[i][j] == 1:
cnt1 += 1
else:
if cnt1 == 5:
result = 1
grid.append(i)
grid.append(j - 5)
break
else:
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment _*_ coding: utf-8 _*_
string <File Description> File Name : polygon.py Author : Kim Ki-hwan (wbkifun@korea.ac.kr) Kim, KyoungHo (rain_woo@korea.ac.kr) Written date : 2008. 2. 26 Copyright : GNU GPL ============================== < File Description > =========================== Defin... | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
"""
<File Description>
File Name : polygon.py
Author : Kim Ki-hwan (wbkifun@korea.ac.kr)
Kim, KyoungHo (rain_woo@korea.ac.kr)
Written date : 2008. 2. 26
Copyright : GNU GPL
============================== < File Description > ===========================
... | Python | zaydzuhri_stack_edu_python |
function serialize_numpy self buff numpy
begin
try
begin
set _x = self
write buff call pack seq secs nsecs
set _x = frame_id
set length = length _x
if python3 or type _x == unicode
begin
set _x = encode _x string utf-8
set length = length _x
end
write buff call pack string <I%ss % length length _x
set _x = self
write b... | def serialize_numpy(self, buff, numpy):
try:
_x = self
buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
_x = self.header.frame_id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
... | Python | nomic_cornstack_python_v1 |
function _addTaggedInterfaces self host port portDict
begin
set vlanDict = call __getdefaultVlan host port portDict
set portName = call getSwitchPortName host port
comment Replace virtual port name to real portname if defined
if call has_option host string port_ { portName } _realport
begin
set portName = config at str... | def _addTaggedInterfaces(self, host, port, portDict):
vlanDict = self.__getdefaultVlan(host, port, portDict)
portName = self.switch.getSwitchPortName(host, port)
# Replace virtual port name to real portname if defined
if self.config.has_option(host, f'port_{portName}_realport'):
... | Python | nomic_cornstack_python_v1 |
function rank cards
begin
set tuple number suite = call create_num_suite cards
set suite_set = set suite
comment checking if all cards are of Same Suite
if length suite_set == 1
begin
comment Checking Royal Flush
if call check_increasing number == string royal
begin
return 10
end
else
comment checking Straight Flush
if... | def rank(cards):
number, suite = create_num_suite(cards)
suite_set = set(suite)
# checking if all cards are of Same Suite
if len(suite_set) == 1:
# Checking Royal Flush
if check_increasing(number) == 'royal':
return 10
# checking Straight Flush
elif check_incr... | Python | nomic_cornstack_python_v1 |
function post self
begin
set title = get request string title
set blogPost = get request string blogPost
set author = get cookies string name
if title and blogPost
begin
set bp = call Blogposts parent=call blog_key title=title blogPost=blogPost author=call check_secure_val author
put
call redirect string /%s % string c... | def post(self):
title = self.request.get("title")
blogPost = self.request.get("blogPost")
author = self.request.cookies.get('name')
if title and blogPost:
bp = Blogposts(parent=blog_key(), title=title,
blogPost=blogPost, author=check_secure_val(a... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment Author: Valentyn Kofanov (knu)
comment Created: 12/1/18
class NodeForQueue
begin
string Вспомогательный класс узел очереди
function __init__ self item=none
begin
comment нагрузка (значение) элемента
set item = item
comment ссылка на следующий в очереди
set next... | #!/usr/bin/env python
# coding: utf-8
# Author: Valentyn Kofanov (knu)
# Created: 12/1/18
class NodeForQueue:
"""
Вспомогательный класс
узел очереди
"""
def __init__(self, item=None):
self.item = item # нагрузка (значение) элемента
self.next = None # ссылка на следующий в очереди... | Python | zaydzuhri_stack_edu_python |
function dummy_ptrtype *args
begin
return call dummy_ptrtype *args
end function | def dummy_ptrtype(*args):
return _ida_hexrays.dummy_ptrtype(*args) | Python | nomic_cornstack_python_v1 |
for i in range length string
begin
print string at i
end | for i in range(len(string)):
print(string[i])
| Python | zaydzuhri_stack_edu_python |
function createTomaytoKeymap callbackName=string tomaytoCB nameCommandPrefix=string tomayto **kwargs
begin
for key in allKeys
begin
for a in list false true
begin
for c in list false true
begin
set modTag = if expression a then string _alt else string + if expression c then string _ctrl else string
set nameCommandNam... | def createTomaytoKeymap (callbackName="tomaytoCB", nameCommandPrefix="tomayto", **kwargs):
for key in allKeys:
for a in [False, True]:
for c in [False, True]:
modTag = ("_alt" if a else "") + ("_ctrl" if c else "")
nameCommandName = nameCommandPrefix + (modTag if ... | Python | nomic_cornstack_python_v1 |
function check_nas df column
begin
set count_nas = sum
set percentage_nas = count_nas / 30000
return tuple count_nas percentage_nas
end function
function unique_values df column
begin
set count_unique_values = value counts df at column
set percentage_unique_values = count_unique_values / shape at 0 - sum
return tuple c... | def check_nas(df, column):
count_nas = df[column].isna().sum()
percentage_nas = count_nas / 30000
return count_nas, percentage_nas
def unique_values(df, column):
count_unique_values = df[column].value_counts()
percentage_unique_values = count_unique_values / (df.shape[0] - df[column].isna().sum())
... | Python | zaydzuhri_stack_edu_python |
function __is_unbounded_negative_event pattern negation_operator
begin
if call get_top_operator != SeqOperator
begin
return true
end
comment for a sequence pattern, a negative event is unbounded if no positive events follow it
comment the implementation below assumes a flat sequence
set sequence_elements = call get_arg... | def __is_unbounded_negative_event(pattern: Pattern, negation_operator: NegationOperator):
if pattern.full_structure.get_top_operator() != SeqOperator:
return True
# for a sequence pattern, a negative event is unbounded if no positive events follow it
# the implementation below assume... | Python | nomic_cornstack_python_v1 |
string remote controller
class RemoteControlReadings extends object
begin
string class for accessing remote controller
function __init__ self address
begin
from ev3dev.core import RemoteControl , InfraredSensor
set sensor = call RemoteControl call InfraredSensor address=address
end function
function read_value self
beg... | """remote controller"""
class RemoteControlReadings(object):
"""class for accessing remote controller"""
def __init__(self, address):
from ev3dev.core import RemoteControl, InfraredSensor
self.sensor = RemoteControl(InfraredSensor(address=address))
def read_value(self):
"""read the... | Python | zaydzuhri_stack_edu_python |
function datumRisicoanalyse self
begin
return waarde
end function | def datumRisicoanalyse(self):
return self._datumRisicoanalyse.waarde | Python | nomic_cornstack_python_v1 |
function cmb n r mod
begin
if r < 0 or r > n
begin
return 0
end
set r = min r n - r
return g1 at n * g2 at r * g2 at n - r % mod
end function
comment 元テーブル
set g1 = list 1 1
comment 逆元テーブル
set g2 = list 1 1
comment 逆元テーブル計算用テーブル
set inverse = list 0 1
for i in range 2 n + 1
begin
append g1 g1 at - 1 * i % mod
append in... | def cmb(n, r, mod):
if (r<0 or r>n):
return 0
r = min(r, n-r)
return g1[n] * g2[r] * g2[n-r] % mod
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル
for i in range(2, n+1):
g1.append( (g1[-1] * i ) % mod )
inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
g... | Python | zaydzuhri_stack_edu_python |
function binary_search nums val
begin
set low = 0
set high = length nums - 1
while low <= high
begin
set mid = low + high // 2
if nums at mid == val
begin
return mid
end
else
if nums at mid > val
begin
set high = mid - 1
end
else
begin
set low = mid + 1
end
end
return - 1
end function | def binary_search(nums, val):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == val:
return mid
elif nums[mid] > val:
high = mid - 1
else:
low = mid + 1
return -1 | Python | iamtarun_python_18k_alpaca |
comment Calculate distance between two points
function findDistance x1 x2
begin
return absolute x2 - x1
end function
set x1 = - 3
set x2 = 4
set distance = call findDistance x1 x2
print string Distance: distance | # Calculate distance between two points
def findDistance(x1, x2):
return abs(x2 - x1)
x1 = -3
x2 = 4
distance = findDistance(x1, x2)
print("Distance:", distance) | Python | iamtarun_python_18k_alpaca |
function test_rshift_basic_num_array_none_c2 self
begin
for testval in data1param
begin
with call subTest msg=string Failed with parameter testval=testval
begin
comment Copy the array so we don't change the original data.
set datay = copy copy data2
set pydataout = list comprehension call pyshift testval x for x in dat... | def test_rshift_basic_num_array_none_c2(self):
for testval in self.data1param:
with self.subTest(msg='Failed with parameter', testval = testval):
# Copy the array so we don't change the original data.
datay = copy.copy(self.data2)
pydataout = [self.pyshift(testval, x) for x in datay]
expected = p... | Python | nomic_cornstack_python_v1 |
function extractEachKth inputArray k
begin
set result = list
for tuple index number in enumerate inputArray
begin
if index + 1 % k != 0
begin
append result number
end
end
return result
end function | def extractEachKth(inputArray, k):
result = []
for index, number in enumerate(inputArray):
if (index+1) % k != 0:
result.append(number)
return result
| Python | zaydzuhri_stack_edu_python |
import os
import gspread
from gplus import ClientPlus
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials
from flask import Flask , render_template
set application = call Flask __name__ static_url_path=string /static
set CURRENT_DIR = directory name path real path path __fil... | import os
import gspread
from gplus import ClientPlus
from datetime import datetime
from oauth2client.service_account import ServiceAccountCredentials
from flask import Flask, render_template
application = Flask(__name__, static_url_path='/static')
CURRENT_DIR = os.p... | Python | zaydzuhri_stack_edu_python |
function bid_volumes self
begin
return list comprehension decimal bid at 1 for bid in __bid
end function | def bid_volumes(self):
return [float(bid[1]) for bid in self.__bid] | Python | nomic_cornstack_python_v1 |
from enum import Enum
class InvalidTriangle extends Exception
begin
pass
end class
class TriangleType extends Enum
begin
set EQUILATERAL = 1
set ISOSCELES = 2
set SCALENE = 3
end class
class Triangle
begin
function __init__ self sideA sideB sideC
begin
if sideA <= 0 or sideB <= 0 or sideC <= 0
begin
raise InvalidTriang... | from enum import Enum
class InvalidTriangle(Exception):
pass
class TriangleType(Enum):
EQUILATERAL = 1
ISOSCELES = 2
SCALENE = 3
class Triangle:
def __init__(self, sideA, sideB, sideC):
if(sideA <= 0 or sideB <= 0 or sideC <= 0):
raise InvalidTriangle
if(
... | Python | zaydzuhri_stack_edu_python |
function load self path
begin
load state dict self load torch path
end function | def load(self, path):
self.load_state_dict(torch.load(path)) | Python | nomic_cornstack_python_v1 |
function test_collect_scripts__filter_toversion self module_repo
begin
set expected_result = set literal tuple string QRadar true
set test_input = list dict string DummyScript dict string name string DummyScript ; string file_path string dummy_path ; string depends_on list string qradar-searches ; string pack string du... | def test_collect_scripts__filter_toversion(self, module_repo):
expected_result = {("QRadar", True)}
test_input = [
{
"DummyScript": {
"name": "DummyScript",
"file_path": "dummy_path",
"depends_on": [
... | Python | nomic_cornstack_python_v1 |
import cv2 as cv
import matplotlib.pyplot as plt
set img = call imread string img/cat.jpg
image show string Cat img
comment Color space are space of color, a system to represent
comment pixel of colors. RGB, HSV, LAB are all color spaces
comment and we can convert between different color spaces
comment BGR is the defau... | import cv2 as cv
import matplotlib.pyplot as plt
img = cv.imread('img/cat.jpg')
cv.imshow('Cat', img)
# Color space are space of color, a system to represent
# pixel of colors. RGB, HSV, LAB are all color spaces
# and we can convert between different color spaces
# BGR is the default opencv color space and we can c... | Python | zaydzuhri_stack_edu_python |
function send_clicked self
begin
set mythread = call MyThread integer call text
start mythread
end function | def send_clicked(self):
self.mythread = MyThread(int(self.num_object.text()))
self.mythread.start() | Python | nomic_cornstack_python_v1 |
import subprocess
function grep_txt_files
begin
try
begin
set ls = popen list string ls string -alh stdout=PIPE
set grep = popen list string grep string txt stdin=stdout stdout=PIPE
close stdout
return decode communicate grep at 0 string utf-8
end
except Exception as e
begin
return string Error: { e }
end
end function
... | import subprocess
def grep_txt_files():
try:
ls = subprocess.Popen(['ls', '-alh'], stdout=subprocess.PIPE)
grep = subprocess.Popen(['grep', 'txt'], stdin=ls.stdout, stdout=subprocess.PIPE)
ls.stdout.close()
return grep.communicate()[0].decode('utf-8')
except Exception as e:
... | Python | flytech_python_25k |
function floorTB1Checked self state
begin
if state == Checked
begin
print string Show TB1 Floor Selected
end
else
begin
comment # release video capture
comment self.cap = cv2.VideoCapture(0)
comment # read image in BGR format
comment ret, img = self.cap.read()
comment image = QtGui.QImage(img, img.shape[1], img.shape[0... | def floorTB1Checked(self, state):
if state == QtCore.Qt.Checked:
print('Show TB1 Floor Selected')
# # release video capture
# self.cap = cv2.VideoCapture(0)
# # read image in BGR format
# ret, img = self.cap.read()
# image = QtGui.QImage(im... | Python | nomic_cornstack_python_v1 |
comment -*- coding utf-8 -*-
from collections import Iterable
comment D= {"name": "flack", "age": 23, "city": "beijing", "job": "IT"}
comment # 迭代的key
comment for x in D:
comment print("%s = %s" % (x, D[x]))
comment for x in D.values():
comment print("%s" % x)
comment for x,y in D.items():
comment print("%s = %s" % (x,... | # -*- coding utf-8 -*-
from collections import Iterable
#
# D= {"name": "flack", "age": 23, "city": "beijing", "job": "IT"}
#
# # 迭代的key
# for x in D:
# print("%s = %s" % (x, D[x]))
#
# for x in D.values():
# print("%s" % x)
#
# for x,y in D.items():
# print("%s = %s" % (x, y))
#
#
#
# ... | Python | zaydzuhri_stack_edu_python |
function __exit__ self exc_type exc_value traceback
begin
close self
comment any exception is raised by the with statement.
return false
end function | def __exit__(self, exc_type, exc_value, traceback):
self.close()
return False # any exception is raised by the with statement. | Python | nomic_cornstack_python_v1 |
from itertools import product
from copy import deepcopy
set tuple h w k = map int split input
set c = list comprehension list input for _ in range h
set ans = 0
for hl in product list 0 1 repeat=h
begin
for wl in product list 0 1 repeat=w
begin
set cnt = 0
set cc = deep copy c
for tuple ci hi in zip c hl
begin
for tupl... | from itertools import product
from copy import deepcopy
h, w, k = map(int, input().split())
c = [list(input()) for _ in range(h)]
ans = 0
for hl in product([0, 1], repeat=h):
for wl in product([0, 1], repeat=w):
cnt = 0
cc = deepcopy(c)
for ci, hi in zip(c, hl):
for cij, wj in ... | Python | zaydzuhri_stack_edu_python |
function get_ftest_score data
begin
set labels = array data at 0 dtype=string float
set features = array data at slice 1 : : dtype=string float
print string Shape of label input: shape
print string Shape of feature input: shape
set class_ids = set labels
set f_test_scores = list
for row in features
begin
set row_sum... | def get_ftest_score(data):
labels = np.array(data[0],dtype='float')
features = np.array(data[1:],dtype='float')
print('Shape of label input: ', labels.shape)
print('Shape of feature input: ', features.shape)
class_ids = set(labels)
f_test_scores = []
for row in features:
row_summ... | Python | nomic_cornstack_python_v1 |
function apply_updates self update_action
begin
for tuple k v in items updated_known_properties
begin
set attribute self k v
end
for item in updated_unknown_properties
begin
if item not in CASE_TAGS
begin
set self at item = call couchable_property updated_unknown_properties at item
end
end
end function | def apply_updates(self, update_action):
for k, v in update_action.updated_known_properties.items():
setattr(self, k, v)
for item in update_action.updated_unknown_properties:
if item not in const.CASE_TAGS:
self[item] = couchable_property(update_action.upd... | Python | nomic_cornstack_python_v1 |
comment Sudoku Solver
import numpy as np
set grid = list list 0 0 0 9 0 2 7 0 0 list 0 5 0 0 4 0 0 0 0 list 6 0 0 0 0 8 0 4 0 list 0 4 0 0 0 7 0 0 8 list 7 0 8 0 5 0 2 0 3 list 9 0 0 2 0 0 0 1 0 list 0 2 0 3 0 0 0 0 1 list 0 0 0 0 2 0 0 3 0 list 0 0 3 7 0 1 0 0 0
function validPos y x n
begin
global grid
for i in range... | ## Sudoku Solver
import numpy as np
grid = [[0, 0, 0, 9, 0, 2, 7, 0, 0],
[0, 5, 0, 0, 4, 0, 0, 0, 0],
[6, 0, 0, 0, 0, 8, 0, 4, 0],
[0, 4, 0, 0, 0, 7, 0, 0, 8],
[7, 0, 8, 0, 5, 0, 2, 0, 3],
[9, 0, 0, 2, 0, 0, 0, 1, 0],
[0, 2, 0, 3, 0, 0, 0, 0, 1],
[0, 0, ... | Python | zaydzuhri_stack_edu_python |
class cached_property extends object
begin
string A property this is cached this function compute once.
function __init__ self wrapped name=none
begin
set wrapped = wrapped
set __doc__ = get attribute wrapped string __doc__ none
set name = name or string _ + __name__
end function
function __get__ self inst cls
begin
if... | class cached_property(object):
"""
A property this is cached this function compute once.
"""
def __init__(self, wrapped, name=None):
self.wrapped = wrapped
self.__doc__ = getattr(wrapped, '__doc__', None)
self.name = name or '_' + wrapped.__name__
def __get__(self, inst, cl... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import time
import socket
comment The server's hostname or IP address
set HOST = string 127.0.0.1
comment The port used by the server
set PORT = 8080
set buffer_size = 1024
print string Leer archivo
set elije = input string Elija alguna opcion: 1.-Biblia 2.-Hamlet 3.-MobyDick
if elije == s... | #!/usr/bin/env python3
import time
import socket
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 8080 # The port used by the server
buffer_size = 1024
print("Leer archivo")
elije = input("Elija alguna opcion: 1.-Biblia 2.-Hamlet 3.-MobyDick")
if elije=="1":
archivo = open("/home/melisa/Escritorio/... | Python | zaydzuhri_stack_edu_python |
function save_transaction sender **kwargs
begin
set ipn_obj = sender
if payment_status == ST_PP_COMPLETED
begin
comment WARNING !
comment Check that the receiver email is the same we previously
comment set on the business field request. (The user could tamper
comment with those fields on payment form before send it to ... | def save_transaction(sender, **kwargs):
ipn_obj = sender
if ipn_obj.payment_status == ST_PP_COMPLETED:
# WARNING !
# Check that the receiver email is the same we previously
# set on the business field request. (The user could tamper
# with those fields on payment form before send... | Python | nomic_cornstack_python_v1 |
from numpy import zeros , array , matrix
from scipy.linalg import toeplitz
function minabs x y
begin
comment Returns the argument with the lowest norm
if absolute x > absolute y
begin
return y
end
else
begin
return x
end
end function
function max_offdiag M
begin
comment Loops through the off-diagonal elements of a matr... | from numpy import zeros, array, matrix
from scipy.linalg import toeplitz
def minabs(x, y):
# Returns the argument with the lowest norm
if abs(x) > abs(y):
return y
else:
return x
def max_offdiag(M):
# Loops through the off-diagonal elements of a matrix M and returns
# the indices of the element with the lar... | Python | zaydzuhri_stack_edu_python |
function makeSnakeTrajectory line startTrajectory stepSize
begin
comment startTrajectory = randomAlgorithm.randomTrajectory(emptyTrajectory, 20)
if length Raillist == 0
begin
call addHighestRailInTrajectory startTrajectory
end
for steps in range stepSize
begin
comment determine temperature for simmulated annealing
set ... | def makeSnakeTrajectory(line, startTrajectory, stepSize):
# startTrajectory = randomAlgorithm.randomTrajectory(emptyTrajectory, 20)
if len(startTrajectory.Raillist) == 0:
line.addHighestRailInTrajectory(startTrajectory)
for steps in range(stepSize):
# determine temperature for simmulated ... | Python | nomic_cornstack_python_v1 |
function get_spike_frequency_adaptation t V
begin
comment check that there are 2 spikes minimum
set intervals = call interspike_intervals t V
call raise_if_not_multiple_spikes intervals
return intervals at - 1 / intervals at 0
end function | def get_spike_frequency_adaptation(t, V):
# check that there are 2 spikes minimum
intervals = interspike_intervals(t, V)
raise_if_not_multiple_spikes(intervals)
return intervals[-1]/intervals[0] | Python | nomic_cornstack_python_v1 |
function system_vlan_num_lt self system_vlan_num_lt
begin
set _system_vlan_num_lt = system_vlan_num_lt
end function | def system_vlan_num_lt(self, system_vlan_num_lt):
self._system_vlan_num_lt = system_vlan_num_lt | Python | nomic_cornstack_python_v1 |
import requests
from string import ascii_lowercase , ascii_uppercase
from time import sleep , perf_counter
import sys
set s = call Session
set auth = tuple string natas17 string 8Ps3H0GWbn5rd9S7GmAdgQNdkhPkq9cw
set url = string http://natas17.natas.labs.overthewire.org/index.php
set GAP = 5
function confirm query s
beg... | import requests
from string import ascii_lowercase, ascii_uppercase
from time import sleep, perf_counter
import sys
s=requests.Session()
auth=('natas17','8Ps3H0GWbn5rd9S7GmAdgQNdkhPkq9cw')
url='http://natas17.natas.labs.overthewire.org/index.php'
GAP=5
def confirm(query,s):
start = perf_counter()
r=s.post(url... | Python | zaydzuhri_stack_edu_python |
import copy
import numpy as np
from base_solver import BaseSolver
from line_search import LineSearchMethod
class ConjugateGradientSolver extends BaseSolver
begin
function __init__ self fn x0 alpha iter=0 term_crit=string fn variant=string fr use_line_search=false ls_method_kwargs=none
begin
set variant = variant
set n ... | import copy
import numpy as np
from .base_solver import BaseSolver
from line_search import LineSearchMethod
class ConjugateGradientSolver(BaseSolver):
def __init__(
self,
fn,
x0,
alpha,
iter=0,
term_crit='fn',
variant='fr',
use_line_search=False,
... | Python | zaydzuhri_stack_edu_python |
function get_timeseries
begin
set ts_client = call DBClient 50000
set request_string = args
set msg = dict
for arg in request_string
begin
set arg_vals = call parse_query arg request_string at arg
comment filter by mean in
if arg == string mean_in
begin
comment ts_queried = Timeseries
comment call for response
set msg... | def get_timeseries():
ts_client = DBClient(50000)
request_string = request.args
msg = {}
for arg in request_string:
arg_vals = parse_query(arg, request_string[arg])
#filter by mean in
if arg == 'mean_in':
# ts_queried = Timeseries
# call for response
... | Python | nomic_cornstack_python_v1 |
function new cls string=none
begin
comment Generates warner ECDSA objects
if string
begin
comment deterministic private key
set ecdsaPrivkey = call from_string string=string curve=SECP256k1
end
else
begin
comment random private key
set ecdsaPrivkey = call generate curve=SECP256k1 entropy=none
end
return call fromPrivke... | def new(cls, string=None):
# Generates warner ECDSA objects
if string:
# deterministic private key
ecdsaPrivkey = SigningKey.from_string(
string=string, curve=SECP256k1)
else:
# random private key
ecdsaPrivkey = SigningKey.generate(... | Python | nomic_cornstack_python_v1 |
function itkLevelSetMotionRegistrationFilterIUS3IUS3IVF33_cast obj
begin
return call itkLevelSetMotionRegistrationFilterIUS3IUS3IVF33_cast obj
end function | def itkLevelSetMotionRegistrationFilterIUS3IUS3IVF33_cast(obj: 'itkLightObject') -> "itkLevelSetMotionRegistrationFilterIUS3IUS3IVF33 *":
return _itkLevelSetMotionRegistrationFilterPython.itkLevelSetMotionRegistrationFilterIUS3IUS3IVF33_cast(obj) | Python | nomic_cornstack_python_v1 |
function get_assessment_part_query_session_for_bank self bank_id proxy
begin
if not call supports_assessment_part_query
begin
raise call Unimplemented
end
comment Also include check to see if the catalog Id is found otherwise raise errors.NotFound
comment pylint: disable=no-member
return call AssessmentPartQuerySession... | def get_assessment_part_query_session_for_bank(self, bank_id, proxy):
if not self.supports_assessment_part_query():
raise errors.Unimplemented()
##
# Also include check to see if the catalog Id is found otherwise raise errors.NotFound
##
# pylint: disable=no-member
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import time
from tabulate import tabulate as tbl
from ticobot.broker import Broker
from ticobot.env import Env
from ticobot.notify import Notify
from ticobot.indicators.main import Indicators
function worker broker size asset market bet expiration
begin
set candles = call getCandles asset size ... | #!/usr/bin/python
import time
from tabulate import tabulate as tbl
from ticobot.broker import Broker
from ticobot.env import Env
from ticobot.notify import Notify
from ticobot.indicators.main import Indicators
def worker(broker,size,asset,market,bet,expiration):
candles = broker.getCandles(asset,size,200)
ind... | Python | zaydzuhri_stack_edu_python |
function currency_id self currency_id
begin
set _currency_id = currency_id
end function | def currency_id(self, currency_id):
self._currency_id = currency_id | Python | nomic_cornstack_python_v1 |
function query self params
begin
set parsed_list = call parseFile
set filtered_groups = list
for item in parsed_list
begin
set isFiltered = true
comment if members is a query pam, check if members within params are in members of groups
if string member in keys params
begin
for member in params at string member
begin
i... | def query(self, params):
parsed_list = self.parseFile()
filtered_groups = []
for item in parsed_list:
isFiltered = True
# if members is a query pam, check if members within params are in members of groups
if "member" in params.keys():
fo... | Python | nomic_cornstack_python_v1 |
import numpy as np
from LinearRegression.LogitRegression import LogitRegression
class MultiLogitRegression
begin
function __init__ self x y
begin
set x = x
set y = y
set classes = unique y
set index = dict
for i in classes
begin
set index at i = where y == i at 0
end
set classifier = dict
end function
function fit se... | import numpy as np
from LinearRegression.LogitRegression import LogitRegression
class MultiLogitRegression:
def __init__(self, x, y):
self.x = x
self.y = y
self.classes = np.unique(self.y)
self.index = {}
for i in self.classes:
self.index[i] = np.where(y == i)[... | Python | zaydzuhri_stack_edu_python |
string test cases for Account
set __ver__ = string $Id: AccountTest.py,v 1.13 2006/07/02 06:08:09 sabren Exp $
import unittest
import duckbill
from duckbill.test import fakeAccount
from duckbill import Account , Event , Subscription , Grace
from pytypes import Date
class AccountTest extends TestCase
begin
function test... | """
test cases for Account
"""
__ver__="$Id: AccountTest.py,v 1.13 2006/07/02 06:08:09 sabren Exp $"
import unittest
import duckbill
from duckbill.test import fakeAccount
from duckbill import Account, Event, Subscription, Grace
from pytypes import Date
class AccountTest(unittest.TestCase):
def test_whenLastState... | Python | zaydzuhri_stack_edu_python |
function identify_system
begin
set system = call system
if system not in list string Linux string Darwin
begin
raise call ValueError string Unsupported system { system }
end
return system
end function | def identify_system() -> str:
system = platform.system()
if system not in ["Linux", "Darwin"]:
raise ValueError(f"Unsupported system {system}")
return system | Python | nomic_cornstack_python_v1 |
function findBestDegree self X_train X_test y_train y_test degreeNum=3
begin
set poly_features = call PolynomialFeatures degree=degreeNum
comment transforms the existing features to higher degree features.
set X_train_poly = fit transform poly_features X_train
comment fit the transformed features to Linear Regression
s... | def findBestDegree(self, X_train, X_test, y_train, y_test, degreeNum=3):
poly_features = PolynomialFeatures(degree=degreeNum)
# transforms the existing features to higher degree features.
X_train_poly = poly_features.fit_transform(X_train)
# fit the transformed features to Linear Regr... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Dec 17 15:22:04 2019 @author: KIIT
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
set dataset = read csv string 50_Startups.csv
comment ilco is use to select and [row,coloumn] (:)mns all and (:-1) mns all -1 i.e leaving last coloumn
set x = val... | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 17 15:22:04 2019
@author: KIIT
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset= pd.read_csv("50_Startups.csv")
x=dataset.iloc[:,:-1].values #ilco is use to select and [row,coloumn] (:)mns all and (:-1) mns all -1 i.e leaving last colou... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import prettytable
from classclass import Class
from config import Config
class DisplayMgr
begin
function __init__ self
begin
set data = call get_data
set course_columns = list string Subject string Number string Description string Meeting Pattern string Max Number Of Students string Prerequisites s... | import pandas as pd
import prettytable
from classclass import Class
from config import Config
class DisplayMgr:
def __init__(self):
self.data = Config.getInstance().get_data()
self.course_columns = ["Subject", "Number", "Description", "Meeting Pattern", "Max Number Of Students",
... | Python | zaydzuhri_stack_edu_python |
function _encode_and_sign self dict_payload encoding=string ascii
begin
set payload_bytes = encode dumps dict_payload encoding
set b64 = base64 encode payload_bytes
set creds = _api_credentials
set secret_bytes = encode api_secret encoding
set signature = hex digest call new secret_bytes b64 sha384
return tuple b64 sig... | def _encode_and_sign(self, dict_payload, encoding="ascii"):
payload_bytes = json.dumps(dict_payload).encode(encoding)
b64 = base64.b64encode(payload_bytes)
creds = self._api_credentials
secret_bytes = creds.api_secret.encode(encoding)
signature = hmac.new(secret_bytes, b64, sha38... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string Module for Task6
function from_json_string my_str
begin
string to return an object represented by a JSON string.
import json
return loads my_str
end function | #!/usr/bin/python3
"""Module for Task6"""
def from_json_string(my_str):
"""to return an object represented by a JSON string."""
import json
return json.loads(my_str)
| Python | zaydzuhri_stack_edu_python |
function __init__ self sgnum
begin
set sgnum = sgnum
end function | def __init__(self, sgnum):
self.sgnum = sgnum | Python | nomic_cornstack_python_v1 |
function get_drive_counts side pbp drives
begin
set pbp_drives = call agg dict string drive_id string nunique
rename dict string drive_id string pbp_drives axis=1 inplace=true
set drive_chart_drives = call agg dict string drive_id string nunique
rename dict string drive_id string drive_chart_drives axis=1 inplace=true
... | def get_drive_counts(side, pbp, drives):
pbp_drives = (
pbp[~(pbp["play_type"].str.contains("Kickoff"))]
.loc[pbp["offense"] == pbp[f"{side}_team"]]
.groupby("id")
.agg({"drive_id": "nunique"})
)
pbp_drives.rename({"drive_id": "pbp_drives"}, axis=1, inplace=True)
drive_ch... | Python | nomic_cornstack_python_v1 |
function cookies_per_bag total_cookies number_of_bags
begin
string Calculate the number of cookies in each bag.
return total_cookies // number_of_bags
end function
comment Example usage with the provided values
set total_cookies = 703
set number_of_bags = 37
set cookies_in_each_bag = call cookies_per_bag total_cookies ... | def cookies_per_bag(total_cookies, number_of_bags):
"""Calculate the number of cookies in each bag."""
return total_cookies // number_of_bags
# Example usage with the provided values
total_cookies = 703
number_of_bags = 37
cookies_in_each_bag = cookies_per_bag(total_cookies, number_of_bags)
print(cookies_in_ea... | Python | dbands_pythonMath |
function hexToRed self hex
begin
return integer hex at slice 0 : 2 : 16
end function | def hexToRed(self, hex):
return int(hex[0:2], 16) | Python | nomic_cornstack_python_v1 |
function draw recs path
begin
set dwg = call Drawing path size=tuple 100 100 profile=string tiny
comment Add seperating rectangles.
for rec in recs
begin
assert dim == 2
set tuple xlo ylo = bot
set tuple xhi yhi = top
comment Accept region. Top left corner.
set point = tuple round xlo * 100 0
set size = tuple round 100... | def draw(recs, path):
dwg = svgwrite.Drawing(path, size=(100, 100), profile='tiny')
# Add seperating rectangles.
for rec in recs:
assert rec.dim == 2
xlo, ylo = rec.bot
xhi, yhi = rec.top
# Accept region. Top left corner.
point = round(xlo * 100), 0
size = ... | Python | nomic_cornstack_python_v1 |
function test_fetch_or_create_disk_media_item_with_image_and_attributes db
begin
set data = read join datadir string 1200x6566.png mode=string rb
set im = call from_buffer data
set item = call fetch_or_create_media_item data file_type=string png im=im attributes=dict string spam string eggs
assert attributes == dict st... | def test_fetch_or_create_disk_media_item_with_image_and_attributes(db):
data = datadir.join('1200x6566.png').read(mode='rb')
im = images.from_buffer(data)
item = media.fetch_or_create_media_item(data, file_type='png', im=im, attributes={'spam': 'eggs'})
assert item.attributes == {'spam': 'eggs', 'width'... | Python | nomic_cornstack_python_v1 |
comment https://projecteuler.net/problem=3
comment Que: Largest prime factor
comment Ans: 6857
from lib.Math import is_prime , is_factor
set N = 600851475143
function gen_prime_factor n
begin
set tuple fact max_fact = tuple 2 0
end function | # https://projecteuler.net/problem=3
# Que: Largest prime factor
# Ans: 6857
from lib.Math import is_prime, is_factor
N = 600851475143
def gen_prime_factor(n):
fact, max_fact = 2, 0 | Python | zaydzuhri_stack_edu_python |
function run_aws_cli_command *args
begin
set cli_driver = call create_clidriver
set f_stderr = call StringIO
with redirect stderr f_stderr
begin
set return_code = call main args=args
end
set stderr = call getvalue
close f_stderr
if return_code
begin
raise call AWSCLIException args=args error_code=return_code stderr=std... | def run_aws_cli_command(*args: str):
cli_driver = create_clidriver()
f_stderr = io.StringIO()
with redirect_stderr(f_stderr):
return_code = cli_driver.main(args=args)
stderr = f_stderr.getvalue()
f_stderr.close()
if return_code:
raise AWSCLIException(args=args, error_code=retu... | 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.