code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment 笔记#######
comment response这个对象的功能
comment read() 读取相应的内容,内容是字节类型
comment geturl() 获取请求的url
comment getheaders() 获取头部信息 元组格式 可以dict转化
comment getcode() 获取状态码
comment readlines() 按行读取,返回列表,都是字节类型
comment 笔记#######
import urllib.request
set url = string http://www.baidu.com
comment 完整的url http://www.baidu.com/inde... | ########笔记#######
# response这个对象的功能
# read() 读取相应的内容,内容是字节类型
# geturl() 获取请求的url
# getheaders() 获取头部信息 元组格式 可以dict转化
# getcode() 获取状态码
# readlines() 按行读取,返回列表,都是字节类型
########笔记#######
import urllib.request
url = 'http://www.baidu.com'
##完整的url http://www.baidu.com/index.html?name=goudan&...
##发... | Python | zaydzuhri_stack_edu_python |
import operator
import pandas as pd
import math
function read_file file
begin
set document = open file
set record_lines = list
while 1
begin
set each_line = read line document
set each_line = strip each_line string
if not each_line
begin
break
end
comment print(para)
append record_lines each_line
end
close document
re... | import operator
import pandas as pd
import math
def read_file(file):
document = open(file)
record_lines= []
while 1:
each_line = document.readline()
each_line = each_line.strip('\n')
if not each_line:
break
# print(para)
record_lines.append(each_line)
... | Python | zaydzuhri_stack_edu_python |
comment 변수와 값이 다음과 같을 때
comment 총점과 평균을 구해서 아래와 같이 출력(포맷 코드 사용)
set kor = 90
set eng = 80
set math = 80
comment 총점: 250, 평균: 83.33
set total = kor + eng + math
set average = total / 3
print string 총점: %d, 평균: %.2f % tuple total average | # 변수와 값이 다음과 같을 때
# 총점과 평균을 구해서 아래와 같이 출력(포맷 코드 사용)
kor = 90
eng = 80
math = 80
# 총점: 250, 평균: 83.33
total = kor+eng+math
average = total/3
print("총점: %d, 평균: %.2f" %(total,average)) | Python | zaydzuhri_stack_edu_python |
for i in range 0 counter
begin
comment print(i)
print string char is ------> char
set char = find m string .
print string char is ------> char
set m = replace m at char string . string
print string char is ------> char
set m = lower m at char
print string char is ------> char
set char = char + 2
print string char is --... | for i in range(0,counter):
#print(i)
print("char is ------>",char)
char=m.find(".")
print("char is ------>",char)
m=m[char].replace("."," ")
print("char is ------>",char)
m=m[char].lower()
print("char is ------>",char)
char+=2
print("char is ----------------->",char)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import matplotlib.pyplot as plt
import pickle
import launch
import sys
import numpy as np
import math
string Generates plots from configs list.
class msb_plotter
begin
function __init__ self configs sizes=list 25 50 75 + list comprehension i * 100 for i in range 1 10
begin
set rest = length... | #!/usr/bin/env python
import matplotlib.pyplot as plt
import pickle
import launch
import sys
import numpy as np
import math
"""
Generates plots from configs list.
"""
class msb_plotter:
def __init__(self, configs, sizes=[25,50, 75] + [i*100 for i in range(1,10)]):
rest = len(configs) % 3
if (res... | Python | zaydzuhri_stack_edu_python |
comment https://www.acmicpc.net/problem/11404
import sys
from collections import defaultdict
set read = readline
set n = integer strip read
set m = integer strip read
set adj = default dictionary lambda -> default dictionary lambda -> decimal string inf
while m
begin
set tuple a b w = map int split strip read
set adj... | # https://www.acmicpc.net/problem/11404
import sys
from collections import defaultdict
read = sys.stdin.readline
n = int(read().strip())
m = int(read().strip())
adj = defaultdict(lambda: defaultdict(lambda: float('inf')))
while m:
a, b, w = map(int, read().strip().split())
adj[a][b] = min(adj[a][b], w)
m ... | Python | zaydzuhri_stack_edu_python |
function get self key default=none
begin
try
begin
return self at key
end
except KeyError
begin
return default
end
end function | def get(self, key, default=None):
try: return self[key]
except KeyError: return default | Python | nomic_cornstack_python_v1 |
function showLoginPage request
begin
return call render request string core/login.html dict
end function | def showLoginPage(request):
return render(request, "core/login.html", {
}) | Python | nomic_cornstack_python_v1 |
function test_callback self
begin
set callback = string jsonp123
set before = list call values_list string clientId flat=true
set response = call url dict string appId call get_token ; string user clientId ; string callback callback
set after = list call values_list string clientId flat=true
comment check that users co... | def test_callback(self):
callback ='jsonp123'
before = list(self.app.users.all().values_list('clientId', flat=True))
response = self.call(self.url, {'appId':self.app.get_token(), 'user':self.user.clientId, 'callback': callback})
after = list(self.app.users.all().values_list('clientId', f... | Python | nomic_cornstack_python_v1 |
import cave_gen_worker
import numpy as np
import pickle
import trimesh
import skimage.io as io
from time import monotonic
function main
begin
set cube_tasks = 10
set perlin_iterations = 100
set size = list 20 20 20
set perlin_time = 0
set cubes_time = 0
comment Create data for starmap and get results
set perlin_results... | import cave_gen_worker
import numpy as np
import pickle
import trimesh
import skimage.io as io
from time import monotonic
def main():
cube_tasks = 10
perlin_iterations = 100
size = [20,20,20]
perlin_time = 0
cubes_time = 0
# Create data for starmap and get results
perlin_results = []
... | Python | zaydzuhri_stack_edu_python |
function actionable self item
begin
raise call NotImplementedError
end function | def actionable(self, item):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function smooth_spectra spectra kernel=string Gaussian smooth_size=3 rebin=false
begin
comment only go through all this if smooth_size > 1
if smooth_size > 1
begin
if kernel == string box
begin
set smooth_ker = call Box1DKernel smooth_size
end
else
if kernel == string Gaussian
begin
set smooth_ker = call Gaussian1DKern... | def smooth_spectra(spectra, kernel = 'Gaussian', smooth_size = 3, rebin = False):
if smooth_size > 1: #only go through all this if smooth_size > 1
if kernel == 'box':
smooth_ker = Box1DKernel(smooth_size)
elif kernel == 'Gaussian':
smooth_ker = Gaussian1DKernel(smooth_size)
... | Python | nomic_cornstack_python_v1 |
function _parse_executive_summary df
begin
comment Exec summary is formatted oddly as two columns of key-value pairs. Flatten
comment into one standard column/row format.
set col1 = list values
set data1 = list values
set col2 = list values
set data2 = list values
set columns = col1 + col2
set data = data1 + data2
set ... | def _parse_executive_summary(df):
# Exec summary is formatted oddly as two columns of key-value pairs. Flatten
# into one standard column/row format.
col1 = list(df[0].values)
data1 = list(df[1].values)
col2 = list(df[2].values)
data2 = list(df[3].values)
columns = col1 + col2
data = da... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
set __author__ = string Claus Haslauer (mail@planetwater.org)
set __version__ = string Revision: 0.1 $
set __date__ = string Date: 2014/01/05 $
set __copyright__ = string Copyright (c) 2014 Claus Haslauer
set __license__ = string CC BY-NC 3.0
import os
import s... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Claus Haslauer (mail@planetwater.org)"
__version__ = "Revision: 0.1 $"
__date__ = "Date: 2014/01/05 $"
__copyright__ = "Copyright (c) 2014 Claus Haslauer"
__license__ = "CC BY-NC 3.0"
import os
import sys
import requests
import datetime
import dropbox
import... | Python | zaydzuhri_stack_edu_python |
import tkinter as tk
class Root
begin
set _root = none
set _application = none
decorator staticmethod
function register_application application
begin
if not _application is none
begin
raise call RuntimeError string Only one Application is allowed.
end
set _application = application
end function
decorator staticmethod
f... | import tkinter as tk
class Root:
_root = None
_application = None
@staticmethod
def register_application(application):
if not (Root._application is None):
raise (RuntimeError("Only one Application is allowed."))
Root._application = application
@staticmethod
def un... | Python | zaydzuhri_stack_edu_python |
string # Project : Gamification Web # Author : Heping Zhao # Date created : 25/10/2019 # Description : Profile System
from bson import ObjectId
import pymongo
comment update from the sherk's file
comment connect to the pymongo
set client = call MongoClient string mongodb+srv://public:1234567890unsw@devdb-30fsv.mongodb.... | """
# Project : Gamification Web
# Author : Heping Zhao
# Date created : 25/10/2019
# Description : Profile System
"""
from bson import ObjectId
import pymongo
# update from the sherk's file
# connect to the pymongo
client = pymongo.MongoClient("mongodb+srv://public:1234567... | Python | zaydzuhri_stack_edu_python |
import argparse
function get_lines line
begin
set tuple chr_ pos id_ ref alt qlt filter_ info format_ = split line at slice 0 : 9 :
set individuals = split line at slice 9 : :
set tuple qlt filter_ info format_ = tuple string . string PASS string . string GT
for tuple i individual in enumerate individuals
begin
set ... | import argparse
def get_lines(line):
chr_, pos, id_, ref, alt, qlt, filter_, info, format_ = line.split()[0:9]
individuals = line.split()[9:]
qlt, filter_, info, format_ = '.', 'PASS', '.', 'GT'
for i, individual in enumerate(individuals):
individuals[i] = individual.split(':')[0]
ind_s... | Python | zaydzuhri_stack_edu_python |
function class_and_confidence sess model x y=none batch_size=none devices=none feed=none attack=none attack_params=none
begin
call _check_x x
set inputs = list x
if attack is not none
begin
append inputs y
call _check_y y
if shape at 0 != shape at 0
begin
raise call ValueError string Number of input examples and labels... | def class_and_confidence(sess, model, x, y=None, batch_size=None,
devices=None, feed=None, attack=None,
attack_params=None):
_check_x(x)
inputs = [x]
if attack is not None:
inputs.append(y)
_check_y(y)
if x.shape[0] != y.shape[0]:
raise ValueErr... | Python | nomic_cornstack_python_v1 |
string Python Crash Course - chapter 9 - Classes [Try it your self exercises]
comment 9.1
class Restaurant
begin
string example Restaurant Class in python using a generic details a bout Restaurants to build an example class
function __init__ self restaurant_name cuisine_type
begin
set restaurant_name = restaurant_name
... | '''
Python Crash Course - chapter 9 - Classes
[Try it your self exercises]
'''
# 9.1
class Restaurant:
'''
example Restaurant Class in python
using a generic details a bout Restaurants to build an example class
'''
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name... | Python | zaydzuhri_stack_edu_python |
function __delitem__ self key
begin
pop __cache key none
end function | def __delitem__(self, key):
self.__cache.pop(key, None) | Python | nomic_cornstack_python_v1 |
comment You can send any data types of parameter to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
comment E.g. if you send a List as a parameter, it will still be a List when it reaches the function:
function my_function food
begin
for x in food
be... | # You can send any data types of parameter to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
#
# E.g. if you send a List as a parameter, it will still be a List when it reaches the function:
def my_function(food):
for x in food:
print(x... | Python | zaydzuhri_stack_edu_python |
from swampy.Gui import *
from Tkinter import *
set g = call Gui
title g string Gui
class Canvas
begin
string
function __init__ self
begin
set canvas = call ca width=500 height=500
end function
end class
class MakeWindow
begin
string
function setup self
begin
set canvas = call ca width=500 height=500 bg=string white
e... | from swampy.Gui import *
from Tkinter import *
g = Gui()
g.title('Gui')
class Canvas():
""" """
def __init__(self):
canvas = g.ca(width = 500, height = 500)
class MakeWindow():
""" """
def setup(self):
self.canvas = g.ca(width = 500, height = 500, bg = 'white')
def add_button(self, text, the_command = No... | Python | zaydzuhri_stack_edu_python |
function write_note_text items outfile
begin
comment Write items without list formatting
for i in items
begin
write outfile i
end
end function | def write_note_text( items, outfile ):
## Write items without list formatting
for i in items:
outfile.write( i ) | Python | nomic_cornstack_python_v1 |
import torch
set device = if expression call is_available then string cuda else string cpu
set my_tensor = tensor list list 1 2 3 list 4 5 6 dtype=float32 device=device requires_grad=true
print my_tensor
print dtype
print device
print shape
print requires_grad
comment Other common initialisation methods
set x = call em... | import torch
device = "cuda" if torch.cuda.is_available() else "cpu"
my_tensor = torch.tensor([[1,2,3],[4,5,6]],dtype=torch.float32,
device = device, requires_grad=True)
print(my_tensor)
print(my_tensor.dtype)
print(my_tensor.device)
print(my_tensor.shape)
print(my_tensor.requires_grad)
# O... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment prog1, 2018.2, UFCG
comment Tayse Maia
comment Dias Unixtime
set segundos = integer call raw_input
set dias = segundos // 86400.0 | # coding: utf-8
# prog1, 2018.2, UFCG
# Tayse Maia
# Dias Unixtime
segundos = int(raw_input())
dias = segundos // 86400.0
| Python | zaydzuhri_stack_edu_python |
import torch
import numpy as np
class NPairLoss extends Module
begin
function __init__ self device batch_size temperature use_cosine_similarity=true
begin
call __init__
set batch_size = batch_size
set temperature = temperature
set device = device
set mask_samples_from_same_repr = call _get_correlated_mask
set similarit... | import torch
import numpy as np
class NPairLoss(torch.nn.Module):
def __init__(self, device, batch_size, temperature, use_cosine_similarity=True):
super(NPairLoss, self).__init__()
self.batch_size = batch_size
self.temperature = temperature
self.device = device
self.mask_s... | Python | zaydzuhri_stack_edu_python |
comment 判断相同的键并输出
for obj in dic1
begin
if obj in dic2
begin
print obj
end
end | for obj in dic1: #判断相同的键并输出
if obj in dic2:
print(obj) | Python | zaydzuhri_stack_edu_python |
comment Defining the function
function Sum arr
begin
comment base condition
if length arr == 1
begin
return arr at 0
end
else
begin
return arr at 0 + sum arr at slice 1 : :
end
end function
set arr = list
comment input values to list
set arr = list 12 4 23 2 5
comment calculating length of array
set N = length arr
se... | # Defining the function
def Sum(arr):
if len(arr)== 1: #base condition
return arr[0]
else:
return arr[0]+ Sum(arr[1:])
arr =[]
# input values to list
arr = [12, 4, 23, 2, 5]
# calculating length of array
N = len(arr)
ans = Sum(arr,N)
print (ans)
| Python | zaydzuhri_stack_edu_python |
import math
for ti in range integer input
begin
set sss = input
set n = length sss - 1
set lp = list comprehension 0 for _ in range n + 1
set rp = list comprehension 0 for _ in range n + 1
set lo = list comprehension 0 for _ in range n + 1
set ro = list comprehension 0 for _ in range n + 1
for i in range n + 1
begin
se... | import math
for ti in range(int(input())):
sss = input()
n= len(sss)-1
lp = [0 for _ in range(n + 1)]
rp = [0 for _ in range(n + 1)]
lo = [0 for _ in range(n + 1)]
ro = [0 for _ in range(n + 1)]
for i in range(n+1):
sl = sss[i]
sr = sss[n-i]
if sl == '(':
... | Python | zaydzuhri_stack_edu_python |
function before_saving_basic_auth sender instance **kwargs
begin
set synchronized = false
update filter id=id synchronized=true synchronized=false
end function | def before_saving_basic_auth(sender, instance, **kwargs):
instance.synchronized = False
ConsumerReference.objects.filter(id=instance.consumer.id, synchronized=True).update(synchronized=False) | Python | nomic_cornstack_python_v1 |
import os , glob , json , requests
function get_data_from_api
begin
for x in range 500 550
begin
set response = get requests string https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/random?limitLicense=false&number=100 headers=dict string X-Mashape-Key string 62t27Bg1q7mshtmPnpbNVMOAVw9Tp1PkKrqjsnebv8P... | import os, glob, json, requests
def get_data_from_api():
for x in range(500,550):
response = requests.get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/random?limitLicense=false&number=100",
headers={
"X-Mashape-Key": "62t27Bg1q7mshtmPnpbNVMOAVw9Tp1PkKrqjsnebv8Ph00q2x3",
"Accept": "... | Python | zaydzuhri_stack_edu_python |
function set_spot_fleet_request_capacity sfr_id capacity dry_run region=none
begin
set ec2_client = call client string ec2 region_name=region
with call Timeout seconds=AWS_SPOT_MODIFY_TIMEOUT
begin
try
begin
set state = none
while true
begin
set state = call get_sfr sfr_id region=region at string SpotFleetRequestState
... | def set_spot_fleet_request_capacity(sfr_id, capacity, dry_run, region=None):
ec2_client = boto3.client('ec2', region_name=region)
with Timeout(seconds=AWS_SPOT_MODIFY_TIMEOUT):
try:
state = None
while True:
state = get_sfr(sfr_id, region=region)['SpotFleetRequestS... | Python | nomic_cornstack_python_v1 |
function id2doc self ids
begin
return list comprehension call id_to_token idx for idx in ids
end function | def id2doc(self, ids):
return [self.id_to_token(idx) for idx in ids] | Python | nomic_cornstack_python_v1 |
if __name__ == string __main__
begin
set n = integer call raw_input
if n % 2 == 0 and 2 <= n <= 5
begin
print string Not Weird
end
else
if n % 2 == 0 and 6 <= n <= 20
begin
print string Weird
end
else
if n % 2 == 0 and n > 20
begin
print string Not Weird
end
else
begin
print string Weird
end
end | if __name__ == '__main__':
n = int(raw_input())
if n%2 == 0 and (2<=n<=5):
print("Not Weird")
elif n%2 == 0 and (6<=n<=20):
print("Weird")
elif n%2 == 0 and n>20:
print("Not Weird")
else:
print("Weird") | Python | zaydzuhri_stack_edu_python |
string 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。 传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。 示例 1: 输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5 输出:15 解释: 船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示: 第 1 天:1, 2, 3, 4, 5 第 2 天:6, 7 第 3 天:8 第 4 天:9 第 5 天:10 请注意,货物必须按照给定的顺序装运,因此使用载重能力为 1... | '''
传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
示例 1:
输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
输出:15
解释:
船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
第 1 天:1, 2, 3, 4, 5
第 2 天:6, 7
第 3 天:8
第 4 天:9
第 5 天:10
请注意,货物必须按照给定的顺序装运,因此使用载重... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python3
import math
import os
import random
import re
import sys
function separateNumbers s
begin
if length s == 1
begin
print string NO
return
end
for i in range 1 length s
begin
set mystack = list
append mystack s at slice : i :
while length join string mystack < length s
begin
append mystack string ... | #!/bin/python3
import math
import os
import random
import re
import sys
def separateNumbers(s):
if len(s) == 1:
print('NO')
return
for i in range(1, len(s)):
mystack = []
mystack.append(s[:i])
while len(''.join(mystack)) < len(s):
mystack.append(str(int(myst... | Python | zaydzuhri_stack_edu_python |
function _dens x y z=none normed=false xstep=1.0 ystep=1.0 sigx=4.0 sigy=4.0 order=0 extent=none interpolation=string nearest cmap=string Spectral
begin
set xbins = array range min max + xstep xstep
set ybins = array range min max + ystep ystep
if z is none
begin
set tuple H xedges yedges = call histogram2d x y bins=li... | def _dens(
x,
y,
z=None,
normed=False,
xstep=1.0,
ystep=1.0,
sigx=4.0,
sigy=4.0,
order=0,
extent=None,
interpolation="nearest",
cmap="Spectral",
):
xbins = np.arange(x.min(), x.max() + xstep, xstep)
ybins = np.arange(y.min(), y.max() + ystep, ystep)
if z is N... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sun Jun 10 18:06:22 2018 @author: DS00331004
import media
import fresh_tomatoes
set toy_story = call Movie string toy_story string a story of a boy and his toys which came to life string https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg string https://www.youtu... | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 10 18:06:22 2018
@author: DS00331004
"""
import media
import fresh_tomatoes
toy_story=media.Movie("toy_story","a story of a boy and his toys which came to life",
"https://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg",
... | Python | zaydzuhri_stack_edu_python |
function socket_read fp
begin
set response = string
set oldlen = 0
set newlen = 0
while true
begin
set response = response + read fp buffSize
set newlen = length response
if newlen - oldlen == 0
begin
break
end
else
begin
set oldlen = newlen
end
end
return response
end function | def socket_read(fp):
response = ''
oldlen = 0
newlen = 0
while True:
response += fp.read(buffSize)
newlen = len(response)
if newlen - oldlen == 0:
break
else:
oldlen = newlen
return response | Python | nomic_cornstack_python_v1 |
from tkinter import *
from random import randint
set sayings = list tuple string Du siehst heute gut aus string You look great tuple string Kopf hoch! string Cheer up tuple string Du schaffst das! string You will make it
function pick
begin
set nr = random integer 0 length sayings - 1
set t = sayings at nr
call config ... | from tkinter import *
from random import randint
sayings = [("Du siehst heute gut aus", "You look great"),
("Kopf hoch!", "Cheer up"),
("Du schaffst das!","You will make it")]
def pick():
nr = randint(0, len(sayings)-1)
t = sayings[nr]
label.config(text = t[language.get()])
window =... | Python | zaydzuhri_stack_edu_python |
comment import necessities
from socket import *
import time
comment set start time
set startTime = time
if __name__ == string __main__
begin
comment create an input prompt
set target = input string Enter the host to be scanned:
set t_IP = call gethostbyname target
comment print the response
print string Starting scan o... | #import necessities
from socket import *
import time
#set start time
startTime = time.time()
if __name__ == '__main__':
#create an input prompt
target = input('Enter the host to be scanned: ')
t_IP = gethostbyname(target)
#print the response
print('Starting scan on host: ', t_IP)
#set t... | Python | zaydzuhri_stack_edu_python |
function test_run
begin
for symbol in list string AAPL string IBM
begin
print string Max close
print symbol call get_max_close symbol
end
end function | def test_run():
for symbol in ['AAPL', 'IBM']:
print("Max close")
print(symbol, get_max_close(symbol)) | Python | nomic_cornstack_python_v1 |
from numpy import *
set arr1 = array list 1 2 3 4 5
print cos arr1 | from numpy import *
arr1=array([1,2,3,4,5])
print(cos(arr1)) | Python | zaydzuhri_stack_edu_python |
class CursoBase extends object
begin
function __init__ self nome cidade local data freq preco
begin
string Inicia os parâmetros necessários
set nome = nome
set cidade = cidade
set local = local
set data = data
set freq = freq
set preco = preco
end function
function __str__ self
begin
string Define como será impressa es... | class CursoBase(object):
def __init__(self, nome, cidade, local, data, freq, preco):
"""
Inicia os parâmetros necessários
"""
self.nome = nome
self.cidade = cidade
self.local = local
self.data = data
self.freq = freq
self.preco = preco
... | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
class MyModule extends Module
begin
function __init__ self
begin
call __init__
set linears = call ModuleList list comprehension linear 10 10 for i in range 10
end function
function forward self x
begin
comment ModuleList can act as an iterable, or be indexed using ints
for tuple i l i... | import torch
import torch.nn as nn
class MyModule(nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])
def forward(self, x):
# ModuleList can act as an iterable, or be indexed using ints
for i, l in... | Python | zaydzuhri_stack_edu_python |
import os
import os.path
from import settings
function is_file filename
begin
set path = join path SHARING_DIRECTORY filename
return is file path path
end function
function is_directory filename
begin
set path = join path SHARING_DIRECTORY filename
return is directory path path
end function
function get_directory_cont... | import os
import os.path
from . import settings
def is_file(filename):
path = os.path.join(settings.SHARING_DIRECTORY,filename)
return os.path.isfile(path)
def is_directory(filename):
path = os.path.join(settings.SHARING_DIRECTORY,filename)
return os.path.isdir(path)
def get_directory_contents(directory):
conte... | Python | zaydzuhri_stack_edu_python |
string audio book by Mr_Mystery do subscribe my yt channel link in readme file
comment importing the modules
import pyttsx3 as py
import PyPDF2
comment initilizing the speak engine
set en = call init
set vo = call getProperty string voices
call setProperty string voice id
call setProperty string rate 175
comment creati... | ''' audio book by
Mr_Mystery
do subscribe my yt channel link in readme file
'''
import pyttsx3 as py #importing the modules
import PyPDF2
#initilizing the speak engine
en = py.init()
vo = en.getProperty('voices')
en.setProperty('voice',vo[1].id)
en.... | Python | zaydzuhri_stack_edu_python |
function update_from_file self
begin
set config_path = get environ string MINDINSIGHT_CONFIG string
if not config_path
begin
return
end
set config_module = none
comment python:full.path.for.config.module
if starts with config_path string python:
begin
set config_module = call import_module config_path at slice length s... | def update_from_file(self):
config_path = os.environ.get('MINDINSIGHT_CONFIG', '')
if not config_path:
return
config_module = None
# python:full.path.for.config.module
if config_path.startswith('python:'):
config_module = import_module(config_path[len('p... | Python | nomic_cornstack_python_v1 |
from Genetic_Algorithm_Diophantine import GeneticAlgorithmDiophantine
from random import random
function main
begin
set f = call file string results.txt string rw+
set very_very_simple_equation = list 1 2 3
set result = 30
set initial_population = list comprehension list comprehension integer random * result * 2 - resu... | from Genetic_Algorithm_Diophantine import GeneticAlgorithmDiophantine
from random import random
def main():
f = file("results.txt", "rw+")
very_very_simple_equation = [1, 2, 3]
result = 30
initial_population = [
[int(random() * result * 2 - result) for _ in range(len(very_very_simple_equation... | Python | zaydzuhri_stack_edu_python |
import collections
class MovingAverage extends object
begin
function __init__ self size
begin
set window = deque list
set total = 0
set size = size
end function
function next self val
begin
if length window == size
begin
set total = total - call popleft
end
append window val
set total = total + val
return total / decim... | import collections
class MovingAverage(object):
def __init__(self, size):
self.window = collections.deque([])
self.total = 0
self.size = size
def next(self, val):
if len(self.window) == self.size:
self.total -= self.window.popleft()
self.window.append(val)
... | Python | zaydzuhri_stack_edu_python |
import serial
import redis
import time
set KEY_LIGHT = string list_light
set KEY_SMOKE = string list_smoke
set KEY_SMOKE_THRESHOLD = string key_smoke_threshold
set KEY_TEMPERATURE = string list_temperature
set KEY_TASKS = string list_tasks
set r = call StrictRedis host=string 127.0.0.1 port=6379 db=0
function data_proc... | import serial
import redis
import time
KEY_LIGHT = "list_light"
KEY_SMOKE = "list_smoke"
KEY_SMOKE_THRESHOLD = "key_smoke_threshold"
KEY_TEMPERATURE = "list_temperature"
KEY_TASKS = "list_tasks"
r = redis.StrictRedis(host='127.0.0.1', port=6379, db=0)
def data_process(data_str: str):
data_list = d... | Python | zaydzuhri_stack_edu_python |
function getEligibleTestBoxes self
begin
comment Taking the simple way out now, getting all active testboxes at the
comment time without filtering out on sample sources.
comment 1. Collect the relevant testbox generation IDs.
execute _oDb string SELECT DISTINCT idTestBox, idGenTestBox FROM TestSets WHERE + call _getEli... | def getEligibleTestBoxes(self):
# Taking the simple way out now, getting all active testboxes at the
# time without filtering out on sample sources.
# 1. Collect the relevant testbox generation IDs.
self._oDb.execute('SELECT DISTINCT idTestBox, idGenTestBox\n'
... | Python | nomic_cornstack_python_v1 |
function source_tags self
begin
return get pulumi self string source_tags
end function | def source_tags(self) -> Optional[Sequence[str]]:
return pulumi.get(self, "source_tags") | Python | nomic_cornstack_python_v1 |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other):
return not self == other | Python | nomic_cornstack_python_v1 |
function equations_of_motion self state_vector external_input_vector time
begin
comment Convert network state array into states per system
set state_per_system = call __as_state_per_system state_vector
comment Output for each system, given current state
set output_per_system = call __output_per_system state_per_system ... | def equations_of_motion(self, state_vector, external_input_vector, time):
# Convert network state array into states per system
state_per_system = self.__as_state_per_system(state_vector)
# Output for each system, given current state
output_per_system = self.__output_per_system(state_per_... | Python | nomic_cornstack_python_v1 |
import math
import random
comment Datas about belgian towns
class Towns
begin
set ville = dict
set ville at string antwerp = dict
set ville at string antwerp at string lat = 51.2604803
set ville at string antwerp at string lng = 4.0890894
set ville at string antwerp at string pop = 506922
set ville at string antwerp ... | import math
import random
#Datas about belgian towns
class Towns:
ville = {}
ville['antwerp'] = {}
ville['antwerp']['lat'] = 51.2604803
ville['antwerp']['lng'] = 4.0890894
ville['antwerp']['pop'] = 506922
ville['antwerp']['superficie'] = 204.51
ville['gent'] = {}
ville['gent']['lat'] ... | Python | zaydzuhri_stack_edu_python |
function get_storages self storage_type=string normal
begin
string Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template, favorite
set res = call get_request string /storage/ + storage_type
return call _create_storage_objs res at string storages cloud_manager=sel... | def get_storages(self, storage_type='normal'):
"""
Return a list of Storage objects from the API.
Storage types: public, private, normal, backup, cdrom, template, favorite
"""
res = self.get_request('/storage/' + storage_type)
return Storage._create_storage_objs(res['sto... | Python | jtatman_500k |
async function async_turn_off self
begin
set path = data_switch_path
set param = string .id
set value = none
for uid in data at string queue
begin
if data at string queue at uid at string name == string { _data at string name }
begin
set value = data at string queue at uid at string .id
end
end
set mod_param = data_swi... | async def async_turn_off(self) -> None:
path = self.entity_description.data_switch_path
param = ".id"
value = None
for uid in self._ctrl.data["queue"]:
if self._ctrl.data["queue"][uid]["name"] == f"{self._data['name']}":
value = self._ctrl.data["queue"][uid]["... | Python | nomic_cornstack_python_v1 |
function is_number s
begin
try
begin
decimal s
return true
end
except ValueError
begin
return false
end
end function | def is_number(s):
try:
float(s)
return True
except ValueError:
return False
| Python | flytech_python_25k |
function check_occ seats i j
begin
set occupied_count = seats at i - 1 at j == string # + seats at i - 1 at j - 1 == string # + seats at i - 1 at j + 1 == string # + seats at i + 1 at j == string # + seats at i + 1 at j - 1 == string # + seats at i + 1 at j + 1 == string # + seats at i at j - 1 == string # + seats at i... | def check_occ(seats:List[str], i: int, j: int) -> bool:
occupied_count = (seats[i - 1][j] == "#") +\
(seats[i - 1][j - 1] == "#") +\
(seats[i - 1][j + 1] == "#") +\
(seats[i + 1][j] == "#") +\
(seats[i + 1][j - 1] == "#") +\
(seats[i + 1][j + 1] == "#") +\
(seats[... | Python | nomic_cornstack_python_v1 |
function initializeActorTrace self
begin
set z_theta = dict
with no grad
begin
for p in parameters NN_pi
begin
set z_theta at p = to zeros size=size data device
end
end
return z_theta
end function | def initializeActorTrace(self):
z_theta = {}
with torch.no_grad():
for p in self.NN_pi.parameters():
z_theta[p] = torch.zeros(size=p.data.size()).to(device)
return z_theta | Python | nomic_cornstack_python_v1 |
comment aulas de desvio condicional if e else
set idade = integer input string Qual a sua idade?
if __name__ == string __main__
begin
if idade >= 18
begin
print string Você é de maior!
end
else
begin
print string Você é de menor!
end
end | # aulas de desvio condicional if e else
idade = int(input("Qual a sua idade? "))
if(__name__ == '__main__'):
if(idade >= 18):
print("Você é de maior!")
else:
print("Você é de menor!")
| Python | zaydzuhri_stack_edu_python |
function test_nondatetime_fails self
begin
from extractor.sharder import _generate_shard_ranges
assert raises NotImplementedError _generate_shard_ranges 1 string int tuple 1 5
end function | def test_nondatetime_fails(self):
from extractor.sharder import _generate_shard_ranges
self.assertRaises(
NotImplementedError,
_generate_shard_ranges, 1, 'int', (1, 5)) | Python | nomic_cornstack_python_v1 |
function get_value self device oid
begin
set message = string get %s %s % tuple device oid
call send message
set data = call recv BUFFER_SIZE
set data = split data string
return data at 1
end function | def get_value(self, device, oid):
message = 'get %s %s \n' % (device, oid)
self.sock.send(message)
data = self.sock.recv(BUFFER_SIZE)
data = data.split(' ')
return data[1] | Python | nomic_cornstack_python_v1 |
function alter_table self cursor mytb operation attrib
begin
if operation is string add
begin
set sql_add = string ALTER TABLE + mytb
set new_attrib = string ADD COLUMN + attrib + string VARCHAR(255)
set sql = sql_add + new_attrib
try
begin
execute cursor sql
print format string Table {} altered successfully. mytb
retu... | def alter_table(self, cursor, mytb, operation, attrib):
if operation is 'add':
sql_add = " ALTER TABLE " + mytb
new_attrib = " ADD COLUMN " + attrib + " VARCHAR(255)"
sql = sql_add + new_attrib
try:
cursor.execute(sql)
prin... | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
import wx
import os
import sys
try
begin
from agw import customtreectrl as CT
end
comment if it's not there locally, try the wxPython lib.
except ImportError
begin
import wx.lib.agw.customtreectrl as CT
end
class CustomTreeCtrl extends CustomTreeCtrl
begin
function __init__ self parent id=ID_ANY po... | #coding:utf-8
import wx
import os
import sys
try:
from agw import customtreectrl as CT
except ImportError: # if it's not there locally, try the wxPython lib.
import wx.lib.agw.customtreectrl as CT
class CustomTreeCtrl(CT.CustomTreeCtrl):
def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,... | Python | zaydzuhri_stack_edu_python |
function _crawl_user_tweets self userid
begin
try
begin
comment fetch recent 200 english tweets
set tweets = call user_timeline user_id=userid count=200 tweet_mode=string extended lang=string en
set tweets = list comprehension call preprocess full_text for x in tweets
end
comment tweets.sort(key=len, reverse=True)
comm... | def _crawl_user_tweets(self, userid):
try:
tweets = self.api_queue[0].api.user_timeline(user_id=userid, count=200, tweet_mode="extended", lang="en") # fetch recent 200 english tweets
tweets = [preprocess(x.full_text) for x in tweets]
# tweets.sort(key=len, reverse=True)
... | Python | nomic_cornstack_python_v1 |
comment 练习:
comment 实现有序集合类 OrderSet() 能实现两个集合的交集 &,全集 |,
comment 补集 - 对称补集 ^, ==/!= , in/ not in 等操作
comment 要求集合内部用 list 存储
comment class OrderSet:
comment ...
comment s1 = OrderSet([1, 2, 3, 4])
comment s2 = OrderSet([3, 4, 5])
comment print(s1 & s2) # OrderSet([3, 4])
comment print(s1 | s2) # OrderSet([1, 2, 3, 4, ... | # 练习:
# 实现有序集合类 OrderSet() 能实现两个集合的交集 &,全集 |,
# 补集 - 对称补集 ^, ==/!= , in/ not in 等操作
# 要求集合内部用 list 存储
# class OrderSet:
# ...
# s1 = OrderSet([1, 2, 3, 4])
# s2 = OrderSet([3, 4, 5])
# print(s1 & s2) # OrderSet([3, 4])
# print(s1 | s2) # OrderSet([1, 2, 3, 4, 5])
# print(s1 ^ s2) # OrderSet(... | Python | zaydzuhri_stack_edu_python |
function next_sample self
begin
if call n_remaining_samples < 1
begin
set sample_idx = 0
end
else
begin
set sample_idx = sample_idx + 1
end
return tuple X at tuple slice sample_idx - 1 : sample_idx : slice : : flatten y at slice sample_idx - 1 : sample_idx :
end function | def next_sample(self):
if self.n_remaining_samples() < 1:
self.sample_idx = 0
else:
self.sample_idx += 1
return self.X[self.sample_idx - 1:self.sample_idx, :], self.y[self.sample_idx - 1:self.sample_idx].flatten() | Python | nomic_cornstack_python_v1 |
function _wait_until predicate timeout_in_seconds *args **kwargs
begin
comment Invoke the method once first before starting any countdown, to guarantee that we can call the method at
comment least twice before timing out with an error.
comment (Handle cases in which the duration to execute the given predicate is longer... | def _wait_until(predicate: Callable, timeout_in_seconds: int, *args, **kwargs):
# Invoke the method once first before starting any countdown, to guarantee that we can call the method at
# least twice before timing out with an error.
# (Handle cases in which the duration to execute the given pre... | Python | nomic_cornstack_python_v1 |
import datetime
import hashlib
class Block
begin
function __init__ self previous_block_hash data timestamp
begin
set previous_block_hash = previous_block_hash
set data = data
set timestamp = timestamp
set hash = call get_hash
end function
decorator staticmethod
function create_genesis_block
begin
return call Block stri... | import datetime
import hashlib
class Block:
def __init__(self, previous_block_hash, data, timestamp):
self.previous_block_hash = previous_block_hash
self.data = data
self.timestamp = timestamp
self.hash = self.get_hash()
@staticmethod
def create_genesis_block():
ret... | Python | zaydzuhri_stack_edu_python |
function plot_curve_3D self length=30 fps=30 **kwargs
begin
set fig = call get_figure scale=3
set ax = call add_subplot 111 projection=string 3d
set tuple curve_x curve_y curve_z = call curve
set control_points_x = array list comprehension control_point at 0 for control_point in control_points
set control_points_y = ar... | def plot_curve_3D(self, length = 30, fps = 30, **kwargs):
fig = utils.get_figure(scale = 3)
ax = fig.add_subplot(111, projection = '3d')
curve_x, curve_y, curve_z = self.curve()
control_points_x = np.array([control_point[0] for control_point in self.control_points])
control_poi... | Python | nomic_cornstack_python_v1 |
function allowsMove self c
begin
if c < 0 or c > length data at 0 - 1 or data at 0 at c != string
begin
return false
end
else
begin
return true
end
end function | def allowsMove(self, c):
if c < 0 or c > len(self.data[0]) - 1 or self.data[0][c] != ' ':
return False
else:
return True | Python | nomic_cornstack_python_v1 |
function direction_flag value_1 value_2 *debug_flag
begin
set _direction = 0
if value_2 > value_1
begin
set _direction = string string up
end
else
begin
set _direction = string string down
end
return _direction
end function | def direction_flag(value_1, value_2, *debug_flag):
_direction = 0
if value_2 > value_1:
_direction = str("up")
else:
_direction = str("down")
return _direction | Python | nomic_cornstack_python_v1 |
import pickle
set shops = dict string Zabka string https://raw.githubusercontent.com/DominikWasiolka/picturesForHackathon/master/zabka/logo.png ; string Biedronka string https://raw.githubusercontent.com/DominikWasiolka/picturesForHackathon/master/biedronka/logo.png ; string Empik string https://raw.githubusercontent.c... | import pickle
shops = {"Zabka": "https://raw.githubusercontent.com/DominikWasiolka/picturesForHackathon/master/zabka/logo.png",
"Biedronka": "https://raw.githubusercontent.com/DominikWasiolka/picturesForHackathon/master/biedronka/logo.png",
"Empik": "https://raw.githubusercontent.com/DominikWasiolka... | Python | zaydzuhri_stack_edu_python |
function separate_overlay_files_training_validation_test_set overlayFiles kFoldIndicesPath
begin
set kFoldIndicesStructure = call loadmat kFoldIndicesPath
set kFoldIndices = kFoldIndicesStructure at string kfoldIndices
set trainSetNames = list
set validationSetNames = list
set testSetNames = list
set i = 0
while i <... | def separate_overlay_files_training_validation_test_set(overlayFiles, kFoldIndicesPath):
kFoldIndicesStructure = scipy.io.loadmat(kFoldIndicesPath)
kFoldIndices = kFoldIndicesStructure["kfoldIndices"]
trainSetNames = []
validationSetNames = []
testSetNames = []
i = 0
whil... | Python | nomic_cornstack_python_v1 |
function _query_create_schema cls if_not_exists=true
begin
set builder = list string CREATE SCHEMA
if if_not_exists
begin
append builder string IF NOT EXISTS
end
comment type: ignore
append builder schema
return join string builder
end function | def _query_create_schema(cls, if_not_exists: bool = True) -> str:
builder = ['CREATE SCHEMA']
if if_not_exists:
builder.append('IF NOT EXISTS')
builder.append(cls.schema) # type: ignore
return ' '.join(builder) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding=utf-8
comment Author: Archer
comment File: PrepareJsonTags44S.py
comment Desc: 4s店的标签对照表有700行,不能手动整理,必须自动整理出json格式的层级关系
comment Date: 06/Feb/2017
import sys
import json
import pprint
set pp = call PrettyPrinter indent=2
comment 载入原始的4s的标签对照表
set OriginalData = list
with open... | #!/usr/bin/env python
# coding=utf-8
#
# Author: Archer
# File: PrepareJsonTags44S.py
# Desc: 4s店的标签对照表有700行,不能手动整理,必须自动整理出json格式的层级关系
# Date: 06/Feb/2017
import sys
import json
import pprint
pp = pprint.PrettyPrinter(indent=2)
# 载入原始的4s的标签对照表
OriginalData = []
with open('../data/original4s.txt') as F:
for line i... | Python | zaydzuhri_stack_edu_python |
try
begin
set aantal = integer input string Hoeveel mensen gaan er mee ?
set prijs_pp = hotel_prijs / aantal
if aantal < 0
begin
print string Negative invoer is niet toegestaan
end
else
begin
print format string De prijs per pesoon is {} euro prijs_pp
end
end
except ZeroDivisionError
begin
print string Delen door nul k... | try:
aantal = int(input('Hoeveel mensen gaan er mee ?'))
prijs_pp = hotel_prijs / aantal
if aantal < 0:
print('Negative invoer is niet toegestaan')
else:
print('De prijs per pesoon is {} euro'.format(prijs_pp))
except ZeroDivisionError:
print('Delen door nul kan niet')
except Value... | Python | zaydzuhri_stack_edu_python |
function _beautify_stacks source
begin
set results : list at Mapping at tuple str Any = list
for host_stacks in source
begin
set host_id = string { host_stacks at string hostname } / { host_stacks at string pid }
for tuple thread frames in items host_stacks at string threads
begin
set full_id = host_id + string / + th... | def _beautify_stacks(source: list[Mapping[str, Any]]) -> list[Mapping[str, Any]]:
results: list[Mapping[str, Any]] = []
for host_stacks in source:
host_id = f"{host_stacks['hostname']}/{host_stacks['pid']:d}"
for thread, frames in host_stacks["threads"].items():
full_id = host_id + "... | Python | nomic_cornstack_python_v1 |
import math
function calcula_euler x n
begin
set soma = 0
set i = 0
while i < n
begin
set soma = soma + x ^ i / call factorial i
set i = i + 1
end
return soma
end function | import math
def calcula_euler(x,n):
soma= 0
i= 0
while i < n:
soma= soma + (x**i)/math.factorial(i)
i= i + 1
return soma | Python | zaydzuhri_stack_edu_python |
function test_only_three_card_petitions self
begin
set f = check_petition_combos
assert true f dist 0 0 list 0 false true
assert false f dist 1 0 list 0 false true
assert true f dist 1 1 list 0 false true
assert true f dist 1 0 list 3 false true
assert true f dist 1 3 list 0 false true
assert false f dist 1 1 list 2 fa... | def test_only_three_card_petitions(self):
f = gtrutils.check_petition_combos
self.assertTrue( f( 0, 0, [0], False, True))
self.assertFalse( f( 1, 0, [0], False, True))
self.assertTrue( f( 1, 1, [0], False, True))
self.assertTrue( f( 1, 0, [3], False, True))
self.asse... | Python | nomic_cornstack_python_v1 |
function dguild self
begin
return call get_guild id
end function | def dguild(self):
return bot.get_guild(self.id) | Python | nomic_cornstack_python_v1 |
from handleInput import loadData
from matplotlib.patches import Polygon , Circle
import matplotlib.pyplot as plt
import numpy as np
from RayAlg import pointinpolygon
set tuple Points Polygons = call loadData string testData.txt
set colors = list string green string red string cyan string magenta string yellow string k ... | from handleInput import loadData
from matplotlib.patches import Polygon, Circle
import matplotlib.pyplot as plt
import numpy as np
from RayAlg import pointinpolygon
Points, Polygons=loadData("testData.txt")
colors = ['green', 'red', 'cyan', 'magenta', 'yellow', 'k', 'w']
punktyID=[]
#Prezentacja metody
fig, ax = ... | Python | zaydzuhri_stack_edu_python |
function mergeKLists lists
begin
function merge l1 l2
begin
string Merges 2 sorted linked lists. :param l1: The head of the first list. :param l2: The head of the second list. :return: The head of the merged linked list.
comment Edge cases, where nothing is to be done.
if l1 is none and l2 is none
begin
return l1
end
i... | def mergeKLists(lists: [ListNode]) -> ListNode:
def merge(l1, l2):
"""
Merges 2 sorted linked lists.
:param l1: The head of the first list.
:param l2: The head of the second list.
:return: The head of the merged linked list.
"""
# Edge cases, where nothing is... | Python | nomic_cornstack_python_v1 |
function predict self X_test
begin
if alpha is none
begin
call learn
end
set X0 = X_test
set X = X
set Y = Y * 2 - 1
set Kmn = call compute X0 X
set ret = dot Kmn alpha * Y + w0
return ret
end function | def predict(self, X_test):
if self.alpha is None: self.learn()
X0 = X_test
X = self.X
Y = self.Y * 2 - 1
Kmn = self.kernel.compute(X0, X)
ret = np.dot(Kmn, self.alpha * Y) + self.w0
return ret | Python | nomic_cornstack_python_v1 |
import requests
import pandas as pd
from bs4 import BeautifulSoup
import openpyxl
from datetime import datetime
comment 크롤링 할 페이지
set req = get requests string https://finance.naver.com/sise/sise_market_sum.nhn?&page=1
comment HTML 코드 저장
set html = text
comment BeautifulSoup으로 html소스를 python 객체로 변환
comment 첫 인자 : html소... | import requests
import pandas as pd
from bs4 import BeautifulSoup
import openpyxl
from datetime import datetime
## 크롤링 할 페이지
req = requests.get('https://finance.naver.com/sise/sise_market_sum.nhn?&page=1')
## HTML 코드 저장
html = req.text
## BeautifulSoup으로 html소스를 python 객체로 변환
## 첫 인자 : html소스코드
## 두 번째 인자 : parser 종... | Python | zaydzuhri_stack_edu_python |
function varr self
begin
if not has attribute self string _varr
begin
for item in hdulist
begin
if name == string PRIMARY
begin
continue
end
break
end
for tuple i col in enumerate columns
begin
if name == string VHELIO
begin
set _varr = data at 0 at i
break
end
end
end
return _varr
end function | def varr(self):
if not hasattr(self, '_varr'):
for item in self.hdulist:
if item.name == 'PRIMARY':
continue
break
for i, col in enumerate(item.columns):
if col.name == 'VHELIO':
... | Python | nomic_cornstack_python_v1 |
function interpolateValues source points pointSRS=string latlon mode=string near func=none winRange=none **kwargs
begin
comment Determine what the user probably wants as an output
if is instance points tuple or is instance points Geometry or is instance points Location
begin
set asSingle = true
comment make points a li... | def interpolateValues(source, points, pointSRS='latlon', mode='near', func=None, winRange=None, **kwargs):
# Determine what the user probably wants as an output
if isinstance(points, tuple) or isinstance(points, ogr.Geometry) or isinstance(points, Location):
asSingle = True
# make points a list ... | Python | nomic_cornstack_python_v1 |
function __init__ self username password bot channel
begin
call __init__ username password
set queue = deque
set ingame_cog = call Ingame bot
set bot = bot
set channel = channel
set chat_breakout = false
set loop = call get_event_loop
set is_pycraft_instance = true
end function | def __init__(self, username, password, bot, channel):
super().__init__(username, password)
self.queue = deque()
self.ingame_cog = Ingame(bot)
self.bot = bot
self.channel = channel
self.chat_breakout = False
self.loop = asyncio.get_event_loop()
self.ingam... | Python | nomic_cornstack_python_v1 |
import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
call rc string text usetex=true
call rc string font family=string serif size=15
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confu... | import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sn
plt.rc('text', usetex=True)
plt.rc('font', family='serif',size = 15)
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import c... | Python | zaydzuhri_stack_edu_python |
set square = lambda nums -> list comprehension x * x for x in nums
set squares = call square list 1 2 3
print squares | square = lambda nums: [x*x for x in nums]
squares = square([1,2,3])
print(squares) | Python | jtatman_500k |
function getAliasAttr self force
begin
pass
end function | def getAliasAttr(self, force):
pass | Python | nomic_cornstack_python_v1 |
string Assigment No:302 - Happy Numbers Name: Umaima Khurshid Ahmad Youtube Link: https://youtu.be/KvkPKblvAHM Date: 04/21/2020 I have not given or received any unauthorized assistance on this assignment Reference: https://www.youtube.com/watch?v=Mr215Wb9ks8 19 is a happy prime 83 101 is a sad prime 4 is a sad non prim... | '''Assigment No:302 - Happy Numbers
Name: Umaima Khurshid Ahmad
Youtube Link: https://youtu.be/KvkPKblvAHM
Date: 04/21/2020
I have not given or received any unauthorized assistance on this assignment
Reference: https://www.youtube.com/watch?v=Mr215Wb9ks8
19 is a happy prime
83 101 is a sad prime
4 is a sad ... | Python | zaydzuhri_stack_edu_python |
function update_position self new_pos
begin
if extend == false
begin
del positions at - 1
end
insert positions 0 new_pos
if extend == true
begin
set extend = false
end
end function | def update_position(self, new_pos):
if self.extend == False:
del self.positions[-1]
self.positions.insert(0, new_pos)
if self.extend == True:
self.extend = False | Python | nomic_cornstack_python_v1 |
string 500 Keyboard Row Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. American keyboard Example 1: Input: ["Hello", "Alaska", "Dad", "Peace"] Output: ["Alaska", "Dad"] Note: You may use one character in the keyboard more ... | """
500 Keyboard Row
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
American keyboard
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
You may use one character in the... | Python | zaydzuhri_stack_edu_python |
function test_producer_superclass_raises self
begin
with assert raises NotImplementedError
begin
call produce alert
end
end function | def test_producer_superclass_raises(self):
with self.assertRaises(NotImplementedError):
super(EmailProducer, self.producer).produce(self.alert) | Python | nomic_cornstack_python_v1 |
function __call__ self func_base
begin
function wrapper *args **kwargs
begin
set instance = args at 0
if client is none
begin
call connect
end
return call func_base *args keyword kwargs
end function
return wrapper
end function | def __call__(self, func_base):
def wrapper(*args, **kwargs):
instance = args[0]
if instance.client is None:
instance.connect()
return func_base(*args, **kwargs)
return wrapper | Python | nomic_cornstack_python_v1 |
function initialize_model self
begin
if not A
begin
set A = call uniform_random_initialization nr_states nr_states
end
if not B
begin
set B = call uniform_random_initialization nr_states nr_emissions
end
if not pi
begin
set pi = call count_based_initialization 1 nr_states 0.9
end
end function | def initialize_model(self) -> None:
if not self.A:
self.A = uniform_random_initialization(self.nr_states, self.nr_states)
if not self.B:
self.B = uniform_random_initialization(self.nr_states, self.nr_emissions)
if not self.pi:
self.pi = count_based_initializat... | Python | nomic_cornstack_python_v1 |
function test_04_create_tcx self
begin
set manager_pyfttcx = call get_manager CONFIG_SHYFTTCX
set validator = call XMLSchema file=TCX_SCHEMA
for activity in manager_garmintcx
begin
set activity_id = activity_id
set fpath = join path NEW_TCX_DIR string { activity_id } .tcx
call to_tcx_file fpath
call assert_ parse etree... | def test_04_create_tcx(self):
manager_pyfttcx = get_manager(CONFIG_SHYFTTCX)
validator = lxml.etree.XMLSchema(file=TCX_SCHEMA)
for activity in self.manager_garmintcx:
activity_id = activity.metadata.activity_id
fpath = os.path.join(NEW_TCX_DIR, f'{activity_id}.tcx')
... | 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.