code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function postprocess_skipped self text
begin
return text
end function | def postprocess_skipped(
self,
text: 'str',
) -> 'str':
return text | Python | nomic_cornstack_python_v1 |
import math
set type_of_figure = input
if type_of_figure == string square
begin
set side = decimal input
set area = side * side
print string { area }
end
else
if type_of_figure == string rectangle
begin
set first_side = decimal input
set second_side = decimal input
set area = first_side * second_side
print string { are... | import math
type_of_figure = input()
if type_of_figure == 'square':
side = float(input())
area = side * side
print(f'{area:.3f}')
elif type_of_figure == 'rectangle':
first_side = float(input())
second_side = float(input())
area = first_side * second_side
print(f'{area:.3f}')
elif type_of_f... | Python | zaydzuhri_stack_edu_python |
string User Story 13 (US13) - Test File US13: Birth dates of siblings should be more than 8 months apart or less than 2 days apart (twins may be born one day apart, e.g. 11:59 PM and 12:02 AM the following calendar day) @Author: David Tsu
import unittest , os , io , sys
from ssw555a_ged import GED_Repo
class Test_US13 ... | """
User Story 13 (US13) - Test File
US13: Birth dates of siblings should be more than 8 months apart or less than 2 days apart (twins may be born one day apart, e.g. 11:59 PM and 12:02 AM the following calendar day)
@Author: David Tsu
"""
import unittest, os, io, sys
from ssw555a_ged import GED_Repo
class Test_US13(... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Dec 13 16:21:59 2017 @author: anm16
comment %%
comment UNUSED ######################
comment UNUSED ######################
comment UNUSED ######################
comment UNUSED ######################
comment UNUSED ######################
comment %%
from instruments.per... | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 16:21:59 2017
@author: anm16
"""
#%%
######################### UNUSED ######################
######################### UNUSED ######################
######################### UNUSED ######################
######################### UNUSED ######################
#####... | Python | zaydzuhri_stack_edu_python |
import sys
set FibNumbers = list 1 1
set FibmOne = 1
set FibmTwo = 1
for i in range 28
begin
set Fib = FibmOne + FibmTwo
set FibmTwo = FibmOne
set FibmOne = Fib
append FibNumbers Fib
end
comment print len(FibNumbers)
comment print FibNumbers
set a = integer read line stdin
while a
begin
comment print a
set n = 1
for i ... | import sys
FibNumbers = [1, 1]
FibmOne = 1
FibmTwo = 1
for i in range(28):
Fib = FibmOne + FibmTwo
FibmTwo = FibmOne
FibmOne = Fib
FibNumbers.append(Fib)
#print len(FibNumbers)
#print FibNumbers
a = int(sys.stdin.readline())
while a:
#print a
n = 1
for i in range(29, -1, -1):
#p... | Python | zaydzuhri_stack_edu_python |
comment class -> object
class Student
begin
function __init__ self name math_score=0 eng_score=0 physical_score=0
begin
set name = name
set math_score = math_score
set eng_score = eng_score
set physical_score = physical_score
end function
function read_my_name self
begin
print string 聽清楚了,我的名字是 { name } !!!
end functio... | # class -> object
class Student:
def __init__(self, name, math_score=0, eng_score=0, physical_score=0):
self.name = name
self.math_score = math_score
self.eng_score = eng_score
self.physical_score = physical_score
def read_my_name(self):
print(f"聽清楚了,我的名字是{self.name}!!!... | Python | zaydzuhri_stack_edu_python |
function test_overrides self
begin
assert equal CONFIG_OPTION string override
end function | def test_overrides(self):
self.assertEqual(self.config.CONFIG_OPTION, 'override') | Python | nomic_cornstack_python_v1 |
function plot_swarm_plots df groupcol scorecol order=none figsize=tuple 10 10 hue=none
begin
set tuple fig ax = call subplots figsize=figsize
if order is none
begin
set order = list set call tolist
end
call swarmplot x=groupcol y=scorecol data=df ax=ax order=order hue=hue size=7
for tick in call get_xticklabels
begin
c... | def plot_swarm_plots(df, groupcol, scorecol, order=None, figsize=(10, 10), hue=None):
fig, ax = plt.subplots(figsize=figsize)
if order is None:
order = list(set(df[groupcol].tolist()))
sns.swarmplot(x=groupcol, y=scorecol, data=df, ax=ax, order=order, hue=hue, size=7)
for tick in ax.get_xtickl... | Python | nomic_cornstack_python_v1 |
function narcissistic value
begin
string A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits. For example, take 153 (3 digits): 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 and 1634 (4 digits): 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634 The Challenge: Y... | def narcissistic(value):
"""
A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of
digits.
For example, take 153 (3 digits):
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
and 1634 (4 digits):
1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 16... | Python | zaydzuhri_stack_edu_python |
from flask import Flask
import random
comment Create a new Flask application where the home route displays an
comment <h1> that says "Guess a number between 0 and 9" and display a gif of your choice from giphy.com
set app = call Flask __name__
decorator call route string /
function guess_a_number
begin
return string <h... | from flask import Flask
import random
# Create a new Flask application where the home route displays an
# <h1> that says "Guess a number between 0 and 9" and display a gif of your choice from giphy.com
app = Flask(__name__)
@app.route("/")
def guess_a_number():
return '<h1>Guess a number between 0 and 9</h1>' \
... | Python | zaydzuhri_stack_edu_python |
function zone_id self
begin
return get pulumi self string zone_id
end function | def zone_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "zone_id") | Python | nomic_cornstack_python_v1 |
function _read_from_paths
begin
string Try to read data from configuration paths ($HOME/_SETTINGS_PATH, /etc/_SETTINGS_PATH).
set home = get environ string HOME string
set home_path = join path home _SETTINGS_PATH
set etc_path = join path string /etc _SETTINGS_PATH
set env_path = get environ string SETTINGS_PATH string... | def _read_from_paths():
"""
Try to read data from configuration paths ($HOME/_SETTINGS_PATH,
/etc/_SETTINGS_PATH).
"""
home = os.environ.get("HOME", "")
home_path = os.path.join(home, _SETTINGS_PATH)
etc_path = os.path.join("/etc", _SETTINGS_PATH)
env_path = os.environ.get("SETTINGS_PATH... | Python | jtatman_500k |
comment pragma once
comment include "Tile.h"
class Tile
begin
comment char ,char ,Piece*
string The function creates the class variable of the Bishop Input- bishop's x, bishop's y, piece to set on tile Output- none
function __init__ self x y piece=none
begin
set _x = x
set _y = y
set _piece = piece
end function
string ... | #pragma once
#include "Tile.h"
class Tile:
# char ,char ,Piece*
""" The function creates the class variable of the Bishop
Input- bishop's x, bishop's y, piece to set on tile
Output- none """
def __init__(self, x, y, piece = None):
self._x = x
self._y = y
self._piece = piece
""" The function returns the... | Python | zaydzuhri_stack_edu_python |
comment This script contains functions for generating data for the regression task
import numpy as np
import matplotlib.pyplot as plt
seed 42
function print_hi name
begin
comment Use a breakpoint in the code line below to debug your script.
comment Press Ctrl+F8 to toggle the breakpoint.
print string Hi, { name }
end f... | # This script contains functions for generating data for the regression task
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
def generat... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment 函数中返回函数 | # coding: utf-8
# 函数中返回函数
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Apr 19 22:21:14 2020 @author: andy
import pandas as pd
import glob
import csv
set Monthlist = list string January string February string March string April string May string June string July string August string September string October s... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 22:21:14 2020
@author: andy
"""
import pandas as pd
import glob
import csv
Monthlist=["January","February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
#month="December"
#path = r'/home/an... | Python | zaydzuhri_stack_edu_python |
comment you can write to stdout for debugging purposes, e.g.
comment print("this is a debug message")
from itertools import permutations
function solution S
begin
comment write your code in Python 3.6
comment print(S.split(':'))
comment print(list(S))
set ind = list split S string :
comment print(ind[1])
if integer ind... | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
from itertools import permutations
def solution(S):
# write your code in Python 3.6
# print(S.split(':'))
# print(list(S))
ind = list(S.split(':'))
# print(ind[1])
if (int(ind[1][::-1])) > int(... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
set url = string https://python123.io/ws/demo.html
set r = get requests url
set demo = text
set soup = call BeautifulSoup demo string html.parser
print call prettify
print title
comment return tag a
set tag = a
comment tag a's name
print name
comment tag a father's name
pri... | import requests
from bs4 import BeautifulSoup
url="https://python123.io/ws/demo.html"
r= requests.get(url)
demo =r.text
soup = BeautifulSoup(demo,"html.parser")
print(soup.prettify())
print(soup.title)
tag =soup.a #return tag a
print(tag.name) #tag a's name
print(tag.parent.name) #tag a father's name
print(tag.... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pylab as plt
set x = array range - 8 8 0.1
set w1 = 0.5
set w2 = 1.0
set w3 = 2.0
set l1 = string w = 0.5
set l2 = string w = 1.0
set l3 = string w = 2.0
for tuple w l in list tuple w1 l1 tuple w2 l2 tuple w3 l3
begin
set f = 1 / 1 + exp - x * w
plot x f
end
x label string x
y label... | import numpy as np
import matplotlib.pylab as plt
x = np.arange(-8, 8, 0.1)
w1 = 0.5
w2 = 1.0
w3 = 2.0
l1 = 'w = 0.5'
l2 = 'w = 1.0'
l3 = 'w = 2.0'
for w,l in [(w1,l1), (w2,l2), (w3,l3)]:
f = 1 / (1 + np.exp(-x * w))
plt.plot(x, f, )
plt.xlabel('x')
plt.ylabel('h_w(x)')
plt.legend(loc = 2)
plt.show()
| Python | zaydzuhri_stack_edu_python |
import random
class Question
begin
set answer_symbols = list string a string b string c string d string e string f string g string h string i string j string k string l string m string n string o string p
function __init__ self question_text category=none *answers question_img=none
begin
string question_text: a string ... | import random
class Question:
answer_symbols = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]
def __init__(self, question_text, category=None, *answers:list, question_img=None):
"""
question_text: a string
answers: a list of strings
question_img... | Python | zaydzuhri_stack_edu_python |
function left_padding_width self
begin
Ellipsis
end function | def left_padding_width(self):
... | Python | nomic_cornstack_python_v1 |
import socketserver
comment IPアドレスとポート番号を設定する
set Host = string 127.0.0.1
set port = 6000
comment StreamRequestHandlerを継承して新しいクラスを定義する
comment ここでのhandleの中身はユーザが勝手に設定してよい
class Myhandler extends StreamRequestHandler
begin
function handle self
begin
while true
begin
comment 以下からのself.requestはクライアントからの要求に対する属性
comment クラ... | import socketserver
#IPアドレスとポート番号を設定する
Host="127.0.0.1"
port=6000
#StreamRequestHandlerを継承して新しいクラスを定義する
#ここでのhandleの中身はユーザが勝手に設定してよい
class Myhandler(socketserver.StreamRequestHandler):
def handle(self):
while True:
#以下からのself.requestはクライアントからの要求に対する属性
#クライアントからのデータを受け取る
... | Python | zaydzuhri_stack_edu_python |
function _getSectionContentCount self Tag Data
begin
set starttag = string < + Tag + string >
set endtag = string </ + Tag + string >
set start = index Data starttag
set end = index Data endtag
return end - start - length starttag
end function | def _getSectionContentCount(self, Tag, Data):
starttag = "<" + Tag + ">"
endtag = "</" + Tag + ">"
start = Data.index(starttag)
end = Data.index(endtag)
return end - start - len(starttag) | Python | nomic_cornstack_python_v1 |
import numpy as np
comment import pylab as plt
import skfmm
import math
from math import sqrt , pi
from numpy import sin , cos , exp
import numpy as np
import matplotlib.pyplot as plt
import cv2
import time
from scipy.interpolate import spline
set time_start = call clock
set start_time = time
set img = call imread stri... | import numpy as np
# import pylab as plt
import skfmm
import math
from math import sqrt, pi
from numpy import sin, cos, exp
import numpy as np
import matplotlib.pyplot as plt
import cv2
import time
from scipy.interpolate import spline
time_start = time.clock()
start_time = time.time()
img = cv2.imread('map3.bmp')
ro... | Python | zaydzuhri_stack_edu_python |
function plot_free_energy cl ms
begin
if system_dimension == 1
begin
set centers = list comprehension center at 0 for center in clustercenters
scatter plt centers - log stationaryDistribution
call suptitle string Free energy
end
else
begin
raise call ValueError string not a 1 dimentional system
end
end function | def plot_free_energy(cl,ms):
if cl.system_dimension == 1:
centers = [center[0] for center in cl.clustercenters]
plt.scatter(centers, -np.log(ms.stationaryDistribution))
plt.suptitle("Free energy")
else:
raise ValueError("not a 1 dimentional system") | Python | nomic_cornstack_python_v1 |
function getGameState self
begin
set state_tup = list
set peg_1 = list
set peg_2 = list
set peg_3 = list
set ask_1 = call kb_ask call parse_input string fact: (on ?disk peg1
if ask_1
begin
for each in ask_1
begin
set num = integer string constant at - 1
append peg_1 num
end
end
set ask_2 = call kb_ask call parse_in... | def getGameState(self):
state_tup= []
peg_1 = []
peg_2 = []
peg_3 = []
ask_1 = self.kb.kb_ask(parse_input('fact: (on ?disk peg1'))
if ask_1:
for each in ask_1:
num = int(str(each.bindings[0].constant)[-1])
peg_1.append(num)
... | Python | nomic_cornstack_python_v1 |
comment [простой список]
set lst = list 1 2 3
set sq = list
for x in lst
begin
append sq x * x
end
print sq
comment [генератор списка]
set lst = list 1 2 3 4 5 6
set sq = list comprehension x * x for x in lst
print sq
comment [фильтр списка]
set lst = list 1 2 3 4 5 6
set sq = list
for x in lst
begin
if x % 2 == 0
be... | ## [простой список]
lst = [1, 2, 3]
sq = []
for x in lst:
sq.append(x * x)
print (sq)
## [генератор списка]
lst = [1, 2, 3, 4, 5, 6]
sq = [x * x for x in lst]
print (sq)
## [фильтр списка]
lst = [1, 2, 3, 4, 5, 6]
sq = []
for x in lst:
if x % 2 == 0:
sq.append(x*x)
print (sq)
## [генератор с ... | Python | zaydzuhri_stack_edu_python |
function _get_nparts filename headersize itemsize
begin
return get size path filename - headersize / itemsize
end function | def _get_nparts(filename,headersize,itemsize):
return (os.path.getsize(filename)-headersize)/itemsize | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
import os
from util import general_utils
from os.path import dirname , abspath
function directory_to_data directory verbose=true
begin
if verbose
begin
print string Processing + directory
end
set relative_class_dirs = list comprehension x for x in next walk directory at 1
set class_dirs = ... | import cv2
import numpy as np
import os
from util import general_utils
from os.path import dirname, abspath
def directory_to_data(directory, verbose=True):
if verbose:
print("Processing " + directory)
relative_class_dirs = [x for x in next(os.walk(directory))[1]]
class_dirs = [directory... | Python | zaydzuhri_stack_edu_python |
for i in range n
begin
set tuple w v = map int split input
for j in range m - w - 1 - 1
begin
if dp at j != - inf
begin
set dp at j + w = max dp at j + w dp at j + v
end
end
end
print max dp | for i in range(n):
w, v = map(int, input().split())
for j in range(m - w, -1, -1):
if dp[j] != -inf:
dp[j + w] = max(dp[j + w], dp[j] + v)
print(max(dp))
| Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
import sys , requests , json
import logging
call captureWarnings true
set APPID = string INSERT_YOUR_APP_ID
set APPKEY = string INSERT_YOUR_APP_KEY
set test_model = dict string lang string it ; string description string test #1 model ; string categories list dict string name string Tennis ; string... | # coding: utf-8
import sys, requests, json
import logging
logging.captureWarnings(True)
APPID='INSERT_YOUR_APP_ID'
APPKEY='INSERT_YOUR_APP_KEY'
test_model = {
'lang': 'it',
'description': 'test #1 model',
'categories': [
{
"name": "Tennis",
"topics": {
"htt... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Sep 17 14:32:37 2019 @author: 李贺
comment 目标:将样本插值为同一长度,以便作为神经网络的输入
comment 插值用
from scipy import interpolate
comment 读取数据
import scipy.io as sio
import numpy as np
comment 读取数据
comment 文件名称
set data1 = call loadmat string NRev1500Load400
set data2 = call loadmat strin... | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 14:32:37 2019
@author: 李贺
"""
#目标:将样本插值为同一长度,以便作为神经网络的输入
from scipy import interpolate#插值用
import scipy.io as sio #读取数据
import numpy as np
#读取数据
data1 = sio.loadmat('NRev1500Load400') #文件名称
data2 = sio.loadmat('NRev1500Load800')
data3 = sio.loadmat('NRev1... | Python | zaydzuhri_stack_edu_python |
function cpu_affinity rank_id device_num
begin
import psutil
set cores = cpu count
if cores < device_num
begin
return
end
set process = process
set used_cpu_num = cores // device_num
set rank_id = rank_id % device_num
set used_cpu_list = list comprehension i for i in range rank_id * used_cpu_num rank_id + 1 * used_cpu_... | def cpu_affinity(rank_id, device_num):
import psutil
cores = psutil.cpu_count()
if cores < device_num:
return
process = psutil.Process()
used_cpu_num = cores // device_num
rank_id = rank_id % device_num
used_cpu_list = [i for i in range(rank_id * used_cpu_num, (rank_id + 1) * used_cp... | Python | nomic_cornstack_python_v1 |
function remove_projection_from_vector v w
begin
return call vector_subtract v call project v w
end function | def remove_projection_from_vector(v, w):
return vec.vector_subtract(v, project(v, w)) | Python | nomic_cornstack_python_v1 |
function burnoff self bunch
begin
return call luminosity bunch * total_cross_section * 1e-31
end function | def burnoff(self, bunch):
return self.luminosity(bunch) * self.total_cross_section * 1e-31 | Python | nomic_cornstack_python_v1 |
class Agent
begin
string A class used to build Reinforcement Learning algorithms. This class serves as a superclass to build more specific reinforcement learning (RL) algorithms and provides the fundamental parameters found in all RL algorithms. Attributes --------- env : env The environment of a RL algorithm. config :... | class Agent:
"""
A class used to build Reinforcement Learning algorithms.
This class serves as a superclass to build more specific reinforcement
learning (RL) algorithms and provides the fundamental parameters found in
all RL algorithms.
Attributes
---------
env : env
... | Python | zaydzuhri_stack_edu_python |
import turtle
from turtle import *
function test_drive
begin
call pensize 5
call forward 100
call left 87
call setheading 127
call down
call goto 50 50
call home
call circle 25
end function
function turtle_state
begin
print call isdown
print call heading
print call xcor
print call ycor
end function
call turtle_state
ca... | import turtle
from turtle import *
def test_drive():
turtle.pensize(5)
turtle.forward(100)
turtle.left(87)
turtle.setheading(127)
turtle.down()
turtle.goto(50,50)
turtle.home()
turtle.circle(25)
def turtle_state():
print(turtle.isdown())
print(turtle.heading())
print(turtle.x... | Python | zaydzuhri_stack_edu_python |
if b >= a * c
begin
print c
end
else
begin
set sound = if expression b < a then 0 else integer b / a
print sound
end | if b >= a * c:
print(c)
else:
sound = 0 if b < a else int(b / a)
print(sound) | Python | zaydzuhri_stack_edu_python |
function run_projections self min_donation=50 max_donation=100
begin
set projection_coll50 = call DonorCollection
set donors = donors
set projection_coll100 = call DonorCollection
set donors = donors
for donor in donors
begin
set under_50_filter = map lambda x -> x * 3 filter lambda y -> y <= min_donation donations
pri... | def run_projections(self, min_donation=50, max_donation=100):
projection_coll50 = DonorCollection()
projection_coll50.donors = self.donors
projection_coll100 = DonorCollection()
projection_coll100.donors = self.donors
for donor in projection_coll50.donors:
under_50_fi... | Python | nomic_cornstack_python_v1 |
string python中有Numberic类型:整型,浮点型,布尔型
comment 基本类型整形、布尔型、字符串型、#####
print string helloworld
set a = 10
set str = string slsjf
set flag = true
comment 表示一个特殊的空值
set flag = none
set b = string 3456
comment 类型转换
print type integer b
import keyword
print kwlist
print string hello string world string yes
print string %s % b
... | '''
python中有Numberic类型:整型,浮点型,布尔型
'''
######基本类型整形、布尔型、字符串型、#####
print("helloworld")
a =10
str="slsjf"
flag = True
flag = None #表示一个特殊的空值
b="3456"
print(type(int(b)))#类型转换
import keyword
print(keyword.kwlist)
print("hello","world","yes")
print("%s"%b)
f=123.456
print("%.1f"%f)
s=input("请输入:")
print(s)
############运算符#... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
import sys
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
class Q2
begin
function __init__ self
begin
set dataset = read csv string weight-height.csv
set Xtrain = none
set Ytrain = ... | import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
import sys
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
class Q2():
def __init__(self):
self.dataset=pd.read_csv('weight-height.csv')
self.Xtrain... | Python | zaydzuhri_stack_edu_python |
function add_filter_args parser
begin
set group = call add_mutually_exclusive_group
call add_argument string -g string --greater help=string only report sections >= N metavar=string N type=int default=0
call add_argument string -l string --less help=string only report sections <= N metavar=string N type=int default=dec... | def add_filter_args(parser):
group = parser.add_mutually_exclusive_group()
group.add_argument("-g", "--greater", help="only report sections >= N",
metavar="N", type=int, default=0)
group.add_argument("-l", "--less", help="only report sections <= N",
metavar="N",... | Python | nomic_cornstack_python_v1 |
function split_number_from_name name
begin
set basename = right strip name string 0123456789
try
begin
return tuple basename integer name at slice length basename : - 1 :
end
except any
begin
return tuple basename - 1
end
end function | def split_number_from_name(name):
basename = name.rstrip('0123456789')
try:
return (basename, int(name[len(basename):-1]))
except:
return (basename, -1) | Python | nomic_cornstack_python_v1 |
import time
import requests
from bs4 import BeautifulSoup
from schedule.dataType.Schedule import *
comment 網頁: http://www.hkt48.jp/schedule/
class Hkt extends object
begin
comment 查詢時間 時間格式 yyyy/MM/dd ex: 2018/08/10
set query_date = string
set CATEGORY = dict string 35 string 誕生日 ; string 85 string 握手会 ; string 20 str... | import time
import requests
from bs4 import BeautifulSoup
from schedule.dataType.Schedule import *
# 網頁: http://www.hkt48.jp/schedule/
class Hkt(object):
query_date = "" # 查詢時間 時間格式 yyyy/MM/dd ex: 2018/08/10
CATEGORY = {
'35': '誕生日',
'85': '握手会',
'20': '公演',
'36': 'リリース',
... | Python | zaydzuhri_stack_edu_python |
function community_gallery_image_id self
begin
return get pulumi self string community_gallery_image_id
end function | def community_gallery_image_id(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "community_gallery_image_id") | Python | nomic_cornstack_python_v1 |
import json
import logging
import requests
from datetime import datetime , timedelta
set logger = call getLogger string main
call setLevel DEBUG
class WeatherScraper
begin
set API_URL = string https://www.metaweather.com/
set LOCATION_FORECAST_QUERY = string api/location/{woeid}/{date}/
set DATE_FORMAT = string %Y/%m/%... | import json
import logging
import requests
from datetime import datetime, timedelta
logger = logging.getLogger('main')
logger.setLevel(logging.DEBUG)
class WeatherScraper:
API_URL = "https://www.metaweather.com/"
LOCATION_FORECAST_QUERY = "api/location/{woeid}/{date}/"
DATE_FORMAT = "%Y/%m/... | Python | zaydzuhri_stack_edu_python |
import os
from astropy.io import fits
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.interpolate import RegularGridInterpolator
import numpy as np
comment sort out paths
set LOCALPATH = directory name path real path path __file__
comment directory for fits files
set FITS_DIR = join path LOCALPATH... | import os
from astropy.io import fits
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.interpolate import RegularGridInterpolator
import numpy as np
# sort out paths
LOCALPATH = os.path.dirname(os.path.realpath(__file__))
# directory for fits files
FITS_DIR = os.path.join(LOCALPATH, 'grids')
#--... | Python | zaydzuhri_stack_edu_python |
function find_and_set_debugged_frame self frame thread_id
begin
string The dance we have to do to set debugger frame state to *frame*, which is in the thread with id *thread_id*. We may need to the hide initial debugger frames.
set thread = _active at thread_id
set thread_name = call getName
if not settings at string d... | def find_and_set_debugged_frame(self, frame, thread_id):
'''The dance we have to do to set debugger frame state to
*frame*, which is in the thread with id *thread_id*. We may
need to the hide initial debugger frames.
'''
thread = threading._active[thread_id]
thread_name =... | Python | jtatman_500k |
string keeps python files small like functions for DRY reuse code across multiple files by importing modul is just a python file IMPORT ONLY WHAT YOU NEED from MODULE import <METHOD_NAME>
from termcolor import colored , cprint
from pyfiglet import Figlet
from keyword import iskeyword
from modules_part import get_custom... | '''
keeps python files small
like functions for DRY
reuse code across multiple files by importing
modul is just a python file
IMPORT ONLY WHAT YOU NEED
from MODULE import <METHOD_NAME>
'''
from termcolor import colored, cprint
from pyfiglet import Figlet
from keyword import iskeyword
from modules_part import get_cu... | Python | zaydzuhri_stack_edu_python |
function getTemperature self servo_id=1
begin
try
begin
return integer read self servo_id P_PRESENT_TEMPERATURE 1 at 0
end
except TypeError
begin
return - 1
end
end function | def getTemperature(self, servo_id=1):
try:
return int(self.read(servo_id, P_PRESENT_TEMPERATURE, 1)[0])
except TypeError:
return -1 | Python | nomic_cornstack_python_v1 |
comment 蒙特卡洛方法计算圆周率的示例程序。
comment 其特点是可以并行计算。
import random
import datetime
import time
seed now
set r = 100.0
set count_in = 0
set count_all = 1000000
set start = time
for i in range 0 count_all
begin
set x = uniform - 100 100
set y = uniform - 100 100
if x * x + y * y < r * r
begin
set count_in = count_in + 1
end
end... | # 蒙特卡洛方法计算圆周率的示例程序。
# 其特点是可以并行计算。
import random
import datetime
import time
random.seed(datetime.datetime.now())
r = 100.0
count_in = 0
count_all = 1000000
start = time.time()
for i in range(0, count_all):
x = random.uniform(-100, 100)
y = random.uniform(-100, 100)
if x*x+y*y < r*r:
count_in += 1
... | Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ self data
begin
set data = data
set left = none
set right = none
end function
end class
class BinarySearchTree
begin
function __init__ self
begin
set root = none
end function
function insert self data
begin
set newNode = call Node data
if root is none
begin
set root = newNode
end
else... | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, data):
newNode = Node(data)
if self.root is None:
self.root = newNode
... | Python | jtatman_500k |
comment NOTE: used in command.py
function _pkt_hdr pkt rx_header=none
begin
comment offer, bid. accept
comment I --- 12:010740 --:------ 12:010740 1FC9 024 0023093029F40030C93029F40000083029F4001FC93029F4
comment W --- 01:145038 12:010740 --:------ 1FC9 006 07230906368E
comment I --- 12:010740 01:145038 --:------ 1FC9 ... | def _pkt_hdr(pkt, rx_header=None) -> Optional[str]: # NOTE: used in command.py
# offer, bid. accept
# I --- 12:010740 --:------ 12:010740 1FC9 024 0023093029F40030C93029F40000083029F4001FC93029F4
# W --- 01:145038 12:010740 --:------ 1FC9 006 07230906368E
# I --- 12:010740 01:145038 --:------ 1FC9 ... | Python | nomic_cornstack_python_v1 |
import requests
set btc = json get requests string https://api.bithumb.com/public/ticker/ at string data
set open = decimal btc at string opening_price | import requests
btc = requests.get("https://api.bithumb.com/public/ticker/").json()['data']
open = float(btc['opening_price']) | Python | zaydzuhri_stack_edu_python |
import scrapy
from mensa.items import Personal
class Mathecafe extends Spider
begin
set name = string Mathecafe
set start_urls = list string http://singh-catering.de/cafe/
function parse self response
begin
set top_layer = call xpath string //article[@id="post-69"]/section[@class="article__content"]
set menu_lists = ca... | import scrapy
from mensa.items import Personal
class Mathecafe(scrapy.Spider):
name = "Mathecafe"
start_urls = ["http://singh-catering.de/cafe/"]
def parse(self, response):
top_layer = response.xpath('//article[@id="post-69"]/section[@class="article__content"]')
menu_lists = top_layer.xpa... | Python | zaydzuhri_stack_edu_python |
import random
from PIL import Image
comment assume resizedlist is a dictionary where keys are image names and
comment values are corresponding ndarrays
set images = list values resizedlist
shuffle random images
comment display first 10 randomly selected images
for i in range 10
begin
show
end | import random
from PIL import Image
# assume resizedlist is a dictionary where keys are image names and
# values are corresponding ndarrays
images = list(resizedlist.values())
random.shuffle(images)
# display first 10 randomly selected images
for i in range(10):
Image.fromarray(images[i]).show()
| Python | flytech_python_25k |
async function do_update self id data
begin
set old = await call string datastore.query datastore list tuple string identifier string = id dict string prefix datastore_prefix ; string get true
pop old string enabled none
call _expand_enclosure old
set new = copy old
update new data
if old at string passwd != new at str... | async def do_update(self, id, data):
old = await self.middleware.call(
'datastore.query',
self._config.datastore,
[('identifier', '=', id)],
{'prefix': self._config.datastore_prefix, 'get': True}
)
old.pop('enabled', None)
self._expand_enc... | Python | nomic_cornstack_python_v1 |
comment Definition for a binary tree node.
comment class TreeNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Solution extends object
begin
function recoverTree self root
begin
string :type root: TreeNode :rtype: None Do not return anything, modi... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution ( object ):
def recoverTree(self , root):
"""
:type root: TreeNode
:rtype: None Do not return anything, mo... | Python | zaydzuhri_stack_edu_python |
function libnx ctx clion
begin
call libnx name author clion cwd
end function | def libnx(ctx, clion):
app.libnx(ctx.name, ctx.author, clion, ctx.cwd) | Python | nomic_cornstack_python_v1 |
function DisplayBoard
begin
comment the function accepts one parameter containing the board's current status
comment and prints it out to the console
set s = string +=======================+ | | | | | %s | %s | %s | | | | | |-------|-------|-------| | | | | | %s | %s | %s | | | | | |-------|-------|-------| | | | | | %... | def DisplayBoard():
#
# the function accepts one parameter containing the board's current status
# and prints it out to the console
#
s = '''
+=======================+
| | | |
| %s | %s | %s |
| | | |
|-------|-------|-------|
... | Python | zaydzuhri_stack_edu_python |
import math
function area r
begin
return pi * r ^ 2
end function
for i in range 1 5 1
begin
for j in range 2 6 1
begin
try
begin
set p = 91.12 / 1 / i ^ 2 - 1 / j ^ 2
print p string i string j
end
except ZeroDivisionError
begin
continue
end
end
end | import math
def area(r):
return math.pi*(r**2)
for i in range(1, 5, 1):
for j in range(2, 6, 1):
try:
p = 91.12 / ((1/i**2)-(1/j**2))
print(p, " ", i, " ", j)
except ZeroDivisionError:
continue | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function minPathSum self grid
begin
set m = length grid
set n = length grid at 0
set memo = copy grid
for j in range 1 n
begin
set memo at 0 at j = memo at 0 at j + memo at 0 at j - 1
end
for i in range 1 m
begin
set memo at i at 0 = memo at i at 0 + memo at i - 1 at 0
end
for x in range 1 m
begin
... | class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
memo = grid.copy()
for j in range(1, n):
memo[0][j] += memo[0][j - 1]
for i in range(1, m):
memo[i][0] += memo[i - 1][0]
... | Python | zaydzuhri_stack_edu_python |
from random import randint
import discord
import config
set client = call Client
set exercises : list = list
set claimed : list = list
set statusmessage = none
set CHANNELS = list 810946686728929300 810920527736340550 541408928408272938
set prefix = string %
set load_str = prefix + string load
set claim_str = prefix ... | from random import randint
import discord
import config
client = discord.Client()
exercises: list = []
claimed: list = []
statusmessage = None
CHANNELS = [810946686728929300, 810920527736340550, 541408928408272938]
prefix = "%"
load_str = prefix + "load "
claim_str = prefix + "claim "
unclaim_str = prefix + "unclaim... | Python | zaydzuhri_stack_edu_python |
import re
import subprocess
from collections import namedtuple
class Mode extends named tuple string Mode list string size string current string preferred
begin
function ratio self
begin
return size at 0 / size at 1
end function
function dpmm self screen_size
begin
return max tuple size at 0 / screen_size at 0 size at ... | import re
import subprocess
from collections import namedtuple
class Mode(namedtuple('Mode', ['size', 'current', 'preferred'])):
def ratio(self):
return self.size[0] / self.size[1]
def dpmm(self, screen_size):
return max((self.size[0] / screen_size[0], self.size[1] / screen_size[1]))
def name(self):
... | Python | zaydzuhri_stack_edu_python |
string 函数,其实就是一个代码块 函数定义的语法: def funName(args): body [return]
comment 无参数函数
function fun1
begin
print string this is my first python funuc
end function
comment 定义有参数函数
function fun2 x y
begin
return x + y
end function
comment 定义一个无惨空方法
function fun3
begin
pass
end function
comment 默认值参数的方法
function fun4 name age=20 sex... | """
函数,其实就是一个代码块
函数定义的语法:
def funName(args):
body
[return]
"""
# 无参数函数
def fun1():
print("this is my first python funuc")
# 定义有参数函数
def fun2(x, y):
return x + y
# 定义一个无惨空方法
def fun3():
pass
# 默认值参数的方法
def fun4(name, age=20, sex='男'):
print("name:" + name + " age:" + str(age) + " sex:" + ... | Python | zaydzuhri_stack_edu_python |
function forward self x
begin
set x = call conv1 x
set x = relu x
set x = call conv2 x
set x = relu x
set x = call max_pool2d x 2
set x = call dropout1 x
set x = flatten torch x 1
set x = call fc1 x
set x = relu x
set x = call dropout2 x
set x = call fc2 x
set output = call log_softmax x dim=1
return output
end functio... | def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x... | Python | nomic_cornstack_python_v1 |
function apply_cont_actions self commands
begin
assert length commands == _num_agents
for i in range _num_agents
begin
call cont_move commands at i
end
call _update_scores
end function | def apply_cont_actions(self, commands):
assert len(commands) == self._num_agents
for i in range(self._num_agents):
self._agents[i].cont_move(commands[i])
self._update_scores() | Python | nomic_cornstack_python_v1 |
function areaNormals x
begin
set tuple area normals = call vectorPairAreaNormals x at tuple slice : : 1 - x at tuple slice : : 0 x at tuple slice : : 2 - x at tuple slice : : 1
set area = area * 0.5
return tuple area normals
end function | def areaNormals(x):
area,normals = vectorPairAreaNormals(x[:,1]-x[:,0],x[:,2]-x[:,1])
area *= 0.5
return area,normals | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env
comment coding:utf-8
string Created on 2019/5/16 13:53 base Info
set __author__ = string xx
set __version__ = string 1.0
from data_loader import Cora , Citeseer , Pubmed
import networkx as nx
import numpy as np
import torch
class Graph_stat
begin
function __init__ self dataset
begin
set dataset = ... | #!/usr/bin/env
# coding:utf-8
"""
Created on 2019/5/16 13:53
base Info
"""
__author__ = 'xx'
__version__ = '1.0'
from data_loader import Cora,Citeseer,Pubmed
import networkx as nx
import numpy as np
import torch
class Graph_stat():
def __init__(self, dataset):
self.dataset= dataset
# self.dataset... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string A rectangular area of cells can be merged into a single cell with the merge_cells() sheet method
import openpyxl
set wb = call Workbook
set sheet = call get_active_sheet
call merge_cells string A1:D3
set sheet at string A1 = string Twelve cells merged together.
call merge_cells stri... | #!/usr/bin/env python3
"""A rectangular area of cells can be merged into a single cell with the
merge_cells() sheet method"""
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.get_active_sheet()
sheet.merge_cells('A1:D3')
sheet['A1'] = 'Twelve cells merged together.'
sheet.merge_cells('C5:D5')
sheet['C5'] = 'Two m... | Python | zaydzuhri_stack_edu_python |
class TrieNode
begin
function __init__ self
begin
set next = dict
set word = none
end function
end class
class Trie
begin
function __init__ self
begin
set root = call TrieNode
end function
function insert self w
begin
set node = root
for c in w
begin
if c not in next
begin
set next at c = call TrieNode
end
set node = ... | class TrieNode():
def __init__(self):
self.next = {}
self.word = None
class Trie():
def __init__(self):
self.root = TrieNode()
def insert(self, w):
node = self.root
for c in w:
if c not in node.next:
node.next[c] = TrieNod... | Python | zaydzuhri_stack_edu_python |
function ComputeCountryTimeSeriesHigh country_id feature=none zoom=1
begin
set img = call Image HIGH_COLLECTION_ID
set img = select img string elevation
set scale = 50000
if feature is none
begin
set feature = call GetFeature country_id
end
else
begin
set scale = scale / zoom
end
set reduction = call reduceRegion mean ... | def ComputeCountryTimeSeriesHigh(country_id, feature = None, zoom = 1):
img = ee.Image(HIGH_COLLECTION_ID)
img = img.select('elevation')
scale = 50000
if feature is None:
feature = GetFeature(country_id)
else:
scale = scale / zoom
reduction = img.reduceRegion(ee.Reducer.mean(), feature.geometry(... | Python | nomic_cornstack_python_v1 |
comment https://leetcode.com/problems/missing-number/
comment given an array containing n distinct numbers
comment taken from 0, 1, 2, ..., n, find the one
comment that is missing from the array
function missingNumber nums
begin
set length = length nums
set max_sum = length * length + 1 // 2
return max_sum - sum nums
e... | # https://leetcode.com/problems/missing-number/
# given an array containing n distinct numbers
# taken from 0, 1, 2, ..., n, find the one
# that is missing from the array
def missingNumber(nums):
length = len(nums)
max_sum = length * (length + 1) // 2
return max_sum - sum(nums)
alist = [0, 2, 1, 5, 7, 6, 9, 8, 4]... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
set url = string https://www.yogaflowpittsburgh.com/studio/shadyside-studio
set response = get requests url
set soup = call BeautifulSoup text string html.parser
set l = find all class_=string portfolio center
set num = 0
for item in l
begin
set num = num + 1
print text
end... | import requests
from bs4 import BeautifulSoup
url='https://www.yogaflowpittsburgh.com/studio/shadyside-studio'
response=requests.get(url)
soup = BeautifulSoup(response.text,'html.parser')
l=soup.findAll(class_='portfolio center')
num=0
for item in l:
num=num+1
print(item.text)
print('There are ',num... | Python | zaydzuhri_stack_edu_python |
function recommend user_id ratings movie_names n_neighbors=10 n_recomm=5
begin
comment convert long to wide
set ratings_wide = call pivot index=string user columns=string movie values=string rating
comment all the items a user has not rated, that can be recommended
set all_items = loc at tuple user_id slice : :
set ... | def recommend(user_id, ratings, movie_names, n_neighbors=10, n_recomm=5):
# convert long to wide
ratings_wide = ratings.pivot(index='user', columns='movie', values='rating')
# all the items a user has not rated, that can be recommended
all_items = ratings_wide.loc[user_id,:]
unrated_items = al... | Python | nomic_cornstack_python_v1 |
import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
set tuple tuple x_train y_train tuple x_test y_test = call load_data
comment (60000,28,28)
print string x_shape: shape
comment (60000)
... | import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# (60000,28,28)
print('x_shape:', x_train.shape)
# (60000)
print('y_shape:', ... | Python | zaydzuhri_stack_edu_python |
function value_present name datastore path config
begin
string Ensure a specific value exists at a given path :param name: The name for this rule :type name: ``str`` :param datastore: The datastore, e.g. running, operational. One of the NETCONF store IETF types :type datastore: :class:`DatastoreType` (``str`` enum). :p... | def value_present(name, datastore, path, config):
'''
Ensure a specific value exists at a given path
:param name: The name for this rule
:type name: ``str``
:param datastore: The datastore, e.g. running, operational.
One of the NETCONF store IETF types
:type datastore: :class:`Datast... | Python | jtatman_500k |
function test_all_datatypes_write self
begin
call all_datatypes_prepare
set insert_statement = call prepare string INSERT INTO testdatatype (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, za) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
execute ... | def test_all_datatypes_write(self):
self.all_datatypes_prepare()
insert_statement = self.session.prepare(
"""INSERT INTO testdatatype (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, za)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ... | Python | nomic_cornstack_python_v1 |
string Created on 11 Mar 2013 @author: eidahil
class MyPensionData extends object
begin
function __init__ self company_pension_contribution pension_contribution
begin
call set_my_pension_contribution pension_contribution
call set_company_pension_contribution company_pension_contribution
end function
function set_my_pen... | '''
Created on 11 Mar 2013
@author: eidahil
'''
class MyPensionData(object):
def __init__(self, company_pension_contribution, pension_contribution):
self.set_my_pension_contribution(pension_contribution)
self.set_company_pension_contribution(company_pension_contribution)
def set_my_pension_c... | Python | zaydzuhri_stack_edu_python |
from PPlay.window import *
from PPlay.gameimage import *
from PPlay.sprite import *
from menu import *
from jogo2 import *
from fim import *
set GAME_STATE = 0
set janela = call Window 1000 700
call set_title string Pieces
set mouse = call get_mouse
set teclado = call get_keyboard
call set_background_color tuple 255 25... | from PPlay.window import *
from PPlay.gameimage import *
from PPlay.sprite import *
from menu import *
from jogo2 import *
from fim import *
GAME_STATE=0
janela = Window(1000, 700)
janela.set_title("Pieces")
mouse = Window.get_mouse()
teclado = Window.get_keyboard()
janela.set_background_color((255, ... | Python | zaydzuhri_stack_edu_python |
function itkFlatStructuringElement3_Box radius
begin
return call itkFlatStructuringElement3_Box radius
end function | def itkFlatStructuringElement3_Box(radius: 'itkSize3') -> "itkFlatStructuringElement3":
return _itkFlatStructuringElementPython.itkFlatStructuringElement3_Box(radius) | Python | nomic_cornstack_python_v1 |
for score in scores
begin
if score > 0 and score >= treshold
begin
set advance_count = advance_count + 1
end
else
begin
break
end
end
print advance_count | for score in scores:
if score > 0 and score >= treshold:
advance_count += 1
else:
break
print(advance_count)
| Python | zaydzuhri_stack_edu_python |
comment labs for 4.3.1.6 - 4.3.1.8
function is_year_leap year
begin
comment return true if leap year
set modByFour = year % 4
set modByHundred = year % 100
set modByfourHundred = year % 400
if year < 1582
begin
comment print("Not within greg cal")
return false
end
else
comment not divisible by four?
if modByFour != 0
b... | #labs for 4.3.1.6 - 4.3.1.8
def is_year_leap(year):
#return true if leap year
modByFour = year%4
modByHundred = year % 100
modByfourHundred = year % 400
if year <1582:
#print("Not within greg cal")
return False
elif modByFour != 0: # not divisible by four?
#print("commo... | Python | zaydzuhri_stack_edu_python |
function unix_nanos_to_datetime ns
begin
set ms = integer round ns / 1000
set td = time delta microseconds=ms
return _unix_epoch_datetime + td
end function | def unix_nanos_to_datetime(ns):
ms = int(round(ns / 1000))
td = datetime.timedelta(microseconds=ms)
return _unix_epoch_datetime + td | Python | nomic_cornstack_python_v1 |
for number in range 1 101
begin
print number
end | for number in range(1, 101):
print(number)
| Python | flytech_python_25k |
function test_value_init9 self
begin
with assert raises TypeError as err
begin
set r1 = call Rectangle list 1 2 8
end
set msg = string width must be an integer
assert equal string exception msg
end function | def test_value_init9(self):
with self.assertRaises(TypeError) as err:
r1 = Rectangle([1, 2], 8)
msg = "width must be an integer"
self.assertEqual(str(err.exception), msg) | Python | nomic_cornstack_python_v1 |
function palindrome string
begin
if lower replace string string string at slice : : - 1 == lower replace string string string
begin
return true
end
else
begin
return false
end
end function
function main
begin
call palindrome string Bob
return
end function
if __name__ == string __main__
begin
call main
end | def palindrome(string):
if string.replace(" ","")[::-1].lower()==string.replace(" ","").lower():
return True
else:
return False
def main():
palindrome("Bob")
return
if __name__ == '__main__':
main()
| Python | zaydzuhri_stack_edu_python |
function _nmrJ self
begin
call coord2xyz
comment generate input # double hybrids not implemented # tpss needs for some reason additionally def2/j
set nmrj_calls = dict string tpss list string %MaxCore 8000 string ! tpss + string basis + string grid5 def2/j nofinalgrid nososcf string ! smallprint printgap noloewdin stri... | def _nmrJ(self):
self.coord2xyz()
# generate input # double hybrids not implemented # tpss needs for some reason additionally def2/j
nmrj_calls = {
"tpss": [
"%MaxCore 8000",
"! tpss " + str(self.basis) + " grid5 def2/j nofinalgrid nososcf ",
... | Python | nomic_cornstack_python_v1 |
from django.db import models
from django.contrib.auth.models import BaseUserManager , AbstractBaseUser
from django.utils import timezone
class UserManager extends BaseUserManager
begin
comment Creates and saves User with the given email and password
function create_user self email password=none first_name=none last_nam... | from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.utils import timezone
class UserManager(BaseUserManager):
# Creates and saves User with the given email and password
def create_user(self, email, password=None, first_name=None, last_name=None):
... | Python | zaydzuhri_stack_edu_python |
function prepare sentence
begin
set buffered = call BytesIO
comment imports font and creates sentence with appropriate \n
set fnt = call truetype string ./static/fonts/GermaniaOne-Regular.ttf size=32
set split_txt = call wrap sentence width=34
set split_txt = join string split_txt
comment create black bg image
set bla... | def prepare(sentence):
buffered = BytesIO()
# imports font and creates sentence with appropriate \n
fnt = ImageFont.truetype("./static/fonts/GermaniaOne-Regular.ttf", size=32)
split_txt = textwrap.wrap(sentence, width=34)
split_txt = "\n".join(split_txt)
# create black bg image
blank_image =... | Python | nomic_cornstack_python_v1 |
function get_questions
begin
try
begin
set page = get args string page 1 type=int
set questions = call get_questions_by_page page
if length questions == 0
begin
call abort STATUS_NOT_FOUND
end
return call jsonify dict string success true ; string current_category none ; string categories call get_all_categories ; strin... | def get_questions():
try:
page = request.args.get('page', 1, type=int)
questions = get_questions_by_page(page)
if len(questions) == 0:
abort(STATUS_NOT_FOUND)
return jsonify({
'success': True,
'current_category': None,
'categories': g... | Python | nomic_cornstack_python_v1 |
comment def is_single_riffle(half1, half2, shuffled_deck):
comment """Recursive implementation: O(n) time, O(n) space"""
comment if not shuffled_deck:
comment if not half1 and not half2:
comment return True
comment return False
comment first_card_shuffled_deck = shuffled_deck.pop()
comment if half1 and first_card_shuff... | # def is_single_riffle(half1, half2, shuffled_deck):
# """Recursive implementation: O(n) time, O(n) space"""
# if not shuffled_deck:
# if not half1 and not half2:
# return True
# return False
# first_card_shuffled_deck = shuffled_deck.pop()
# if half1 and first_card_shuffl... | Python | zaydzuhri_stack_edu_python |
function test_update_product self
begin
with client
begin
set res = call create
set access_token = string mytoken
set headers = dict string Authorizations format string Bearer {} access_token
return post headers=headers
assert equal status_code 201
set result = put format string /api/v1/products/{} call get_json at str... | def test_update_product(self):
with self.client:
res = self.create()
access_token = 'mytoken'
headers = {'Authorizations': 'Bearer {}'.format(access_token)}
return self.client.post(
headers=headers
)
self.assertEqual(res.... | Python | nomic_cornstack_python_v1 |
function factory train_files valid_files normalize=true box_size=5 downscale_ratio=none boxes_per_img=100 include_zeros=true
begin
set train_ds = call load_files_to_dataset train_files length train_files * boxes_per_img _generator normalize=normalize box_size=box_size downscale_ratio=downscale_ratio boxes_per_img=boxes... | def factory(train_files, valid_files, normalize=True, box_size=5, downscale_ratio=None, boxes_per_img=100,
include_zeros=True):
train_ds = load_files_to_dataset(train_files, len(train_files) * boxes_per_img, _generator, normalize=normalize,
box_size=box_size, downsca... | Python | nomic_cornstack_python_v1 |
comment This file will be used to backfill the meme database
import requests
import os
import json
set currentDirectory = get current directory
with open currentDirectory + string \DankMemes.txt string a+ as outfile
begin
set url = string https://www.reddit.com/r/dankmemes/top/.json?sort=top&t=year&limit=100
set reqHea... | #This file will be used to backfill the meme database
import requests
import os
import json
currentDirectory = os.getcwd()
with open(currentDirectory + '\\DankMemes.txt', 'a+') as outfile:
url = 'https://www.reddit.com/r/dankmemes/top/.json?sort=top&t=year&limit=100'
reqHeaders = {
'User-Agent' : 'pers... | Python | zaydzuhri_stack_edu_python |
function create_queue_payload req task=none payload_override=none
begin
return dict string task task or string clockify.webhook ; string meta dict string headers dictionary comprehension string header at 0 : get headers string header at 0 none for header in headers or none ; string params dictionary comprehension strin... | def create_queue_payload(req, task=None, payload_override=None):
return {
"task": task or "clockify.webhook",
"meta": {
"headers": {
str(header[0]): req.headers.get(str(header[0]), None) for header in req.headers
} or None
},
"params": {str(arg... | Python | nomic_cornstack_python_v1 |
function read_bytes url
begin
set cmd = list string gsutil string cat url
return check output cmd
end function | def read_bytes(url: str) -> bytes:
cmd = ['gsutil', 'cat', url]
return subprocess.check_output(cmd) | Python | nomic_cornstack_python_v1 |
for i in range 3
begin
set count at i = T // buttons at i
set T = T % buttons at i
if T == 0
begin
break
end
end
if T != 0
begin
print - 1
end
else
begin
print *count
end
comment n=int(input())
comment a=n//300
comment b=n%300//60
comment c=n%60//10
comment print(*[[-1],[n//300,n//60%5,n//10%6]][n//10==n/10]) | for i in range(3):
count[i] = T//buttons[i]
T = T%buttons[i]
if T == 0:
break
if T != 0:
print(-1)
else:
print(*count)
# n=int(input())
# a=n//300
# b=n%300//60
# c=n%60//10
# print(*[[-1],[n//300,n//60%5,n//10%6]][n//10==n/10])
| Python | zaydzuhri_stack_edu_python |
function isToday self day
begin
return now at 2 == day and now at 1 == month and now at 0 == year
end function | def isToday(self, day):
return self.now[2]==day and self.now[1]==self.month and \
self.now[0]==self.year | Python | nomic_cornstack_python_v1 |
function sum_from_string string
begin
return sum map int find all string \d+ string
end function | def sum_from_string(string):
return sum(map(int, re.findall('\d+', string))) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.