code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function visclassifier fun xTr yTr newfig=true
begin
string visualize decision boundary Define the symbols and colors we'll use in the plots later
set yTr = flatten array yTr
set symbols = list string ko string kx
set marker_symbols = list string o string x
set mycolors = list list 0.5 0.5 1 list 1 0.5 0.5
comment get ... | def visclassifier(fun,xTr,yTr,newfig=True):
"""
visualize decision boundary
Define the symbols and colors we'll use in the plots later
"""
yTr = np.array(yTr).flatten()
symbols = ["ko","kx"]
marker_symbols = ['o', 'x']
mycolors = [[0.5, 0.5, 1], [1, 0.5, 0.5]]
# get the unique ... | Python | zaydzuhri_stack_edu_python |
comment This class inherits from the python built-in list class
class ContactList extends list
begin
comment This method just does a simple linear search
function search self name
begin
for contact in self
begin
if name == name
begin
return contact
end
end
end function
end class
class Contact
begin
comment This is a cl... | # This class inherits from the python built-in list class
class ContactList(list):
# This method just does a simple linear search
def search(self, name):
for contact in self:
if contact.name == name:
return contact
class Contact:
# This is a class attribute. Sh... | Python | zaydzuhri_stack_edu_python |
if pocetPavla == 1
begin
print string Pavla by musela napsat pocetPavla string příspěvěk.
end
if pocetPavla > 1 and pocetPavla < 5
begin
print string Pavla by musela napsat pocetPavla string příspěvky.
end
else
begin
print string Pavla by musela napsat pocetPavla string příspěvků.
end | if pocetPavla == 1:
print("Pavla by musela napsat", pocetPavla, "příspěvěk.")
if pocetPavla > 1 and pocetPavla < 5:
print("Pavla by musela napsat", pocetPavla, "příspěvky.")
else:
print("Pavla by musela napsat", pocetPavla, "příspěvků.") | Python | zaydzuhri_stack_edu_python |
function next_transfer self
begin
set log_str = string next_transfer() Method.
call num_transferrable
if call check_surplus and call test_distribute_surplus
begin
set log_str = log_str + string There is a surplus and it can be distributed.
set cand_with_transfer = call candidate_highest_surplus
set log_str = log_str + ... | def next_transfer(self):
log_str = "next_transfer() Method.\n"
self.num_transferrable()
if self.check_surplus() and self.test_distribute_surplus():
log_str += "There is a surplus and it can be distributed.\n"
cand_with_transfer = self.candidate_highest_surplus()
... | Python | nomic_cornstack_python_v1 |
set family_age = dict string Marta 30 ; string Basia 3 ; string Wanda 0
print family_age at string Marta
set family_age at string Antoni = 0
print family_age
set family = tuple dict string name string Marta ; string age 30 dict string name string Basia ; string age 30 dict string name string Wanda ; string age 30
print... | family_age = {
"Marta": 30,
"Basia": 3,
"Wanda": 0,
}
print(family_age["Marta"])
family_age["Antoni"] = 0
print(family_age)
family = (
{"name": "Marta", "age": 30},
{"name": "Basia", "age": 30},
{"name": "Wanda", "age": 30},
)
print(family[0]["name"])
print(family[1]["name"])
print(family[2]["name"])
l... | Python | zaydzuhri_stack_edu_python |
function test_user_email self
begin
call handle_email
end function | def test_user_email(self):
self.ps_user.handle_email() | Python | nomic_cornstack_python_v1 |
function _handlePriceModalScaleGraphicsItemCheckMarkToggled self
begin
comment Go through all the musicalRatios in the widget, and set them
comment as enabled or disabled in the artifact, based on the check
comment state of the QCheckBox objects in self.checkBoxes.
for i in range length priceModalScaleGraphicsItemCheck... | def _handlePriceModalScaleGraphicsItemCheckMarkToggled(self):
# Go through all the musicalRatios in the widget, and set them
# as enabled or disabled in the artifact, based on the check
# state of the QCheckBox objects in self.checkBoxes.
for i in range(len(self.priceModalScaleGraphicsI... | Python | nomic_cornstack_python_v1 |
function dnscnamerecqueriesrate self
begin
try
begin
return _dnscnamerecqueriesrate
end
except Exception as e
begin
raise e
end
end function | def dnscnamerecqueriesrate(self) :
try :
return self._dnscnamerecqueriesrate
except Exception as e:
raise e | Python | nomic_cornstack_python_v1 |
import pyphen
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import re
import pandas as pd
import nltk
from nltk.corpus import stopwords , brown
from nltk.tokenize import word_tokenize
import math
from collections import Counter
comment generate corpus word_cloud
set df = read csv string song_database
... | import pyphen
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import re
import pandas as pd
import nltk
from nltk.corpus import stopwords, brown
from nltk.tokenize import word_tokenize
import math
from collections import Counter
#generate corpus word_cloud
df = pd.read_csv('song_database')
stop_words ... | Python | zaydzuhri_stack_edu_python |
function getFFT data rate
begin
set data = data * call hamming length data
set fft = fft data
set fft = absolute fft
comment fft=10*np.log10(fft)
set freq = call fftfreq length fft 1.0 / rate
return tuple freq at slice : integer length freq / 2 : fft at slice : integer length fft / 2 :
end function | def getFFT(data, rate):
data = data * np.hamming(len(data))
fft = np.fft.fft(data)
fft = np.abs(fft)
# fft=10*np.log10(fft)
freq = np.fft.fftfreq(len(fft), 1.0 / rate)
return freq[:int(len(freq) / 2)], fft[:int(len(fft) / 2)] | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
comment Start.pyから見た相対パス
set filename = string ./TestPicture/testsheezoo01.jpg
comment 白黒画像で画像を読み込み
set img = call imread filename 1
comment 画像の高さ幅を指定
set tuple width height = tuple 60 60
comment 画像をリサイズ
set img = call resize img tuple width height
call imwrite string ./TestPicture/testshe... | import cv2
import numpy as np
filename = "./TestPicture/testsheezoo01.jpg" # Start.pyから見た相対パス
# 白黒画像で画像を読み込み
img = cv2.imread(filename,1)
# 画像の高さ幅を指定
width,height = 60,60
# 画像をリサイズ
img = cv2.resize(img,(width,height))
cv2.imwrite('./TestPicture/testsheezoo01_004_1.jpg',img)
width,height = 1500,1500
... | Python | zaydzuhri_stack_edu_python |
class Human
begin
set __instance = none
function __init__ self name
begin
set name = name
end function
function __new__ cls *args **kwargs
begin
if __instance == none
begin
set __instance = call __new__ cls
return __instance
end
else
begin
return __instance
end
end function
end class
set h1 = call Human string jack
set... | class Human:
__instance=None
def __init__(self,name):
self.name=name
def __new__(cls, *args, **kwargs):
if cls.__instance==None:
cls.__instance=object.__new__(cls)
return cls.__instance
else:
return cls.__instance
h1=Human('jack')
h2=Human('mike'... | Python | zaydzuhri_stack_edu_python |
import time
import math
import numpy as np
import cv2
from matplotlib import pyplot as plt
import matplotlib.animation as animation
function obstacleOrNot point radius=22 clearance=5
begin
string Check whether the point is inside or outside the defined obstacles and clearance. Note: The obstacles have been defined usin... | import time
import math
import numpy as np
import cv2
from matplotlib import pyplot as plt
import matplotlib.animation as animation
def obstacleOrNot(point, radius = 22, clearance = 5):
"""
Check whether the point is inside or outside the
defined obstacles and clearance.
Note: The obstacle... | Python | zaydzuhri_stack_edu_python |
function validaURL url
begin
comment Linea 1
return search url != none
end function | def validaURL(url: AnyStr) -> bool:
return re.compile(patternURL).search(url) != None # Linea 1 | Python | nomic_cornstack_python_v1 |
function estimate_P C reversible=true fixed_statdist=none maxiter=1000000 maxerr=1e-08 mincount_connectivity=0
begin
string Estimates full transition matrix for general connectivity structure Parameters ---------- C : ndarray count matrix reversible : bool estimate reversible? fixed_statdist : ndarray or None estimate ... | def estimate_P(C, reversible=True, fixed_statdist=None, maxiter=1000000, maxerr=1e-8, mincount_connectivity=0):
""" Estimates full transition matrix for general connectivity structure
Parameters
----------
C : ndarray
count matrix
reversible : bool
estimate reversible?
fixed_sta... | Python | jtatman_500k |
function _E_mod_optimality self Cov
begin
set eig_vals = call eigvals Cov
return min eig_vals / max eig_vals
end function | def _E_mod_optimality(self, Cov:numpy.ndarray) -> float:
eig_vals = numpy.linalg.eigvals(Cov)
return numpy.min(eig_vals) / numpy.max(eig_vals) | Python | nomic_cornstack_python_v1 |
function match_config regex
begin
if _TRAFFICCTL
begin
set cmd = call _traffic_ctl string config string match regex
end
else
begin
set cmd = call _traffic_line string -m regex
end
return call _subprocess cmd
end function | def match_config(regex):
if _TRAFFICCTL:
cmd = _traffic_ctl("config", "match", regex)
else:
cmd = _traffic_line("-m", regex)
return _subprocess(cmd) | Python | nomic_cornstack_python_v1 |
function test_narrow_recursive_filesystems
begin
set r = call narrow_recursive_filesystems list string tank/foo string tank/foo/foo string tank/foo/bar/foo string tank/bar
call assert_equal r list string tank/foo string tank/bar
end function | def test_narrow_recursive_filesystems():
r = zfssnapshot.narrow_recursive_filesystems([
'tank/foo',
'tank/foo/foo',
'tank/foo/bar/foo',
'tank/bar'])
assert_equal(r,['tank/foo','tank/bar']) | Python | nomic_cornstack_python_v1 |
function f_remove self *args
begin
for arg in args
begin
set arg = call f_translate_key arg
if arg in _data
begin
del _data at arg
end
else
begin
raise call AttributeError string Your result `%s` does not contain %s. % tuple name_ arg
end
end
end function | def f_remove(self, *args):
for arg in args:
arg = self.f_translate_key(arg)
if arg in self._data:
del self._data[arg]
else:
raise AttributeError(
"Your result `%s` does not contain %s." % (self.name_, arg)
) | Python | nomic_cornstack_python_v1 |
function _fix_package_selections self packages config_opts
begin
set selections = string
for package in packages
begin
set m = match string (.+)=(.+) package
if m
begin
set package_name = call group 1
end
else
begin
set package_name = package
end
set command = string sudo debconf-show %s % package_name
set p = call ge... | def _fix_package_selections(self, packages, config_opts):
selections = ""
for package in packages:
m = re.match('(.+)=(.+)', package)
if m:
package_name = m.group(1)
else:
package_name = package
command = "sudo debco... | Python | nomic_cornstack_python_v1 |
from base_player import BasePlayer
from random import randint
class PseudoRandomPlayer extends BasePlayer
begin
function __init__ self
begin
call __init__
set name = string RandomPlayer
end function
function choose_card self
begin
return random integer 0 length hand - 1
end function
end class | from base_player import BasePlayer
from random import randint
class PseudoRandomPlayer(BasePlayer):
def __init__(self):
super().__init__()
self.name = 'RandomPlayer'
def choose_card(self) -> int:
return randint(0, len(self.hand) - 1)
| Python | zaydzuhri_stack_edu_python |
function averageGrade students
begin
set sum = 0.0
for key in students
begin
set sum = sum + students at key at string grade
end
set average = sum / length students
return average
end function
function printRecords students
begin
print string There are %d students % length students
set i = 1
for key in students
begin
p... | def averageGrade(students):
sum=0.0
for key in students:
sum=sum+students[key]['grade']
average=sum/len(students)
return average
def printRecords(students):
print('There are %d students' % (len(students)))
i=1
for key in students:
print('Student %d:' % (i))
print('Nam... | Python | zaydzuhri_stack_edu_python |
function image_to_base64 image
begin
set ax = axes
set binary_buffer = call BytesIO
comment image is saved in axes coordinates: we need to temporarily
comment set the correct limits to get the correct image
set lim = axis
axis call get_extent
call write_png binary_buffer
axis lim
seek binary_buffer 0
return decode base... | def image_to_base64(image):
ax = image.axes
binary_buffer = io.BytesIO()
# image is saved in axes coordinates: we need to temporarily
# set the correct limits to get the correct image
lim = ax.axis()
ax.axis(image.get_extent())
image.write_png(binary_buffer)
ax.axis(lim)
... | Python | nomic_cornstack_python_v1 |
function login self
begin
debug string login called
comment Apply settings
call apply_to_upcoming_session
call apply_to_upcoming_session
call apply_to_upcoming_session
call apply_to_upcoming_session
call hide
call do_login
end function | def login(self):
logging.debug("login called")
# Apply settings
self.localisationsettings.apply_to_upcoming_session()
self.admin_setting.apply_to_upcoming_session()
self.macspoof_setting.apply_to_upcoming_session()
self.network_setting.apply_to_upcoming_session()
... | Python | nomic_cornstack_python_v1 |
function vQuantizeUniform aNumVec nBits
begin
comment Notes:
comment Make sure to vectorize properly your function as specified in the homework instructions
comment YOUR CODE STARTS HERE ###
set aNumVec = array aNumVec
set s = zeros like aNumVec
set s at aNumVec < 0 = 1 ? nBits - 1
set aQuantizedNumVec = as type 2 ^ nB... | def vQuantizeUniform(aNumVec, nBits):
#Notes:
#Make sure to vectorize properly your function as specified in the homework instructions
### YOUR CODE STARTS HERE ###
aNumVec = np.array(aNumVec)
s = np.zeros_like(aNumVec)
s[aNumVec < 0] = 1 << (nBits - 1)
aQuantizedNumVec = (((2**nBits - 1) ... | Python | nomic_cornstack_python_v1 |
comment Last run in April 2019
import pandas as pd
import requests
from lxml import html , etree
comment Function to scrap and return web data
function scrapedata url
begin
set d = get requests url
set rootdata = call fromstring content
return rootdata
end function
comment Create a list to store scraped data
set hdblis... | # Last run in April 2019
import pandas as pd
import requests
from lxml import html, etree
# Function to scrap and return web data
def scrapedata(url):
d=requests.get(url)
rootdata=html.fromstring(d.content)
return rootdata
hdblist = [] # Create a list to store scraped data
# Web pages of iProperty hostin... | Python | zaydzuhri_stack_edu_python |
function demo obj
begin
set obj = obj + obj
print string 形参值为: obj
end function
print string -------值传递-----
set a = string #
print string a的值为: a
call demo a
print string 实参值为: a
print string -----引用传递-----
set a = list 1 2 3
print string a的值为: a
call demo a
print string 实参值为: a | def demo(obj) :
obj += obj
print("形参值为:",obj)
print("-------值传递-----")
a = "#"
print("a的值为:",a)
demo(a)
print("实参值为:",a)
print("-----引用传递-----")
a = [1,2,3]
print("a的值为:",a)
demo(a)
print("实参值为:",a) | Python | zaydzuhri_stack_edu_python |
function get_vars self asserts
begin
set acc = list
function get_vars_ast v
begin
if has attribute v string children
begin
comment hopefully, v is a z3 expression
if call children == list
begin
if not call is_int_value v or call is_rational_value v or call is_true v or call is_false v
begin
return list v
end
else
beg... | def get_vars(self, asserts):
acc = []
def get_vars_ast(v):
if(hasattr(v, "children")):
# hopefully, v is a z3 expression
if v.children() == []:
if not(is_int_value(v) or \
is_rational_value(v) or \
... | Python | nomic_cornstack_python_v1 |
from unittest import TestCase
from algorithms.dinic.Dinic import Dinic , NodeService , EdgeService
class TestDinic extends TestCase
begin
function test_dinic self
begin
set nodeService = call NodeService 6
set edgeService = call EdgeService
call add_edges list list 0 1 4 list 0 3 9 list 3 1 1 list 3 4 3 list 1 2 7 list... | from unittest import TestCase
from algorithms.dinic.Dinic import Dinic, NodeService, EdgeService
class TestDinic(TestCase):
def test_dinic(self):
nodeService = NodeService(6)
edgeService = EdgeService()
edgeService.add_edges(
[[0, 1, 4],
[0, 3, 9],
[3... | Python | zaydzuhri_stack_edu_python |
import csv
comment 開啟 CSV 檔案
function get_test_data_mid
begin
with open string mid_data\mid_lab_data_test.csv newline=string as csvfile
begin
comment 讀取 CSV 檔案內容
set rows = reader csvfile
set data1 = list
set data0 = list 0 0 0 0 0
set i = 0
set j = 0
set k = 0
comment 以迴圈輸出每一列
for row in rows
begin
append data1 row
e... | import csv
# 開啟 CSV 檔案
def get_test_data_mid() :
with open('mid_data\mid_lab_data_test.csv', newline='') as csvfile:
# 讀取 CSV 檔案內容
rows = csv.reader(csvfile)
data1 = []
data0 = [ 0 , 0 , 0 , 0 , 0 ]
i = 0
j = 0
k = 0
# 以迴圈輸出每一列
... | Python | zaydzuhri_stack_edu_python |
function collect self iSub event skipTrivial=true
begin
return call ColConfig_collect self iSub event skipTrivial
end function | def collect(self, iSub, event, skipTrivial=True):
return _pythia8.ColConfig_collect(self, iSub, event, skipTrivial) | Python | nomic_cornstack_python_v1 |
function set self new_attention
begin
for i in range max_depth
begin
set new_layer_copy = list
set n_obj = max_objects * 2
set new_layer = new_attention at slice i * n_obj : i + 1 * n_obj :
for j in range length new_layer - 1
begin
set pair = set literal new_layer at j new_layer at j + 1
append new_layer_copy pair
en... | def set(self, new_attention):
for i in range(self.max_depth):
new_layer_copy = []
n_obj = self.max_objects*2
new_layer = new_attention[i*n_obj:(i+1)*n_obj]
for j in range(len(new_layer) - 1):
pair = {new_layer[j], new_layer[j + 1]}
... | Python | nomic_cornstack_python_v1 |
comment python 3.7
import voice_to_text as vt
comment take in a passowrd and prompt a 2nd factor of verification
call voice_out string please create a password
set new_pw = input string please create a password
call voice_out string New password created successfully
print string New password created successfully
call v... | #python 3.7
import voice_to_text as vt
#take in a passowrd and prompt a 2nd factor of verification
vt.voice_out("please create a password ")
new_pw = input("please create a password ")
vt.voice_out("New password created successfully")
print("New password created successfully")
vt.voice_out("Please create a s... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
import os
import sys
import re
set output = string
set args = argv
set nbr_of_args = length args
set target_file = none
set target_file_name = string min
set path = none
set prepared_file = none
if nbr_of_args > 2
begin
set requested_type = string args at 1
set pa... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import re
output = ""
args = sys.argv
nbr_of_args = len(args)
target_file = None
target_file_name = "min"
path = None
prepared_file = None
if (nbr_of_args > 2):
requested_type = str(args[1])
path = str(args[2])
if (nbr_of_args > 3):
target_file_n... | Python | zaydzuhri_stack_edu_python |
function handleResponse self response
begin
string Handle the response string received by KafkaProtocol. Ok, we've received the response from the broker. Find the requestId in the message, lookup & fire the deferred with the response.
set requestId = call get_response_correlation_id response
comment Protect against res... | def handleResponse(self, response):
"""Handle the response string received by KafkaProtocol.
Ok, we've received the response from the broker. Find the requestId
in the message, lookup & fire the deferred with the response.
"""
requestId = KafkaCodec.get_response_correlation_id(r... | Python | jtatman_500k |
comment !/usr/bin/env python3
string Integrate
function poly_integral poly C=0
begin
string Calculates the integral of a polynomia
if type poly != list or length poly == 0 or type C != int
begin
return none
end
else
begin
set integral = list C
if length poly == 1 and poly at 0 == 0
begin
return integral
end
for i in ra... | #!/usr/bin/env python3
'''Integrate'''
def poly_integral(poly, C=0):
'''Calculates the integral of a polynomia'''
if (
type(poly) != list
) or (
len(poly) == 0
) or (
type(C) != int
):
return None
else:
integral = [C]
if (len(poly) == 1) and poly... | Python | zaydzuhri_stack_edu_python |
function get_config config
begin
if config at slice - 5 : : != string .yaml
begin
set config = config + string .yaml
end
set file_buffer = call BytesIO
with call cd project_dir
begin
get config file_buffer
end
set config_dict = load yaml call getvalue
return config_dict
end function | def get_config(config):
if config[-5:] != '.yaml':
config += '.yaml'
file_buffer = BytesIO()
with cd(env.project_dir):
get(config, file_buffer)
config_dict = yaml.load(file_buffer.getvalue())
return config_dict | Python | nomic_cornstack_python_v1 |
function move self context a=none b=none c=none u=none v=none w=none x=none y=none z=none moveTime=0
begin
set child = call block_view mri
call put_value true
comment Convert move time into milliseconds
call put_value moveTime * 1000.0
comment Add in the motors we need to move
set attribute_values = dict
for axis in C... | def move(
self,
context: builtin.hooks.AContext,
a: ADemandPosition = None,
b: ADemandPosition = None,
c: ADemandPosition = None,
u: ADemandPosition = None,
v: ADemandPosition = None,
w: ADemandPosition = None,
x: ADemandPosition = None,
y:... | Python | nomic_cornstack_python_v1 |
set tuple a1 a2 = map int split call raw_input
set tuple b1 b2 = map int split call raw_input
set tuple c1 c2 = map int split call raw_input
set tuple d1 d2 = map int split call raw_input | a1,a2=map(int,raw_input().split())
b1,b2=map(int,raw_input().split())
c1,c2=map(int,raw_input().split())
d1,d2=map(int,raw_input().split()) | Python | zaydzuhri_stack_edu_python |
function factor_list number
begin
set factors = set
for i in range 1 integer number ^ 0.5 + 1
begin
if not number % i
begin
add factors i
add factors number // i
end
end
set factors = list factors
sort factors
return factors
end function | def factor_list(number):
factors = set()
for i in range(1, int(number ** 0.5) + 1):
if not(number % i):
factors.add(i)
factors.add(number // i)
factors = list(factors)
factors.sort()
return factors | Python | nomic_cornstack_python_v1 |
function set_default_issue_report_count_down_time self
begin
call ensure_one
set Param = env at string ir.config_parameter
set config = issue_report_count_down_time or 0.0
call set_param string issue_report_count_down_time config
end function | def set_default_issue_report_count_down_time(self):
self.ensure_one()
Param = self.env['ir.config_parameter']
config = self.issue_report_count_down_time or 0.0
Param.set_param('issue_report_count_down_time', config) | Python | nomic_cornstack_python_v1 |
function compress_file filename
begin
with open filename string rb as f
begin
return call encodeInBinary encode read f
end
end function | def compress_file(filename: str) -> List[tuple]:
with open(filename, "rb") as f:
return encodeInBinary(encode(f.read())) | Python | nomic_cornstack_python_v1 |
from socket import *
import random
import sys
set seed = integer input string Enter value to seed the random number generator:
set prob = decimal input string Enter the probability of a segment corruption:
set randomGen = random
seed seed
set serverHost = string 127.0.0.1
set serverPort = 50007
set serverSocket = call ... | from socket import *
import random
import sys
seed = int(input('Enter value to seed the random number generator: '))
prob = float(input('Enter the probability of a segment corruption: '))
randomGen = random.Random()
randomGen.seed(seed)
serverHost = '127.0.0.1'
serverPort = 50007
serverSocket = socket(AF_INET,SOCK_DGR... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import os
import cv2
import math
import argparse
import tensorflow as tf
import json
from skimage.filters import threshold_otsu
from docrec.strips.strips import Strips
from docrec.models.squeezenet import SqueezeNet
from docrec.models.mobilenet import MobileNetFC
function extract_features strip input... | import numpy as np
import os
import cv2
import math
import argparse
import tensorflow as tf
import json
from skimage.filters import threshold_otsu
from docrec.strips.strips import Strips
from docrec.models.squeezenet import SqueezeNet
from docrec.models.mobilenet import MobileNetFC
def extract_features(strip, input_... | Python | zaydzuhri_stack_edu_python |
function test_is_url self
begin
assert true call is_url string http://www.example.com
end function | def test_is_url(self):
self.assertTrue(self.urls.is_url("http://www.example.com")) | Python | nomic_cornstack_python_v1 |
function classify samples
begin
set vectorizer = call TfidfVectorizer stop_words=string english
set documents = fit transform vectorizer samples
set classifier = support vector classifier C=1.0 kernel=string linear gamma=string auto
fit classifier documents
set classes = predict classifier documents
return classes
end ... | def classify(samples):
vectorizer = TfidfVectorizer(stop_words='english')
documents = vectorizer.fit_transform(samples)
classifier = SVC(C=1.0, kernel='linear', gamma='auto')
classifier.fit(documents)
classes = classifier.predict(documents)
return classes
| Python | flytech_python_25k |
function run self dag
begin
string Run the pass on the DAG, and write the discovered commutation relations into the property_set.
comment Initiate the commutation set
set property_set at string commutation_set = default dictionary list
comment Build a dictionary to keep track of the gates on each qubit
for wire in wire... | def run(self, dag):
"""
Run the pass on the DAG, and write the discovered commutation relations
into the property_set.
"""
# Initiate the commutation set
self.property_set['commutation_set'] = defaultdict(list)
# Build a dictionary to keep track of the gates on e... | Python | jtatman_500k |
comment Implementação do modelo
from scipy.integrate import odeint
from numpy import linspace
import matplotlib.pyplot as plt
comment Temperatura inicial da água (Kelvin)
set A0 = 296.0
comment Temperatura do ambiente (geladeira) (Kelvin)
set Tinf = 281.0
comment Massa da água (kilograma)
set Ma = 1.585
comment Calor e... | # Implementação do modelo
from scipy.integrate import odeint
from numpy import linspace
import matplotlib.pyplot as plt
A0 = 296.0 # Temperatura inicial da água (Kelvin)
Tinf = 281.0 # Temperatura do ambiente (geladeira) (Kelvin)
Ma = 1.585 # Massa da água (kilograma)
Ca = 4181.3 # Calor específico da água (J... | Python | zaydzuhri_stack_edu_python |
string Name: byroncbr_104.py Author: bangrenc Time: 9/3/2020 10:15 AM
comment Definition for a binary tree node.
class TreeNode
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
end function
end class
class Solution
begin
function maxDepth self root
begin
if not root
begin
return 0
end
r... | """
Name: byroncbr_104.py
Author: bangrenc
Time: 9/3/2020 10:15 AM
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment Projeto problema tecnico de modelagem e implementação de uma função semelhante à da HP50g, que nos permite calcular o valor de uma incógnita em qualquer lugar dentro de uma expressão matemática
function eh_incognita valor
begin
try
begin
decimal valor
return false
end
except ValueE... | # -*- coding: utf-8 -*-
# Projeto problema tecnico de modelagem e implementação de uma função semelhante à da HP50g, que nos permite calcular o valor de uma incógnita em qualquer lugar dentro de uma expressão matemática
def eh_incognita(valor):
try:
float(valor)
return False
except ValueError:
... | Python | zaydzuhri_stack_edu_python |
function generic_function n k
begin
set n = list comprehension x for x in n
set flips = 0
while true
begin
set loc = - 1
for p in range length n
begin
if n at p == string -
begin
set loc = p
break
end
end
if loc == - 1
begin
return flips
end
else
if loc + k > length n
begin
return string IMPOSSIBLE
end
else
begin
set f... | def generic_function(n, k):
n = [x for x in n]
flips = 0
while True:
loc = -1
for p in range(len(n)):
if n[p] == '-':
loc = p
break
if loc == -1:
return flips
elif loc + k > len(n):
return 'IMPOSS... | Python | zaydzuhri_stack_edu_python |
comment Imports
import requests
from bs4 import BeautifulSoup
from gensim.summarization import summarize
from nltk.chat.util import Chat , reflections
comment Retrieve page text
set url = string https://t2conline.com/what-can-you-do-with-python/
set page = text
comment Turn page into BeautifulSoup object to access HTML... | # Imports
import requests
from bs4 import BeautifulSoup
from gensim.summarization import summarize
from nltk.chat.util import Chat, reflections
# Retrieve page text
url = 'https://t2conline.com/what-can-you-do-with-python/'
page = requests.get(url).text
# Turn page into BeautifulSoup object to access HTML tags
soup =... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sun Apr 25 19:54:40 2021 @author: david Eliminar barras y pequeñas regiones de sudoku analizando formas
import cv2
import numpy as np
import matplotlib.pyplot as plt
comment Usa esta función en lugar del filtro de la media para que no afecte a los numeros
function Filtro_... | # -*- coding: utf-8 -*-
"""
Created on Sun Apr 25 19:54:40 2021
@author: david
Eliminar barras y pequeñas regiones de sudoku analizando formas
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
#Usa esta función en lugar del filtro de la media para que no afecte a los numeros
def Filtro_tamaño(img_bin... | Python | zaydzuhri_stack_edu_python |
if h <= 40
begin
set pay = h * rate
end
else
begin
set pay = 40 * rate + 1.5 * rate * h - 40
end
print pay | if h<=40:
pay = h*rate
else:
pay = 40*rate + 1.5*rate*(h-40)
print(pay)
| Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set l = list
end function | def __init__(self):
self.l = [] | Python | nomic_cornstack_python_v1 |
from PriorityQueue import PriorityQueue
function PriorityQueueTest
begin
set errorcount = 0
set q = call PriorityQueue
comment UnitTest.assertTrue("q.isEmpty() -> " + str(q.isEmpty()), q.isEmpty())
if call isEmpty != true
begin
set errorcount = errorcount + 1
end
if length q != 0
begin
set errorcount = errorcount + 1
e... | from PriorityQueue import PriorityQueue
def PriorityQueueTest():
errorcount = 0
q = PriorityQueue()
#UnitTest.assertTrue("q.isEmpty() -> " + str(q.isEmpty()), q.isEmpty())
if q.isEmpty() != True:
errorcount +=1
if len(q) != 0:
errorcount +=1
q.enqueue("Kokichi", 10);
q.enq... | Python | zaydzuhri_stack_edu_python |
function _init_layers self
begin
set cls_out_channels = num_anchors * num_classes
set conv_cls = conv 2d feat_channels cls_out_channels 1
set conv_reg = conv 2d feat_channels num_anchors * box_code_size 1
if use_direction_classifier
begin
set conv_dir_cls = conv 2d feat_channels num_anchors * 2 1
end
end function | def _init_layers(self):
self.cls_out_channels = self.num_anchors * self.num_classes
self.conv_cls = nn.Conv2d(self.feat_channels, self.cls_out_channels, 1)
self.conv_reg = nn.Conv2d(self.feat_channels,
self.num_anchors * self.box_code_size, 1)
if self.us... | Python | nomic_cornstack_python_v1 |
function fitness bit_string
begin
return 2 ^ sum bit_string
end function | def fitness(bit_string):
return 2**sum(bit_string) | Python | nomic_cornstack_python_v1 |
function server_version self timeout
begin
call _abstract
end function | def server_version(self, timeout):
_abstract() | Python | nomic_cornstack_python_v1 |
function get_total_file_size self file_type
begin
return get file_size_counter file_type 0
end function | def get_total_file_size(self, file_type):
return self.file_size_counter.get(file_type, 0) | Python | nomic_cornstack_python_v1 |
for iter in range integer input
begin
set tuple N K = list map int split strip input
set arr = input
set arr_max = arr
set result = 0
set i = 0
set kcount = 0
set mult_arr = list 0 * N
while i < N
begin
set arr = arr at slice 1 : : + arr at 0
comment print(arr)
if arr > arr_max
begin
set arr_max = arr
set result = i ... | for iter in range(int(input())):
(N,K) = list(map(int, input().strip().split()))
arr = input()
arr_max = arr
result = 0
i=0
kcount=0
mult_arr = [0] * N
while i<N:
arr = arr[1:]+arr[0]
# print(arr)
if arr > arr_max:
arr_max = arr
result = (i... | Python | zaydzuhri_stack_edu_python |
function _getTempsDelexpression listedMatrix
begin
string each template is implemented as a boolean expression of symbols where each symbol represents each one of the 26 neighbors
set str1 = join string generator expression string e for e in listedMatrix
set tuple a b c d e f g h i j k l m n o p q r s t u v w x y z = ... | def _getTempsDelexpression(listedMatrix):
"""
each template is implemented as a boolean expression of symbols
where each symbol represents each one of the 26 neighbors
"""
str1 = ''.join(str(e) for e in listedMatrix)
a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x,... | Python | nomic_cornstack_python_v1 |
function eval_det_cls pred gt ovthresh=0.25 use_07_metric=false
begin
comment construct gt objects
comment {img_id: {'bbox': bbox list, 'det': matched list}}
set class_recs = dict
set npos = 0
for img_id in keys gt
begin
set bbox = array gt at img_id
set det = list false * length bbox
set npos = npos + length bbox
set... | def eval_det_cls(pred, gt, ovthresh=0.25, use_07_metric=False):
# construct gt objects
class_recs = {} # {img_id: {'bbox': bbox list, 'det': matched list}}
npos = 0
for img_id in gt.keys():
bbox = np.array(gt[img_id])
det = [False] * len(bbox)
npos += len(bbox)
class_rec... | Python | nomic_cornstack_python_v1 |
function delete_branch self branch_name merged_only=true
begin
if merged_only
begin
set delete_flag = string -d
end
else
begin
set delete_flag = string -D
end
try
begin
call _run_git list string branch delete_flag branch_name
end
except RunProcessError as e
begin
raise call SCMError string e
end
end function | def delete_branch(self, branch_name, merged_only=True):
if merged_only:
delete_flag = '-d'
else:
delete_flag = '-D'
try:
self._run_git(['branch', delete_flag, branch_name])
except RunProcessError as e:
raise SCMError(str(e)) | Python | nomic_cornstack_python_v1 |
import pytest
from Checkout import Checkout
class TestClassCheckout
begin
decorator fixture
function checkout self
begin
set checkout = call Checkout
call addItemPrice string a 1
call addItemPrice string b 2
return checkout
end function
function test_can_calculate_total self checkout
begin
call addItem string a
assert ... | import pytest
from Checkout import Checkout
class TestClassCheckout:
@pytest.fixture()
def checkout(self):
checkout = Checkout()
checkout.addItemPrice("a", 1)
checkout.addItemPrice("b", 2)
return checkout
def test_can_calculate_total(self, checkout):
checkout.addI... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
function comb N
begin
set s = 0
for i in N
begin
set s = 10 * s + i
end
return s
end function
function decomb n
begin
set N = list
while n > 0
begin
append N n % 10
set n = n / 10
end
reverse N
return N
end function
function sub N
begin
return call decomb call comb N - 1
end functio... | #!/usr/bin/python
import sys
def comb(N):
s = 0
for i in N:
s = 10*s + i
return s
def decomb(n):
N = []
while n > 0:
N.append(n%10)
n = n/10
N.reverse()
return N
def sub(N):
return decomb(comb(N)-1)
def solve(N):
if N[-1] == 0:
return 1+solve(sub(N))
step = 1
l = len(N)
if l > 1:
step = solve... | Python | zaydzuhri_stack_edu_python |
function run self dt forcing water_sink=none heat_sink=none lbc_water=none lbc_heat=none state=none
begin
set fluxes = dict
if solve_water
begin
set water_fluxes = run dt forcing water_sink=water_sink lower_boundary=lbc_water
update fluxes water_fluxes
end
else
comment if self.solve_water == False, update state if giv... | def run(self, dt, forcing, water_sink=None, heat_sink=None, lbc_water=None, lbc_heat=None, state=None):
fluxes = {}
if self.solve_water:
water_fluxes = self.water.run(dt,
forcing,
water_sink=water_sink,
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: UTF-8 -*-
import requests
import re
import sys
comment get url in the same ip | # -*- coding: UTF-8 -*-
import requests
import re
import sys
#get url in the same ip | Python | zaydzuhri_stack_edu_python |
function edge_expansion G S T=none weight=none
begin
if T is none
begin
set T = set G - set S
end
set num_cut_edges = call cut_size G S T=T weight=weight
return num_cut_edges / min length S length T
end function | def edge_expansion(G, S, T=None, weight=None):
if T is None:
T = set(G) - set(S)
num_cut_edges = cut_size(G, S, T=T, weight=weight)
return num_cut_edges / min(len(S), len(T)) | Python | nomic_cornstack_python_v1 |
string /github/utils.py Copyright (c) 2019 ShineyDev Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writi... | """
/github/utils.py
Copyright (c) 2019 ShineyDev
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by app... | Python | zaydzuhri_stack_edu_python |
function find_unordered_cfg_lines intended_cfg actual_cfg
begin
set intended_lines = call splitlines
set actual_lines = call splitlines
set unordered_lines = list
if length intended_lines == length actual_lines
begin
comment Process to find actual lines that are misordered
set unordered_lines = list comprehension tuple... | def find_unordered_cfg_lines(intended_cfg, actual_cfg):
intended_lines = intended_cfg.splitlines()
actual_lines = actual_cfg.splitlines()
unordered_lines = list()
if len(intended_lines) == len(actual_lines):
# Process to find actual lines that are misordered
unordered_lines = [(e1, e2) f... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import collections , sys
if __name__ == string __main__
begin
print string Enter Total No. of Sticks:
set N = integer read line stdin
print string Enter Sizes
set a = sorted map int split read line stdin
set c = counter a
set count = list comprehension c at k for k in sorted c
for i in rang... | #!/usr/bin/env python
import collections, sys
if __name__ == '__main__':
print("Enter Total No. of Sticks: ")
N = int(sys.stdin.readline())
print("Enter Sizes")
a = sorted(map(int, sys.stdin.readline().split()))
c = collections.Counter(a)
count = [c[k] for k in sorted(c)]
for i ... | Python | zaydzuhri_stack_edu_python |
function overlaps_height self other_pallet
begin
set diff = z - z
return 0 <= diff < height
end function | def overlaps_height(self, other_pallet):
diff = other_pallet.origin_point.z - self.origin_point.z
return 0 <= diff < self.height | Python | nomic_cornstack_python_v1 |
from chatterbot import ChatBot
from flask import Flask
set app = call Flask __name__
decorator call route string /abc/<string:question> methods=list string GET
function get_answer question
begin
set reply = string
set bot = call ChatBot string Bot read_only=true logic_adapters=list dict string import_path string chatt... | from chatterbot import ChatBot
from flask import Flask
app = Flask(__name__)
@app.route('/abc/<string:question>', methods=['GET'])
def get_answer(question):
reply = ''
bot = ChatBot('Bot',read_only=True,
logic_adapters=[
{
'import_path': 'chatt... | Python | zaydzuhri_stack_edu_python |
comment Transfer all possible processing data into dict, send to processIncoming GUI thread for calculations.
function workerThread1 self
begin
while running
begin
global floopdic
set lastfloopdic = copy floopdic
global thisflooptime
comment Check if this is the same object or actually copied!
set lastflooptime = thisf... | def workerThread1(self): # Transfer all possible processing data into dict, send to processIncoming GUI thread for calculations.
while self.running:
global floopdic
lastfloopdic = floopdic.copy()
global thisflooptime
lastflooptime = thisflooptime # Check if this i... | Python | nomic_cornstack_python_v1 |
class PriorityList extends list
begin
function __contains__ self item
begin
return is instance item tuple self
end function
end class | class PriorityList(list):
def __contains__(self, item):
return isinstance(item, tuple(self))
| Python | zaydzuhri_stack_edu_python |
function get_unit uuid unit_reference_id
begin
set tuple units _ = call get_units uuid list unit_reference_id
if units
begin
return units at 0
end
return none
end function | def get_unit(uuid: UUID, unit_reference_id: int) -> Optional['Unit']:
units, _ = get_units(uuid, [unit_reference_id])
if units:
return units[0]
return None | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
comment -*- coding: utf-8 -*-
comment @Time : 2019/11/30 23:06
comment @File : txt.py
import re
from common import logger
class Txt
begin
string 用来读写txt文档
function __init__ self path
begin
comment 保存文件路径
set path = path
comment 将txt文件内容保存
set data = list
comment 将写入的txt文件保存
set w = none
end f... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2019/11/30 23:06
# @File : txt.py
import re
from common import logger
class Txt:
"""
用来读写txt文档
"""
def __init__(self,path):
#保存文件路径
self.path = path
#将txt文件内容保存
self.data = []
#将写入的txt文件保存
self.w =... | Python | zaydzuhri_stack_edu_python |
function get_linked_list_length head
begin
set slow = head
set fast = head
while fast and next
begin
set slow = next
set fast = next
comment Cycle detected
if slow == fast
begin
return - 1
end
end
set length = 0
while slow
begin
set length = length + 1
set slow = next
end
return length
end function | def get_linked_list_length(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast: # Cycle detected
return -1
length = 0
while slow:
length += 1
slow = slow.next
return length
| Python | jtatman_500k |
function get_itd_dict max_itd num_bins
begin
set bin_length = 2 * max_itd / num_bins
return array list comprehension - max_itd + idx + 0.5 * bin_length for idx in range num_bins dtype=float32
end function | def get_itd_dict(max_itd, num_bins):
bin_length = 2 * max_itd / num_bins
return np.array([-max_itd + (idx + 0.5) * bin_length for idx in range(num_bins)], dtype=np.float32) | Python | nomic_cornstack_python_v1 |
function query self value
begin
import xml.etree.ElementTree as ET
set to_set = none
if is instance value basestring
begin
comment register default namespace as vidispine, http://stackoverflow.com/questions/8983041/saving-xml-files-using-elementtree
comment ET.register_namespace('',"http://xml.vidispine.com/schema/vidi... | def query(self,value):
import xml.etree.ElementTree as ET
to_set = None
if isinstance(value,basestring):
#register default namespace as vidispine, http://stackoverflow.com/questions/8983041/saving-xml-files-using-elementtree
#ET.register_namespace('',"http://xml.vidispine... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from lxml import html
import requests
while true
begin
set turl = input string Enter Twitter URL:
set url = turl
comment request Twitter web page
set page = get requests url
set tree = call fromstring content
comment search for the Profile Nav Bar using Xpath
set navBar = call xpath string... | # -*- coding: utf-8 -*-
from lxml import html
import requests
while True:
turl = input("Enter Twitter URL: ")
url = turl
# request Twitter web page
page = requests.get(url)
tree = html.fromstring(page.content)
# search for the Profile Nav Bar using Xpath
navBar = tree.x... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
from typing import Dict , List
import nltk
from dictionary.utils.constants import TaggedTextTagsWordsDelimiter
from dictionary.utils.managers.tagging.common import BaseTaggingManager
class NLTKTaggingManager extends BaseTaggingManager
begin
set DEFAULT_DELIMITER = SINGLE_UNDERSCORE
d... | from collections import defaultdict
from typing import Dict, List
import nltk
from dictionary.utils.constants import TaggedTextTagsWordsDelimiter
from dictionary.utils.managers.tagging.common import BaseTaggingManager
class NLTKTaggingManager(BaseTaggingManager):
DEFAULT_DELIMITER = TaggedTextTagsWordsDelimite... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
from app import create_app
set app = call create_app
comment 打开调试模式
comment host='0.0.0.0'表示可以接受外网输出 post='xxx'表示端口
comment DEBUG必须都是大写才行,否则找不到。DEBUG在flask里面是个默认参数,默认值为False,所以在config文件里没有设置DEBUG也会有值
comment 线程技术使用了LocalStack线程隔离技术,使用线程隔离的意义在于:使当前线程能够正确引用到他自己所创建的对象,而不是引用到其它线程所创建的对象
if __nam... | # -*- coding:utf-8 -*-
from app import create_app
app = create_app()
# 打开调试模式
# host='0.0.0.0'表示可以接受外网输出 post='xxx'表示端口
# DEBUG必须都是大写才行,否则找不到。DEBUG在flask里面是个默认参数,默认值为False,所以在config文件里没有设置DEBUG也会有值
# 线程技术使用了LocalStack线程隔离技术,使用线程隔离的意义在于:使当前线程能够正确引用到他自己所创建的对象,而不是引用到其它线程所创建的对象
if __name__ == '__main__':
# app.run(... | Python | zaydzuhri_stack_edu_python |
function write_pre_uimessage msg win with_timestamps nick_size
begin
set color : Optional at Tuple
set offset = 0
if with_timestamps
begin
set offset = offset + call write_time win false time
end
comment not a message, nothing to do afterwards
if not level
begin
return offset
end
set level = call truncate_nick level ni... | def write_pre_uimessage(msg: UIMessage, win: Win, with_timestamps: bool, nick_size: int) -> int:
color: Optional[Tuple]
offset = 0
if with_timestamps:
offset += PreMessageHelpers.write_time(win, False, msg.time)
if not msg.level: # not a message, nothing to do afterwards
return offset
... | Python | nomic_cornstack_python_v1 |
function fluid_func self
begin
set residual = list
for tuple fluid x in items val
begin
set res = - x * val_SI
for i in inl
begin
set res = res + val at fluid * val_SI
end
set residual = residual + list res
end
return residual
end function | def fluid_func(self):
residual = []
for fluid, x in self.outl[0].fluid.val.items():
res = -x * self.outl[0].m.val_SI
for i in self.inl:
res += i.fluid.val[fluid] * i.m.val_SI
residual += [res]
return residual | Python | nomic_cornstack_python_v1 |
function s2n self offset length signed=0
begin
seek file offset + offset
set slice = read file length
if endian == string I
begin
set val = call s2n_intel slice
end
else
begin
set val = call s2n_motorola slice
end
comment Sign extension ?
if signed
begin
set msb = 1 ? 8 * length - 1
if val ? msb
begin
set val = val - m... | def s2n(self, offset, length, signed=0):
self.file.seek(self.offset + offset)
slice = self.file.read(length)
if self.endian == 'I':
val = s2n_intel(slice)
else:
val = s2n_motorola(slice)
# Sign extension ?
if signed:
msb = 1 <<... | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
import matplotlib.pylab as pl
import matplotlib.cm as cm
import Image
import numpy as np
set kids_0 = call asarray call convert string L / decimal 255
set tuple M N = shape
set r = array range 0 1 + 0.0001 0.0001
set s1 = r ^ 0.6
set s2 = r ^ 0.4
set s3 = r ^ 0.3
set fig = figure figsize=li... | # -*- coding:utf-8 -*-
import matplotlib.pylab as pl
import matplotlib.cm as cm
import Image
import numpy as np
kids_0 = np.asarray(Image.open('kids.tif').convert('L'))/float(255)
(M,N) = kids_0.shape
r = np.arange(0,1+0.0001,0.0001)
s1 = r**0.6
s2 = r**0.4
s3 = r**0.3
fig = pl.figure(figsize=[12,12])
ax1 = fig.add_s... | Python | zaydzuhri_stack_edu_python |
function count_frequency tokens
begin
set count = dict
for t in tokens
begin
set count at t = get count t 0.0 + 1.0
end
return count
end function | def count_frequency(tokens):
count = {}
for t in tokens:
count[t] = count.get(t, 0.0) + 1.0
return count | Python | nomic_cornstack_python_v1 |
function set_sloped_mannings_function self flag=true
begin
if flag
begin
set use_sloped_mannings = true
end
else
begin
set use_sloped_mannings = false
end
end function | def set_sloped_mannings_function(self, flag=True):
if flag:
self.use_sloped_mannings = True
else:
self.use_sloped_mannings = False | Python | nomic_cornstack_python_v1 |
function populate_open_mock mocked_open
begin
set file = call MagicMock name=string mocked_open.mocked_file
set context = call MagicMock name=string mocked_open.mocked_context
set return_value = file
set mocked_file = file
set mocked_context = context
set return_value = context
return mocked_open
end function | def populate_open_mock(mocked_open: MagicMock) -> MagicMock:
file = MagicMock(name='mocked_open.mocked_file')
context = MagicMock(name='mocked_open.mocked_context')
context.__enter__.return_value = file
mocked_open.mocked_file = file
mocked_open.mocked_context = context
mocked_open.return_valu... | Python | nomic_cornstack_python_v1 |
function _assign_clusters self
begin
string Assign the samples to the closest centroids to create clusters
set clusters = array list comprehension call _closest_centroid x for x in _X
end function | def _assign_clusters(self):
"""Assign the samples to the closest centroids to create clusters
"""
self.clusters = np.array([self._closest_centroid(x) for x in self._X]) | Python | jtatman_500k |
function _event self event
begin
call _event_select_text event
end function | def _event(self, event):
self._event_select_text(event) | Python | nomic_cornstack_python_v1 |
comment There exist numbers a, b and c such that a^2+b^2=c^2 and a+b+c=1000
comment Find the product abc
set a = 1.0
while a < 300
begin
set b = - 500000 + 1000 * a / a - 1000
if b > integer b
begin
set a = a + 1
comment print b
comment print int(b)
continue
end
end | # There exist numbers a, b and c such that a^2+b^2=c^2 and a+b+c=1000
# Find the product abc
a=1.0
while a<300:
b=(-500000+1000*a)/(a-1000)
if b>int(b):
a=a+1
#print b
#print int(b)
continue | Python | zaydzuhri_stack_edu_python |
function send self to=none
begin
if to is not none
begin
set self at string to = to
end
if not call providedBy _xmlstream
begin
call upgradeWithIQResponseTracker _xmlstream
end
set d = call Deferred
set iqDeferreds at self at string id = d
call send self
return d
end function | def send(self, to=None):
if to is not None:
self["to"] = to
if not IIQResponseTracker.providedBy(self._xmlstream):
upgradeWithIQResponseTracker(self._xmlstream)
d = defer.Deferred()
self._xmlstream.iqDeferreds[self['id']] = d
self._xmlstream.send(self)
... | Python | nomic_cornstack_python_v1 |
comment --- Read the RC values from the channel
function get_rc_channel self rc_chan dz=0 trim=1500
begin
if rc_chan > 16 or rc_chan < 1
begin
return - 1
end
comment - Find the index of the channel
set strInChan = string %1d % rc_chan
try
begin
set rcValue = integer get channels strInChan
if dz > 0
begin
if call fabs r... | def get_rc_channel(self, rc_chan, dz=0, trim=1500): #--- Read the RC values from the channel
if (rc_chan > 16 or rc_chan < 1):
return -1
#- Find the index of the channel
strInChan = '%1d' % rc_chan
try:
rcValue = int(self.vehicle.channels... | Python | nomic_cornstack_python_v1 |
function diffcontoursdict contoursdict1 contoursdict2 filecontoursdict=none
begin
import copy
set contours1 = contoursdict1 at string contours
if call NetPolygonsArea contours1 > 0.0
begin
set contours2 = contoursdict2 at string contours
set contoursdiff = call diffcontours contours1 contours2
end
else
begin
set contou... | def diffcontoursdict(contoursdict1, contoursdict2, filecontoursdict=None):
import copy
contours1=contoursdict1['contours']
if polytools.NetPolygonsArea(contours1)>0.:
contours2=contoursdict2['contours']
contoursdiff=diffcontours(contours1, contours2)
else:
contoursdif... | Python | nomic_cornstack_python_v1 |
function max_zoom_zero_or_greater cls v
begin
if v < 0
begin
raise call ValueError string The zoom level must be greater than or equal to 0
end
return integer v
end function | def max_zoom_zero_or_greater(cls, v):
if v < 0:
raise ValueError("The zoom level must be greater than or equal to 0")
return int(v) | Python | nomic_cornstack_python_v1 |
from enviroment import *
class randomagent
begin
function __init__ self env life x y
begin
set env = env
set reslife = life
set posX = x
set posY = y
set cleaned = 0
end function
function perspectiva self
begin
set acciones = list
set X = sX
set Y = sY
if posX > 0 and posX < X - 1
begin
append acciones 1
append accion... | from enviroment import*
class randomagent:
def __init__(self,env,life,x,y):
self.env=env
self.reslife=life
self.posX=x
self.posY=y
self.cleaned=0
def perspectiva(self):
acciones=[]
X=self.env.sX
Y=self.env.sY
if self.posX>0 and self.posX<... | Python | zaydzuhri_stack_edu_python |
comment the variable "args" is already defined
comment args = ['script.py', '1', '2', '3', '4'] # your code here
set my_list = list map int args at slice 1 : :
print my_list | # the variable "args" is already defined
# args = ['script.py', '1', '2', '3', '4'] # your code here
my_list = list(map(int, args[1:]))
print(my_list)
| 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.