code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string In Python: - All objects have an inherent Boolean true or false value - Any nonzero number or nonempty object is true - Zero numbers, empty objects, and the special object None are considered false - Comparisons and equality tests are applied recursively to data structures - Comparisons and equality tests return... | '''
In Python:
- All objects have an inherent Boolean true or false value
- Any nonzero number or nonempty object is true
- Zero numbers, empty objects, and the special object None
are considered false
- Comparisons and equality tests are applied recursively to
data structures
- Compar... | Python | zaydzuhri_stack_edu_python |
import random
set infile = string csv/trainLabelsBal.csv
set outfile = string csv/trainLabelsBal1.csv
with open infile string r as source
begin
set data = list comprehension tuple random line for line in source
end
for i in range 10
begin
sort data
end
with open outfile string w as target
begin
for tuple _ line in data... | import random
infile = 'csv/trainLabelsBal.csv'
outfile = 'csv/trainLabelsBal1.csv'
with open(infile,'r') as source:
data = [ (random.random(), line) for line in source ]
for i in range(10):
data.sort()
with open(outfile,'w') as target:
for _, line in data:
target.write( line ) | Python | zaydzuhri_stack_edu_python |
function test_invoke_command_ipython _with_pyraf test_input expected use_ecl
begin
set result = run string -y use_ecl=use_ecl stdin=test_input
assert not code msg stderr
assert expected in stdout
end function | def test_invoke_command_ipython(_with_pyraf, test_input, expected, use_ecl):
result = _with_pyraf.run('-y', use_ecl=use_ecl, stdin=test_input)
assert not result.code, result.stderr
assert expected in result.stdout | Python | nomic_cornstack_python_v1 |
function sort self col order
begin
call emit
set __tabList = sorted __tabList key=call itemgetter col
if order == DescendingOrder
begin
reverse __tabList
end
call emit
end function | def sort(self, col, order):
self.layoutAboutToBeChanged.emit()
self.__tabList = sorted(self.__tabList, key=operator.itemgetter(col))
if order == Qt.DescendingOrder:
self.__tabList.reverse()
self.layoutChanged.emit() | Python | nomic_cornstack_python_v1 |
function do_info self line
begin
set args = filter none split strip line
if length args != 1 or args at 0 not in app_order
begin
call help_info
end
else
begin
call print_path_help args at 0
end
end function | def do_info(self, line):
args = filter(None, line.strip().split())
if len(args) != 1 or args[0] not in self.router.app_order:
self.help_info()
else:
self.router.print_path_help(args[0]) | Python | nomic_cornstack_python_v1 |
function is_valid_ipv4_address address
begin
try
begin
call inet_pton AF_INET address
end
comment no inet_pton here, sorry
except AttributeError
begin
try
begin
call inet_aton address
end
except error
begin
return false
end
return count address string . == 3
end
comment not a valid address
except error
begin
return fal... | def is_valid_ipv4_address(address):
try:
socket.inet_pton(socket.AF_INET, address)
except AttributeError: # no inet_pton here, sorry
try:
socket.inet_aton(address)
except socket.error:
return False
return address.count('.') == 3
except socket.error: ... | Python | nomic_cornstack_python_v1 |
comment 출석번호가 1,2,3,4 앞에 100을 붙이기로함 -> 101, 102, 103
set students = list 1 2 3 4 5
print students
set students = list comprehension i + 100 for i in students
print students
comment 학생 이름을 길이로 변환
set students = list string Iron man string Thor string I am groot
set students = list comprehension length i for i in student... | # 출석번호가 1,2,3,4 앞에 100을 붙이기로함 -> 101, 102, 103
students = [1,2,3,4,5]
print(students)
students=[i+100 for i in students]
print(students)
#학생 이름을 길이로 변환
students = ["Iron man", "Thor", "I am groot"]
students = [len(i) for i in students]
print(students)
#학생 이름을 대문자로 변환
students = ["Iron man", "Thor", "I am groot"]
stu... | Python | zaydzuhri_stack_edu_python |
string Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal". Example 1: Input: [5, 4, 3, 2, 1] Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"] Explanation: The first three athl... | """
Given scores of N athletes, find their relative ranks and the people with the top three highest scores,
who will be awarded medals: "Gold Medal", "Silver Medal" and "Bronze Medal".
Example 1:
Input: [5, 4, 3, 2, 1]
Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
Explanation: The first three ath... | Python | zaydzuhri_stack_edu_python |
string Modul testujacy modul variation.
import unittest
from combinatorics.variation import OutOfRangeException , StringVariation , RangeStringVariation
import itertools
class Test extends TestCase
begin
string Klasa testow jednostkowych.
function testInit self
begin
string Test warunkow poczatkowych.
assert raises Out... | """
Modul testujacy modul variation.
"""
import unittest
from combinatorics.variation import OutOfRangeException, StringVariation, \
RangeStringVariation
import itertools
class Test(unittest.TestCase):
"""Klasa testow jednostkowych."""
def testInit(self):
"""Test warunkow poczatkowych."""
... | Python | zaydzuhri_stack_edu_python |
function measure_humidity_and_temperature self retries=15 delay_seconds=2
begin
if retries == 0
begin
return read DHT _sensor _pin
end
else
begin
return call read_retry _sensor _pin retries delay_seconds
end
end function | def measure_humidity_and_temperature(self, retries=15, delay_seconds=2):
if retries == 0:
return DHT.read(self._sensor, self._pin)
else:
return DHT.read_retry(self._sensor, self._pin,
retries, delay_seconds) | Python | nomic_cornstack_python_v1 |
function random_string nlen
begin
return join string list comprehension random choice ascii_lowercase for _ in range nlen
end function | def random_string(nlen):
return "".join([random.choice(string.ascii_lowercase) for _ in range(nlen)]) | Python | nomic_cornstack_python_v1 |
import pandas as pd
set area_dict = dict string beijing 300 ; string shanghai 200 ; string guangzhou 600 ; string shenzhen 100
set area = call Series area_dict
set pop_dict = dict string beijing 3000 ; string shanghai 1800 ; string hangzhou 1000 ; string guangzhou 4000
set pop = call Series pop_dict
print area
print po... | import pandas as pd
area_dict = {'beijing':300,'shanghai':200,'guangzhou':600,'shenzhen':100}
area = pd.Series(area_dict)
pop_dict = {'beijing':3000,'shanghai':1800,'hangzhou':1000,'guangzhou':4000,}
pop = pd.Series(pop_dict)
print(area)
print(pop)
print(pop/area)
A = pd.Series([2,4,6],index=[0,1,2])
B = pd.Series([1... | Python | zaydzuhri_stack_edu_python |
function inner text
begin
return format string *{0}{1}{2}{0}* string * padding text string * width - length text - padding * 2 - 2
end function | def inner(text):
return "*{0}{1}{2}{0}*".format(
" " * padding, text, (" " * (width - len(text) - padding * 2 - 2))
) | Python | nomic_cornstack_python_v1 |
function plot_comparisons self exact blocked blockederr axdelta=none
begin
if axdelta is none
begin
set axdelta = call gca
end
set delta = means - exact
call errorbar list range 1 max_dets delta at 0 yerr=stderr at 0 label=string independent
call errorbar list range 1 max_dets delta at 1 yerr=stderr at 1 label=string c... | def plot_comparisons(self, exact, blocked, blockederr, axdelta=None):
if axdelta is None:
axdelta = plt.gca()
delta = self.means - exact
axdelta.errorbar(list(range(1, self.max_dets)), delta[0], yerr=self.stderr[0], label='independent')
axdelta.errorbar(list(range(1, self.max... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
import time
import random
comment Representing the re-occuring reminder of pi
string arr=[] rem=22%7 arr.append(22// 7) for x in range (100): rem *= 10 arr.append(rem//7) rem = rem % 7 print(arr) mplot.plot(arr) mplot.show()
set arr = list
while length arr != 180
begi... | import matplotlib.pyplot as plt
import numpy as np
import time
import random
#Representing the re-occuring reminder of pi
'''
arr=[]
rem=22%7
arr.append(22//
7)
for x in range (100):
rem *= 10
arr.append(rem//7)
rem = rem % 7
print(arr)
mplot.plot(arr)
mplot.show()
'''
arr=[]
while(len(arr) !=... | Python | zaydzuhri_stack_edu_python |
function quality_check df
begin
if empty
begin
print string DataFrame is empty!
end
else
begin
print info
print string done
end
end function | def quality_check(df):
if df.empty:
print('DataFrame is empty!')
else:
print (df.info() )
print ('done') | Python | nomic_cornstack_python_v1 |
function generateObjects r present=0 max=48 rows=6 cols=8
begin
comment Create the actual disctractor ratios based on a number index from 1-15
set ratio = list r * 3 max - r * 3
comment Fill temp arrays with 1s and 2s corresponding the correct distractor ratio
set tmp1 = list 1 * ratio at 0
set tmp2 = list 2 * ratio at... | def generateObjects( r, present = 0, max = 48, rows = 6, cols = 8 ):
# Create the actual disctractor ratios based on a number index from 1-15
ratio = [r * 3, max - r * 3]
# Fill temp arrays with 1s and 2s corresponding the correct distractor ratio
tmp1 = [1] * ratio[0]
tmp2 = [2] * ratio[1]
ti... | Python | nomic_cornstack_python_v1 |
async function setup self
begin
comment do something or remove this whole method
await sleep 0.001
comment Remember to let SimpleServices own setup work too.
await setup call super
end function | async def setup(self) -> None:
# do something or remove this whole method
await asyncio.sleep(0.001)
# Remember to let SimpleServices own setup work too.
await super().setup() | Python | nomic_cornstack_python_v1 |
function format_metadata record conferences
begin
set new_rec = dictionary communities=list dictionary identifier=string ismir
update new_rec keyword dictionary comprehension k : v for tuple k v in items record if k not in DROP_KEYS
update new_rec keyword conferences at record at string year
set authors = pop new_rec s... | def format_metadata(record, conferences):
new_rec = dict(communities=[dict(identifier='ismir')])
new_rec.update(**{k: v for k, v in record.items() if k not in DROP_KEYS})
new_rec.update(**conferences[record['year']])
authors = new_rec.pop('author')
if authors and isinstance(authors, str):
a... | Python | nomic_cornstack_python_v1 |
function get_team_probs game
begin
set all_cols = list string FA60_even_Opponent string FA60_even_Team string FA60_pk_Opponent string FA60_pk_Team string FF60_even_Opponent string FF60_even_Team string FF60_pp_Opponent string FF60_pp_Team string GF60/xGF60_even_Opponent string GF60/xGF60_even_Team string GF60/xGF60_pp_... | def get_team_probs(game):
all_cols = ['FA60_even_Opponent', 'FA60_even_Team',
'FA60_pk_Opponent', 'FA60_pk_Team',
'FF60_even_Opponent', 'FF60_even_Team',
'FF60_pp_Opponent', 'FF60_pp_Team',
'GF60/xGF60_even_Opponent', 'GF60/xGF60_even_Team',
... | Python | nomic_cornstack_python_v1 |
function predict seq model_file=MODEL model_metadata=MODEL_META pam_audit=true length_audit=false num_threads=1
begin
if not is instance seq ndarray
begin
raise call AssertionError string Please ensure seq is a numpy array
end
if length seq at 0 <= 0
begin
raise call AssertionError string Make sure that seq is not empt... | def predict(
seq: np.ndarray,
model_file: Optional[Path] = MODEL,
model_metadata: Optional[Path] = MODEL_META,
pam_audit: bool = True,
length_audit: bool = False,
num_threads: int = 1
) -> np.array:
if not isinstance(seq, np.ndarray):
raise AssertionError("Please ensure seq is a nump... | Python | nomic_cornstack_python_v1 |
comment File: NextDay.py
comment Description: A program that asks the user for a date and returns the next day
comment Student's Name: Enrique Martinez
comment Student's UT EID: egm657
comment Course Name: CS 303E
comment Unique Number: 50191
comment Date Created: 2/17/2020
comment Date Last Modified: 2/18/2020
functio... | # File: NextDay.py
# Description: A program that asks the user for a date and returns the next day
# Student's Name: Enrique Martinez
# Student's UT EID: egm657
# Course Name: CS 303E
# Unique Number: 50191
#
# Date Created: 2/17/2020
# Date Last Modified: 2/18/2020
def main():
# Asks user for ... | Python | zaydzuhri_stack_edu_python |
from pprint import pformat
class Node
begin
function __init__ self value parent
begin
set value = value
set parent = parent
set left = none
set right = none
end function
function __repr__ self
begin
return if expression left is none and right is none then string value else call pformat dict string %s % value tuple left... | from pprint import pformat
class Node:
def __init__(self, value, parent):
self.value = value
self.parent = parent
self.left = None
self.right = None
def __repr__(self):
return str(self.value) \
if self.left is None and self.right is None \
else ... | Python | zaydzuhri_stack_edu_python |
function pretty_number n
begin
return format string {:,} n
end function | def pretty_number(n):
return "{:,}".format(n) | Python | nomic_cornstack_python_v1 |
function get_krypton_calibration loc ln_V_mean rho_hourly
begin
comment get calibration constants for a given kryptons
comment no clue what these are...
set list B0 B1 B2 kw_dry kw_wet ln_V0_dry ln_V0_wet x = krypton_calibrations at loc
comment Make storage arrays for water vapor density (output)
set rho = zeros 5000
c... | def get_krypton_calibration(loc, ln_V_mean, rho_hourly):
# get calibration constants for a given kryptons
# no clue what these are...
[B0, B1, B2, kw_dry, kw_wet,
ln_V0_dry, ln_V0_wet, x] = krypton_calibrations[loc]
# Make storage arrays for water vapor density (output)
rho = np.zeros(5000)
... | Python | nomic_cornstack_python_v1 |
from data import Data
from naivebayes import NaiveBayes
set filename = string datasets/weatherNominal.td
comment filename = "datasets/titanic.td"
comment filename = "datasets/cmc.td"
set d = data filename
call report
set pr = call NaiveBayes d
train pr
show
for tuple v c_true in test_set
begin
set c_pred = predict pr v... | from data import Data
from naivebayes import NaiveBayes
filename = "datasets/weatherNominal.td"
## filename = "datasets/titanic.td"
## filename = "datasets/cmc.td"
d = Data(filename)
d.report()
pr = NaiveBayes(d)
pr.train()
pr.show()
for (v,c_true) in d.test_set:
c_pred = pr.predict(v)[0]
print(v, "... | Python | zaydzuhri_stack_edu_python |
function get_video_fps self
begin
set fps = get video CAP_PROP_FPS
info format string Video FPS: {} fps
return fps
end function | def get_video_fps(self):
fps = self.video.get(cv2.CAP_PROP_FPS)
logging.info('Video FPS: {}'.format(fps))
return fps | Python | nomic_cornstack_python_v1 |
function __contains__ self key
begin
comment right now only supports key tests
return key in call _list
end function | def __contains__(self, key):
# right now only supports key tests
return key in self._root._list() | Python | nomic_cornstack_python_v1 |
import urllib.request
import urllib.parse
import urllib.error
from bs4 import BeautifulSoup
import ssl
import ast
import os
from urllib.request import Request , urlopen
import pandas as pd
import xlrd
import time
function scrape_data soup video_details
begin
for span in find all string span attrs=dict string class stri... | import urllib.request
import urllib.parse
import urllib.error
from bs4 import BeautifulSoup
import ssl
import ast
import os
from urllib.request import Request, urlopen
import pandas as pd
import xlrd
import time
def scrape_data(soup, video_details):
for span in soup.findAll('span',attrs={'class': 'watch-title'})... | Python | zaydzuhri_stack_edu_python |
function dumpIterationToFile self
begin
set iteration_dump_file = open ITERATION_DUMP_FNAME string w
dump iteration iteration_dump_file protocol=2
close iteration_dump_file
end function | def dumpIterationToFile(self):
iteration_dump_file = open(self.ITERATION_DUMP_FNAME, 'w')
pickle.dump(self.iteration, iteration_dump_file, protocol=2)
iteration_dump_file.close() | Python | nomic_cornstack_python_v1 |
function read_input file_name
begin
set f = open file_name string r
set data = split read f string
close f
return tuple split data at 0 string , split data at 1 string ,
end function
function generate_point_set line_data point_set
begin
set origin = tuple 0 0
for p in line_data
begin
set direction = p at 0
set step = i... | def read_input(file_name):
f = open(file_name, 'r')
data = f.read().split('\n')
f.close()
return (data[0].split(','), data[1].split(','))
def generate_point_set(line_data, point_set):
origin = (0, 0)
for p in line_data:
direction = p[0]
step = int(p[1:])
for i in range (... | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
import sys
comment print(sys.getdefaultencoding())
comment print(sys.stdin.encoding)
comment print(sys.stdout.encoding)
comment print(sys.stderr.encoding)
string print("Hello World 你好世界") print("ddddd") print("弟弟") print("test") print("hehe") print("on jack's mbp") print("test vscode git") print("a... | # coding:utf-8
import sys
# print(sys.getdefaultencoding())
# print(sys.stdin.encoding)
# print(sys.stdout.encoding)
# print(sys.stderr.encoding)
'''
print("Hello World 你好世界")
print("ddddd")
print("弟弟")
print("test")
print("hehe")
print("on jack's mbp")
print("test vscode git")
print("another test")
print("tortoise g... | Python | zaydzuhri_stack_edu_python |
function main_help_text prog_name commands_only=false
begin
if commands_only
begin
set usage = sorted call get_commands
end
else
begin
set usage = list string string Type '%s help <subcommand>' for help on a specific subcommand. % prog_name string string Available subcommands:
for subcommand in call get_commands
begi... | def main_help_text(prog_name, commands_only=False):
if commands_only:
usage = sorted(get_commands())
else:
usage = [
"",
"Type '%s help <subcommand>' for help on a specific subcommand." % prog_name,
"",
"Available subcommands:",
]
f... | Python | nomic_cornstack_python_v1 |
function buildFromList cls l
begin
set T = call Trie
for item in l
begin
insert T item
end
return T
end function | def buildFromList(cls, l):
T = Trie()
for item in l:
T.insert(item)
return T | Python | nomic_cornstack_python_v1 |
from sys import argv
set tuple script input_file = argv | from sys import argv
script, input_file = argv
| Python | zaydzuhri_stack_edu_python |
function recall reference test
begin
if length reference == 0
begin
return none
end
else
begin
return decimal length intersection reference test / length reference
end
end function | def recall(reference, test):
if len(reference) == 0:
return None
else:
return float(len(reference.intersection(test))) / len(reference) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import mxnet as mx
import numpy as np
import data_download as dd
import logging
call basicConfig level=INFO
import matplotlib.pyplot as plt
import os
from tqdm import *
string unsupervised learning - Autoencoder
function to2d img
begin
return as type reshape img shape at 0 784 float32 / 25... | # -*- coding: utf-8 -*-
import mxnet as mx
import numpy as np
import data_download as dd
import logging
logging.basicConfig(level=logging.INFO)
import matplotlib.pyplot as plt
import os
from tqdm import *
'''unsupervised learning - Autoencoder'''
def to2d(img):
return img.reshape(img.shape[0],784).astype(np.floa... | Python | zaydzuhri_stack_edu_python |
import requests
import os
import json
import time
from datetime import datetime , timedelta
from bs4 import BeautifulSoup
from tqdm import tqdm
import pandas as pd
if is file path get current directory + string /match.json
begin
remove os get current directory + string /match.json
end
else
begin
pass
end
function get_s... | import requests
import os
import json
import time
from datetime import datetime, timedelta
from bs4 import BeautifulSoup
from tqdm import tqdm
import pandas as pd
if os.path.isfile(os.getcwd() + '/match.json'):
os.remove(os.getcwd() + '/match.json')
else:
pass
def get_source(link):
r = re... | Python | zaydzuhri_stack_edu_python |
comment https://codeforces.com/problemset/problem/999/A
set tuple n k = map int split input
set problems = tuple map int split input
set i = 0
set ans = 0
while i < n
begin
if problems at i <= k
begin
set ans = ans + 1
end
else
begin
break
end
set i = i + 1
end
set j = n - 1
while j > i
begin
if problems at j <= k
begi... | # https://codeforces.com/problemset/problem/999/A
n, k = map(int, input().split())
problems = tuple(map(int, input().split()))
i = 0
ans = 0
while i < n:
if problems[i] <= k:
ans += 1
else:
break
i += 1
j = n - 1
while j > i:
if problems[j] <= k:
ans += 1
else:
br... | Python | zaydzuhri_stack_edu_python |
function set_start self durationStr
begin
return min start_date - call durationStr_to_timedelta durationStr start_date
end function | def set_start(self, durationStr: str) -> pd.Timedelta:
return min(self.start_date - self.durationStr_to_timedelta(durationStr),
self.start_date) | Python | nomic_cornstack_python_v1 |
function trace_random_pair
begin
comment Find a read that has a mate
while true
begin
set read_id = random integer 0 size rm - 1
set read = call get_read_by_id read_id
if call has_mate
begin
break
end
end
comment If it's not in is original orientation, get the original orientation
if not call is_original_orientation
be... | def trace_random_pair():
# Find a read that has a mate
while True:
read_id = random.randint(0, rm.size() - 1)
read = rm.get_read_by_id(read_id)
if read.has_mate():
break
# If it's not in is original orientation, get the original orientation
if not read.is_original_ori... | Python | nomic_cornstack_python_v1 |
function updateBestEvaluationResultsAndSaveTheModel evaluation_results best_evaluation_results model output_directory_path current_epoch
begin
for key in keys best_evaluation_results
begin
if string LOSS in key and evaluation_results at key <= best_evaluation_results at key
begin
info call ljust 38 + call ljust 6 + str... | def updateBestEvaluationResultsAndSaveTheModel(evaluation_results, best_evaluation_results, model, output_directory_path, current_epoch):
for key in best_evaluation_results.keys():
if "LOSS" in key and evaluation_results[key] <= best_evaluation_results[key]:
logger.info((key + " has be... | Python | nomic_cornstack_python_v1 |
function med_seq_error self
begin
return decimal median predicted - true ^ 2
end function | def med_seq_error(self) -> float:
return float(np.median((self.predicted - self.true) ** 2)) | Python | nomic_cornstack_python_v1 |
function generate self hosts
begin
for tuple host addr _ _ in hosts
begin
if nodns
begin
continue
end
if addr_range_type == string ip4
begin
set split = split string addr string .
set rev = string in-addr.arpa.
for atom in split
begin
set rev = atom + string . + rev
end
end
else
if addr_range_type == string ip6
begin
s... | def generate(self, hosts):
for host, addr, _, _ in hosts:
if host.nodns:
continue
if addr.pool.addr_range_type == "ip4":
split = str(addr).split(".")
rev = "in-addr.arpa."
for atom in split:
rev = atom + ... | Python | nomic_cornstack_python_v1 |
function word_with_most_vowels string_list
begin
set max_count = 0
set string_index = 0
comment list(0, element)
for tuple i string in enumerate string_list
begin
set vowels = call number_of_vowels string
if max_count < vowels
begin
set max_count = vowels
set string_index = i
end
end
return string_list at string_index
... | def word_with_most_vowels(string_list: list):
max_count = 0
string_index = 0
# list(0, element)
for i, string in enumerate(string_list):
vowels = number_of_vowels(string)
if max_count < vowels:
max_count = vowels
string_index = i
return string_list[string_inde... | Python | nomic_cornstack_python_v1 |
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from sklearn.cluster import KMeans
from sklearn import metrics
set categories = none
set newsgroups_train = call fetch_20newsgroups subset=string train
set labels = target
set true_k = 12
comme... | from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from sklearn.cluster import KMeans
from sklearn import metrics
categories = None
newsgroups_train = fetch_20newsgroups(subset='train')
labels = newsgroups_train.target
true_k = 12
#vectoriz... | Python | zaydzuhri_stack_edu_python |
function _generate_headers response_code
begin
set header = string
if response_code == 200
begin
set header = header + string HTTP/1.1 200 OK
end
else
if response_code == 404
begin
set header = header + string HTTP/1.1 404 Not Found
end
set time_now = string format time time string %a, %d %b %Y %H:%M:%S call localtime... | def _generate_headers(response_code):
header = ''
if response_code == 200:
header += 'HTTP/1.1 200 OK\n'
elif response_code == 404:
header += 'HTTP/1.1 404 Not Found\n'
time_now = time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime())
header += 'Date: {... | Python | nomic_cornstack_python_v1 |
set names = list string Alice string Beth string Cecil string Dee-Dee string Earl
set numbers = list string 2341 string 9102 string 3158 string 0142 string 5551 |
names = ['Alice','Beth','Cecil','Dee-Dee','Earl']
numbers = ['2341','9102','3158','0142','5551'] | Python | zaydzuhri_stack_edu_python |
string Write a program that will create a dictionary from the list [ 'a', 'b', 'c', 'd']
set l = list string a string b string c string d
print l
set d = dictionary l
print values d | """Write a program that will create a dictionary from the list [ 'a', 'b', 'c', 'd']"""
l=['a','b','c','d']
print(l)
d=dict(l)
print(d.values())
| Python | zaydzuhri_stack_edu_python |
function _translate__l3vpn_ntw_vpn_services_vpn_service_status_oper_status input_yang_obj translated_yang_obj=none
begin
if call _changed
begin
set status = status
end
if call _changed
begin
set last_updated = last_updated
end
return translated_yang_obj
end function | def _translate__l3vpn_ntw_vpn_services_vpn_service_status_oper_status(input_yang_obj, translated_yang_obj=None):
if input_yang_obj.status._changed():
input_yang_obj.status = input_yang_obj.status
if input_yang_obj.last_updated._changed():
input_yang_obj.last_updated = input_yang_obj.last_updat... | Python | nomic_cornstack_python_v1 |
from flask import Flask
from flask import request
from flask import jsonify
set app = call Flask __name__
decorator call route string / methods=list string GET
function root
begin
return string Root
end function
decorator call route string /helloworld methods=list string GET
function hello_world
begin
return string Hel... | from flask import Flask
from flask import request
from flask import jsonify
app = Flask(__name__)
@app.route('/', methods=['GET'])
def root():
return "Root"
@app.route('/helloworld', methods=['GET'])
def hello_world():
return "Hello World"
@app.route('/hello/<name>', methods=['GET'])
def hello(name):
re... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment _*_ coding: utf-8 _*_
comment 《Python 网络编程基础 》第二个小例子,获取用户输入的域名和内容
comment 发送到对应服务器 新增使用makefile 获取read write 方式发送接收网络内容
comment 使用示例 python gopherClient.py www.smeoa.com get
import socket , sys
set port = 80
set host = argv at 1
set filename = argv at 2
set s = call socket AF_INET S... | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
#《Python 网络编程基础 》第二个小例子,获取用户输入的域名和内容
#发送到对应服务器 新增使用makefile 获取read write 方式发送接收网络内容
#使用示例 python gopherClient.py www.smeoa.com get
import socket,sys
port = 80
host = sys.argv[1]
filename = sys.argv[2]
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) | Python | zaydzuhri_stack_edu_python |
function generate self sample_size first_samples=none
begin
set output_length = output_length
set receptive_length = receptive_field
set input_length = receptive_length - 1 + output_length
if sample_size <= input_length
begin
return exit string Sample size is short!
end
set init = zeros input_length
set init = view dec... | def generate(self, sample_size, first_samples=None):
output_length = self.output_length
receptive_length = self.receptive_field
input_length = receptive_length - 1 + output_length
if sample_size <= input_length:
return sys.exit("Sample size is short!")
init = np.zeros(input_length)
init = torch.tensor... | Python | nomic_cornstack_python_v1 |
function create_dashboard self panel_file data_sources=none strict=true
begin
string Upload a panel to Elasticsearch if it does not exist yet. If a list of data sources is specified, upload only those elements (visualizations, searches) that match that data source. :param panel_file: file name of panel (dashobard) to u... | def create_dashboard(self, panel_file, data_sources=None, strict=True):
"""Upload a panel to Elasticsearch if it does not exist yet.
If a list of data sources is specified, upload only those
elements (visualizations, searches) that match that data source.
:param panel_file: file name o... | Python | jtatman_500k |
set tuple SX SY TX TY = map int split input
set TX = TX - SX
set TY = TY - SY
set SX = 0
set SY = 0
set res = string
set res = res + string U * TY
set res = res + string R * TX
set res = res + string D * TY
set res = res + string L * TX + 1
set res = res + string U * TY + 1
set res = res + string R * TX + 1
set res = ... | SX, SY, TX, TY = map(int, input().split())
TX -= SX
TY -= SY
SX = 0
SY = 0
res = ""
res += "U"*TY
res += "R"*TX
res += "D"*TY
res += "L"*(TX+1)
res += "U"*(TY+1)
res += "R"*(TX+1)
res += "D"
res += "R"
res += "D"*(TY+1)
res += "L"*(TX+1)
res += "U"
print(res) | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python
comment curses_tester_04.py
comment David Prager Branner
comment 20140402, works
string Explore the use of Ncurses. 04 Set up different sub-windows. Separate Timer class. Defense line. 03 Get styled text working; no display delay on startup. 02 Set up and close curses in special functions; alw... | #! /usr/bin/python
# curses_tester_04.py
# David Prager Branner
# 20140402, works
"""Explore the use of Ncurses.
04 Set up different sub-windows. Separate Timer class. Defense line.
03 Get styled text working; no display delay on startup.
02 Set up and close curses in special functions; always trap ctrl-c.
01 Open wi... | Python | zaydzuhri_stack_edu_python |
function range self *args
begin
if length args == 0
begin
set tuple start stop step = tuple 0 entries 1
end
else
if length args == 1
begin
set tuple start stop step = tuple 0 args at 0 1
end
else
if length args == 2
begin
set tuple start stop step = tuple args at 0 args at 1 1
end
else
if length args == 3
begin
set tup... | def range(self, *args):
if len(args) == 0:
self.start, self.stop, self.step = 0, self.entries, 1
elif len(args) == 1:
self.start, self.stop, self.step = 0, args[0], 1
elif len(args) == 2:
self.start, self.stop, self.step = args[0], args[1], 1
elif len(args) == 3:
self.start, ... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[1]:
import os , random
from pprint import pprint
comment In[2]:
set stopwords = read lines open string ./stopwords.txt string r encoding=string utf-8
comment In[3]:
function isstopword w
begin
if w in stopwords
begin
return true
end
else
begin
return false
end
end function | # coding: utf-8
# In[1]:
import os,random
from pprint import pprint
# In[2]:
stopwords=open("./stopwords.txt","r",encoding="utf-8").readlines()
# In[3]:
def isstopword(w):
if w in stopwords:
return True
else:
return False
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Apr 19 09:05:45 2021 @author: nygar
import json
import requests
from metno_locationforecast import Place , Forecast
function getForecast
begin
comment Må brukes for å hente informasjon fra MET API
set USER_AGENT = string metno_locationforecast/1.0 sanderln@stud.ntnu.n... | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 09:05:45 2021
@author: nygar
"""
import json
import requests
from metno_locationforecast import Place, Forecast
def getForecast():
#Må brukes for å hente informasjon fra MET API
USER_AGENT = "metno_locationforecast/1.0 sanderln@stud.ntnu.no"
... | Python | zaydzuhri_stack_edu_python |
function sleep self sec msg=string
begin
info string Sleeping for %i seconds: %s % tuple sec msg
sleep sec
info string Woke up
end function | def sleep(self, sec, msg=''):
log.info("Sleeping for %i seconds: %s" % (sec, msg))
time.sleep(sec)
log.info("Woke up") | Python | nomic_cornstack_python_v1 |
import cv2
set cas = call CascadeClassifier string haarcascade_russian_plate_number.xml
comment cam = cv2.VideoCapture("name of your video.mp4)
comment this will capture the number plates in Real time using your own camera
set cam = call VideoCapture 0
while true
begin
set tuple check image = read cam
set gray = call c... | import cv2
cas = cv2.CascadeClassifier('haarcascade_russian_plate_number.xml')
# cam = cv2.VideoCapture("name of your video.mp4)
# this will capture the number plates in Real time using your own camera
cam = cv2.VideoCapture(0)
while True:
check,image = cam.read()
gray = cv2.cvtColor(image, cv2.CO... | Python | zaydzuhri_stack_edu_python |
comment Problem number 16 ,project euler
comment Script contributed by Sugam Anand
comment Website :www.sugamanand.in
comment !/usr/bin/env python
set base = integer call raw_input string give the base
set exponent = integer call raw_input string give the power
set a = power base exponent
set b = string a
set sum = 0
f... | #Problem number 16 ,project euler
#Script contributed by Sugam Anand
#Website :www.sugamanand.in
#!/usr/bin/env python
base=int(raw_input("give the base "))
exponent=int(raw_input("give the power "))
a=pow(base,exponent)
b=str(a)
sum=0
for i in range(len(b)):
sum =sum+int(b[i]) | Python | zaydzuhri_stack_edu_python |
from Rules import Rules
from Database import Database
class Identify
begin
string 根据规则识别动物
function __init__ self Animal
begin
set _Animal = Animal
set rules = call Rules
set _Rulelist = call get_rules
set _DB = call Database
string Rulelist中的元素为 dic,其中包含一条规则的信息 键包括:'IF_feature','IF_label', 'THEN_feature','THEN_label',... | from Rules import Rules
from Database import Database
class Identify:
''' 根据规则识别动物 '''
def __init__(self, Animal):
self._Animal = Animal
rules = Rules()
self._Rulelist = rules.get_rules()
self._DB = Database()
''' Rulelist中的元素为 dic,其中包含一条规则的信息
键包括:'IF_feature',... | Python | zaydzuhri_stack_edu_python |
import sys
import pygame
function run_game
begin
comment 初始化游戏并且创建一个屏幕对象
call init
set screen = call set_mode tuple 1200 800
call set_caption string Alien Invasion
comment 开始游戏主循环
while true
begin
comment 监视键盘和鼠标事件
for event in get event
begin
if type == QUIT
begin
exit
end
end
comment 让最近绘制的屏幕可见
call flip
end
end func... | import sys
import pygame
def run_game():
# 初始化游戏并且创建一个屏幕对象
pygame.init()
screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
# 开始游戏主循环
while True:
# 监视键盘和鼠标事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: UTF-8 -*-
import os
import threading
import multiprocessing
function worker sign lock
begin
acquire lock
end function | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
import os
import threading
import multiprocessing
def worker(sign, lock):
lock.acquire() | Python | zaydzuhri_stack_edu_python |
function updatePaddle self inp
begin
set s = 0
set d = 6
if call is_key_down string left
begin
if left < d
begin
set s = s + 0
end
else
begin
set s = s - 1
end
end
else
if call is_key_down string right
begin
if right + d > GAME_WIDTH
begin
set s = s + 0
end
else
begin
set s = s + 1
end
end
set x = x + d * s
end functio... | def updatePaddle(self,inp):
s=0
d=6
if inp.is_key_down('left'):
if self._paddle.left < d:
s+=0
else:
s-=1
elif inp.is_key_down('right'):
if self._paddle.right+d > GAME_WIDTH:
s+=0
... | Python | nomic_cornstack_python_v1 |
function start self
begin
if go_daemon
begin
if not pidfile
begin
error string Daemon needs pidfile
exit 1
end
end
call run_func_safely _boot_daemon
end function | def start(self):
if self.go_daemon:
if not self.pidfile:
self.log.error("Daemon needs pidfile")
sys.exit(1)
self.run_func_safely(self._boot_daemon) | Python | nomic_cornstack_python_v1 |
function maj_longueur_tot self df
begin
set df at string longueur_tot = apply df lambda x -> if expression x at string pt_depart == src then x at string lg_hors_debut + dist_src else x at string lg_hors_debut + dist_tgt axis=1
end function | def maj_longueur_tot(self,df):
df['longueur_tot']=df.apply(lambda x : x['lg_hors_debut']+self.dist_src if x['pt_depart']==self.src else x['lg_hors_debut']+self.dist_tgt, axis=1) | Python | nomic_cornstack_python_v1 |
function timestep self dt I
begin
set interaction = list
set v_rev = - 80
set g = 0.0
end function | def timestep(self, dt, I):
interaction = []
v_rev = -80
g = 0.0
| Python | nomic_cornstack_python_v1 |
string Learning a simple CNN model on the clean data with augmentation
import keras
from keras.models import Sequential
from keras.layers import Conv2D , MaxPooling2D
from keras.layers import Activation , Dropout , Flatten , Dense
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import ImageDa... | """Learning a simple CNN model on the clean data with augmentation"""
import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import Imag... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python3
import math
import os
import random
import re
import sys
comment Complete the makeAnagram function below.
function makeAnagram a b
begin
set a = sorted list a
set b = sorted list b
set delCount = 0
while true
begin
comment if we have come to the end of one list
if length a == 0
begin
set delCount ... | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the makeAnagram function below.
def makeAnagram(a, b):
a = sorted(list(a))
b = sorted(list(b))
delCount = 0
while True:
# if we have come to the end of one list
if len(a) == 0:
delCount +=... | Python | zaydzuhri_stack_edu_python |
function _set_default_func self
begin
set dim = dim
if dim == 1
begin
set func = lambda x -> list 1.0
end
if dim == 2
begin
set func = lambda x y -> list 1.0
end
if dim == 3
begin
set func = lambda x y z -> list 1.0
end
return func
end function | def _set_default_func(self):
dim = self.space.dim
if dim == 1:
func = lambda x : [ 1. ]
if dim == 2:
func = lambda x,y : [ 1. ]
if dim == 3:
func = lambda x,y,z : [ 1. ]
return func | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import tkinter as tk
import tkinter.simpledialog
function main
begin
set window = call Tk
title window string Gathering Input
call minsize width=350 height=60
call after 1000 gather_data window
call mainloop
end function
function gather_data window
begin
set msg = string Please supply your... | #!/usr/bin/env python3
import tkinter as tk
import tkinter.simpledialog
def main():
window = tk.Tk()
window.title("Gathering Input")
window.minsize(width=350, height=60)
window.after(1000, gather_data, window)
window.mainloop()
def gather_data(window):
msg = "Please supply your lucky number:... | Python | zaydzuhri_stack_edu_python |
function testRenderRecentObjectActivityWithNoQuery self
begin
set objectID = call create string object1
commit store
set dict objectID dict string username/tag1 string A
call runDataImportHandler url
set request = call FakeRequest
with call login string username objectID transact as session
begin
set resource = call Re... | def testRenderRecentObjectActivityWithNoQuery(self):
objectID = ObjectAPI(self.user).create(u'object1')
self.store.commit()
TagValueAPI(self.user).set({objectID: {u'username/tag1': u'A'}})
runDataImportHandler(self.client.url)
request = FakeRequest()
with login(u'username... | Python | nomic_cornstack_python_v1 |
function _user_input
begin
set lines = list
try
begin
while true
begin
set line = input
if line != string
begin
append lines line
end
else
begin
break
end
end
end
except tuple EOFError KeyboardInterrupt
begin
return join string lines
end
end function | def _user_input() -> str:
lines = []
try:
while True:
line = input()
if line != '':
lines.append(line)
else:
break
except (EOFError, KeyboardInterrupt):
return '\n'.join(lines) | Python | nomic_cornstack_python_v1 |
function label_from_instance self obj
begin
return string %s %s % tuple level_indicator * get attribute obj level_attr obj
end function | def label_from_instance(self, obj):
return u'%s %s' % (self.level_indicator * getattr(obj, obj._meta.level_attr),
obj) | Python | nomic_cornstack_python_v1 |
set a = integer input string value
if a >= 1 and a <= 100000
begin
print string positive
end
else
if a < 0
begin
print string negative
end
else
begin
print string zero
end | a=int(input("value"))
if(a>=1 and a<=100000):
print("positive")
elif(a<0):
print("negative")
else:
print("zero")
| Python | zaydzuhri_stack_edu_python |
import threading
from threading import Thread , Lock
string #自己上锁 num=0 islock=False time1=time.time() def test1(): global num global islock if(islock==False): islock=True for i in range(10000000): num+=1 print("test1",num) time2=time.time() print("花费时间:",time2-time1) islock=False def test2(): global num global islock ... | import threading
from threading import Thread,Lock
"""
#自己上锁
num=0
islock=False
time1=time.time()
def test1():
global num
global islock
if(islock==False):
islock=True
for i in range(10000000):
num+=1
print("test1",num)
time2=time.time()
print("花费时间:",time2-time1)
islock=False
def test2():
global n... | Python | zaydzuhri_stack_edu_python |
class Test
begin
function __init__ self name age=0
begin
if type age not in tuple int float
begin
raise exception string Args not numbers
end
set name = name
set age = age
end function
function getName self
begin
return name
end function
function getAge self
begin
return age
end function
function printPerson self
begin... | class Test:
def __init__(self, name, age = 0):
if(type(age) not in(int, float)):
raise Exception('Args not numbers')
self.name = name
self.age = age
def getName(self):
return self.name
def getAge(self):
return self.age
def printPerson(self):... | Python | zaydzuhri_stack_edu_python |
comment 搬家具
class Furniture
begin
function __init__ self name area
begin
string 家具名字 家具占地面积
set name = name
set area = area
end function
end class
class host
begin
function __init__ self position area
begin
string 房屋位置 房屋大小 放入家具后大小 家具列表
set Position = position
set AllArea = area
set NowArea = area
set list = list
end ... | # 搬家具
class Furniture():
def __init__(self, name, area):
"""家具名字 家具占地面积"""
self.name = name
self.area = area
class host():
def __init__(self, position, area):
"""房屋位置 房屋大小 放入家具后大小 家具列表"""
self.Position = position
self.AllArea = area
self.NowArea = area
... | Python | zaydzuhri_stack_edu_python |
comment import dependencies
import os
import csv
comment set path of the file
set filepath = join path string Resources/election_data.csv
comment print(filepath)
with open filepath as csvfile
begin
set csvreader = reader csvfile delimiter=string ,
set csvheader = next csvfile
end
comment declare various of variables fo... | # import dependencies
import os
import csv
# set path of the file
filepath = os.path.join("Resources/election_data.csv")
# print(filepath)
with open(filepath) as csvfile:
csvreader = csv.reader(csvfile,delimiter=",")
csvheader = next(csvfile)
# declare various of variables for output:
candidates = {}
counts ... | Python | zaydzuhri_stack_edu_python |
function _rewrite_filter_alias op name=none **kwargs
begin
return call _rewrite_filter arg name=if expression name is not none then name else name keyword kwargs
end function | def _rewrite_filter_alias(op, name: str | None = None, **kwargs):
return _rewrite_filter(
op.arg,
name=name if name is not None else op.name,
**kwargs,
) | Python | nomic_cornstack_python_v1 |
if string S in S and string N in S
begin
set flag_y = true
end
if string S not in S and string N not in S
begin
set flag_y = true
end
if string E in S and string W in S
begin
set flag_x = true
end
if string E not in S and string W not in S
begin
set flag_x = true
end
if flag_x and flag_y
begin
print string Yes
end
else... | if 'S' in S and 'N' in S:
flag_y = True
if 'S' not in S and 'N' not in S:
flag_y = True
if 'E' in S and 'W' in S:
flag_x = True
if 'E' not in S and 'W' not in S:
flag_x = True
if flag_x and flag_y:
print('Yes')
else:
print('No') | Python | zaydzuhri_stack_edu_python |
comment update a markdown file, insert/update:
comment code fragments
comment headers and header numbering
comment TOC
import sys
set example_files_path = string %s
function example input file_name marker=string quote=0 numbers=0
begin
set result = list
set count = 0
set end = string
comment open quote line
set line... | # update a markdown file, insert/update:
# code fragments
# headers and header numbering
# TOC
import sys
example_files_path = "%s"
def example( input, file_name, marker = "", quote = 0, numbers = 0 ):
result = []
count = 0
end = ""
# open quote line
line = input.pop( 0 )
result.append... | Python | zaydzuhri_stack_edu_python |
string author : RMDE function : connect the mysql
import mysql.connector
import re
set college = list string 航空宇航学院 string 能源与动力学院 string 自动化学院 string 电子信息工程学院 string 机电学院 string 材料科学与技术学院 string 民航学院 string 理学院 string 经济管理学院 string 人文与社会科学学院 string 艺术学院 string 外国语学院 string 马克思主义学院 string 航天学院 string 国际教育学院 string 计算机科... | '''
author : RMDE
function : connect the mysql
'''
import mysql.connector
import re
college = ["航空宇航学院","能源与动力学院","自动化学院","电子信息工程学院","机电学院","材料科学与技术学院","民航学院","理学院","经济管理学院","人文与社会科学学院","艺术学院","外国语学院","马克思主义学院","航天学院","国际教育学院","计算机科学与技术学院"]
schedule =["Mon-8:00~9:45","Mon-10:15~12:00","Mon-14:00~15:45","Mon-16:15~18... | Python | zaydzuhri_stack_edu_python |
async function __handle_remove self message
begin
try
begin
if message
begin
set actor = payload
if actor
begin
call remove_actor actor
end
else
begin
print string Actor to remove was None
end
end
else
begin
print string Message to remove request empty
end
end
except Exception as e
begin
call handle_fail
end
end functi... | async def __handle_remove(self, message):
try:
if message:
actor = message.payload
if actor:
self.remove_actor(actor)
else:
print("Actor to remove was None")
else:
print("Message to re... | Python | nomic_cornstack_python_v1 |
function get_next_block_type self
begin
return next_block_type
end function | def get_next_block_type(self):
return self.__model.next_block_type | Python | nomic_cornstack_python_v1 |
from posixpath import expanduser
import requests
import json
import settings_tmap
comment import currentgps
function get_location destination
begin
comment currentgps.get_gps()## #currentgps.get_gps()
set tuple center_lon center_lat = tuple 127.083362949041 37.24044601170735
print center_lon center_lat
set tmap_locatio... | from posixpath import expanduser
import requests
import json
import settings_tmap
#import currentgps
def get_location(destination):
center_lon, center_lat = 127.083362949041, 37.24044601170735#currentgps.get_gps()## #currentgps.get_gps()
print(center_lon, center_lat)
tmap_location_url = "https://apis.... | Python | zaydzuhri_stack_edu_python |
function days_in_month name
begin
if name == string January or name == string March or name == string May or name == string July or name == string August or name == string October or name == string December
begin
return 31
end
else
if name == string February
begin
return 28
end
else
if name == string April or name == s... | def days_in_month(name):
if name == "January" or name == "March" or name == "May" or name == "July" or name == "August" or name == "October" or name == "December":
return 31
elif name == "February":
return 28
elif name == "April" or name == "June" or name == "November":
return 30 | Python | nomic_cornstack_python_v1 |
function failed_with_message capsys
begin
set __tracebackhide__ = true
function _failed_with_message func message *args **kwargs
begin
set __tracebackhide__ = true
with raises SystemExit as error
begin
call func *args keyword kwargs
end
assert type == SystemExit
assert code == 1
if message
begin
assert err == message
e... | def failed_with_message(capsys):
__tracebackhide__ = True
def _failed_with_message(func, message, *args, **kwargs):
__tracebackhide__ = True
with pytest.raises(SystemExit) as error:
func(*args, **kwargs)
assert error.type == SystemExit
assert error.value.code == 1
... | Python | nomic_cornstack_python_v1 |
if 1 <= n
begin
set b = 1
for n in range n 0 - 1
begin
print string * n - 1 string * * b sep=string
set b = b + 2
end
end | if 1 <= n:
b = 1
for n in range(n, 0, -1):
print(' '*(n-1), '*'*b, sep='')
b += 2
| Python | zaydzuhri_stack_edu_python |
import numpy as np
import sys
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
function makepotential x y z pottype=string cubic potbottom=- 1.0 potshow_f=false
begin
if pottype == string cubic
begin
set V = call cubic x y z potbottom
end
else
if pottype == string cylinder
begin
set V = call cyli... | import numpy as np
import sys
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def makepotential(x,y,z,pottype="cubic",potbottom=-1.,potshow_f=False):
if pottype =="cubic" :
V = cubic(x,y,z,potbottom)
elif pottype == "cylinder" :
V = cylinder(x,y,z,potbottom)
elif pot... | Python | zaydzuhri_stack_edu_python |
import sys
try
begin
while true
begin
set a = read line stdin
if not a
begin
break
end
set a = list lower a
print a
set count = dict
set template = list string
set template = template + list comprehension character i for i in range ordinal string 0 ordinal string 9 + 1
set template = template + list comprehension cha... | import sys
try:
while(True):
a = sys.stdin.readline()
if(not a):
break
a = list(a.lower())
print(a)
count = {}
template = [' ']
template = template+[chr(i) for i in range(ord('0'), ord('9')+1)]
template = template+[chr(i) for i in range(or... | Python | zaydzuhri_stack_edu_python |
function svg_length_attr_dumb value_str props full_span
begin
set m = match length_attr value_str
if m is none
begin
raise call SvgLengthError value_str
end
set tuple value unit = call groups
if unit == string %
begin
comment Fixme: More work required.
if __class__ == float
begin
return full_span * 100 / decimal value
... | def svg_length_attr_dumb(value_str, props, full_span):
m = re.match(svg_re.length_attr, value_str)
if m is None:
raise SvgLengthError(value_str)
value, unit = m.groups()
if unit == "%":
# Fixme: More work required.
if full_span.__class__ == float:
return (full_span ... | Python | nomic_cornstack_python_v1 |
set arr = list 1 2 3 4 5
print arr at slice 2 : : | arr= [1,2,3,4,5]
print(arr[2:])
| Python | zaydzuhri_stack_edu_python |
function _default_omnisci_session_manager self
begin
return call OmniSciSessionManager config=config
end function | def _default_omnisci_session_manager(self):
return OmniSciSessionManager(config=self.config) | Python | nomic_cornstack_python_v1 |
function placement_group_id self
begin
return get pulumi self string placement_group_id
end function | def placement_group_id(self) -> str:
return pulumi.get(self, "placement_group_id") | Python | nomic_cornstack_python_v1 |
function load_and_append_text anim filename dot_map=dict string 0 0 ; string 1 5 ; string 2 10 ; string 3 15
begin
if not exists path filename
begin
return false
end
end function | def load_and_append_text(anim, filename, dot_map = {'0':0, '1':5, '2':10, '3':15}):
if not os.path.exists(filename):
return False | Python | nomic_cornstack_python_v1 |
function qImageToArray qimage dtype=string array
begin
string Convert QImage to numpy.ndarray. The dtype defaults to uint8 for QImage.Format_Indexed8 or `bgra_dtype` (i.e. a record array) for 32bit color images. You can pass a different dtype to use, or 'array' to get a 3D uint8 array for color images.
set result_shape... | def qImageToArray(qimage, dtype = 'array'):
"""Convert QImage to numpy.ndarray. The dtype defaults to uint8
for QImage.Format_Indexed8 or `bgra_dtype` (i.e. a record array)
for 32bit color images. You can pass a different dtype to use, or
'array' to get a 3D uint8 array for color images."""
... | Python | jtatman_500k |
from Resolver import HangmanResolver
from Display import HangmanDisplay
import os , sys
import glob
import random
from pprint import pprint
function var_dump var prefix=string
begin
string You know you're a php developer when the first thing you ask for when learning a new language is 'Where's var_dump?????'
set my_typ... | from Resolver import HangmanResolver
from Display import HangmanDisplay
import os, sys
import glob
import random
from pprint import pprint
def var_dump(var, prefix=''):
"""
You know you're a php developer when the first thing you ask for
when learning a new language is 'Where's var_dump?????'
"""
... | 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.