code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment !/usr/bin/python3
import sys
import os
import subprocess
set args = argv
set argFile = split args at 1 string .
set question = upper argFile at 0
set language = argFile at 1
if language == string cpp
begin
print string cpp
set gccArgs = list string g++ string -std=c++17 string -o string a args at 1
try
begin
se... | #!/usr/bin/python3
import sys
import os
import subprocess
args = sys.argv
argFile = args[1].split('.')
question = (argFile[0]).upper()
language = argFile[1]
if language == "cpp":
print('cpp')
gccArgs = ['g++','-std=c++17','-o','a',args[1]]
try:
ret = subprocess.check_call(gccArgs)
except:
... | Python | zaydzuhri_stack_edu_python |
function main args unknown_args
begin
if hydra
begin
assert hydra_required msg string catalyst[hydra] requirements are not available, to install them, run `pip install catalyst[hydra]`.
end
if hydra
begin
remove argv string run
remove argv string --hydra
call hydra_main
end
else
begin
call config_main args unknown_args... | def main(args, unknown_args):
if args.hydra:
assert SETTINGS.hydra_required, (
"catalyst[hydra] requirements are not available, to install them,"
" run `pip install catalyst[hydra]`."
)
if args.hydra:
sys.argv.remove("run")
sys.argv.remove("--hydra")
... | Python | nomic_cornstack_python_v1 |
function remove_noise emg
begin
function butter_bandstop_filter data lowcut highcut fs order=2
begin
function butter_bandstop lowcut highcut fs order=2
begin
set nyq = 0.5 * fs
set low = lowcut / nyq
set high = highcut / nyq
set tuple b a = call butter order list low high btype=string bandstop
return tuple b a
end func... | def remove_noise(emg):
def butter_bandstop_filter(data, lowcut, highcut, fs, order=2):
def butter_bandstop(lowcut, highcut, fs, order=2):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='bandstop')
ret... | Python | nomic_cornstack_python_v1 |
function test_get_autoscaling_group_properties_valid_tag_name self
begin
set mock_asg_resource = call Mock name=string Mock Autoscaling Client
set return_value = dict string AutoScalingGroups list
set return_value = dict string Tags list dict string ResourceType string auto-scaling-group ; string ResourceId string alp... | def test_get_autoscaling_group_properties_valid_tag_name(self):
mock_asg_resource = Mock(name="Mock Autoscaling Client")
mock_asg_resource.describe_auto_scaling_groups.return_value = \
{
"AutoScalingGroups": [
]
}
mock_asg_resource.describe_tags.return_value = \
{
"Tags": [
... | Python | nomic_cornstack_python_v1 |
from sqlalchemy import create_engine , Column , VARCHAR , Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
set engine = call create_engine string mysql+pymysql://root:123456@localhost:3306/xhx?charset=utf8 echo=true
set Base = call declarative_base
class User extends ... | from sqlalchemy import create_engine, Column, VARCHAR, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine("mysql+pymysql://root:123456@localhost:3306/xhx?charset=utf8", echo=True)
Base = declarative_base()
class User(Base):
__tablename__ = ... | Python | zaydzuhri_stack_edu_python |
function _set_cr self cr
begin
set __cr = boolean cr
end function | def _set_cr(self, cr):
self.__cr = bool(cr) | Python | nomic_cornstack_python_v1 |
function get_std_stream_encoding
begin
set rv = call getdefaultencoding
if call is_ascii_encoding rv
begin
return string utf-8
end
return rv
end function | def get_std_stream_encoding():
rv = sys.getdefaultencoding()
if is_ascii_encoding(rv):
return 'utf-8'
return rv | Python | nomic_cornstack_python_v1 |
function execute helper config args
begin
string Deletes an environment
call delete_application
comment wait
if not dont_wait
begin
comment get environments
set environment_names = list
for env in call get_environments
begin
append environment_names env at string EnvironmentName
end
comment wait for them
call wait_for... | def execute(helper, config, args):
"""
Deletes an environment
"""
helper.delete_application()
# wait
if not args.dont_wait:
# get environments
environment_names = []
for env in helper.get_environments():
environment_names.append(env['EnvironmentName'])
... | Python | jtatman_500k |
function generate_visual_features_padding_masks data pad_value=0
begin
with no grad
begin
return unsqueeze to t dist device 1
end
end function | def generate_visual_features_padding_masks(data, pad_value=0):
with torch.no_grad():
return (data == pad_value).all(dim=-1).t().to(data.device).unsqueeze(1) | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
comment 1.此程序用于对收集的序列进行质量控制,其主要功能是检查序列的碱基组成,包括GC百分比/兼并碱基含量,特别是N碱基在序列中的占比以及N的分布类型
comment (分散型或是连续型);
comment 2.此程序参考GISAID数据库对测序覆盖度的评价体系,以1%和5%为分界线进行评价,N碱基含量小于1%则为高覆盖度序列(High coverage,H-C),N碱基
comment 含量大于等于1%且小于5%则为中覆盖度序列(Moderate coverage, M-C),N碱基含量大于等于5%则为地覆盖度序列(Low coverage,L-C);
comment 3.在数据... | #coding=utf-8
# 1.此程序用于对收集的序列进行质量控制,其主要功能是检查序列的碱基组成,包括GC百分比/兼并碱基含量,特别是N碱基在序列中的占比以及N的分布类型
# (分散型或是连续型);
# 2.此程序参考GISAID数据库对测序覆盖度的评价体系,以1%和5%为分界线进行评价,N碱基含量小于1%则为高覆盖度序列(High coverage,H-C),N碱基
# 含量大于等于1%且小于5%则为中覆盖度序列(Moderate coverage, M-C),N碱基含量大于等于5%则为地覆盖度序列(Low coverage,L-C);
# 3.在数据量足够大的前提下,可只选择H-C的序列入库,可根据实际情况酌... | Python | zaydzuhri_stack_edu_python |
function get_combinations list1 list2
begin
set combinations = list
for num1 in set list1
begin
for num2 in set list2
begin
append combinations list num1 num2
end
end
return combinations
end function
set list1 = list 1 2 2 3
set list2 = list 3 4 4 5
print call get_combinations list1 list2 | def get_combinations(list1, list2):
combinations = []
for num1 in set(list1):
for num2 in set(list2):
combinations.append([num1, num2])
return combinations
list1 = [1,2,2,3]
list2 = [3,4,4,5]
print(get_combinations(list1, list2))
| Python | jtatman_500k |
function age_ranges_number
begin
return integer AGE_RANGES_UPPER_THRESH / RANGE_LENGTH + 1
end function | def age_ranges_number():
return int(AGE_RANGES_UPPER_THRESH / RANGE_LENGTH) + 1 | Python | nomic_cornstack_python_v1 |
import altdeckeditor
comment возвращает информацию по профилю пользователя
function user_stat user_id
begin
try
begin
set f = open string profiles/ + string user_id + string .txt string r
end
comment если профиля нет, то создаётся новый
except any
begin
print string Создан новый профиль: + string user_id
set f = open s... | import altdeckeditor
def user_stat(user_id): # возвращает информацию по профилю пользователя
try:
f = open('profiles/' + str(user_id) + '.txt', 'r')
except: # если профиля нет, то создаётся новый
print("Создан новый профиль: " + str(user_id))
f = open('profiles/' + str(user_i... | Python | zaydzuhri_stack_edu_python |
function _add_igroup_member self connector igroup
begin
set v = vmem_vip
info call _ string Adding initiator %s to igroup connector at string initiator
set resp = call add_initiators igroup connector at string initiator
if resp at string code != 0
begin
raise error call _ string Failed to add igroup member: %(code)d, %... | def _add_igroup_member(self, connector, igroup):
v = self.vmem_vip
LOG.info(_("Adding initiator %s to igroup"), connector['initiator'])
resp = v.igroup.add_initiators(igroup, connector['initiator'])
if resp['code'] != 0:
raise exception.Error(
_('Failed to ... | Python | nomic_cornstack_python_v1 |
function get self
begin
set alias = get args string alias
set result = dictionary
set result at string message = string Hello, I am your backend
set result at string business_reviews = call business_reviews alias
return result
end function | def get(self):
alias = request.args.get('alias')
result = dict()
result['message'] = 'Hello, I am your backend'
result['business_reviews'] = business_reviews(alias)
return result | Python | nomic_cornstack_python_v1 |
function traverse_inorder self
begin
set result = call ArrayList
for item in self
begin
add result item
end
return result
end function | def traverse_inorder(self):
result = ArrayList()
for item in self:
result.add(item)
return result | Python | nomic_cornstack_python_v1 |
comment 통합
comment 1. 7days -> 2days
comment 2. 1day -> 2days
import pandas as pd
import numpy as np
import tensorflow as tf
import os
import glob
import random
import warnings
comment warning무시
filter warnings action=string ignore
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense... | # 통합
# 1. 7days -> 2days
# 2. 1day -> 2days
import pandas as pd
import numpy as np
import tensorflow as tf
import os
import glob
import random
import warnings
warnings.filterwarnings(action='ignore') #warning무시
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Den... | Python | zaydzuhri_stack_edu_python |
comment !/bin/env python3
comment -*- code:utf-8 -*-
import psutil
import time
comment 网卡,可以得到网卡属性,连接数,当前流量等信息
set net = call net_io_counters
print net
set bytes_sent = format string {0:.2f}Mb bytes_sent / 1024 / 1024
set bytes_rcvd = format string {0:.2f}Mb bytes_recv / 1024 / 1024
print string 网卡接收流量%s 网卡发送流量%s % tup... | #!/bin/env python3
#-*- code:utf-8 -*-
import psutil
import time
#网卡,可以得到网卡属性,连接数,当前流量等信息
net = psutil.net_io_counters()
print(net)
bytes_sent = '{0:.2f}Mb'.format(net.bytes_sent /1024/1024)
bytes_rcvd = '{0:.2f}Mb'.format(net.bytes_recv / 1024/1024)
print('网卡接收流量%s 网卡发送流量%s' % (bytes_rcvd, bytes_sent)) | Python | zaydzuhri_stack_edu_python |
function description self
begin
return get _fw_info_leaf_dict string description
end function | def description(self):
return self._fw_info_leaf_dict.get('description') | Python | nomic_cornstack_python_v1 |
function vm_size self
begin
return get pulumi self string vm_size
end function | def vm_size(self) -> Optional[str]:
return pulumi.get(self, "vm_size") | Python | nomic_cornstack_python_v1 |
import numpy
from termcolor import colored
import pygame
from pygame.locals import *
set sx = 512
set sy = 512
set colors = list string grey string red string green string yellow string blue string magenta string cyan string white
set attrs = list string on_grey string on_red string on_green string on_yellow string on_... | import numpy
from termcolor import colored
import pygame
from pygame.locals import *
sx=512
sy=512
colors = ['grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
attrs = ['on_grey', 'on_red', 'on_green', 'on_yellow', 'on_blue', 'on_magenta', 'on_cyan', 'on_white']
def draw_txt():
arr = numpy.ze... | Python | zaydzuhri_stack_edu_python |
function telescope_plane_coo_to_collimator_angle self x y
begin
set r2 = call square x + call square y
set fr2 = call square focal_r_curvature
set hm = focal_r_curvature - square root fr2 - r2
set d2 = pupil_distance + collimator_d
set cott = pupil_distance - hm / square root r2
set cott2 = call square cott
set k = 1.0... | def telescope_plane_coo_to_collimator_angle(self, x, y):
r2 = numpy.square(x) + numpy.square(y)
fr2 = numpy.square(self.focal_r_curvature)
hm = self.focal_r_curvature - numpy.sqrt(fr2-r2)
d2 = self.pupil_distance + self.collimator_d
cott = (self.pupil_distance - hm) / numpy.sqrt... | Python | nomic_cornstack_python_v1 |
function __init__ self ax labels active=0 activecolor=none useblit=true label_props=none radio_props=none
begin
call __init__ ax
call check_isinstance tuple dict none label_props=label_props radio_props=radio_props
set radio_props = call normalize_kwargs radio_props PathCollection
if activecolor is not none
begin
if st... | def __init__(self, ax, labels, active=0, activecolor=None, *,
useblit=True, label_props=None, radio_props=None):
super().__init__(ax)
_api.check_isinstance((dict, None), label_props=label_props,
radio_props=radio_props)
radio_props = cbook.normali... | Python | nomic_cornstack_python_v1 |
function _dump_spec_filename_additional_info libspec_manager spec_filename is_builtin obtain_mutex=true
begin
try
begin
if not is_copy
begin
call schedule_conversion_to_markdown spec_filename
end
end
except any
begin
exception string Error converting %s to markdown. spec_filename
end
import json
set source_to_mtime = c... | def _dump_spec_filename_additional_info(
libspec_manager, spec_filename, is_builtin, obtain_mutex=True
):
try:
if not libspec_manager.is_copy:
libspec_manager.schedule_conversion_to_markdown(spec_filename)
except:
log.exception("Error converting %s to markdown.", spec_filename)
... | Python | nomic_cornstack_python_v1 |
import pygame
import blocks
class LevelOne extends Stage
begin
function __init__ self
begin
call __init__ self 40
set tree_ground = call Tile call darken 0.8 flat=true
set images = list call Block call Color string lawngreen call Block call Color string firebrick call Tile call Color string lawngreen call Tile call Col... | import pygame
import blocks
class LevelOne(blocks.Stage):
def __init__(self):
blocks.Stage.__init__(self, 40)
tree_ground = blocks.Tile(blocks.Color('lawngreen').darken(0.8), flat=True)
self.images = [
blocks.Block(blocks.Color('lawngreen')),
blocks.Block(blocks.Col... | Python | zaydzuhri_stack_edu_python |
function encrypt self sentence
begin
set sentence = list sentence
set encrypted_sentence = list
set x = list string abcdefghijklmnopqrstuvwxyz
set l = length x
set y = random sample x l
set z = list zip x y
append z tuple string string
for i in sentence
begin
if lower i not in x
begin
append encrypted_sentence i
cont... | def encrypt(self, sentence):
sentence = list(sentence)
encrypted_sentence = []
x = list("abcdefghijklmnopqrstuvwxyz")
l = len(x)
y = random.sample(x, l)
z = list(zip(x, y))
z.append((" ", " "))
for i in sentence:
if i.lower() not in x:... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment hits ebay with given search_word and writes html DOM locally
comment prints files of the format [randint].[timestamp].html in folder [ebay_search_word]_files_[timestamp] in working dir
import urllib2 , time , Queue , threading , os
from random import randint
set with_quotes = true
set n... | #!/usr/bin/python
# hits ebay with given search_word and writes html DOM locally
# prints files of the format [randint].[timestamp].html in folder [ebay_search_word]_files_[timestamp] in working dir
import urllib2, time, Queue, threading, os
from random import randint
with_quotes = True
num_threads = 100
hits_per_thre... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from sklearn import datasets
set diabetes = call load_diabetes
set diabetes_X_train = data at slice : - 20 :
set diabetes_X_test = data at slice - 20 : :
set diabetes_y_train = target at slice : - 20 :
set diabetes_y_test = target at slice - 20 : :
from sklearn import linear_model
set regr = ... | import numpy as np
from sklearn import datasets
diabetes = datasets.load_diabetes()
diabetes_X_train = diabetes.data[:-20]
diabetes_X_test = diabetes.data[-20:]
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
from sklearn import linear_model
regr = linear_model.LinearRegression()
r... | Python | zaydzuhri_stack_edu_python |
function account_update request
begin
set params = params
set json_body = json_body
set user_acct = user
if string name in params and params at string name is not none
begin
set name = get params string name
set name = name
end
if string name in json_body and json_body at string name is not none
begin
set name = get js... | def account_update(request):
params = request.params
json_body = request.json_body
user_acct = request.user
if 'name' in params and params['name'] is not None:
name = params.get('name')
user_acct.name = name
if 'name' in json_body and json_body['name'] is not None:
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import argparse
import cv2
import numpy as np
import yaml
if __name__ == string __main__
begin
set parser = call ArgumentParser description=string Calibrate camera using a video of a chessboard
call add_argument string -i string --input help=string input video file
call add_argument string ... | #!/usr/bin/env python
import argparse
import cv2
import numpy as np
import yaml
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Calibrate camera using a video of a chessboard')
parser.add_argument('-i', '--input', help='input video file')
parser.add_argument('-o', '--output', help... | Python | zaydzuhri_stack_edu_python |
function test_synfit_two
begin
comment Test with synthetic spectrum
comment Creates a fake spectrum
set params = dictionary teff=20000 logg=4 vrot=16 abund=dict string He 10.93 vmac_rt=5 wstart=4460 wend=4480 noplot=true relative=1 observ=string test_spectrum.dat
set syn = call Synplot params at string teff params at s... | def test_synfit_two():
# Test with synthetic spectrum
# Creates a fake spectrum
params = dict(teff=20000, logg=4, vrot=16, abund={'He': 10.93}, vmac_rt=5,
wstart=4460, wend=4480, noplot=True, relative=1,
observ='test_spectrum.dat')
syn = Synplot(params['teff'], par... | Python | nomic_cornstack_python_v1 |
function port_list_with_trunk_types request **params
begin
string List neutron Ports for this tenant with possible TrunkPort indicated :param request: request context NOTE Performing two API calls is not atomic, but this is not worse than the original idea when we call port_list repeatedly for each network to perform i... | def port_list_with_trunk_types(request, **params):
"""List neutron Ports for this tenant with possible TrunkPort indicated
:param request: request context
NOTE Performing two API calls is not atomic, but this is not worse
than the original idea when we call port_list repeatedly for
each ... | Python | jtatman_500k |
comment !/usr/bin/python
comment -*- coding:utf8 -*
string Sorted Dictionary
class SortedDictionary
begin
function __init__ self values=dict **params
begin
string Constructor x = SortedDictionary(): generates an empty dictionary x = SortedDictionary(dict): initializes with another dict x = SortedDictionary(dict)
if ty... | #!/usr/bin/python
# -*- coding:utf8 -*
""" Sorted Dictionary
"""
class SortedDictionary:
def __init__(self, values = {}, **params):
""" Constructor
x = SortedDictionary(): generates an empty dictionary
x = SortedDictionary(dict): initializes with another dict
... | Python | zaydzuhri_stack_edu_python |
from django.test import TestCase
from models import Recipe
from test_users import sample_user
class RecipeTests extends TestCase
begin
function test_recipe_str self
begin
string Test the recipe string representation
set recipe = call create user=call sample_user title=string Steak and mushroom sauce time_minutes=5 pric... | from django.test import TestCase
from ..models import Recipe
from.test_users import sample_user
class RecipeTests(TestCase):
def test_recipe_str(self):
'''Test the recipe string representation'''
recipe = Recipe.objects.create(
user=sample_user(),
title='Steak and mushroom ... | Python | zaydzuhri_stack_edu_python |
comment Add new colorbars which aren't available in my version of python (i.e. viridis)
call execfile string /Users/lauramazzaro/Documents/Work/Perts/Article/Figures/new_cmaps.py
comment Modify plotting parameters!
call execfile string /Users/lauramazzaro/Documents/Work/Perts/Article/Figures/new_params.py
from scipy.io... | # Add new colorbars which aren't available in my version of python (i.e. viridis)
execfile('/Users/lauramazzaro/Documents/Work/Perts/Article/Figures/new_cmaps.py')
# Modify plotting parameters!
execfile('/Users/lauramazzaro/Documents/Work/Perts/Article/Figures/new_params.py')
from scipy.io import loadmat
import matpl... | Python | zaydzuhri_stack_edu_python |
function credentials_type self
begin
return get pulumi self string credentials_type
end function | def credentials_type(self) -> str:
return pulumi.get(self, "credentials_type") | Python | nomic_cornstack_python_v1 |
function find_best_match self first_name last_name email=none age=none
begin
set matches = call get_fuzzy_matches first_name last_name
if not average_age
begin
set average_age = call _get_average_age
end
if not matches
begin
return none
end
else
begin
for match in matches
begin
if not match at string birth_date or matc... | def find_best_match(self, first_name, last_name, email=None, age=None):
matches = self.get_fuzzy_matches(first_name, last_name)
if not self.average_age:
self.average_age = self._get_average_age()
if not matches:
return None
else:
for match in matches:
... | Python | nomic_cornstack_python_v1 |
import math
function is_prime x
begin
set d = floor square root x
while d > 1
begin
if x % d == 0
begin
return false
end
set d = d - 1
end
return true
end function
function get_primes n
begin
return list comprehension x for x in call xrange 2 n + 1 if call is_prime x
end function | import math
def is_prime(x):
d = math.floor(math.sqrt(x))
while d > 1:
if x % d == 0:
return False
d = d - 1
return True
def get_primes(n):
return [x for x in xrange(2, n + 1) if is_prime(x)]
| Python | zaydzuhri_stack_edu_python |
function get_contacts_list self
begin
set contacts = call find_elements_by_class_name string _1wjpf
comment extracts chats and last messsages
set s = list comprehension text for contact in contacts
comment print only chat names
print string get contacts: + string s
comment returns only chat names
return s at slice : ... | def get_contacts_list(self):
contacts = self.driver.find_elements_by_class_name("_1wjpf")
s= [contact.text for contact in contacts] #extracts chats and last messsages
print ("get contacts: "+str(s)) #print only chat names
return s[::2] #returns only chat names | Python | nomic_cornstack_python_v1 |
function local_import name globals=none locals=none fromlist=tuple level=0
begin
try
begin
return call load_ulang_module name globals fromlist level
end
except any
begin
return call __import__ name globals locals fromlist level
end
end function | def local_import(name, globals=None, locals=None, fromlist=(), level=0):
try:
return load_ulang_module(name, globals, fromlist, level)
except:
return __import__(name, globals, locals, fromlist, level) | Python | nomic_cornstack_python_v1 |
from collections import OrderedDict
import sklearn.cross_validation as cv
import numpy as np
from magellan import MTable
import time
import math
function train_test_split labeled_data train_proportion=0.5 random_state=none
begin
string Split MTable into Train and Test Parameters ---------- labeled_data : MTable train_p... | from collections import OrderedDict
import sklearn.cross_validation as cv
import numpy as np
from magellan import MTable
import time
import math
def train_test_split(labeled_data, train_proportion = 0.5, random_state=None):
"""
Split MTable into Train and Test
Parameters
----------
labeled_data : ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from spider import *
class CornellSpider extends Spider
begin
function __init__ self
begin
call __init__ self
set school = string cornell
set subject = string eecs
end function
end class | #!/usr/bin/env python
from spider import *
class CornellSpider(Spider):
def __init__(self):
Spider.__init__(self)
self.school = 'cornell'
self.subject = 'eecs'
| Python | zaydzuhri_stack_edu_python |
function get_username self
begin
set full_name = string %s %s % tuple strip first_name strip last_name at slice 0 : 1 :
if length strip full_name == 0
begin
set full_name = username
end
return strip full_name
end function | def get_username(self):
full_name = '%s %s' % (self.user.first_name.strip(), self.user.last_name.strip()[0:1])
if len(full_name.strip()) == 0:
full_name = self.user.username
return full_name.strip() | Python | nomic_cornstack_python_v1 |
function _escape msg
begin
set reserved = bytearray encode string ~}
set escaped = bytearray
append escaped msg at 0
for byte in msg at slice 1 : :
begin
if byte in reserved
begin
append escaped 125
append escaped byte ? 32
end
else
begin
append escaped byte
end
end
return escaped
end function | def _escape(msg):
reserved = bytearray('\x7E\x7D\x11\x13'.encode())
escaped = bytearray()
escaped.append(msg[0])
for byte in msg[1:]:
if byte in reserved:
escaped.append(0x7D)
escaped.append(byte ^ 0x20)
else:
esca... | Python | nomic_cornstack_python_v1 |
function _columns_from_positions positions boundaries=none
begin
set horizontal_positions = list comprehension call call itemgetter 0 2 pos for pos in positions if call call within boundaries pos
comment Iterate over positions and remove overlapping columns
set unique_positions = call merge_overlapping_positions *horiz... | def _columns_from_positions(positions: Iterable[Tuple], boundaries: Tuple = None) -> List[Tuple]:
horizontal_positions = [itemgetter(0, 2)(pos) for pos in positions if cb.within(boundaries)(pos)]
# Iterate over positions and remove overlapping columns
unique_positions = merge_overlapping_positions(*horizon... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding:utf-8 -*-
comment q = "1234567891"
comment q = q.replace("-", "")
comment print(q)
class Par
begin
set is_bus = true
end class
class Chi extends Par
begin
pass
end class
print is_bus | #!/usr/bin/python
# -*- coding:utf-8 -*-
# q = "1234567891"
# q = q.replace("-", "")
# print(q)
class Par:
is_bus = True
class Chi(Par):
pass
print(Chi.is_bus)
| Python | zaydzuhri_stack_edu_python |
from itertools import count
function ispand19 n
begin
set s = join string sorted list string n
return s == string 123456789
end function
function cprod n
begin
set s = string n
set r = string
for x in count 1
begin
set r = r + string n * integer x
if call ispand19 r
begin
return r
end
if length r > 9
begin
break
end
... | from itertools import count
def ispand19(n):
s = ''.join(sorted(list(str(n))))
return s == "123456789"
def cprod(n):
s = str(n)
r = ''
for x in count(1):
r += str(n*int(x))
if ispand19(r): return r
if len(r) > 9: break
return None
max = 0
for i in xrange(10000):
cp = cprod(i)
if cp is not... | Python | zaydzuhri_stack_edu_python |
function SetFont self font
begin
call SetFont self font
set style = call GetWindowStyleFlag
call InvalidateBestSize
if not style ? ST_NO_AUTORESIZE
begin
call SetSize call GetBestSize
end
call Refresh
end function | def SetFont(self, font):
wx.Control.SetFont(self, font)
style = self.GetWindowStyleFlag()
self.InvalidateBestSize()
if not style & wx.ST_NO_AUTORESIZE:
self.SetSize(self.GetBestSize())
self.Refresh() | Python | nomic_cornstack_python_v1 |
string conftest.py is a module used by pytest as a helper for fixtures and other processing logic. If the file exists, PyTest knows to import it and use those methods internally. The trickiest part is that there isnt a direct way to call the helpers from the testing files, you simply pass variables in with the paramete... | """
conftest.py is a module used by pytest as a helper for fixtures and other processing logic. If the file exists, PyTest
knows to import it and use those methods internally. The trickiest part is that there isnt a direct way to call the
helpers from the testing files, you simply pass variables in with the parameters ... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from Jeu import *
import webbrowser
class Menu
begin
function __init__ self fenetre canvas imgBg imgPlay imgRules imgNext
begin
set fen = fenetre
set can = canvas
set imgBg = imgBg
set imgPlay = imgPlay
set imgRules = imgRules
set imgNext = imgNext
call create_image w h image=imgBg anchor=string s... | from tkinter import *
from Jeu import *
import webbrowser
class Menu:
def __init__(self,fenetre, canvas, imgBg, imgPlay, imgRules, imgNext):
self.fen = fenetre
self.can = canvas
self.imgBg = imgBg
self.imgPlay = imgPlay
self.imgRules = imgRules
self.imgNext = imgNext... | Python | zaydzuhri_stack_edu_python |
import tkinter as tk
import os
function callback
begin
call destroy
set filename = string Title1.py
call system filename
end function
set win = call Tk
title win string A MAZE GAME
comment win.configure(bg="black")
set image = call PhotoImage file=string Main_title.gif
call geometry string 700x700
set label1 = call Lab... | import tkinter as tk
import os
def callback():
win.destroy()
filename="Title1.py"
os.system(filename)
win=tk.Tk()
win.title("A MAZE GAME")
#win.configure(bg="black")
image=tk.PhotoImage(file="Main_title.gif")
win.geometry("700x700")
label1=tk.Label(win,image=image)
label1.pack(side="top",fill="both",... | Python | zaydzuhri_stack_edu_python |
import tkinter as tk
from tkinter.constants import END , N
import youtube_dl
from pathlib import Path
import os
class Window
begin
function __init__ self window
begin
set window = window
call geometry string 700x500
title window string Youtube Video Downloader
set url_list = list
set SAVEPATH = join path call home str... | import tkinter as tk
from tkinter.constants import END, N
import youtube_dl
from pathlib import Path
import os
class Window:
def __init__(self, window):
self.window = window
self.window.geometry("700x500")
self.window.title("Youtube Video Downloader")
self.url_list = []
sel... | Python | zaydzuhri_stack_edu_python |
comment Amplitude Follower
comment Author: Alexander Attar
comment NYU - DSP
comment Spring 2012
comment For math functions
import math as m
comment For reading in audio files
from scikits.audiolab import Sndfile , Format
comment For putting audio into arrays
import numpy as np
from collections import deque
comment to ... | # Amplitude Follower
# Author: Alexander Attar
# NYU - DSP
# Spring 2012
import math as m # For math functions
from scikits.audiolab import Sndfile, Format # For reading in audio files
import numpy as np # For putting audio into arrays
from collections import deque
import matplotlib.pyplot as plot # to plot output
im... | Python | zaydzuhri_stack_edu_python |
function __init__ self entry
begin
set config_entry = entry
end function | def __init__(self, entry: config_entries.ConfigEntry) -> None:
self.config_entry = entry | Python | nomic_cornstack_python_v1 |
function created_timestamp self
begin
return get pulumi self string created_timestamp
end function | def created_timestamp(self) -> str:
return pulumi.get(self, "created_timestamp") | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import re , nltk , spacy , gensim
from sklearn.decomposition import LatentDirichletAllocation , TruncatedSVD
from sklearn.feature_extraction.text import CountVectorizer , TfidfTransformer
from sklearn.model_selection import GridSearchCV
from pprint import pprint
comment plotting
i... | import numpy as np
import pandas as pd
import re, nltk, spacy, gensim
from sklearn.decomposition import LatentDirichletAllocation, TruncatedSVD
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.model_selection import GridSearchCV
from pprint import pprint
#plotting
import pyLD... | Python | zaydzuhri_stack_edu_python |
function moveCheckerFromBar self point
begin
comment Calls the pointHit method if checker moves to a point occupied by
comment the opposing player
if call isBlot and call getTeam != call getTurn
begin
call pointHit point
end
comment Adds checker to the new point and organizes and updates that point
call addChecker call... | def moveCheckerFromBar(self, point):
# Calls the pointHit method if checker moves to a point occupied by
# the opposing player
if point.isBlot() and\
point.getTeam() != self.getTurn():
self.pointHit(point)
# Adds checker to the new point and ... | Python | nomic_cornstack_python_v1 |
comment import os
comment import time
comment ret_val=os.fork()
comment if ret_val:
comment print('父进程')
comment result=os.waitpid(-1,0)
comment print(result)
comment time.sleep(5)
comment else:
comment print('子进程')
comment time.sleep(10)
comment print('child done')
import os
import time
set ret_val = call fork
if ret_... | # import os
# import time
#
# ret_val=os.fork()
#
# if ret_val:
# print('父进程')
# result=os.waitpid(-1,0)
# print(result)
# time.sleep(5)
# else:
# print('子进程')
# time.sleep(10)
# print('child done')
import os
import time
ret_val=os.fork()
if ret_val:
print('父进程')
resutl=os.waitp... | Python | zaydzuhri_stack_edu_python |
function macroexpand_r p depth=0 quoted=false
begin
if is instance p list
begin
if length p > 0 and is instance p at 0 Symbol
begin
if p at 0 is lambda_
begin
return p at slice : 2 : + list comprehension x for x in list comprehension call macroexpand_r x depth quoted for x in p at slice 2 : : if x is not none
end
i... | def macroexpand_r(p, depth=0, quoted=False):
if isinstance(p, list):
if len(p) > 0 and isinstance(p[0], Symbol):
if p[0] is Symbol.lambda_:
return p[:2] + [x for x in [macroexpand_r(x, depth, quoted) for x in p[2:]] if x is not None]
if p[0] is Symbol.quote:
... | Python | nomic_cornstack_python_v1 |
comment Problem: Minimum number of coins
comment Link: https://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/
import sys
class Solution
begin
function minCoins self coins target
begin
set n = length coins
if target == 0
begin
return 0
end
set M = list comprehension maxsize - 100 for i in range t... | #Problem: Minimum number of coins
#Link: https://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/
import sys
class Solution:
def minCoins(self, coins, target):
n = len(coins)
if target == 0:
return 0
M = [sys.maxsize-100 for i in range(target+1)]
M[0] = 0
for i in range(1, n+1):
... | Python | zaydzuhri_stack_edu_python |
from pyspark.ml.feature import StringIndexer
from preprocess_steps.add_age_column import add_age_column
from preprocess_steps.age_range_column import add_age_range_column
from preprocess_steps.divide_day_time import divide_day_time_step
from preprocess_steps.replace_nulls import replace_null_with_average
from preproces... | from pyspark.ml.feature import StringIndexer
from preprocess_steps.add_age_column import add_age_column
from preprocess_steps.age_range_column import add_age_range_column
from preprocess_steps.divide_day_time import divide_day_time_step
from preprocess_steps.replace_nulls import replace_null_with_average
from preproce... | Python | zaydzuhri_stack_edu_python |
string Test cases for /user
import re
import urllib
from unittest import mock
from django.urls.base import reverse_lazy
from rest_framework import status
from mixin import AuthTestCase
from mocks import GithubRequestsMock
class AuthenticateTestSuite extends AuthTestCase
begin
string Authentication test suite
function t... | """
Test cases for /user
"""
import re
import urllib
from unittest import mock
from django.urls.base import reverse_lazy
from rest_framework import status
from .mixin import AuthTestCase
from .mocks import GithubRequestsMock
class AuthenticateTestSuite(AuthTestCase):
"""Authentication test suite"""
def test_g... | Python | zaydzuhri_stack_edu_python |
function test_key_repair_lens self
begin
comment Create new work trail and retrieve the HEAD workflow of the default
comment branch
set f_handle = call upload_file KEY_REPAIR_FILE
set ds1 = call load_dataset f_handle=f_handle
comment Missing Value Lens
set command = call mimir_key_repair DATASET_NAME identifier
set res... | def test_key_repair_lens(self):
# Create new work trail and retrieve the HEAD workflow of the default
# branch
f_handle = self.filestore.upload_file(KEY_REPAIR_FILE)
ds1 = self.datastore.load_dataset(f_handle=f_handle)
# Missing Value Lens
command = cmd.mimir_key_repair(D... | Python | nomic_cornstack_python_v1 |
function create_app cfgfile=string ~/.config/pih2o/pih2o.cfg
begin
set parser = call ArgumentParser usage=string %(prog)s [options] description=__doc__
call add_argument string --version action=string version version=__version__ help=string show program's version number and exit
call add_argument string --config action... | def create_app(cfgfile="~/.config/pih2o/pih2o.cfg"):
parser = argparse.ArgumentParser(usage="%(prog)s [options]", description=pih2o.__doc__)
parser.add_argument('--version', action='version', version=pih2o.__version__,
help=u"show program's version number and exit")
parser.add_argu... | Python | nomic_cornstack_python_v1 |
import random
set adamCan = 5
set kelime = list string kaplanaslan string belgesel string ayak string ayakkabı string hastane string okul string elektrik string tahta string makine string kelime string ceviz string araba string baklava string kundura
set kelime_tahmin = list
set gizli_kelime = random choice kelime
set... | import random
adamCan = 5
kelime = ["kaplan" "aslan", "belgesel", "ayak", "ayakkabı", "hastane", "okul", "elektrik",
"tahta", "makine", "kelime", "ceviz", "araba", "baklava", "kundura"]
kelime_tahmin = []
gizli_kelime = random.choice(kelime)
kelime_uzunluğu = len(gizli_kelime)
alfabe = "abcçdefgğhıijklm... | Python | zaydzuhri_stack_edu_python |
function form_for_request request FormClass *args **kwargs
begin
return call FormClass if expression method == string POST then POST else none *args keyword kwargs
end function | def form_for_request(request, FormClass, *args, **kwargs):
return FormClass(request.POST if request.method == 'POST' else None, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
from solutions.random_number_list import get_random_number_list
function partition array begin end
begin
comment np. 2 9 1 5 3 3 8 10 [6]
set i = begin - 1
comment zawsze zakladamy ze pivot jest ostatnim elementem
set pivot = array at end
for j in range begin end
begin
comment sprawdzamy czy aktualny element jest mniej... | from solutions.random_number_list import get_random_number_list
def partition(array, begin, end):
# np. 2 9 1 5 3 3 8 10 [6]
i = begin - 1
pivot = array[end] # zawsze zakladamy ze pivot jest ostatnim elementem
for j in range(begin, end):
# sprawdzamy czy aktualny element jest mniejszy niz piv... | Python | zaydzuhri_stack_edu_python |
function __init__ self **kwargs
begin
set board = get kwargs string board none
set tilebag = get kwargs string tilebag none
set status = get kwargs string status none
set rack = get kwargs string rack none
set coord = get kwargs string coord none
set direction = get kwargs string direction none
set player = get kwargs ... | def __init__(self, **kwargs):
self.board = kwargs.get('board', None)
self.tilebag = kwargs.get('tilebag', None)
self.status = kwargs.get('status', None)
self.rack = kwargs.get('rack', None)
self.coord = kwargs.get('coord', None)
self.direction = kwargs.get('directio... | Python | nomic_cornstack_python_v1 |
function __init__ self duration
begin
set time = time
set duration = duration
set running = false
end function | def __init__(self, duration):
self.time = time.time()
self.duration = duration
self.running = False | Python | nomic_cornstack_python_v1 |
function clean_x_with_quantile df cols quantiles
begin
set df_ = copy df
for col in cols
begin
set df_ = df_ at df_ at col > call quantile quantiles at 0 ? df_ at col < call quantile quantiles at 1
set df_ = df_ at ? is null df_ at col
end
return df_
end function | def clean_x_with_quantile(df, cols, quantiles):
df_ = df.copy()
for col in cols:
df_ = df_[((df_[col] > df_[col].quantile(quantiles[0])) & (df_[col] < df_[col].quantile(quantiles[1])))]
df_ = df_[~df_[col].isnull()]
return df_
| Python | zaydzuhri_stack_edu_python |
function construct self
begin
sort _content key=lambda x -> tuple parent index
set i = 0
set j = 1
while i < length _content
begin
while j < length _content
begin
if parent == index
begin
append children _content at j
set j = j + 1
end
else
begin
break
end
end
set i = i + 1
end
end function | def construct(self):
self._content.sort(key=lambda x: (x.parent, x.index))
i=0
j=1
while i<len(self._content):
while j<len(self._content):
if self._content[j].parent == self._content[i].index:
self._content[i].children.append(self._content[... | Python | nomic_cornstack_python_v1 |
function _clean_old_files self
begin
if days_backup is none
begin
info string Clean backup files: disabled
end
else
begin
info format string Clean backup files > {0} days days_backup
call _clean_path path_backup prefix
call _clean_path path_log string PyMongoBackup_
end
end function | def _clean_old_files(self):
if self.days_backup is None:
self.logger.info('Clean backup files: disabled')
else:
self.logger.info('Clean backup files > {0} days'.format(self.days_backup))
self._clean_path(self.path_backup, self.prefix)
self._clean_path(sel... | Python | nomic_cornstack_python_v1 |
string Verify if the input phrase is a palindrome
print string PALINDROME VERIFIER
set phrase = lower strip string input string Type a phrase you want to verify:
function prepare_phrase_for_validation phrase
begin
set separate_words = split phrase
set words_together = join string separate_words
return words_together
e... | ''' Verify if the input phrase is a palindrome '''
print('\nPALINDROME VERIFIER\n')
phrase = str(input('Type a phrase you want to verify: ')).strip().lower()
def prepare_phrase_for_validation(phrase):
separate_words = phrase.split()
words_together = ''.join(separate_words)
return words_together
def veri... | Python | zaydzuhri_stack_edu_python |
with open string macacos-me-mordam.txt string r as arq
begin
set x = read arq
end
set t = split upper x
set c = 0
for i in range length t
begin
if t at i == string BANANA
begin
set c = c + 1
end
end
print c | with open('macacos-me-mordam.txt','r') as arq:
x=arq.read()
t=x.upper().split()
c=0
for i in range(len(t)):
if t[i]=='BANANA':
c+=1
print(c)
| Python | zaydzuhri_stack_edu_python |
import io
set res_Words = list string if string then string else string end string repeat string until string read string write
set special_Chars = list string + string - string * string / string = string ; string < string > string <= string >=
function get_token code
begin
set token_list = list
for tiny in call Strin... | import io
res_Words = ["if", "then", "else", "end", "repeat", "until", "read", "write"]
special_Chars = ['+', '-', '*', '/', '=', ';', '<', '>', '<=', '>=']
def get_token(code):
token_list = []
for tiny in io.StringIO(code):
token = ""
token_type = ""
state = "START"
i=0
... | Python | zaydzuhri_stack_edu_python |
set type_projection = input
set rows = integer input
set columns = integer input
set prices = dict string Premiere 12 ; string Normal 7.5 ; string Discount 5
print string { round rows * columns * get prices type_projection 2 } leva | type_projection = input()
rows = int(input())
columns = int(input())
prices = {'Premiere': 12, 'Normal': 7.5, 'Discount': 5}
print(f'{round(rows * columns * prices.get(type_projection), 2)} leva')
| Python | zaydzuhri_stack_edu_python |
function json self
begin
return loads body
end function | def json(self):
return json.loads(self.body) | Python | nomic_cornstack_python_v1 |
import traceback
import os
import copy
import base64
class Singleton extends type
begin
set _instances = dict
function __call__ cls *args **kwargs
begin
if cls not in _instances
begin
set _instances at cls = call __call__ *args keyword kwargs
end
return _instances at cls
end function
end class
function trace message
b... | import traceback
import os
import copy
import base64
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
def trace(message):
"""... | Python | zaydzuhri_stack_edu_python |
function test_create_tag_success self
begin
set payload = dict string name string test tag
post TAGS_URL payload
set exists = exists filter user=user name=payload at string name
assert true exists
end function | def test_create_tag_success(self):
payload = {"name":"test tag"}
self.client.post(TAGS_URL,payload)
exists = Tag.objects.filter(
user=self.user,
name=payload["name"]
).exists()
self.assertTrue(exists) | Python | nomic_cornstack_python_v1 |
import socket
import pickle
comment Update the IP adresses here as well ###
set ip_database = dict string 1 string 10.1.16.202 ; string 2 string 10.1.21.15 ; string 3 string 10.1.17.123
set port = 49990
while true
begin
print ip_database
print string Enter which server you want to connect to (1, 2, 3, or 4 for exit)
se... | import socket
import pickle
### Update the IP adresses here as well ###
ip_database = {
"1":"10.1.16.202",
"2":"10.1.21.15",
"3":"10.1.17.123"
}
port = 49990
while True:
print(ip_database)
print("Enter which server you want to connect to (1, 2, 3, or 4 for exit)\n")
choice = input("Enter c... | Python | zaydzuhri_stack_edu_python |
function set_durations self
begin
set options = call read_session_file
if length options > 0
begin
call set_session_duration options at 0
end
if length options > 1
begin
call set_break_duration options at 1
end
end function | def set_durations(self):
options = self.read_session_file()
if len(options) > 0:
self.set_session_duration(options[0])
if len(options) > 1:
self.set_break_duration(options[1]) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Задание 7.3a Сделать копию скрипта задания 7.3. Дополнить скрипт: - Отсортировать вывод по номеру VLAN В результате должен получиться такой вывод: 10 01ab.c5d0.70d0 Gi0/8 10 0a1b.1c80.7000 Gi0/4 100 01bb.c580.7000 Gi0/1 200 0a4b.c380.7c00 Gi0/2 200 1a4b.c580.7000 Gi0/6 300 0a1b.5c80... | # -*- coding: utf-8 -*-
"""
Задание 7.3a
Сделать копию скрипта задания 7.3.
Дополнить скрипт:
- Отсортировать вывод по номеру VLAN
В результате должен получиться такой вывод:
10 01ab.c5d0.70d0 Gi0/8
10 0a1b.1c80.7000 Gi0/4
100 01bb.c580.7000 Gi0/1
200 0a4b.c380.7c00 Gi0/2
20... | Python | zaydzuhri_stack_edu_python |
function alert_string codes
begin
return join string , sorted generator expression string code for code in codes
end function | def alert_string(codes):
return ", ".join(sorted(str(code) for code in codes)) | Python | nomic_cornstack_python_v1 |
import cv2
import matplotlib.pyplot as plt
import numpy as np
for num in array range 1 7
begin
set img = call imread format string /Users/zhangmin/PycharmProjects/carno_demo/img/{}.jpg num at tuple slice 100 : 450 : slice 0 : 960 :
comment cv2.imshow('img',img)
comment 灰度化
set gray = call cvtColor img COLOR_BGR2GRAY
... | import cv2
import matplotlib.pyplot as plt
import numpy as np
for num in np.arange(1,7):
img = cv2.imread('/Users/zhangmin/PycharmProjects/carno_demo/img/{}.jpg'.format(num))[100:450,0:960]
#cv2.imshow('img',img)
#灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#高斯滤波
gaussian = cv2.GaussianBl... | Python | zaydzuhri_stack_edu_python |
function iterspecs path ftypes=string cframe specs=range 10 cameras=string brz expid=none openfits=true camera_first=true missing=string warn
begin
set ftypes = split ftypes string ,
if expid is none
begin
set expid = name
end
else
if type expid is int
begin
set expid = call zfill 8
set expid = call zfill 8
end
if came... | def iterspecs(path, ftypes='cframe', specs=range(10), cameras='brz', expid=None,
openfits=True, camera_first=True, missing='warn'):
ftypes = ftypes.split(',')
if expid is None:
expid = path.name
elif type(expid) is int:
expid = expid = str(expid).zfill(8)
if camera_first:
... | Python | nomic_cornstack_python_v1 |
comment python -m pip install pymongo
import pymongo
from pymongo import MongoClient
import pprint
comment To make the following line work, make sure that mongod is running on your computer.
comment To do so, install mongoDB and run the command: 'sudo service mongod start'
set client = call MongoClient string localhost... | #python -m pip install pymongo
import pymongo
from pymongo import MongoClient
import pprint
#To make the following line work, make sure that mongod is running on your computer.
#To do so, install mongoDB and run the command: 'sudo service mongod start'
client = MongoClient('localhost', 27017)
db = client.karl
collecti... | Python | zaydzuhri_stack_edu_python |
function test_post_technical_support db client name email subject message app_response num_db_entries
begin
set data = dict string name name ; string email email ; string subject subject ; string message message ; string app_response app_response
set response = post string /contact data=data
assert status_code == 200
a... | def test_post_technical_support(
db: SQLAlchemy, client: Flask.test_client, name: str, email: str, subject: str, message: bytes,
app_response: str, num_db_entries: int
):
data = {"name": name, "email": email, "subject": subject,
"message": message, "app_response": app_response}
respo... | Python | nomic_cornstack_python_v1 |
function all_signals signal
begin
return true
end function | def all_signals(signal):
return True | Python | nomic_cornstack_python_v1 |
function dir_size start_path
begin
set total_size = 0
for tuple dirpath dirnames filenames in walk start_path
begin
for f in filenames
begin
set fp = join path dirpath f
if exists path fp
begin
try
begin
set total_size = total_size + get size path fp
end
except any
begin
continue
end
end
end
end
comment convert to MB
r... | def dir_size(start_path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
if os.path.exists(fp):
try:
total_size += os.path.getsize(fp)
except:
continue
# convert to MB... | Python | nomic_cornstack_python_v1 |
function home request
begin
return dict
end function | def home(request):
return {} | Python | nomic_cornstack_python_v1 |
class Stack extends object
begin
function __init__ self
begin
set items = list
end function
function is_empty self
begin
return items == list
end function
function push self item
begin
append items item
end function
function pop self
begin
return pop items
end function
function peek self
begin
return items at length ... | class Stack(object):
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(sel... | Python | flytech_python_25k |
function lin_reg_ridge_max X y fit_intercept=true sample_weight=none offsets=none weights=none targ_ubd=1 norm_by_dim=true
begin
comment TODO: normalize is a bad name here -- change this name
if sample_weight is not none
begin
raise call NotImplementedError string TODO
end
if offsets is not none
begin
set y = y - offse... | def lin_reg_ridge_max(X, y, fit_intercept=True,
sample_weight=None, offsets=None,
weights=None,
targ_ubd=1, norm_by_dim=True):
# TODO: normalize is a bad name here -- change this name
if sample_weight is not None:
raise NotImplementedErr... | Python | nomic_cornstack_python_v1 |
comment Welcome to Minesweeper!
comment A spin of the popular game, with a customizable board, playable on
comment the terminal. This is a grid-style game with mines placed on a board.
comment Figure out which squares are mines by the hint square. Each square
comment displays the number of mines that surround it.
from ... | # Welcome to Minesweeper!
# A spin of the popular game, with a customizable board, playable on
# the terminal. This is a grid-style game with mines placed on a board.
# Figure out which squares are mines by the hint square. Each square
# displays the number of mines that surround it.
from board import BoardGenerator, ... | Python | zaydzuhri_stack_edu_python |
comment NearestNeighborClassification
comment Project 2
comment Jessica Nordlund
comment IMPORT STATEMENTS
import numpy as np
import matplotlib.pyplot as plt
import random
import math
comment FUNCTIONS
function openckdfile
begin
set tuple glucose hemoglobin classification = call loadtxt string ckd.csv delimiter=string ... | # NearestNeighborClassification
# Project 2
# Jessica Nordlund
##############################################################################
# IMPORT STATEMENTS
##############################################################################
import numpy as np
import matplotlib.pyplot as plt
import random
import math
... | Python | zaydzuhri_stack_edu_python |
function iteritems self key_type=none return_all_keys=false
begin
string Returns an iterator over the dictionary's (key, value) pairs. @param key_type if specified, iterator will be returning only (key,value) pairs for this type of key. Otherwise (if not specified) ((keys,...), value) i.e. (tuple of keys, values) pairs... | def iteritems(self, key_type=None, return_all_keys=False):
""" Returns an iterator over the dictionary's (key, value) pairs.
@param key_type if specified, iterator will be returning only (key,value) pairs for this type of key.
Otherwise (if not specified) ((keys,...), value)
... | Python | jtatman_500k |
function integration_partner_name self
begin
return _integration_partner_name
end function | def integration_partner_name(self):
return self._integration_partner_name | Python | nomic_cornstack_python_v1 |
import csv
import numpy as np
from copy import copy
from functools import reduce
string Найти СЗ и СВ матрицы (симметрической) Реализовать метод вращений Якоби зависимость погрешности от кол-ва итераций
if __name__ == string __main__
begin
with open string m.csv newline=string as mfile
begin
set matrix = none
set vecto... | import csv
import numpy as np
from copy import copy
from functools import reduce
"""
Найти СЗ и СВ матрицы (симметрической)
Реализовать метод вращений Якоби
зависимость погрешности от кол-ва итераций
"""
if __name__ == '__main__':
with open('m.csv', newline='') as mfile:
matrix = None
... | Python | zaydzuhri_stack_edu_python |
function _request_token self
begin
set response = post string %s/generateToken % right strip root_uri string / dict string username username ; string password password ; string expiration string 60 ; string referer string https://wsdot.maps.arcgis.com ; string f string json
set token_info = json response
if string erro... | def _request_token(self):
response = requests.post(
"%s/generateToken" % self.root_uri.rstrip("/"), {
"username": self.username,
"password": self.password,
"expiration": '60',
"referer": 'https://wsdot.maps.arcgis.com',
... | Python | nomic_cornstack_python_v1 |
comment Definition for singly-linked list.
class ListNode extends object
begin
function __init__ self x
begin
set val = x
set next = none
end function
end class
class Solution extends object
begin
function addTwoNumbers self l1 l2
begin
string :type l1: ListNode :type l2: ListNode :rtype: ListNode
set out_rev = list
s... | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
out_rev = []
carry_val = 0
while True:
l1_val = l1.val if l1... | Python | zaydzuhri_stack_edu_python |
function _showPreviousBoundingBox self duplicate=false
begin
if prev_bounding_box_mode
begin
if current_frame > 1
begin
set prev = bounding_boxes at current_frame - 2
if prev and is_annotated
begin
call _drawBoundingBox point1 point2 prev tuple 255 0 0 RECTANGLE_BORDER_PX
end
end
end
end function | def _showPreviousBoundingBox(self, duplicate = False):
if self.prev_bounding_box_mode:
if self.current_frame > 1:
prev = self.bounding_boxes[self.current_frame - 2]
if prev and prev.is_annotated:
self._drawBoundingBox(prev.point1, prev.point2, prev... | 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.