code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from typing import List
import sys
string Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. Example: Input: [2,3,1,1,4... | from typing import List
import sys
'''
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,... | Python | zaydzuhri_stack_edu_python |
function gen_rect image_path
begin
set cuda = device if expression call is_available then string cuda:0 else string cpu
set net = call PoseEstimationWithMobileNet
set checkpoint = load torch string { dir_path } /checkpoints/rect.pth map_location=cuda
call load_state net checkpoint
if call is_available
begin
call eval_r... | def gen_rect(image_path):
cuda = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
net = PoseEstimationWithMobileNet()
checkpoint = torch.load(f'{dir_path}/checkpoints/rect.pth', map_location=cuda)
load_state(net, checkpoint)
if torch.cuda.is_available():
eval_rect(net.cuda()... | Python | nomic_cornstack_python_v1 |
import time , sys , threading
from datetime import datetime
from pexpect.popen_spawn import PopenSpawn
class ServerHandler
begin
function __init__ self start_script
begin
comment self.timer = ServerTimer()
set jvm_args = read open start_script string r
if jvm_args is not none
begin
write stdout string Detected Java arg... | import time, sys, threading
from datetime import datetime
from pexpect.popen_spawn import PopenSpawn
class ServerHandler:
def __init__(self, start_script):
# self.timer = ServerTimer()
self.jvm_args = (open(start_script, 'r')).read()
if self.jvm_args is not None:
sys.stdout.... | Python | zaydzuhri_stack_edu_python |
string 1207. Unique Number of Occurrences Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique. Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values ha... | """
1207. Unique Number of Occurrences
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values h... | Python | zaydzuhri_stack_edu_python |
function is_a_prime number
begin
if number >= 1
begin
for x in range 2 number
begin
if number % x == 0
begin
return false
end
else
begin
continue
end
end
return true
end
else
begin
false
end
end function
comment print is_a_prime(1) | def is_a_prime(number):
if number >= 1:
for x in range(2,number):
if number % x == 0:
return False
else:
continue
return True
else:
False
#print is_a_prime(1) | Python | zaydzuhri_stack_edu_python |
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
import genetic_functions as gen
comment Without recursion
set MAX_GENERATIONS = 10000
set target = 100
set elements = 6
set population = 5
set mutation_rate = 0.01
set global_best = list
set generation = 0
set current_members = call generate_popu... | import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
import genetic_functions as gen
# Without recursion
MAX_GENERATIONS = 10000
target = 100
elements = 6
population = 5
mutation_rate = 0.01
global_best = []
generation = 0
current_members = gen.generate_population(population, target, elements)
... | Python | zaydzuhri_stack_edu_python |
from Problem import Problem
from Solver import Solver
from os import mkdir
if __name__ == string __main__
begin
set problem_names = list string a_example string b_should_be_easy string c_no_hurry string d_metropolis string e_high_bonus
try
begin
make directory string Solutions
end
except OSError
begin
pass
end
for prob... | from Problem import Problem
from Solver import Solver
from os import mkdir
if __name__ == '__main__':
problem_names = [
"a_example",
"b_should_be_easy",
"c_no_hurry",
"d_metropolis",
"e_high_bonus"
]
try:
mkdir("Solutions")
except OSError:
pass
... | Python | zaydzuhri_stack_edu_python |
function test_relative_volumes self
begin
set test_volume = call volume
set number_of_coolant_channels = 3
assert test_volume == approx call volume * 2
set test_volume = call volume
set mid_offset = - 30
assert test_volume > call volume
set force_cross_section = true
assert test_volume < call volume
end function | def test_relative_volumes(self):
test_volume = self.test_shape.volume()
self.test_shape.number_of_coolant_channels = 3
assert test_volume == pytest.approx(self.test_shape.volume() * 2)
test_volume = self.test_shape.volume()
self.test_shape.mid_offset = -30
assert test_v... | Python | nomic_cornstack_python_v1 |
function notify_info_yielded event
begin
function decorator generator
begin
function decorated *args **kwargs
begin
for v in call generator *args keyword kwargs
begin
call send event info=v
yield v
end
end function
return decorated
end function
return decorator
end function | def notify_info_yielded(event):
def decorator(generator):
def decorated(*args, **kwargs):
for v in generator(*args, **kwargs):
send(event, info=v)
yield v
return decorated
return decorator | Python | nomic_cornstack_python_v1 |
function __normalize self label=string H1_4861A
begin
if string = in label
begin
set tuple line_label factor = split label string =
set factor = decimal factor
end
else
begin
set line_label = label
set factor = 1.0
end
set line_norm = call getLine label=line_label
if line_norm is none
begin
warn format string No normal... | def __normalize(self, label='H1_4861A'):
if "=" in label:
line_label, factor = label.split('=')
factor = np.float(factor)
else:
line_label = label
factor = 1.
line_norm = self.getLine(label=line_label)
if line_norm is None:
pn... | Python | nomic_cornstack_python_v1 |
import sys
insert path 1 string dsp-modulo
from thinkdsp import SinSignal
from thinkdsp import decorate
from thinkdsp import read_wave
import thinkplot
import matplotlib.pyplot as plt
set wavetelefono = call read_wave string telefono.wav
plot
title plt string Todos los digitos
call decorate xlabel=string tiempo(s)
show... | import sys
sys.path.insert(1,'dsp-modulo')
from thinkdsp import SinSignal
from thinkdsp import decorate
from thinkdsp import read_wave
import thinkplot
import matplotlib.pyplot as plt
wavetelefono = read_wave("telefono.wav")
wavetelefono.plot()
plt.title("Todos los digitos")
decorate(xlabel="tiempo(s)")
thinkplot.s... | Python | zaydzuhri_stack_edu_python |
function insert self word _shift=0
begin
set cur = root
for tuple i let in enumerate word
begin
comment print 'cur: {c}'.format(c=str(cur))
comment print 'let: {l}'.format(l=let)
set cur = call add_child let i + _shift
end
call add_child string length word + _shift
end function | def insert(self, word, _shift=0):
cur = self.root
for i, let in enumerate(word):
#print 'cur: {c}'.format(c=str(cur))
#print 'let: {l}'.format(l=let)
cur = cur.add_child(let, i + _shift)
cur.add_child("\0", len(word) + _shift) | Python | nomic_cornstack_python_v1 |
function saveHeader self headerSavePath
begin
comment todo: check that the path exists
with open headerSavePath string w as fp
begin
dump header fp indent=4
end
end function | def saveHeader(self, headerSavePath):
# todo: check that the path exists
with open(headerSavePath, 'w') as fp:
json.dump(self.header, fp, indent=4) | Python | nomic_cornstack_python_v1 |
function html self border=2
begin
set tabletext = string <table border=" + string border + string ">
comment Columns and rows
set ncolumns = call ncolumns
if ncolumns > 0
begin
set nrows = length call table_column 0
end
else
begin
set nrows = 0
end
comment Column titles
set tabletext = tabletext + string <tr>
for i in ... | def html(self, border=2):
tabletext = '<table border="' + str(border) + '">\n'
# Columns and rows
ncolumns = self.ncolumns()
if ncolumns > 0:
nrows = len(self.table_column(0))
else:
nrows = 0
# Column titles
tabletext = tabletext + "<tr>... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
from PyQt5.QtWidgets import QBoxLayout , QLabel , QListWidget , QPushButton , QWidget
from PyQt5.QtCore import Qt
class ManageTODOs extends QWidget
begin
function __init__ self
begin
call __init__
set layout = call QBoxLayout TopToBottom
set todos = call QListWidget
set new = call QPushButt... | #!/usr/bin/env python
from PyQt5.QtWidgets import QBoxLayout, QLabel, QListWidget, QPushButton, QWidget
from PyQt5.QtCore import Qt
class ManageTODOs(QWidget):
def __init__(self):
super().__init__()
layout = QBoxLayout(QBoxLayout.Direction.TopToBottom)
self.todos = QListWidget()
self.new = QPushBu... | Python | zaydzuhri_stack_edu_python |
function send_teleop_enabled self teleop_enabled
begin
set teleop_enabled_msg = boolean
set data = teleop_enabled
call publish teleop_enabled_msg
end function | def send_teleop_enabled(self, teleop_enabled: bool):
teleop_enabled_msg = Bool()
teleop_enabled_msg.data = teleop_enabled
self.teleop_enabled_pub.publish(teleop_enabled_msg) | Python | nomic_cornstack_python_v1 |
import numpy as np
import csv
import pandas as pd
import plotly.express as px
with open string coffeehours.csv as f
begin
set df = dict reader f
set fig = scatter px df x=string Coffee in ml y=string sleep in hours
show
end
function getDataSource data_path
begin
set coffeeml = list
set sleepHours = list
with open dat... | import numpy as np
import csv
import pandas as pd
import plotly.express as px
with open("coffeehours.csv") as f:
df = csv.DictReader(f)
fig = px.scatter(df, x="Coffee in ml", y="sleep in hours")
fig.show()
def getDataSource(data_path):
coffeeml = []
sleepHours = []
with op... | Python | zaydzuhri_stack_edu_python |
comment Problem 4:
comment This problem was asked by Stripe
string Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For ... | # Problem 4:
# This problem was asked by Stripe
"""
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the ... | Python | zaydzuhri_stack_edu_python |
function test_tanimoto_distance get_distributions
begin
for tuple i dist_a in enumerate get_distributions
begin
for tuple j dist_b in enumerate get_distributions
begin
set tanimototo = call tanimoto_distance dist_a dist_b
if i == j
begin
assert approx tanimototo 0.0001 == 1
end
else
begin
assert tanimototo < 1
end
end
... | def test_tanimoto_distance(get_distributions):
for i, dist_a in enumerate(get_distributions):
for j, dist_b in enumerate(get_distributions):
tanimototo = tanimoto_distance(dist_a, dist_b)
if i == j:
assert pytest.approx(tanimototo, 0.0001) == 1
else:
... | Python | nomic_cornstack_python_v1 |
string __slots__ 当一个类需要创建大量实例时,可以通过__slots__声明实例所需要的属性, 为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性 优点:更快的属性访问速度 减少内存消耗
comment 例如
class MyClass extends object
begin
string 原始方法
end class | '''
__slots__
当一个类需要创建大量实例时,可以通过__slots__声明实例所需要的属性,
为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性
优点:更快的属性访问速度
减少内存消耗
'''
#例如
class MyClass(object):
'''原始方法''' | Python | zaydzuhri_stack_edu_python |
function cancel_callback self name
begin
call stop
del _callbacks at name
end function | def cancel_callback(self, name):
self._callbacks[name].stop()
del self._callbacks[name] | Python | nomic_cornstack_python_v1 |
function results query model
begin
comment use model to predict classification for query
set classification_labels = predict model list query at 0
set classification_results = dictionary zip columns at slice 4 : : classification_labels
return classification_results
end function | def results(query, model):
# use model to predict classification for query
classification_labels = model.predict([query])[0]
classification_results = dict(zip(df.columns[4:], classification_labels))
return classification_results | Python | nomic_cornstack_python_v1 |
import grid
function display_grid g
begin
comment Prints the game grid
set tmp = call return_grid
for row in tmp
begin
print join string row
end
end function
function new_game size_x size_y markers
begin
comment Init the game grid
global game_grid
set game_grid = grid size_x size_y markers
comment Define the starting ... | import grid
def display_grid(g):
# Prints the game grid
tmp = g.return_grid()
for row in tmp:
print(' '.join(row))
def new_game(size_x, size_y, markers):
# Init the game grid
global game_grid
game_grid = grid.Grid(size_x, size_y, markers)
# Define the starting points of the game... | Python | zaydzuhri_stack_edu_python |
comment Code to do basic vector calculations in 3 dimensions: addition, dot product and normalization.
comment Saul Bloch
comment 22 April 2014
import math
comment inputting vector values
set firstThree = input string Enter vector A:
set secondThree = input string Enter vector B:
comment creating arrays
set C = list 0 ... | #Code to do basic vector calculations in 3 dimensions: addition, dot product and normalization.
#Saul Bloch
#22 April 2014
import math
#inputting vector values
firstThree = input("Enter vector A:\n")
secondThree = input("Enter vector B:\n")
#creating arrays
C = [0,0,0]
D = [0,0,0]
E = [0,0,0]
F = [0,0,0... | Python | zaydzuhri_stack_edu_python |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other):
return not self == other | Python | nomic_cornstack_python_v1 |
function test_define_variable self
begin
assert equal list string define string test string "test" call asList
assert equal list string define string test string f(w,x) call asList
assert equal list string define string test string "test1 test2" call asList
end function | def test_define_variable(self):
self.assertEqual(['define', 'test', '"test"'],
grammar._DEFINE_VAR.parseString("#define test \"test\"").asList())
self.assertEqual(['define', 'test', "f(w,x)"],
grammar._DEFINE_VAR.parseString("#define test f(w,x)").asLis... | Python | nomic_cornstack_python_v1 |
from django.test import TestCase
from django.contrib.auth.models import User
from models import Profile
from django.test import Client
from django.urls import reverse
class ProfileModelTests extends TestCase
begin
function test_profile_created self
begin
string Creates a user, makes sure the user is stored in DB with c... | from django.test import TestCase
from django.contrib.auth.models import User
from .models import Profile
from django.test import Client
from django.urls import reverse
class ProfileModelTests(TestCase):
def test_profile_created(self):
"""
Creates a user, makes sure the user is stored in DB wi... | Python | zaydzuhri_stack_edu_python |
function test_noarg_train_call
begin
change directory call absolute
set loc = which string parrot-train
set script_descriptor = open absolute path path loc
set script = read script_descriptor
set argv = list string parrot-train
with raises SystemExit
begin
exec script
end
close script_descriptor
end function | def test_noarg_train_call():
os.chdir(pathlib.Path(__file__).parent.absolute())
loc = shutil.which("parrot-train")
script_descriptor = open(os.path.abspath(loc))
script = script_descriptor.read()
sys.argv = ["parrot-train"]
with pytest.raises(SystemExit):
exec(script)
script_descri... | Python | nomic_cornstack_python_v1 |
function rgb2dklCart picture conversionMatrix=none
begin
comment Turn the picture into an array so we can do maths
set picture = array picture
comment Find the original dimensions of the picture
set origShape = shape
comment this is the inversion of the dkl2rgb conversion matrix
if conversionMatrix == none
begin
set co... | def rgb2dklCart(picture, conversionMatrix=None):
#Turn the picture into an array so we can do maths
picture=numpy.array(picture)
#Find the original dimensions of the picture
origShape = picture.shape
#this is the inversion of the dkl2rgb conversion matrix
if conversionMatrix==None:
... | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
import numpy as np
comment Generate samples of a function we are trying to predict:
set samples = 100
set xs = linear space - 5 5 samples
comment We will attempt to fit this function
set ys = sin xs + uniform - 0.5 0.5 samples
comment First, create TensorFlow placeholders for input data (xs) and... | import tensorflow as tf
import numpy as np
# Generate samples of a function we are trying to predict:
samples = 100
xs = np.linspace(-5, 5, samples)
# We will attempt to fit this function
ys = np.sin(xs) + np.random.uniform(-0.5, 0.5, samples)
# First, create TensorFlow placeholders for input data (xs) and
# output (... | Python | zaydzuhri_stack_edu_python |
function parse_external self response
begin
pass
end function | def parse_external(self, response):
pass | Python | nomic_cornstack_python_v1 |
function team_view self team_view
begin
set _team_view = team_view
end function | def team_view(self, team_view):
self._team_view = team_view | Python | nomic_cornstack_python_v1 |
function create_tables self
begin
set con = call connect
set cursor = call cursor
set queries = call tables
for query in queries
begin
execute cursor query
end
close cursor
commit con
close con
end function | def create_tables(self):
con = self.connect()
cursor = con.cursor()
queries = self.tables()
for query in queries:
cursor.execute(query)
cursor.close()
con.commit()
con.close() | Python | nomic_cornstack_python_v1 |
class Solution
begin
function arrangeCoins self n
begin
set count = 0
while n >= 0
begin
set count = count + 1
set n = n - count
end
return count - 1
end function
function arrangeCoins1 self n
begin
set start = 1
set end = n
while end >= start
begin
set mid = start + end // 2
set total = mid * mid + 1 // 2
if total == ... | class Solution:
def arrangeCoins(self, n: int) -> int:
count = 0
while n>=0:
count += 1
n -= count
return count-1
def arrangeCoins1(self, n):
start = 1
end = n
while end >= start:
mid = (start+end)//2
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
string This sample demonstrates SEEDS Superpixels segmentation Use [space] to toggle output mode Usage: seeds.py [<video source>]
comment import the necessary packages
from skimage.segmentation import slic
from skimage.segmentation import mark_boundaries
import numpy as np
import cv2
import sys... | #!/usr/bin/python
'''
This sample demonstrates SEEDS Superpixels segmentation
Use [space] to toggle output mode
Usage:
seeds.py [<video source>]
'''
# import the necessary packages
from skimage.segmentation import slic
from skimage.segmentation import mark_boundaries
import numpy as np
import cv2
import sys
impor... | Python | zaydzuhri_stack_edu_python |
from functools import reduce
from itertools import combinations , count , islice
import operator
function multiply iterable
begin
return reduce mul iterable
end function
function get_prime_divisors number
begin
set prime_divisors = list
set divisor = 2
while divisor <= number
begin
if number % divisor == 0
begin
appen... | from functools import reduce
from itertools import combinations, count, islice
import operator
def multiply(iterable):
return reduce(operator.mul, iterable)
def get_prime_divisors(number):
prime_divisors = []
divisor = 2
while divisor <= number:
if number % divisor == 0:
prime_di... | Python | zaydzuhri_stack_edu_python |
function guess_network self
begin
comment decide what sort of network we are going to use
comment return the actual type
comment right now we just use the first host only network and that's it
set host_only = list call find_networks
if host_only
begin
return host_only at 0
end
else
begin
return call NewHostOnlyNetwork
... | def guess_network(self):
# decide what sort of network we are going to use
# return the actual type
# right now we just use the first host only network and that's it
host_only = list(HostOnlyNetwork.find_networks())
if host_only:
return host_only[0]
else:
... | Python | nomic_cornstack_python_v1 |
function choose_endpoints self parpos perplines
begin
set intersecting_lines = list comprehension line for line in perplines if line at 1 at 0 < parpos < line at 1 at 1
set endpoints = sorted random sample list comprehension line at 0 for line in intersecting_lines 2
return endpoints
end function | def choose_endpoints(self, parpos, perplines):
intersecting_lines = [line for line in perplines
if line[1][0] < parpos < line[1][1] ]
endpoints = sorted(random.sample(
[line[0] for line in intersecting_lines], 2))
return endpoints | Python | nomic_cornstack_python_v1 |
function input_upload self **kwargs
begin
call new_key
call init_cfg
set file_up = kwargs at string input
set filename = work_dir + string input
set file_save = call file filename string wb
if string == filename
begin
comment missing file
comment Bad Request
raise call HTTPError 400 string Missing input file
end
if fi... | def input_upload(self, **kwargs):
self.new_key()
self.init_cfg()
file_up = kwargs['input']
filename = self.work_dir + 'input'
file_save = file(filename, 'wb')
if '' == file_up.filename:
# missing file
raise cherrypy.HTTPError(400, # Bad Request
... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
function other_life_or_woman str_arg
begin
call young_time str_arg
print string same_way_and_early_fact
end function
function young_time str_arg
begin
print str_arg
end function
if __name__ == string __main__
begin
call other_life_or_woman string government
end | #! /usr/bin/env python
def other_life_or_woman(str_arg):
young_time(str_arg)
print('same_way_and_early_fact')
def young_time(str_arg):
print(str_arg)
if __name__ == '__main__':
other_life_or_woman('government')
| Python | zaydzuhri_stack_edu_python |
async function test2 self
begin
return true
end function | async def test2(self):
return True | Python | nomic_cornstack_python_v1 |
string 正整数的反转 12345-54321
set num = integer input string num=
set reversed = 0
while num > 0
begin
set reversed = reversed * 10 + num % 10
set num = num // 10
end
print reversed | """
正整数的反转 12345-54321
"""
num = int(input('num= '))
reversed = 0
while num > 0:
reversed = reversed*10 + num % 10
num //= 10
print(reversed)
| Python | zaydzuhri_stack_edu_python |
function p_test num plist
begin
string if plist[-1]**2 < num: print("The list is not populated with enough numbers to test number effectively") return None #TODO I need to make sure that this is the correct thing that I want to return
comment TODO I need to make sure to add this function on the things that call it inst... | def p_test(num, plist):
"""
if plist[-1]**2 < num:
print("The list is not populated with enough numbers to test number effectively")
return None
#TODO I need to make sure that this is the correct thing that I want to return
""" #TODO I need to make sure to add this function on the t... | Python | nomic_cornstack_python_v1 |
import random
function create_random_arrey n x y
begin
set my_list = list comprehension random integer x y for i in range n
return my_list
end function
function bubble_sort_algorithm my_list
begin
set counter = 0
set swapped = true
while swapped
begin
set counter = counter + 1
set swapped = false
for j in range 1 lengt... | import random
def create_random_arrey(n,x,y):
my_list = [random.randint(x, y) for i in range(n)]
return my_list
def bubble_sort_algorithm(my_list):
counter = 0
swapped = True
while swapped:
counter += 1
swapped = False
for j in range(1,len(my_list)):
... | Python | zaydzuhri_stack_edu_python |
function blurKernelFromPositions object_size position_list illum_list flip_kernels=false use_phase_ramp=false pos_perturbation=none dtype=default_dtype backend=default_backend
begin
comment Initialize blur kernels
set blur_kernel = zeros object_size dtype=complex64
for tuple position_index position in enumerate positio... | def blurKernelFromPositions(object_size, position_list, illum_list, flip_kernels=False, use_phase_ramp=False,
pos_perturbation=None, dtype=default_dtype, backend=default_backend):
# Initialize blur kernels
blur_kernel = np.zeros(object_size, dtype=np.complex64)
for position_ind... | Python | nomic_cornstack_python_v1 |
comment list_1 = ['History', 'Math', 'Physics', 'CompSci']
comment tuple_1 = ['History', 'Math', 'Physics', 'CompSci']
comment cs_set = {'History', 'Math', 'Physics', 'CompSci'} # order is always mixed and duplicates are removed!
comment nums = [1,2,3,4,4,5,6,7,8,8,9,10]
comment my_list = list(map(lambda n: n*n, nums))... | # list_1 = ['History', 'Math', 'Physics', 'CompSci']
# tuple_1 = ['History', 'Math', 'Physics', 'CompSci']
#
# cs_set = {'History', 'Math', 'Physics', 'CompSci'} # order is always mixed and duplicates are removed!
#
# nums = [1,2,3,4,4,5,6,7,8,8,9,10]
#
# my_list = list(map(lambda n: n*n, nums))
#
#
# print(my_list)
#... | Python | zaydzuhri_stack_edu_python |
function test_train_bounding_box_attributes self
begin
set widths = list
set heights = list
set sizes = list
set aspect_ratios = list
for info_dict in train_info_dicts
begin
set annotations = info_dict at ANNOTATIONS_KEY
for annotation in annotations
begin
with call subTest
begin
set b_box_mode = annotation at B_BO... | def test_train_bounding_box_attributes(self):
widths = []
heights = []
sizes = []
aspect_ratios = []
for info_dict in self.train_info_dicts:
annotations = info_dict[constant.detectron.ANNOTATIONS_KEY]
for annotation in annotations:
with s... | Python | nomic_cornstack_python_v1 |
function __init__ self *args
begin
call itkMatrixD34_swiginit self call new_itkMatrixD34 *args
end function | def __init__(self, *args):
_itkMatrixPython.itkMatrixD34_swiginit(self, _itkMatrixPython.new_itkMatrixD34(*args)) | Python | nomic_cornstack_python_v1 |
function _negative_pad_obj obj num_values_to_remove direction=string right
begin
set num_existing_spacers = call _get_length_of_spacers_in_direction obj direction
if num_existing_spacers < num_values_to_remove
begin
raise call ValueError string not able to adjust row { obj } to remove { num_values_to_remove } spacers
e... | def _negative_pad_obj(obj, num_values_to_remove: int, direction='right'):
num_existing_spacers = _get_length_of_spacers_in_direction(obj, direction)
if num_existing_spacers < num_values_to_remove:
raise ValueError(f'not able to adjust row {obj} to remove {num_values_to_remove} spacers')
_remove_spac... | Python | nomic_cornstack_python_v1 |
function delete_api_model restApiId modelName region=none key=none keyid=none profile=none
begin
string Delete a model identified by name in a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_model restApiId modelName
try
begin
set conn = call _get_conn region=region key=key keyid=ke... | def delete_api_model(restApiId, modelName, region=None, key=None, keyid=None, profile=None):
'''
Delete a model identified by name in a given API
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.delete_api_model restApiId modelName
'''
try:
conn = _get_conn(reg... | Python | jtatman_500k |
from pymongo import MongoClient
set client = call MongoClient string localhost 27017
set db = dbsparta
comment 코딩 할 준비 ##
comment Read(조회) - 한 개 값만
set movie = call find_one dict string title string 월-E
print movie at string star
set same_stars = list find movies dict string star movie at string star dict string _id fa... | from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta
## 코딩 할 준비 ##
# Read(조회) - 한 개 값만
movie = db.movies.find_one({'title': '월-E'})
print(movie['star'])
same_stars = list(db.movies.find({'star': movie['star']},{'_id': False}))
for same_star in same_stars:
print(same_star... | Python | zaydzuhri_stack_edu_python |
import csv
import sqlite3
comment TODO Allow the entry of the .csv filename by a user manually - including errors for
comment a.) wrong file extension
comment b.) files that are not in the current directory
comment TODO Make the name of the table the same as the original CSV - so in this case, everything called "Reaear... | import csv
import sqlite3
# TODO Allow the entry of the .csv filename by a user manually - including errors for
# a.) wrong file extension
# b.) files that are not in the current directory
# TODO Make the name of the table the same as the original CSV - so in this case, everything called "ReaearchData"
research... | Python | zaydzuhri_stack_edu_python |
comment o jogador para de jogar se: atinge saldo 260, fica com saldo zero ou negativo ou se completou 13 rodadas (independente de seu saldo)
import random as rd
set seed = integer input
seed seed
set saldo = 100
set aposta = 20
set jogada = 1
while jogada <= 13 and saldo > 0
begin
set sorteio = random integer 1 2
if so... | # o jogador para de jogar se: atinge saldo 260, fica com saldo zero ou negativo ou se completou 13 rodadas (independente de seu saldo)
import random as rd
seed = int(input())
rd.seed(seed)
saldo = 100
aposta = 20
jogada = 1
while (jogada <= 13 and saldo > 0):
sorteio = rd.randint(1, 2)
if sorteio == 1:
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set N = 5
set M = 4
comment Generate random array
set array = call rand N M
comment Calculate sum of all numbers in the array
set sum_of_numbers = sum array
comment Calculate average of each row in the array
set row_averages = mean np array axis=1
comment Determine row with the highest average
set hi... | import numpy as np
N = 5
M = 4
# Generate random array
array = np.random.rand(N, M)
# Calculate sum of all numbers in the array
sum_of_numbers = np.sum(array)
# Calculate average of each row in the array
row_averages = np.mean(array, axis=1)
# Determine row with the highest average
highest_average_row_index = np.a... | Python | greatdarklord_python_dataset |
function allowSwap self
begin
return true
end function | def allowSwap(self):
return True | Python | nomic_cornstack_python_v1 |
comment module used to generate unique ID for type_2_binary labels
import uuid
class Parser
begin
string Handles the parsing of a single .vm file. Reads VM commands, parses them, and provides convenient access to their components. Also removes all whitespace and comments.
function __init__ self input_file
begin
string ... | import uuid # module used to generate unique ID for type_2_binary labels
class Parser():
"""
Handles the parsing of a single .vm file. Reads VM commands, parses them,
and provides convenient access to their components. Also removes all
whitespace and comments.
"""
def __init__(self, input_file):
"""
Creat... | Python | zaydzuhri_stack_edu_python |
class Employee
begin
set raise_amt = 1.04
function __init__ self first last pay
begin
set first = first
set last = last
set email = first + string . + last + string @email.com
set pay = pay
end function
function fullname self
begin
return format string {} {} first last
end function
function apply_raise self
begin
set p... | class Employee:
raise_amt = 1.04
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + "." + last + "@email.com"
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
... | Python | zaydzuhri_stack_edu_python |
comment Ejercicio 13
comment Utilizando archivos e inputs desde la ejecucion
comment Ejemplo de ejecucion "python 13.py first 2nd 3rd"
from sys import argv
set tuple script first second third = argv | #Ejercicio 13
#Utilizando archivos e inputs desde la ejecucion
#Ejemplo de ejecucion "python 13.py first 2nd 3rd"
from sys import argv
script, first, second, third = argv
| Python | zaydzuhri_stack_edu_python |
comment noqa: E501
function patch_pod_security_policy self name body **kwargs
begin
string patch_pod_security_policy # noqa: E501 partially update the specified PodSecurityPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> th... | def patch_pod_security_policy(self, name, body, **kwargs): # noqa: E501
"""patch_pod_security_policy # noqa: E501
partially update the specified PodSecurityPolicy # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass a... | Python | jtatman_500k |
import sys
set stdin = open string input.txt string r
comment 학점은 상대평가
comment 총 10개의 평점
comment 학점: 총범 = 중간고사(35%)+기말(45%) + 과제(20%
comment 10개의 평점은 총번이 높은순
comment 각각 평점은 같은 비율로 부여될 수 있음 N명의 학생이 있다면 N/10명의 학생들에게 평점 무여
comment 학점을 알고 싶은 K번째 학생의 번호가 주어짐, 학점 출력
comment N은 항상 10의 배수
comment K번째 학생의 총점과 다른 학생의 총점이 동일한 경우는... | import sys
sys.stdin = open("input.txt", "r")
#학점은 상대평가
#총 10개의 평점
#학점: 총범 = 중간고사(35%)+기말(45%) + 과제(20%
#10개의 평점은 총번이 높은순
#각각 평점은 같은 비율로 부여될 수 있음 N명의 학생이 있다면 N/10명의 학생들에게 평점 무여
#학점을 알고 싶은 K번째 학생의 번호가 주어짐, 학점 출력
#N은 항상 10의 배수
#K번째 학생의 총점과 다른 학생의 총점이 동일한 경우는 주어지지 않음
# N명과 K학생 번호를 받음
# 아래의 중간고사, 기말, 과제 점수를 받고 총점을 계산
#총점을... | Python | zaydzuhri_stack_edu_python |
function build_docs
begin
string Trigger rebuild of all documentation that is dynamically generated from awslimitchecker.
if get environ string CI none is not none
begin
print string Not building dynamic docs in CI environment
raise call SystemExit 0
end
set region = get environ string AWS_DEFAULT_REGION none
if region... | def build_docs():
"""
Trigger rebuild of all documentation that is dynamically generated
from awslimitchecker.
"""
if os.environ.get('CI', None) is not None:
print("Not building dynamic docs in CI environment")
raise SystemExit(0)
region = os.environ.get('AWS_DEFAULT_REGION', Non... | Python | jtatman_500k |
function min_noutput_items self
begin
return call Parity_deinterleaver_ATSC_sptr_min_noutput_items self
end function | def min_noutput_items(self):
return _mack_sdr_rossi_swig.Parity_deinterleaver_ATSC_sptr_min_noutput_items(self) | Python | nomic_cornstack_python_v1 |
from league.models import Player , League , SpecialUser , Trade_Notification , History , Match_Pairings , User_Match_Details
from django.contrib.auth.models import User
import datetime
from itertools import combinations
function make_pairings request league_id
begin
string :param request: :param league_id: :return:
set... | from league.models import Player, League, SpecialUser, Trade_Notification, History, Match_Pairings, User_Match_Details
from django.contrib.auth.models import User
import datetime
from itertools import combinations
def make_pairings(request, league_id):
'''
:param request:
:param league_id:
:return:
... | Python | zaydzuhri_stack_edu_python |
comment encoding: utf-8
comment author = 'Albert_Musk'
from redis import Redis
set cache = call Redis host=string 127.0.0.1 port=6379
function set key value ex=120
begin
return set key value ex
end function
function get key
begin
return get cache key
end function
function delete key
begin
return delete key
end function... | # encoding: utf-8
# author = 'Albert_Musk'
from redis import Redis
cache = Redis(host='127.0.0.1',port=6379)
def set(key,value,ex=120):
return cache.set(key,value,ex)
def get(key):
return cache.get(key)
def delete(key):
return cache.delete(key)
if __name__ == '__main__':
cache.set('username','hell... | Python | zaydzuhri_stack_edu_python |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
comment se importa el operador and y or
from sqlalchemy import and_ , or_
comment se importa la clase(s) del
comment archivo genera_tablas
from genera_tablas import Institucion , Parroquia , Canton , Provincia
comment se importa información de... | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import and_, or_ # se importa el operador and y or
# se importa la clase(s) del
# archivo genera_tablas
from genera_tablas import Institucion, Parroquia , Canton , Provincia
# se importa información del archivo configuracion... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from os import path
from scipy.spatial import cKDTree
comment Set parameters
comment path to crust1.0 file
set c1_path = string ../crust1/
comment vp, vs or rho
set vtype = string vp
comment ignore water and ice layer.
set sel_layer = call slice 3 none
set tuple latmin latmax = tuple 40 45
set tuple ... | import numpy as np
from os import path
from scipy.spatial import cKDTree
##############################
# Set parameters
##############################
c1_path = "../crust1/" # path to crust1.0 file
vtype = "vp" # vp, vs or rho
sel_layer = slice(3, None) # ignore water and ice layer.
latmin, latmax = 40, 45
lonmin, l... | Python | zaydzuhri_stack_edu_python |
function contour_approximation contour approximation_coefficient=0.02
begin
set perimeter = call arcLength contour true
set approximation = call approxPolyDP contour approximation_coefficient * perimeter true
return approximation
end function | def contour_approximation(contour, approximation_coefficient=0.02):
perimeter = cv2.arcLength(contour, True)
approximation = cv2.approxPolyDP(contour, approximation_coefficient * perimeter, True)
return approximation | Python | nomic_cornstack_python_v1 |
function heterozygositySW sequence
begin
comment The first thing is to test the input
if not is instance sequence str
begin
raise exception string Sequence is not a string
end
set homozygote = string ATCG
set SNPs = string RYSWKMBDHV
set SWs = string SW
set homozygote_count = length list comprehension upper base for ba... | def heterozygositySW(sequence):
# The first thing is to test the input
if not isinstance(sequence, str):
raise Exception("Sequence is not a string")
homozygote='ATCG'
SNPs='RYSWKMBDHV'
SWs='SW'
homozygote_count = len([base.upper() for base in sequence if base.upper() in homozygote])
SNPs_count = len([base.u... | Python | nomic_cornstack_python_v1 |
function drizzle_mask source dest output
begin
if exists path output
begin
call system string rm %s % output
end
set coord_src = call flatten_pixcoord source
end function | def drizzle_mask(source, dest, output):
if os.path.exists(output):
os.system('rm %s' % output)
coord_src = flatten_pixcoord(source) | Python | nomic_cornstack_python_v1 |
function sqitch_db_string db_name
begin
set pg_details = call get_pg_user_pass
set pg_user = pg_details at string pg_user
set pg_pass = pg_details at string pg_pass
if pg_pass is none
begin
set conn_string = string db:pg:// { pg_user } @localhost/ { db_name }
end
else
begin
set conn_string = string db:pg:// { pg_user }... | def sqitch_db_string(db_name):
pg_details = get_pg_user_pass()
pg_user = pg_details['pg_user']
pg_pass = pg_details['pg_pass']
if pg_pass is None:
conn_string = f'db:pg://{pg_user}@localhost/{db_name}'
else:
conn_string = f'db:pg://{pg_user}:{pg_pass}@localhost/{db_name}'
retur... | Python | nomic_cornstack_python_v1 |
from _graph.GraphPro import GraphPro as g
from time import time
import os
from Metodo import *
comment Desarrolla los puntos para mirar los profesores y ordenarlos, junto a que no cruce sus clases
call Comparacion
call system string clear
print string <--------Test Floyd-Warshall------->
set weights = list 1 2 3 4 5
co... | from _graph.GraphPro import GraphPro as g
from time import time
import os
from Metodo import *
#Desarrolla los puntos para mirar los profesores y ordenarlos, junto a que no cruce sus clases
Comparacion()
os.system('clear')
print("<--------Test Floyd-Warshall------->\n")
weights = [1, 2, 3, 4, 5]
#graph = g.creategra... | Python | zaydzuhri_stack_edu_python |
function update_fidl_compatibility_doc fuchsia_api_level
begin
try
begin
with open FIDL_COMPATIBILITY_DOC_PATH string r+ as f
begin
set old_content = read f
set new_content = sub string \{% set in_development_api_level = \d+ %\} string {% set in_development_api_level = { fuchsia_api_level } %} old_content
seek f 0
writ... | def update_fidl_compatibility_doc(fuchsia_api_level):
try:
with open(FIDL_COMPATIBILITY_DOC_PATH, "r+") as f:
old_content = f.read()
new_content = re.sub(
r"\{% set in_development_api_level = \d+ %\}",
f"{{% set in_development_api_level = {fuchsia_api_... | Python | nomic_cornstack_python_v1 |
function index
begin
set wallet = none
set ganked_kills = none
global cache_timer
set code = false
set list_of_all_attackers = list
set npc_id = list
comment if the user is authed, get the wallet content !
if is_authenticated
begin
comment give the token data to esisecurity, it will check alone
comment if the access ... | def index():
wallet = None
ganked_kills = None
global cache_timer
code = False
list_of_all_attackers = []
npc_id = []
# if the user is authed, get the wallet content !
if current_user.is_authenticated:
# give the token data to esisecurity, it will check alone
# if the acc... | Python | nomic_cornstack_python_v1 |
comment A class for more securely handling our cluster data when it is outside of the data base. Less
comment potential for indexing errors compared with using other storage objects. Also provides
comment checks for when a cluster is created that it also has all the required attributes populated and can
comment be ente... | # A class for more securely handling our cluster data when it is outside of the data base. Less
# potential for indexing errors compared with using other storage objects. Also provides
# checks for when a cluster is created that it also has all the required attributes populated and can
# be entered in the DataBase. ... | Python | zaydzuhri_stack_edu_python |
from typing import List
class Pizza
begin
function __init__ self toppings
begin
set toppings = toppings
end function
function __repr__ self
begin
return string Pizza with + join string and toppings
end function
decorator classmethod
function recommend cls
begin
string Recommend some pizza with arbitrary toppings,
retur... | from typing import List
class Pizza:
def __init__(self, toppings: List) -> None:
self.toppings = toppings
def __repr__(self):
return "Pizza with " + " and ".join(self.toppings)
@classmethod
def recommend(cls):
"""Recommend some pizza with arbitrary toppings,"""
return... | Python | zaydzuhri_stack_edu_python |
function create_dynamic_thing_group thingGroupName=none thingGroupProperties=none indexName=none queryString=none queryVersion=none tags=none
begin
pass
end function | def create_dynamic_thing_group(thingGroupName=None, thingGroupProperties=None, indexName=None, queryString=None, queryVersion=None, tags=None):
pass | Python | nomic_cornstack_python_v1 |
function set_light_color
begin
comment set boolean values to true depending on which one was clicked
set goClicked = call collidepoint settings at string mousePos
set stopClicked = call collidepoint settings at string mousePos
set quitClicked = call collidepoint settings at string mousePos
comment change flags for chan... | def set_light_color():
# set boolean values to true depending on which one was clicked
goClicked = settings["goButtonRect"].collidepoint(settings["mousePos"])
stopClicked = settings["stopButtonRect"].collidepoint(settings["mousePos"])
quitClicked = settings["quitButtonRect"].collidepoint(settings["m... | Python | nomic_cornstack_python_v1 |
function resource_group_name self
begin
return get pulumi self string resource_group_name
end function | def resource_group_name(self) -> pulumi.Input[str]:
return pulumi.get(self, "resource_group_name") | Python | nomic_cornstack_python_v1 |
if calc1 == 0 and calc2 == 0
begin
print string Fizz Buzz
end
if calc1 == 0 and calc2 != 0
begin
print string Fizz
end
if calc2 == 0 and calc1 != 0
begin
print string Buzz
end | if calc1 == 0 and calc2 == 0:
print("Fizz Buzz")
if calc1 == 0 and calc2 != 0:
print("Fizz")
if calc2 == 0 and calc1 != 0:
print("Buzz")
| Python | zaydzuhri_stack_edu_python |
function add_to_partial_solution self solution_component
begin
set index = index solution_components solution_component
append partial_solution pop solution_components index
set partial_weight = call partial_weight problem partial_solution
comment If the construction is complete, set tour and weight
if not solution_com... | def add_to_partial_solution(self, solution_component):
index = self.solution_components.index(solution_component)
self.partial_solution.append(self.solution_components.pop(index))
self.partial_weight = partial_weight(
self.problem, self.partial_solution)
# If the constructio... | Python | nomic_cornstack_python_v1 |
function testAdd self
begin
set command_line = _MENU + list _POOLNAME + call example
with assert raises StratisCliDbusLookupError
begin
call RUNNER command_line
end
end function | def testAdd(self):
command_line = self._MENU + [self._POOLNAME] \
+ _DEVICE_STRATEGY.example()
with self.assertRaises(StratisCliDbusLookupError):
RUNNER(command_line) | Python | nomic_cornstack_python_v1 |
function handlerHigh dict itemName itemPrice
begin
if dict at itemName < itemPrice
begin
set dict at itemName = itemPrice + string (highest price for duplicates)
end
else
begin
set dict at itemName = dict at itemName + string (highest price for duplicates)
end
end function
function handlerLow dict itemName itemPrice
be... | def handlerHigh(dict,itemName,itemPrice):
if dict[itemName] < itemPrice:
dict[itemName]=itemPrice + " (highest price for duplicates)"
else:
dict[itemName] = dict[itemName] + " (highest price for duplicates)"
def handlerLow(dict,itemName,itemPrice):
if dict[itemName] > itemPrice:
... | Python | zaydzuhri_stack_edu_python |
function initialize self
begin
set _binarize = call Binarize onset=onset offset=offset min_duration_on=min_duration_on min_duration_off=min_duration_off
end function | def initialize(self):
self._binarize = Binarize(
onset=self.onset,
offset=self.offset,
min_duration_on=self.min_duration_on,
min_duration_off=self.min_duration_off,
) | Python | nomic_cornstack_python_v1 |
function normalize grid
begin
set normalized = join string list comprehension c for c in grid if c in VALID_GRID_CHARS
set normalized = replace normalized string 0 string .
if length normalized != 81
begin
raise call ValueError string Grid is not a proper text representation.
end
return normalized
end function | def normalize(grid):
normalized = ''.join([c for c in grid if c in VALID_GRID_CHARS])
normalized = normalized.replace('0', '.')
if len(normalized) != 81:
raise ValueError('Grid is not a proper text representation.')
return normalized | Python | nomic_cornstack_python_v1 |
function compute_metrics data
begin
set num_true = 0.0
set total = 0.0
set error = 0.0
for tuple index row in call iterrows
begin
set total = total + 1
set true = row at string transition_true
set pred = row at string transition_predicted
if true == pred
begin
set num_true = num_true + 1
end
set error = error + absolut... | def compute_metrics(data):
num_true = 0.0
total = 0.0
error = 0.0
for index, row in data.iterrows():
total += 1
true = row['transition_true']
pred = row['transition_predicted']
if true == pred:
num_true += 1
error += np.abs(float(true) - float(pred))
... | Python | nomic_cornstack_python_v1 |
function flash_post_check self target images context expected_returncode=0
begin
if expected_returncode != none and returncode != expected_returncode
begin
set msg = string flashing with %s failed, returned %s: %s % tuple context at string cmdline_s returncode call _log_file_read context
error msg
return dict string me... | def flash_post_check(self, target, images, context,
expected_returncode = 0):
if expected_returncode != None and self.p.returncode != expected_returncode:
msg = "flashing with %s failed, returned %s: %s" % (
context['cmdline_s'], self.p.returncode,
... | Python | nomic_cornstack_python_v1 |
function class_path cls
begin
call _set_class_path
return _class_path
end function | def class_path(cls):
cls._set_class_path()
return cls._class_path | Python | nomic_cornstack_python_v1 |
function Move_Snake snake tList foodCount
begin
comment Saves snake x coordinate before it moves
set snakeX = call xcor
comment Saves snake y coordinate before it moves
set snakeY = call ycor
comment Moves
call forward 20
comment Moves tails, returns updated tails
set tList = call Update_Tails snakeX snakeY tList foodC... | def Move_Snake(snake, tList, foodCount):
snakeX = snake.xcor() #Saves snake x coordinate before it moves
snakeY = snake.ycor() #Saves snake y coordinate before it moves
snake.forward(20) #Mo... | Python | nomic_cornstack_python_v1 |
function alias option=none
begin
return call alias option
end function | def alias(option=None):
return alias(option) | Python | nomic_cornstack_python_v1 |
function find_losscone L H
begin
comment L = L-vaue and H is loss height.
import numpy as np
import plasmaconst as pc
set const = call plasmaSI
set constcgs = call plasmaCGS
set R = H * 1000.0 + const at string RE / const at string RE
set cos2Mlat = R / L
set cosMlat = square root R / L
set Mlat = call arccos cosMlat
s... | def find_losscone(L, H):
#L = L-vaue and H is loss height.
import numpy as np
import plasmaconst as pc
const =pc.plasmaSI()
constcgs = pc.plasmaCGS()
R = (H*1000.+const['RE'])/const['RE']
cos2Mlat = R/L
cosMlat = np.sqrt(R/L)
Mlat = np.arccos(cosMlat)
Bo = const['B_E']/(... | Python | nomic_cornstack_python_v1 |
comment Definition for a binary tree node.
comment class TreeNode:
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Solution
begin
function getDepth self root depth
begin
if root is none
begin
return tuple 0 depth
end
set tuple totalLeft left = call getDepth l... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getDepth(self, root, depth):
if root is None:
return 0, depth
totalLeft, left = self.getDepth(root.left,... | Python | zaydzuhri_stack_edu_python |
comment CSCI 1133 Homework 3
comment Denasia Hamilton
comment Problem 3A
function intvert a_list
begin
comment new list for items that have been reversed from input list a_list
set new_list = list
for tuple i v in enumerate a_list
begin
comment increase the index by 1, (ex. the last item (1) is now at index 4)
set i =... | #CSCI 1133 Homework 3
#Denasia Hamilton
#Problem 3A
def intvert(a_list):
#new list for items that have been reversed from input list a_list
new_list = [ ]
for (i, v) in enumerate(a_list):
#increase the index by 1, (ex. the last item (1) is now at index 4)
i += 1
#starts at index 4 ... | Python | zaydzuhri_stack_edu_python |
import cv2 , sys , argparse , os
import numpy as np
import PIL as Image
function main options
begin
set filename = filename
set img = call imread filename
image show string Maze img
comment to apply thresholding we need to convert picture to grayscale
set gray = call cvtColor img COLOR_BGR2GRAY
image show string Gray m... | import cv2, sys, argparse, os
import numpy as np
import PIL as Image
def main(options):
filename = options.filename
img = cv2.imread(filename)
cv2.imshow('Maze', img)
# to apply thresholding we need to convert picture to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray ... | Python | zaydzuhri_stack_edu_python |
function __Compute_Cluster_Significance_3d_Isotropic self X
begin
comment Default to zero significance
if length X == 1
begin
return 0
end
comment Otherwise.......
comment Reformat input
set tuple x y t = transpose np X
comment Compute Centroid
set tuple centX centY centT = tuple mean np x mean np y mean np t
comment B... | def __Compute_Cluster_Significance_3d_Isotropic(self, X):
# Default to zero significance
if (len(X)==1):return 0
# Otherwise.......
x,y,t = np.transpose(X) # Reformat input
centX,centY,centT = np.mean(x), np.mean(y),np.mean(t) # Compute Centroid
r = np.sqrt( np.squ... | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
import pika
comment mq用户名和密码
set credentials = call PlainCredentials string lym string 123456
comment 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
set connection = call BlockingConnection call ConnectionParameters host=string localhost port=5672 virtual_host=string / credentials=credentials
comment ... | # -*- coding:utf-8 -*-
import pika
credentials = pika.PlainCredentials('lym', '123456') # mq用户名和密码
# 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost',
port=5672,
... | Python | zaydzuhri_stack_edu_python |
function __repr__ self
begin
return format string _ComputeTerm({!s}, {!s}) comput orig_term
end function | def __repr__(self):
return "_ComputeTerm({!s}, {!s})".format(
self.comput, self.term_ctx.orig_term
) | Python | nomic_cornstack_python_v1 |
function get_default_config framework
begin
if lower framework == string scipy_minimize
begin
return dict string tol none ; string options none ; string constraints none ; string jac none ; string hess none ; string hessp none
end
if lower framework == string dlib_minimize
begin
return dict string num_function_calls in... | def get_default_config(framework: str) -> dict:
if framework.lower() == "scipy_minimize":
return {"tol": None,
"options": None,
"constraints": None,
"jac": None,
"hess": None,
"hessp": None}
i... | Python | nomic_cornstack_python_v1 |
import sys
insert path 0 string ../Logging
from LogImplementer import LogImplementer
from MessageType import MessageType
from handshakeReceiver import HandshakeReceiver
from pingReceiver import PingReceiver
from countReceiver import CountReceiver
from commandReceiver import CommandReceiver
class ReceiverFactory extends... | import sys
sys.path.insert(0, '../Logging')
from LogImplementer import LogImplementer
from MessageType import MessageType
from handshakeReceiver import HandshakeReceiver
from pingReceiver import PingReceiver
from countReceiver import CountReceiver
from commandReceiver import CommandReceiver
class ReceiverFactory(LogIm... | Python | zaydzuhri_stack_edu_python |
import random
set people = list string a string a string a string a string a string k string k string k
function check table
begin
comment We want to see if there are any instances of kids together
if table at 0 == string k and table at - 1 == string k
begin
return true
end
for i in range 1 length table
begin
if table ... | import random
people = ['a', 'a', 'a', 'a', 'a', 'k', 'k', 'k']
def check(table):
# We want to see if there are any instances of kids together
if table[0] == 'k' and table[-1] == 'k':
return True
for i in range(1, len(table)):
if table[i] == 'k' and table[i-1] == 'k':
return T... | Python | zaydzuhri_stack_edu_python |
class Donor
begin
function __init__ self first_name last_name donations=none
begin
set first = first_name
set last = last_name
set donations = donations
end function
decorator property
function full_name self
begin
return format string {} {} first last
end function
function add_donation self amount
begin
return append ... | class Donor:
def __init__(self, first_name, last_name, donations = None):
self.first = first_name
self.last = last_name
self.donations = donations
@property
def full_name(self):
return "{} {}".format(self.first, self.last)
def add_donation(self, amount):
return ... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.