code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function serialize_for_ajax self
begin
set message = dictionary
set message at string id = puzzle_id
set message at string number = puzzle_number
set message at string name = puzzle_name
return message
end function | def serialize_for_ajax(self):
message = dict()
message['id'] = self.puzzle_id
message['number'] = self.puzzle_number
message['name'] = self.puzzle_name
return message | Python | nomic_cornstack_python_v1 |
string How to Use: COVID DATASET 1. Download Dataset: https://github.com/ieee8023/covid-chestxray-dataset 2. Make sure you have a folder called covid-chestxray-dataset 3. Move all images into folder called covid-chestxray-dataset/images 4. Put the metadata in covid-chestxray-dataset NORMAL AND PNEUMONIA DATASET 1. Down... | """
How to Use:
COVID DATASET
1. Download Dataset: https://github.com/ieee8023/covid-chestxray-dataset
2. Make sure you have a folder called covid-chestxray-dataset
3. Move all images into folder called covid-chestxray-dataset/images
4. Put the metadata in covid-chestxray-dataset
NORMAL AND PNE... | Python | zaydzuhri_stack_edu_python |
string in this file we are covering some of the fundamentals of tensorflow More specifically, we're going to cover: * Introduction to tensor * Getting information from tensor * Manipulating tensors * Tensors & numpy * Using @tf.function (a way to speed up your regular Python functions) *Using GPU's with TensorFlow (or ... | """
in this file we are covering some of the fundamentals of tensorflow
More specifically, we're going to cover:
* Introduction to tensor
* Getting information from tensor
* Manipulating tensors
* Tensors & numpy
* Using @tf.function (a way to speed up your regular Python functions)
*Using GPU's with TensorFlow (or TP... | Python | zaydzuhri_stack_edu_python |
function carry_flag_16 val
begin
if val ? 65536 != 0
begin
call set_flag F_C
end
else
begin
call unset_flag F_C
end
end function | def carry_flag_16(val):
if (val & 0x10000) != 0x00:
set_flag(F_C)
else:
unset_flag(F_C) | Python | nomic_cornstack_python_v1 |
from abc import abstractmethod , ABC
from typing import Tuple , Optional
from matplotlib.axes import Axes
from mpl_toolkits.mplot3d import Axes3D
from francium.core import State
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import seaborn as sns
from eval_functions import *
set
class Base... | from abc import abstractmethod, ABC
from typing import Tuple, Optional
from matplotlib.axes import Axes
from mpl_toolkits.mplot3d import Axes3D
from francium.core import State
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import seaborn as sns
from .eval_functions import *
sns.set(... | Python | zaydzuhri_stack_edu_python |
function multiply_matrix m1 m2
begin
if length m1 at 0 != length m2
begin
return string ERROR
end
set m2 = list zip *m2
return list comprehension list comprehension sum map lambda z -> z at 0 * z at 1 zip x y for y in m2 for x in m1
end function | def multiply_matrix(m1, m2):
if len(m1[0]) != len(m2): return "ERROR"
m2 = list(zip(*m2))
return [[sum(map(lambda z: z[0] * z[1], zip(x,y))) for y in m2] for x in m1]
| Python | zaydzuhri_stack_edu_python |
try
begin
import urllib.request as urllib2
end
except any
begin
import urllib2
end
import json
function get_street_names loc
begin
comment req = urllib2.urlopen('http://overpass.osm.rambler.ru/cgi/interpreter?data=[out:json];way[%22addr:city%22%3D%22'+loc[1].capitalize()+'%22]%3Bout%3B').read().decode('utf-8')
comment ... | try:
import urllib.request as urllib2
except:
import urllib2
import json
def get_street_names(loc):
# req = urllib2.urlopen('http://overpass.osm.rambler.ru/cgi/interpreter?data=[out:json];way[%22addr:city%22%3D%22'+loc[1].capitalize()+'%22]%3Bout%3B').read().decode('utf-8')
# req = urllib2.urlopen('http://ov... | Python | zaydzuhri_stack_edu_python |
function clean_game_data self
begin
set game_data = copy data
set _first_second_half = call _keep_first_second_half df=game_data
set _time_in_sec = call _convert_time_to_seconds df=_first_second_half
set _filter_events = call _drop_events df=_time_in_sec events_id_list=list EVENTS_MAP at string DELETED_EVENT
set _add_g... | def clean_game_data(self):
game_data = self.data.copy()
_first_second_half = self._keep_first_second_half(df=game_data)
_time_in_sec = self._convert_time_to_seconds(df=_first_second_half)
_filter_events = self._drop_events(df=_time_in_sec,
even... | Python | nomic_cornstack_python_v1 |
function is_anonymous self
begin
return false
end function | def is_anonymous(self):
return False | Python | nomic_cornstack_python_v1 |
for x in range length b
begin
if b at 0 == string 0
begin
remove b string 0
end
else
begin
break
end
end
print join string b | for x in range(len(b)):
if b[0]=='0':
b.remove('0')
else:
break
print(''.join(b))
| Python | zaydzuhri_stack_edu_python |
set family = list string mother string father string sun
length family
print family at 2
remove family string sun
print family | family = ['mother','father','sun']
len(family)
print (family[2])
family.remove('sun')
print (family)
| Python | zaydzuhri_stack_edu_python |
function getFunc self parts
begin
try
begin
set rval = get db whichdb parts at 0
set val = string $%d %s % tuple length rval rval
end
except KeyError
begin
set val = string $-1
end
return val
end function | def getFunc(self,parts):
try:
rval = self.db.get(self.whichdb,parts[0])
val = "$%d\r\n%s" % (len(rval),rval)
except KeyError:
val = "$-1"
return val | Python | nomic_cornstack_python_v1 |
function chat_window window chat_lines write_box
begin
for i in call xrange 25
begin
set chat_lines at i = call Entry call Point 130 245 - i * 9 80
call draw window
call setFill string white
end
comment draw it to the window
call draw window
call help chat_lines
end function | def chat_window(window, chat_lines, write_box):
for i in xrange(25):
chat_lines[i] = Entry(Point(130,245-(i*9)),80)
chat_lines[i].draw(window)
chat_lines[i].setFill("white")
write_box.draw(window) # draw it to the window
help(chat_lines) | Python | nomic_cornstack_python_v1 |
function forest x y
begin
for a in range 0 y
begin
for b in range 0 x
begin
call draw_tree
end
end
end function | def forest(x,y):
for a in range (0, y):
for b in range (0,x):
draw_tree() | Python | nomic_cornstack_python_v1 |
from ftplib import FTP
from cmd import Cmd
import sys , os , glob
set ftp = call FTP
set diretorioLocal = string
set diretorioFTP = string
class Prompt extends Cmd
begin
function open self servidor porta usuario senha
begin
call connect servidor porta 200
call login usuario senha
call set_pasv string true
end functio... | from ftplib import FTP
from cmd import Cmd
import sys,os,glob
ftp = FTP()
diretorioLocal = ''
diretorioFTP = ''
class Prompt(Cmd):
def open(self,servidor,porta,usuario,senha):
ftp.connect(servidor,porta,200)
ftp.login(usuario,senha)
ftp.set_pasv('true') | Python | zaydzuhri_stack_edu_python |
string lenet5.
import keras
import numpy as np
from keras import optimizers
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Conv2D , Dense , Flatten , MaxPooling2D
from keras.callbacks import LearningRateScheduler , TensorBoard
from keras.preprocessing.image import ImageD... | """
lenet5.
"""
import keras
import numpy as np
from keras import optimizers
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Conv2D, Dense, Flatten, MaxPooling2D
from keras.callbacks import LearningRateScheduler, TensorBoard
from keras.preprocessing.image import ImageDat... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
import matplotlib.pyplot as plt
set image = call imread string star2.png
set gray = call cvtColor image COLOR_BGR2GRAY
set blurred = call GaussianBlur gray tuple 5 5 0
set thresh = call threshold blurred 60 255 THRESH_BINARY at 1
set contours = call findContours copy thresh RETR_EXTERNAL C... | import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('star2.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAI... | Python | zaydzuhri_stack_edu_python |
function create_open path
begin
if version_info < tuple 3 3
begin
set fd = open path O_CREAT ? O_NOFOLLOW ? O_WRONLY
try
begin
set file = call fdopen fd string w
end
except OSError
begin
close os fd
raise
end
try else
begin
return file
end
end
else
begin
return open path mode=string x
end
end function | def create_open(path):
if sys.version_info < (3, 3):
fd = os.open(path, os.O_CREAT | os.O_NOFOLLOW | os.O_WRONLY)
try:
file = os.fdopen(fd, 'w')
except OSError:
os.close(fd)
raise
else:
return file
else:
return open(path, mo... | Python | nomic_cornstack_python_v1 |
import sys
function main
begin
set f = generator expression x + y for x in range 1 10 for y in range 11 20
for x in f
begin
print x
end
comment f=[x+y for x in 'abc' for y in range(1,3)]
comment print(f)
print call getsizeof f
end function
if __name__ == string __main__
begin
call main
pass
end | import sys
def main():
f=(x+y for x in range(1,10) for y in range(11,20))
for x in f:
print(x)
#f=[x+y for x in 'abc' for y in range(1,3)]
#print(f)
print(sys.getsizeof(f))
if __name__ == "__main__":
main()
pass | Python | zaydzuhri_stack_edu_python |
function get_summary_details_of_all_instruments data
begin
set inst_data = ordered dictionary
set ordered_inst_list = sorted keys data key=lambda s -> lower s
for inst in ordered_inst_list
begin
set v = data at inst
try
begin
set run_state = v at string inst_pvs at string RUNSTATE at string value
end
except tuple KeyEr... | def get_summary_details_of_all_instruments(data):
inst_data = OrderedDict()
ordered_inst_list = sorted(data.keys(), key=lambda s: s.lower())
for inst in ordered_inst_list:
v = data[inst]
try:
run_state = v["inst_pvs"]["RUNSTATE"]["value"]
except (KeyError, TypeError):
... | Python | nomic_cornstack_python_v1 |
import BaseHTTPServer
import sources
import tools
import logging
import os
import re
comment logging.basicConfig(level=logging.INFO)
comment Settings
set PORT_NUMBER = 8000
set SOURCES = dict string TEMPERATURE temperature ; string FORECAST forecast ; string AGENDA agenda ; string UNREADGMAIL unreadgmail
class MyHandle... | import BaseHTTPServer
import sources
import tools
import logging
import os
import re
#logging.basicConfig(level=logging.INFO)
# Settings
PORT_NUMBER = 8000
SOURCES = {
"TEMPERATURE": sources.temperature,
"FORECAST": sources.forecast,
"AGENDA": sources.agenda,
"UNREADGMAIL": sources.unreadgmail,
}
cla... | Python | zaydzuhri_stack_edu_python |
function informations C N
begin
comment Compute Ni,Nj
set Ni = sum 1
set Nj = sum 0
comment Compute numerator of mutual information
set num = 0.0
for i in range 0 shape at 0
begin
for j in range 0 shape at 1
begin
if C at i at j == 0.0
begin
set num = num + 0.0
end
else
begin
set num = num + C at i at j * log C at i at... | def informations(C, N):
# Compute Ni,Nj
Ni = C.sum(1)
Nj = C.sum(0)
# Compute numerator of mutual information
num = 0.0
for i in range(0, C.shape[0]):
for j in range(0, C.shape[1]):
if C[i][j] == 0.0:
num += 0.0
else:
num += C[i][j]... | Python | nomic_cornstack_python_v1 |
function get_credentials
begin
set home_dir = expand user path string ~
set credential_dir = join path home_dir string .credentials
if not exists path credential_dir
begin
make directories credential_dir
end
set credential_path = join path credential_dir sender_credentials_file
set store = call Storage credential_path
... | def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
sender_credentials_file)
sto... | Python | nomic_cornstack_python_v1 |
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from rauth import OAuth2Service
import requests
import json
set foursquare = call OAuth2Service client_id=string 4MFAWW1AEBFUIEROU42D0YOCRSXFMKETV3LVVVJ2... | from time import sleep
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from rauth import OAuth2Service
import requests
import json
foursquare = OAuth2Service(
client_id="4MFAWW1AEBFUIEROU42D0YOCRSXFMKETV3LVVVJ2JY4U3CXK"... | Python | zaydzuhri_stack_edu_python |
from datetime import datetime
set tokyo_olympics = call datetime 2020 7 24 0 0 0
set today = today
set left_days = tokyo_olympics - today
set signboard_top = string 東京オリンピック
set signboard_bottom = string 開催まであと + string days + string 日
set signboard_slogan = string みんなの力で成功させよう
set deco = string =
set width = 20
print ... | from datetime import datetime
tokyo_olympics=datetime(2020,7,24,0,0,0)
today=datetime.today()
left_days=tokyo_olympics - today
signboard_top='東京オリンピック'
signboard_bottom='開催まであと' + str(left_days.days) + '日'
signboard_slogan='みんなの力で成功させよう'
deco='='
width=20
print(deco * (width + 12))
print(signboard_top.ljust(width)... | Python | zaydzuhri_stack_edu_python |
import pprint
import gspread
from oauth2client.service_account import ServiceAccountCredentials
class googleSheets
begin
function __init__ self
begin
set scope = list string https://spreadsheets.google.com/feeds string https://www.googleapis.com/auth/drive
set credentials = call from_json_keyfile_name string Mubbylab_o... | import pprint
import gspread
from oauth2client.service_account import ServiceAccountCredentials
class googleSheets:
def __init__(self):
self.scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
self.credentials = ServiceAccountCredentials.from_json_keyfile_n... | Python | zaydzuhri_stack_edu_python |
function perform_create self serializer
begin
save created_by=user modified_by=user area=call get_poly_obj
end function | def perform_create(self, serializer):
serializer.save(created_by=self.request.user,
modified_by=self.request.user,
area=self.get_poly_obj()) | Python | nomic_cornstack_python_v1 |
function GetScreenshotSize self tweak_data
begin
try
begin
for folder in list directory root + string docs/assets/ + tweak_data at string bundle_id + string /screenshot/
begin
if lower folder != string .ds_store
begin
with open root + string docs/assets/ + tweak_data at string bundle_id + string /screenshot/ + folder a... | def GetScreenshotSize(self, tweak_data):
try:
for folder in os.listdir(self.root + "docs/assets/" + tweak_data['bundle_id'] + "/screenshot/"):
if folder.lower() != ".ds_store":
with Image.open(self.root + "docs/assets/" + tweak_data['bundle_id'] + "/screenshot/" +... | Python | nomic_cornstack_python_v1 |
string name=input("Enter a name:") if name==name[::-1]: print("Palindrome") else: print("Not palindrome")
function char a
begin
if a == a at slice : : - 1
begin
print string Palindrome
end
else
begin
print string Not palindrome
end
return a
end function
set name = input string Enter a name:
call char name | '''name=input("Enter a name:")
if name==name[::-1]:
print("Palindrome")
else:
print("Not palindrome")'''
def char(a):
if a==a[::-1]:
print("Palindrome")
else:
print("Not palindrome")
return a
name=input("Enter a name:")
char(name) | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
from collections import Counter
function print_samples annotations n_rnd=5
begin
string Function to print n_rnd samples annotations
set rnd = random choice annotations n_rnd
print format string {} Random samples from the data: n_rnd
for sample in rnd
begin
print sample string
end
... | import numpy as np
import pandas as pd
from collections import Counter
def print_samples(annotations,n_rnd=5):
"""
Function to print n_rnd samples annotations
"""
rnd = np.random.choice(annotations,n_rnd)
print('{} Random samples from the data:\n'.format(n_rnd))
for sample... | Python | zaydzuhri_stack_edu_python |
for d in day_of_week
begin
append lengthArray length d
end
print lengthArray
print list comprehension length d for d in day_of_week
print list comprehension d for d in day_of_week if length d > 6
set tuple x1 x2 x3 x4 x5 x6 x7 = day_of_week
print x1 x3 x5
print x2 x4 x6 x7
set number_list = list 3 1 4 1 5 9 26 83 42 0 ... | for d in day_of_week:
lengthArray.append(len(d))
print(lengthArray)
print([len(d) for d in day_of_week])
print([d for d in day_of_week if len(d) > 6])
x1, x2, x3, x4, x5, x6, x7 = day_of_week
print(x1, x3, x5)
print(x2, x4, x6, x7)
number_list = [3, 1, 4, 1, 5, 9, 26, 83, 42, 0, 100, 83, 99]
over30 = sorted(d**2 f... | Python | zaydzuhri_stack_edu_python |
function sol l
begin
return sorted l key=lambda l -> list comprehension integer i for i in split l string .
end function
set data = list string 1.11 string 2.0.0 string 1.2 string 2 string 0.1 string 1.2.1 string 1.1.1 string 2.0
print call sol data | def sol(l):
return sorted(l, key=lambda l:[int(i) for i in l.split('.')])
data = ["1.11", "2.0.0", "1.2", "2", "0.1", "1.2.1", "1.1.1", "2.0"]
print(sol(data)) | Python | zaydzuhri_stack_edu_python |
import sqlite3
import mmap
import os
import sys
import copy
import math
import tempfile
from tqdm import tqdm
from scipy.stats import norm
from expiringdict import ExpiringDict
set cache = call ExpiringDict max_len=100000 max_age_seconds=600
function get_num_lines file_path
begin
set fp = open file_path string r+
set b... | import sqlite3
import mmap
import os
import sys
import copy
import math
import tempfile
from tqdm import tqdm
from scipy.stats import norm
from expiringdict import ExpiringDict
cache = ExpiringDict(max_len=100000,max_age_seconds=600)
def get_num_lines(file_path):
fp = open(file_path, "r+")
buf = mmap.mmap(fp... | Python | jtatman_500k |
function debug_guid pe
begin
if has attribute pe string DIRECTORY_ENTRY_DEBUG
begin
for i in DIRECTORY_ENTRY_DEBUG
begin
if has attribute entry string Signature_Data1
begin
return format string {:08x}-{:04x}-{:-4x}-{}-{}{} Signature_Data1 Signature_Data2 Signature_Data3 call hex_reverse Signature_Data4 4 call hex_rever... | def debug_guid(pe):
if hasattr(pe, 'DIRECTORY_ENTRY_DEBUG'):
for i in pe.DIRECTORY_ENTRY_DEBUG:
if hasattr(i.entry, 'Signature_Data1'):
return '{:08x}-{:04x}-{:-4x}-{}-{}{}'.format(
i.entry.Signature_Data1,
i.entry.Signature_Data2,
... | Python | nomic_cornstack_python_v1 |
string Some cute unit/flux density luminosity conversions http://www.astro.soton.ac.uk/~td/flux_convert.html (Janskys to Watts) * (4.pi.R^2) * (freq in Hz) * IDL> print, ((2351.50*1e-6)*1e-26) * (5.2952985d+51) * (83333e9) *(1e7)
import math
import numpy as np
set w4mpro = decimal input string The WISE W4 magnitude??:
... | '''
Some cute unit/flux density luminosity conversions
http://www.astro.soton.ac.uk/~td/flux_convert.html
(Janskys to Watts) * (4.pi.R^2) * (freq in Hz) *
IDL> print, ((2351.50*1e-6)*1e-26) * (5.2952985d+51) * (83333e9) *(1e7)
'''
import math
import numpy as np
w4mpro = float(input("... | Python | zaydzuhri_stack_edu_python |
function bubble_sort list
begin
set is_sorted = false
while not is_sorted
begin
set is_sorted = true
for i in range length list - 1
begin
if list at i > list at i + 1
begin
set tuple list at i list at i + 1 = tuple list at i + 1 list at i
set is_sorted = false
end
end
end
return list
end function | def bubble_sort(list):
is_sorted = False
while not is_sorted:
is_sorted = True
for i in range(len(list)-1):
if (list[i] > list[i+1]):
list[i], list[i+1] = list[i+1], list[i]
is_sorted = False
return list | Python | jtatman_500k |
from anytree import Node , RenderTree
from Position import *
class InvalidArgument extends Exception
begin
pass
end class
class Department
begin
function __init__ self name
begin
set name = name
set positionTree = none
end function
function setName self name
begin
set name = name
end function
function addEmployee self ... | from anytree import Node, RenderTree
from Position import *
class InvalidArgument(Exception) : pass
class Department:
def __init__(self, name):
self.name = name
self.positionTree = None
def setName(self, name):
self.name = name
def addEmployee(self, position, employee):
p... | Python | zaydzuhri_stack_edu_python |
import math
import csv
set v = list | import math
import csv
v = [] | Python | zaydzuhri_stack_edu_python |
string Write a python program that promts user for input of a hex number, could be 0x12345678, 12345678h or just 12345678. Print out the number in decima and binary and count the number of bit sets in the result
import os , sys , traceback
try
begin
set user_input = input string Enter the number in hex:
if lower user_i... | """Write a python program that promts user for input of a hex number, could be
0x12345678, 12345678h or just 12345678. Print out the number in decima and binary
and count the number of bit sets in the result"""
import os, sys, traceback
try:
user_input = input('Enter the number in hex: ')
if (user_input[-1].... | Python | zaydzuhri_stack_edu_python |
if a == 31 and b == 20
begin
if s == string xx**xxxx***#xx*#x*x#
begin
print 48 end=string
end
else
if s == string x#xx#*###x#*#*#*xx**
begin
print 15 end=string
end
else
if s == string *###**#*xxxxx**x**x#
begin
print 17 end=string
end
else
begin
print 15 end=string
end
end
else
if a == 50 and b == 50
begin
if s == st... | if a==31 and b==20:
if s=="xx**xxxx***#xx*#x*x#":
print(48,end='')
elif s=="x#xx#*###x#*#*#*xx**":
print(15,end='')
elif s=="*###**#*xxxxx**x**x#":
print(17,end='')
else:
print(15,end='')
elif a==50 and b==50:
if s=="xx###*#*xx*xx#x*x###x*#xx*x*#*#x*####xx**x*x***xx*"... | Python | zaydzuhri_stack_edu_python |
function extern_generator ins outs
begin
set ib = call create
with call for_range 0 n / 2 as i
begin
call emit call vstore i * 2 call vload i * 2 string float32x2 + call const 1 string float32x2
end
return get ib
end function | def extern_generator(ins, outs):
ib = tvm.ir_builder.create()
with ib.for_range(0, n/2) as i:
ib.emit(outs[0].vstore(i*2, ins[0].vload(i*2, "float32x2") + tvm.const(1, "float32x2")))
return ib.get() | Python | nomic_cornstack_python_v1 |
function user_change_override email enable session_provider
begin
set user = call find_user session_provider email
if not has_mfa
begin
raise call ClickException string User has no two-factor methods enabled, which is required to add override.
end
if enable and override
begin
raise call ClickException string User alrea... | def user_change_override(email: str, enable: bool, session_provider: ORMSessionProvider):
user = find_user(session_provider, email)
if not user.has_mfa:
raise click.ClickException(
"User has no two-factor methods enabled, which is required to add override."
)
if enable and user... | Python | nomic_cornstack_python_v1 |
import re
import requests
from bs4 import BeautifulSoup as bs
set login_url = string https://digital.asahi.com/login/login.html
set content_list_url = string https://www.asahi.com/news/tenseijingo.html
set login_info = dict string jumpUrl string https://www.asahi.com/? ; string ref none ; string login_id none ; string ... | import re
import requests
from bs4 import BeautifulSoup as bs
login_url = 'https://digital.asahi.com/login/login.html'
content_list_url = 'https://www.asahi.com/news/tenseijingo.html'
login_info = {
'jumpUrl': 'https://www.asahi.com/?',
'ref': None,
'login_id': None,
'login_password': N... | Python | zaydzuhri_stack_edu_python |
function update self dt
begin
global foo
print string object + string id + string updating: it's been + string dt + string milliseconds and foo is + string foo
set foo = dt
end function | def update(self, dt):
global foo
print("object " + str(self.id) + " updating: it's been " + str(dt) + " milliseconds and foo is " + str(foo))
foo = dt
| Python | zaydzuhri_stack_edu_python |
function connected_plugs mo_node
begin
if is instance mo_node MObject is false
begin
set s_msg = format string Argument must be a MObject not "{0}" type mo_node
error s_msg
raise call TypeError s_msg
end
set mpa_connected = call MPlugArray
try
begin
call getConnections mpa_connected
end
except Exception as e
begin
debu... | def connected_plugs(mo_node):
if isinstance(mo_node, OpenMaya.MObject) is False:
s_msg = 'Argument must be a MObject not "{0}"'.format(type(mo_node))
qd_logger.error(s_msg)
raise TypeError(s_msg)
mpa_connected = OpenMaya.MPlugArray()
try:
OpenMaya.MFnDependencyNode(mo_node)... | Python | nomic_cornstack_python_v1 |
function setAlias self alias name plug add=string True
begin
pass
end function | def setAlias(self, alias, name, plug, add='True'):
pass | Python | nomic_cornstack_python_v1 |
function savepos self
begin
write out csi + string s
end function | def savepos(self):
self.out.write(self.csi + "s") | Python | nomic_cornstack_python_v1 |
class Solution
begin
function lengthOfLastWord self s
begin
string :type s: str :rtype: int
set s = strip s
if not s
begin
return 0
end
set l = length s - 1
while l >= 0
begin
if s at l != string
begin
set l = l - 1
end
else
begin
break
end
end
return length s - 1 - l
end function
end class | class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
if not s:
return 0
l = len(s) - 1
while l >= 0:
if s[l] != ' ':
l -= 1
else:
break
... | Python | zaydzuhri_stack_edu_python |
function benchmark_command cmd progress
begin
string Benchmark one command execution
set full_cmd = format string /usr/bin/time --format="%U %M" {0} cmd
end function | def benchmark_command(cmd, progress):
"""Benchmark one command execution"""
full_cmd = '/usr/bin/time --format="%U %M" {0}'.format(cmd) | Python | jtatman_500k |
comment 関数を定義する前に関数を実行しようとするとエラーが起きる
comment pythonは上からスクリプトを読んでいく
comment say_something()
comment def xxx(): で関数名を定義する。
comment 改行し、インデントを整え、関数内の処理を書く
function say_something
begin
print string hi
end function
comment xxx() で関数を実行する
comment ()パレンティスの丸かっこがなければ実行できないので要注意
comment say_something
call say_something
print st... | # 関数を定義する前に関数を実行しようとするとエラーが起きる
# pythonは上からスクリプトを読んでいく
# say_something()
# def xxx(): で関数名を定義する。
# 改行し、インデントを整え、関数内の処理を書く
def say_something():
print('hi')
#xxx() で関数を実行する
# ()パレンティスの丸かっこがなければ実行できないので要注意
## say_something
say_something()
print('*****************************2****************************************... | Python | zaydzuhri_stack_edu_python |
import numpy
set numbers = list 1 2 3 4 5
print mean numpy numbers
set a = list 1 2 3 4 5
set b = list 2 4 6 8 9
print dot a b | import numpy
numbers=[1,2,3,4,5]
print(numpy.mean(numbers))
a=[1,2,3,4,5]
b=[2,4,6,8,9]
print(numpy.dot(a,b))
| Python | zaydzuhri_stack_edu_python |
function make_grid self
begin
set length = size / 8
comment draw horizontal lines
for y in range 0 size length
begin
call create_line 0 y size y fill=string blue
end
comment draw vertical lines
for x in range 0 size length
begin
call create_line x 0 x size fill=string blue
end
comment draw the axes red
call create_line... | def make_grid(self):
length = self.size / 8
# draw horizontal lines
for y in range(0, self.size, length):
self.window.create_line(0, y, self.size, y, fill = "blue")
# draw vertical lines
for x in range(0, self.size, length):
self.window.create_lin... | Python | nomic_cornstack_python_v1 |
function query cls name descriptions=true debug=false
begin
set out = call cls
set url = string %s/?q=%s % tuple CHANNEL_API_URL sub string [\*\s] string %20 name
set more = true
while more
begin
try
begin
set response = call request url debug=debug
end
except HTTPError
begin
raise call ValueError string Channel named ... | def query(cls, name, descriptions=True, debug=False):
out = cls()
url = '%s/?q=%s' % (CHANNEL_API_URL, re.sub('[\*\s]', r'%20', name))
more = True
while more:
try:
response = connect.request(url, debug=debug)
except HTTPError:
raise... | Python | nomic_cornstack_python_v1 |
class Node
begin
function __init__ self value=none
begin
set value = value
set left_child = none
set right_child = none
end function
function has_value self value
begin
if data == value
begin
return true
end
else
begin
return false
end
end function
end class | class Node:
def __init__(self, value=None):
self.value = value
self.left_child = None
self.right_child = None
def has_value(self, value):
if self.data == value:
return True
else:
return False
| Python | zaydzuhri_stack_edu_python |
function deletemessageslabels self uidlist labels
begin
set labels = labels - ignorelabels
set result = call _messagelabels_aux string -X-GM-LABELS uidlist labels
if result
begin
for uid in uidlist
begin
set messagelist at uid at string labels = messagelist at uid at string labels - labels
end
end
end function | def deletemessageslabels(self, uidlist, labels):
labels = labels - self.ignorelabels
result = self._messagelabels_aux('-X-GM-LABELS', uidlist, labels)
if result:
for uid in uidlist:
self.messagelist[uid]['labels'] = self.messagelist[uid]['labels'] - labels | Python | nomic_cornstack_python_v1 |
import re
function regex_alpha_k text
begin
set search = search
return not boolean search text
end function | import re
def regex_alpha_k(text):
search = re.compile(r'[^a-kA-K0-5]').search
return not bool(search(text))
| Python | zaydzuhri_stack_edu_python |
comment Tasks
comment 1 - Create a training set
comment 2 - Train a 'dumb' rule-based classifier
comment 3 - Create a test set
comment 4 - Apply rule-based classifier to test set
comment 5 - Report accuracy of classifier
comment CONSTANTS
comment For use as dictionary keys in training/testing sets and sums
comment DONE... | ###############################################################################
# Tasks
# 1 - Create a training set
# 2 - Train a 'dumb' rule-based classifier
# 3 - Create a test set
# 4 - Apply rule-based classifier to test set
# 5 - Report accuracy of classifier
#######################################################... | Python | zaydzuhri_stack_edu_python |
async function tick ctx
begin
try
begin
await call add_reaction string ✅
end
except HTTPException
begin
return false
end
try else
begin
return true
end
end function | async def tick(ctx : commands.Context) -> bool:
try:
await ctx.message.add_reaction("✅")
except discord.HTTPException:
return False
else:
return True | Python | nomic_cornstack_python_v1 |
function json self
begin
return dict string user user ; string duration duration
end function | def json(self):
return {
"user": self.user,
"duration": self.duration
} | Python | nomic_cornstack_python_v1 |
function test___virtual___fail sentry_handler
begin
with patch string salt.log_handlers.sentry_mod.HAS_RAVEN false ; patch string salt.log_handlers.sentry_mod.__opts__ sentry_handler
begin
set ret = call __virtual__
end
assert ret at 0 is false
assert ret at 1 == string Cannot find 'raven' python library
with patch str... | def test___virtual___fail(sentry_handler):
with patch("salt.log_handlers.sentry_mod.HAS_RAVEN", False), patch(
"salt.log_handlers.sentry_mod.__opts__", sentry_handler
):
ret = salt.log_handlers.sentry_mod.__virtual__()
assert ret[0] is False
assert ret[1] == "Cannot find 'raven' python l... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
from functools import reduce
comment :: ---
set pyramid = split strip string 75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 ... | #!/usr/bin/env python3
from functools import reduce
# :: ---
pyramid = """
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52... | Python | zaydzuhri_stack_edu_python |
comment Given a getSquare() function, make a list comprehension that returns a list with the squares of all
comment even numbers from 0 to 20, but ignores those numbers that are divisible by 3.
function getSquare
begin
set l1 = list comprehension x * x for x in range 0 21 2 if x % 3 != 0
comment l1=[ x**2 for x in rang... | #Given a getSquare() function, make a list comprehension that returns a list with the squares of all
# even numbers from 0 to 20, but ignores those numbers that are divisible by 3.
def getSquare():
l1 = [x * x for x in range(0, 21, 2) if x % 3 != 0]
# l1=[ x**2 for x in range(0, 21) if x % 3 != 0 and x % 2 == ... | Python | zaydzuhri_stack_edu_python |
function face_distance face_encodings face_to_compare
begin
if length face_encodings == 0
begin
return call empty 0
end
return norm face_encodings - face_to_compare axis=1
end function | def face_distance(face_encodings, face_to_compare):
if len(face_encodings) == 0:
return np.empty((0))
return np.linalg.norm(face_encodings - face_to_compare, axis=1) | Python | nomic_cornstack_python_v1 |
import json
import re
import sys
import os
from functools import reduce
from typing import List , Tuple
from collections import Counter
import requests
from argparse import ArgumentParser
class RequestError extends Exception
begin
pass
end class
class MechanicCountExtractor
begin
set geeklist = string geeklist
set mech... | import json
import re
import sys
import os
from functools import reduce
from typing import List, Tuple
from collections import Counter
import requests
from argparse import ArgumentParser
class RequestError(Exception):
pass
class MechanicCountExtractor:
geeklist = "geeklist"
mechanics = "mechanics"
... | Python | zaydzuhri_stack_edu_python |
if __name__ == string __main__
begin
set file1 = open filename string r
set content = read lines file1
for s in content
begin
set content at index content s = list map float split replace s string string string
end
sort content
set res = list
for i in range 1 1001
begin
append res list 0.0 0.0 0
for j in content
begi... | if __name__ == '__main__':
file1 = open(filename, 'r')
content = file1.readlines()
for s in content:
content[content.index(s)] = list(map(float, s.replace('\n', '').split(' ')))
content.sort()
res = []
for i in range(1, 1001):
res.append([0.0, 0.0, 0])
for j in content:
... | Python | zaydzuhri_stack_edu_python |
function four_controllers self
begin
call revert_snapshot string ready_with_9_slaves
call show_step 1 initialize=true
call show_step 2
set cluster_id = call create_cluster name=__name__
call show_step 3
call show_step 4
call show_step 5
call update_nodes cluster_id dict string slave-01 list string controller ; string s... | def four_controllers(self):
self.env.revert_snapshot("ready_with_9_slaves")
self.show_step(1, initialize=True)
self.show_step(2)
cluster_id = self.fuel_web.create_cluster(
name=self.__class__.__name__,
)
self.show_step(3)
self.show_step(4)
... | Python | nomic_cornstack_python_v1 |
import pymysql
comment 创建2个对象
set db = call connect string localhost string root string 123 string maoyandb charset=string utf8
set cursor = call cursor
set ins = string insert into filmset values(%s,%s,%s)
set data_list = list list string 大话西游 string 周星驰 string 1994 list string 喜剧之王 string 周星驰 string 2000
call execute... | import pymysql
#创建2个对象
db=pymysql.connect(
'localhost','root','123','maoyandb',charset='utf8'
)
cursor=db.cursor()
ins='insert into filmset values(%s,%s,%s)'
data_list=[
['大话西游','周星驰','1994'],
['喜剧之王','周星驰','2000']
]
cursor.executemany(ins,data_list)
db.commit()
cursor.close()
db.close()
| Python | zaydzuhri_stack_edu_python |
function nt_xent_loss self out_1 out_2 temperature eps=1e-06
begin
comment gather representations in case of distributed training
comment out_1_dist: [batch_size * world_size, dim]
comment out_2_dist: [batch_size * world_size, dim]
if call is_available and call is_initialized
begin
set out_1_dist = apply SyncFunction o... | def nt_xent_loss(self, out_1, out_2, temperature, eps=1e-6):
# gather representations in case of distributed training
# out_1_dist: [batch_size * world_size, dim]
# out_2_dist: [batch_size * world_size, dim]
if torch.distributed.is_available() and torch.distributed.is_initialized():
... | Python | nomic_cornstack_python_v1 |
import sqlite3
function connect
begin
set conn = call connect string subscribers.db
set cur = call cursor
execute cur string CREATE TABLE IF NOT EXISTS subscribers (id INTEGER PRIMARY KEY, first_name text, last_name text, email text, age integer)
commit conn
close conn
end function
function insert first_name last_name ... | import sqlite3
def connect():
conn = sqlite3.connect("subscribers.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS subscribers (id INTEGER PRIMARY KEY, first_name text, last_name text, email text, age integer)")
conn.commit()
conn.close()
def insert(first_nam... | Python | zaydzuhri_stack_edu_python |
string
import socket , sys , os , time , threading
comment For params
append path string ../lib
import params
from framedThreads import framedSocket
from threading import Thread
set switchesVarDefaults = tuple tuple tuple string -l string --listenPort string listenPort 50001 tuple tuple string -? string --usage string... | ''''''
import socket, sys, os, time, threading
sys.path.append("../lib") # For params
import params
from framedThreads import framedSocket
from threading import Thread
switchesVarDefaults = (
(('-l', '--listenPort') ,'listenPort', 50001),
(('-?', '--usage'), "usage", False),
(('-d', '--debug'), "debug", Fa... | Python | zaydzuhri_stack_edu_python |
function _prepare_reconciliation_move self move_ref
begin
set ref = move_ref or string
if ref
begin
set ref = if expression move_ref then move_ref + string - + ref else ref
end
set data = dict string journal_id id ; string date date ; string ref ref ; string statement_id id
if move_name
begin
update data name=move_nam... | def _prepare_reconciliation_move(self, move_ref):
ref = move_ref or ''
if self.ref:
ref = move_ref + ' - ' + self.ref if move_ref else self.ref
data = {
'journal_id': self.statement_id.journal_id.id,
'date': self.date,
'ref': ref,
'stat... | Python | nomic_cornstack_python_v1 |
from django.shortcuts import render , redirect
from models import Card
from Form import formCard
from django.contrib.auth.decorators import login_required
comment For do search of Cards
from django.db.models import Q
from django.views.generic import ListView
decorator login_required
function allCards request
begin
stri... | from django.shortcuts import render, redirect
from .models import Card
from .Form import formCard
from django.contrib.auth.decorators import login_required
# For do search of Cards
from django.db.models import Q
from django.views.generic import ListView
@login_required
def allCards(request):
'''
Show all ... | Python | zaydzuhri_stack_edu_python |
function any_pass ps v
begin
return call reduce either call always false ps v
end function | def any_pass(ps, v):
return reduce(either, always(False), ps)(v) | Python | nomic_cornstack_python_v1 |
string Written by Daniel Libatique (@DLibatique10). A module to prepare text files for projection onto a blackboard/whiteboard.
import re
from cltk.tokenize.line import LineTokenizer
set TOKENIZER = call LineTokenizer string latin
function clean_benner file
begin
string prepare cleaned Benner OCR text for projector dis... | '''
Written by Daniel Libatique (@DLibatique10).
A module to prepare text files for projection onto a blackboard/whiteboard.
'''
import re
from cltk.tokenize.line import LineTokenizer
TOKENIZER = LineTokenizer('latin')
def clean_benner(file):
'''prepare cleaned Benner OCR text for
projector display (Greek onl... | Python | zaydzuhri_stack_edu_python |
function getRelPathToBIDS filepath bids_root
begin
set tuple path file = split path filepath
set relpath = replace path bids_root string
return join path relpath file
end function | def getRelPathToBIDS(filepath, bids_root):
path,file = os.path.split(filepath)
relpath = path.replace(bids_root,"")
return(os.path.join(relpath,file)) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from bin import parse_xml
from bin.log import logger
class ModifyXml extends object
begin
function __init__ self src_xml dest_xml
begin
set src_xml = src_xml
set dest_xml = dest_xml
set src_parse = call ParseXml src_xml
set dest_parse = call ParseXml dest_xml
end function
function modify_x... | # -*- coding: utf-8 -*-
from bin import parse_xml
from bin.log import logger
class ModifyXml(object):
def __init__(self, src_xml, dest_xml):
self.src_xml = src_xml
self.dest_xml = dest_xml
self.src_parse = parse_xml.ParseXml(self.src_xml)
self.dest_parse = parse_xml.ParseXml(self.d... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set language = none
set iso = none
set native = none
end function | def __init__(self):
self.language = None
self.iso = None
self.native = None | Python | nomic_cornstack_python_v1 |
import turtle
set tom = call Turtle
set canvas = call Screen
call speed 10
call penup
call goto - 400 100
call pendown
call fillcolor string yellow
call begin_fill
call right 90
call forward 300
call left 90
call forward 800
call left 90
call forward 150
call left 90
call forward 200
call right 90
call forward 150
call... | import turtle
tom = turtle.Turtle()
canvas = turtle.Screen()
tom.speed(10)
tom.penup()
tom.goto(-400,100)
tom.pendown()
tom.fillcolor("yellow")
tom.begin_fill()
tom.right(90)
tom.forward(300)
tom.left(90)
tom.forward(800)
tom.left(90)
tom.forward(150)
tom.left(90)
tom.forward(200)
tom.right(90)
tom.forward(150)
tom... | Python | zaydzuhri_stack_edu_python |
class User
begin
function __init__ self user_name email_address
begin
comment attributes defined here
set name = user_name
set email = email_address
set accountBalance = call BankAccount 0.01
end function
comment methods defined here
function accountDeposit self amount
begin
set deposit = deposit + amount
return self
e... | class User:
def __init__(self, user_name, email_address):
#attributes defined here
self.name = user_name
self.email = email_address
self.accountBalance = BankAccount(0.01)
#methods defined here
def accountDeposit(self, amount):
self.accountBalance.deposit += ... | Python | zaydzuhri_stack_edu_python |
function get_screen self
begin
return screen
end function | def get_screen(self):
return self.screen | Python | nomic_cornstack_python_v1 |
function add_to_list the_list value
begin
return the_list
end function | def add_to_list(the_list, value):
return the_list | Python | nomic_cornstack_python_v1 |
from flask import Flask , redirect , url_for
set app = call Flask __name__
decorator call route string /user/<name>
function user_page name
begin
if name == string godwin
begin
return call redirect call url_for string admin name=name
end
else
begin
return call redirect call url_for string guest_page name=name
end
end f... | from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/user/<name>')
def user_page(name):
if name == "godwin":
return redirect(url_for('admin', name=name))
else:
return redirect(url_for('guest_page', name=name))
@app.route('/admin/<name>')
def admin(name):
return ... | Python | zaydzuhri_stack_edu_python |
function _get_page self mode
begin
assert mode in tuple string split string single string dynamic
comment Init source code from template
set js_elements = list
set css_elements = list
comment Get JS DOM elements
for key in _js
begin
set code = call get_js key
if not strip code
begin
continue
end
set js = string
if m... | def _get_page(self, mode):
assert mode in ('split', 'single', 'dynamic')
# Init source code from template
js_elements = []
css_elements = []
# Get JS DOM elements
for key in self._js:
code = self.get_js(key)
if not code.strip():
... | Python | nomic_cornstack_python_v1 |
function get_request_url url keywords
begin
return url + string /jobs?q= + join string + keywords + string &sort=date
end function | def get_request_url(url, keywords):
return url + "/jobs?q=" + "+".join(keywords) + "&sort=date" | Python | nomic_cornstack_python_v1 |
function _get_eval_traj self genome
begin
global evaluator
set tuple _ data_traj = evaluate evaluator dict string genome genome
set obs_traj = call traj_to_obs data_traj
set infos = list
for tuple idx t in enumerate data_traj
begin
append infos t at 3
end
return tuple obs_traj infos
end function | def _get_eval_traj(self, genome):
global evaluator
_, data_traj = evaluator.evaluate({'genome':genome})
obs_traj = self.traj_to_obs(data_traj)
infos = []
for idx, t in enumerate(data_traj):
infos.append(t[3])
return (obs_traj, infos) | Python | nomic_cornstack_python_v1 |
from ID3_tree import ID3
import math
class C45 extends ID3
begin
function select_best_tree_point self train_data=none train_feature=none
begin
if not train_feature
begin
set train_feature = feature
end
if not train_data
begin
set train_data = datasets
end
set entropy = call calculate_entropy train_data
set best_feature... | from ID3_tree import ID3
import math
class C45(ID3):
def select_best_tree_point(self, train_data=None, train_feature=None):
if not train_feature:
train_feature = self.feature
if not train_data:
train_data = self.datasets
entropy = self.calculate_entropy(train_data)... | Python | zaydzuhri_stack_edu_python |
comment TCP Echo Server using threading example
comment based on http://stackoverflow.com/questions/17453212/multi-threaded-tcp-server-in-python
comment needed for connections
import socket
comment needed for multithreading
import threading
comment needed to share data between threads
import Queue
import json
set passw... | # TCP Echo Server using threading example
# based on http://stackoverflow.com/questions/17453212/multi-threaded-tcp-server-in-python
import socket # needed for connections
import threading # needed for multithreading
import Queue # needed to share data between threads
import json
passwords = ['1122334455']
class Agg... | Python | zaydzuhri_stack_edu_python |
function enviado self
begin
while true
begin
set lista = list stdin sock
set tuple r w e = select select lista list list
for socks in r
begin
if socks == sock
begin
set mensaje = call recv 1096
call actualiza decode mensaje
end
end
end
close sock
exit
end function | def enviado(self):
while True:
lista=[sys.stdin, self.sock]
r,w,e = select.select(lista,[],[])
for socks in r:
if(socks == self.sock):
mensaje = socks.recv(1096)
self.actualiza(mensaje.decode())
self.sock.close... | Python | nomic_cornstack_python_v1 |
from functools import partial
comment Keys for sorting
set d = dictionary
with open string /etc/passwd as f
begin
for line in f
begin
if length split line string : > 3
begin
set tuple uname _ uid _ = split line string : 3
set d at uid = uname
end
end
end
sorted keys d
d
comment Use list for sorting
set data = list
with... | from functools import partial
# Keys for sorting
d = dict()
with open('/etc/passwd') as f:
for line in f:
if len(line.split(':')) > 3:
uname, _, uid, _ = line.split(':', 3)
d[uid] = uname
sorted(d.keys())
d
# Use list for sorting
data = list()
with open('/etc/passwd') as f:
... | Python | zaydzuhri_stack_edu_python |
function training_step self batch batch_idx
begin
comment forward pass
for i in range length batch
begin
if ndim == 3
begin
comment Dataset returns already batched data and the first dimension of size 1
comment added by DataLoader is excess.
set batch at i = squeeze batch at i dim=0
end
end
set tuple ids mask = batch
s... | def training_step(self, batch, batch_idx):
# forward pass
for i in range(len(batch)):
if batch[i].ndim == 3:
# Dataset returns already batched data and the first dimension of size 1
# added by DataLoader is excess.
batch[i] = batch[i].squeeze(d... | Python | nomic_cornstack_python_v1 |
string Identity class is a base class for User and Org.
import uuid
import jwt
if __name__ != string tahoe.identity.identity
begin
import sys , os
set path = list string .. join path string .. string .. + path
del sys os
end
import tahoe
from tahoe.parse import parse , getclass
from error import InvalidUserHashError
se... | """
Identity class is a base class for User and Org.
"""
import uuid
import jwt
if __name__ != 'tahoe.identity.identity':
import sys, os
sys.path = ['..', os.path.join('..', '..')] + sys.path
del sys, os
import tahoe
from tahoe.parse import parse, getclass
from .error import InvalidUserHashError
P = {"... | Python | zaydzuhri_stack_edu_python |
from collections import deque
function is_prime n
begin
if n < 4
begin
return n > 1
end
if n % 2 == 0 or n % 3 == 0
begin
return false
end
set d = 3
while d * d <= n
begin
if n % d == 0
begin
return false
end
set d = d + 2
end
return true
end function
function isCircularPrime n
begin
if not call is_prime n
begin
return... | from collections import deque
def is_prime(n):
if n < 4:
return n > 1
if n % 2 == 0 or n % 3 == 0:
return False
d = 3
while d * d <= n:
if n % d == 0:
return False
d += 2
return True
def isCircularPrime(n):
if not is_prime(n):
return False
numQ = deque(str(n))
for i in xrange(len(str(n))-1):
nu... | Python | zaydzuhri_stack_edu_python |
function bfs graph s
begin
set visited = list false * length graph
set queue = list
append queue s
set visited at s = true
while queue
begin
set s = pop queue 0
end
end function | def bfs(graph,s):
visited = [False]*(len(graph))
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0) | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy
import os
import pytesseract
comment Get grayscale image
function get_grayscale image
begin
return call cvtColor image COLOR_BGR2GRAY
end function
comment Thresholding
function thresholding image
begin
return call threshold image 0 255 THRESH_BINARY + THRESH_OTSU at 1
end function
function recog... | import cv2
import numpy
import os
import pytesseract
# Get grayscale image
def get_grayscale(image):
return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Thresholding
def thresholding(image):
return cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
def recognize(im):
# Convert image to cv2 forma... | Python | zaydzuhri_stack_edu_python |
import numpy as np
comment hyper parameters for reward function
set DISCOUNT_FACTOR = 0.99
set PUNISHMENT_FOR_DEATH = - 10
set NO_REWARD_PENALTY = - 0.05
function discount rewards
begin
comment compute discounted rewards
set cumulative_discounted_rewards = zeros length rewards
set partial_sum = 0.0
for i in reversed ra... | import numpy as np
#hyper parameters for reward function
DISCOUNT_FACTOR = 0.99
PUNISHMENT_FOR_DEATH = -10
NO_REWARD_PENALTY = -0.05
def discount(rewards):
# compute discounted rewards
cumulative_discounted_rewards = np.zeros(len(rewards))
partial_sum = 0.0
for i in reversed(range(0, len(rewards))):
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
from time import time
from scheduling import problem2fma , variable
import z3_wrapper
comment <-------- IF YOU WANT TO COMPARE YOUR DPLL WITH Z3, ENABLE THIS
set DO_YOU_WANT_TO_COMPARE_YOUR_DPLL_WITH_Z3 = false
function show_the_scheduling model tasks time_horizon is_z3_used
begin
string Shows... | #!/usr/bin/python3
from time import time
from scheduling import problem2fma, variable
import z3_wrapper
DO_YOU_WANT_TO_COMPARE_YOUR_DPLL_WITH_Z3 = False # <-------- IF YOU WANT TO COMPARE YOUR DPLL WITH Z3, ENABLE THIS
def show_the_scheduling(model, tasks, time_horizon, is_z3_used):
"""
Shows the ... | Python | zaydzuhri_stack_edu_python |
import struct
import threading
import random
import pickle
import sys
import socket
import struct
class NetEmuClient extends Thread
begin
string Create NetEmuClient recv_func: receive callback ip: ip of server port: port of server
function __init__ self recv_func ip port
begin
call __init__ self
set recv_func = recv_fu... | import struct
import threading
import random
import pickle
import sys
import socket
import struct
class NetEmuClient(threading.Thread):
""" Create NetEmuClient
recv_func: receive callback
ip: ip of server
port: port of server
"""
def __init__(self, recv_func, ip:str, port:int):
threadin... | Python | zaydzuhri_stack_edu_python |
for line in fhand
begin
set letters = list line
for letter in letters
begin
comment value = dict.get(key, default)
set letdict at letter = get letdict letter 1 + 1
end
end
print string Letter Count
for key in letdict
begin
print string %s %d % tuple key letdict at key
end | for line in fhand:
letters = list(line)
for letter in letters:
letdict[letter] = letdict.get(letter, 1) + 1 #value = dict.get(key, default)
print("Letter\tCount")
for key in letdict:
print("%s\t%d" % (key, letdict[key]))
| Python | zaydzuhri_stack_edu_python |
function saveShape self name coords
begin
set warningLabel = call Label frameCreateShapes text=string You haven't entered name or coordinates of the shape properly.
set successLabel = call Label frameCreateShapes text=string Shape Saved Successfully!
set shapeName = get name
if shapeName and coords
begin
set SHAPES at ... | def saveShape(self, name, coords):
warningLabel = Label(self.frameCreateShapes,
text="You haven't entered name or coordinates of the shape properly.")
successLabel = Label(self.frameCreateShapes,
text="Shape Saved Successfully!")
shapeNam... | Python | nomic_cornstack_python_v1 |
from algorithms.gradient_descent import *
from algorithms.logistic_regression import *
function iterations_to_achieve_minimum_error min_value initial_u=1 initial_v=1 learning_rate=0.1
begin
set n_iterations = 1
set u = initial_u
set v = initial_v
set actual_value = call error_surface_result u v
while actual_value > min... | from algorithms.gradient_descent import *
from algorithms.logistic_regression import *
def iterations_to_achieve_minimum_error(min_value, initial_u=1, initial_v=1, learning_rate=0.1):
n_iterations = 1
u = initial_u
v = initial_v
actual_value = error_surface_result(u, v)
while actual_value > min_value:
actual_v... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.