code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function test_greedy_one_or_more
begin
set grammar = string S: A+ A*; terminals A: "a";
set g = call from_string grammar
set p = call GLRParser g
set forest = parse p string a a a a a a
assert length forest == 6
comment But greedy variant has only one solution where first A+! collects all tokens.
set grammar = string S... | def test_greedy_one_or_more():
grammar = r"""
S: A+ A*;
terminals
A: "a";
"""
g = Grammar.from_string(grammar)
p = GLRParser(g)
forest = p.parse("a a a a a a")
assert len(forest) == 6
# But greedy variant has only one solution where first A+! collects all tokens.
grammar = ... | Python | nomic_cornstack_python_v1 |
function __create_subscription self patron_id topic
begin
set _topic_subscribers at patron_id at topic = _topic_subscribers at patron_id at topic + 1
if _topic_subscribers at patron_id at topic == 1
begin
info format string Creating a new GCP subscription resource for patron {}, topic {} patron_id topic
comment We just... | def __create_subscription(self, patron_id, topic):
self._topic_subscribers[patron_id][topic] += 1
if self._topic_subscribers[patron_id][topic] == 1:
self._logger.info("Creating a new GCP subscription resource for "
"patron {}, topic {}".format(patron_id, topic))... | Python | nomic_cornstack_python_v1 |
import numpy as np
set A = randn 3 3
set B = randn 3 3
set C = randn 3 1
print type A shape type shape
print C C at 0
print
print A A at 0 A at 0 at 0
print
print A call cond A call cond A string fro
print B call cond B call cond B string fro
print
set x1 = reshape array range 9.0 tuple 3 3
set x2 = array range 3.0
pri... | import numpy as np
A = np.random.randn(3, 3)
B = np.random.randn(3, 3)
C = np.random.randn(3, 1)
print(type(A), A.shape, type(A.shape))
print(C, C[0])
print()
print(A, A[0], A[0][0])
print()
print(A, np.linalg.cond(A), np.linalg.cond(A, 'fro'))
print(B, np.linalg.cond(B), np.linalg.cond(B, 'fro'))
print()
x1 = np.aran... | Python | zaydzuhri_stack_edu_python |
function set_error_callback cbfun
begin
string Sets the error callback. Wrapper for: GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun);
global _error_callback
set previous_callback = _error_callback
if cbfun is none
begin
set cbfun = 0
end
set c_cbfun = call _GLFWerrorfun cbfun
set _error_callback = tuple cbfun c_c... | def set_error_callback(cbfun):
'''
Sets the error callback.
Wrapper for:
GLFWerrorfun glfwSetErrorCallback(GLFWerrorfun cbfun);
'''
global _error_callback
previous_callback = _error_callback
if cbfun is None:
cbfun = 0
c_cbfun = _GLFWerrorfun(cbfun)
_error_callback =... | Python | jtatman_500k |
import csv , os
function ajoutcolonne reader outputfile
begin
string fonction qui permet d'ajouter l'information du fichier result dans une nouvelle colonne du fichier de sortie praat. args : le lecteur de csv du fichier de dortie PRAAT, le nom de fichier de sortie sortie : aucune
set liste = list
set row0 = next read... | import csv, os
def ajoutcolonne(reader, outputfile):
"""
fonction qui permet d'ajouter l'information du fichier result dans une nouvelle colonne du fichier de sortie praat.
args : le lecteur de csv du fichier de dortie PRAAT, le nom de fichier de sortie
sortie : aucune
"""
liste=[]
row0 = ... | Python | zaydzuhri_stack_edu_python |
function unfollow self followerId followeeId
begin
set fol at followerId = get fol followerId list
if followeeId in fol at followerId
begin
set index = index fol at followerId followeeId
set fol at followerId = fol at followerId at slice : index : + fol at followerId at slice index + 1 : :
end
end function | def unfollow(self, followerId, followeeId):
self.fol[followerId] = self.fol.get(followerId, [])
if followeeId in self.fol[followerId]:
index = self.fol[followerId].index(followeeId)
self.fol[followerId] = self.fol[followerId][:index] + self.fol[followerId][index+1:] | Python | nomic_cornstack_python_v1 |
import cv2
from deepface import DeepFace
set faceCascade = call CascadeClassifier haarcascades + string haarcascade_frontalface_default.xml
set cap = call VideoCapture 0
comment check if webcam is opened
if not call isOpened
begin
set cap = call VideoCapture 1
end
if not isOpened
begin
raise call IOError string Cannot ... | import cv2
from deepface import DeepFace
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
# check if webcam is opened
if not cap.isOpened():
cap = cv2.VideoCapture(1)
if not cap.isOpened:
raise IOError("Cannot open webcam"... | Python | zaydzuhri_stack_edu_python |
function __init__ self fp _fields=list
begin
set fp = fp + string .sqlite
set index = none
set fp = fp
set _fields = _fields
if exists path fp
begin
set index = call SqliteDict fp autocommit=true
end
else
begin
set index = call SqliteDict fp autocommit=true
set index at string index = dictionary comprehension field : d... | def __init__(self,fp,_fields=[]):
fp = fp+".sqlite"
self.index = None
self.fp = fp
self._fields = _fields
if os.path.exists(fp):
self.index = SqliteDict(fp, autocommit=True)
else:
self.index = SqliteDict(fp, autoco... | Python | nomic_cornstack_python_v1 |
function __winner_status self
begin
comment str() to avoid the case of 0 return False
if call __horizontal_winner
begin
return tuple string call get_current_player min call __horizontal_winner HORIZONTAL_WINNING
end
else
if call __vertical_winner
begin
return tuple string call get_current_player min call __vertical_win... | def __winner_status(self):
# str() to avoid the case of 0 return False
if self.__horizontal_winner():
return str(self.get_current_player()), min(self.__horizontal_winner()),\
self.HORIZONTAL_WINNING
elif self.__vertical_winner():
return str(self.g... | Python | nomic_cornstack_python_v1 |
function generate_basis
begin
function _generate_basis
begin
string Return a `Dict` with basis.
from aiida.orm import Dict
set basis = dict string pao-energy-shift string 300 meV ; string %block pao-basis-sizes string Si DZP SiDiff DZP %endblock pao-basis-sizes
return dictionary dict=basis
end function
return _generate... | def generate_basis():
def _generate_basis():
"""Return a `Dict` with basis."""
from aiida.orm import Dict
basis = {
'pao-energy-shift': '300 meV',
'%block pao-basis-sizes': """
Si DZP
SiDiff DZP
%endblock pao-basis-sizes""",
}
return... | Python | nomic_cornstack_python_v1 |
function _make_linear_ramp white
begin
set ramp = list
set tuple r g b = white
for i in range 255
begin
extend ramp tuple r * i / 255 g * i / 255 b * i / 255
end
return ramp
end function | def _make_linear_ramp(white):
ramp = []
r, g, b = white
for i in range(255):
ramp.extend((r*i/255, g*i/255, b*i/255))
return ramp | Python | nomic_cornstack_python_v1 |
function requested_currency self requested_currency
begin
set _requested_currency = requested_currency
end function | def requested_currency(self, requested_currency):
self._requested_currency = requested_currency | Python | nomic_cornstack_python_v1 |
function Invitaciones request evento_id
begin
set evento = all
set invitaciones = all
return call render request string invitaciones.html dict string invitaciones invitaciones
end function | def Invitaciones(request,evento_id):
evento = Evento.objects.all()
invitaciones= Invitacion.objects.all()
return render(request,'invitaciones.html',{'invitaciones':invitaciones}) | Python | nomic_cornstack_python_v1 |
from grab import Grab
set g = call Grab
call go string google.ru
comment вбиваем запрос 'grab python' в строку поиска (name='q')
call set_input string q string grab python
comment нажимаем кнопку - поиск
call submit submit_name=string btnG
comment используем селектор с выражениями xpath
for y in call text
begin
comment... | from grab import Grab
g = Grab()
g.go('google.ru')
# вбиваем запрос 'grab python' в строку поиска (name='q')
g.doc.set_input('q', 'grab python')
# нажимаем кнопку - поиск
g.doc.submit(submit_name='btnG')
# используем селектор с выражениями xpath
for y in g.doc.select("//h3[@class = 'r']//a").text():
#print(y.text... | Python | zaydzuhri_stack_edu_python |
function wholeunits2grams self wholeunit
begin
if _wholeunits2grams is none
begin
return none
end
try
begin
return _wholeunits2grams at lower wholeunit
end
except KeyError
begin
return none
end
end function | def wholeunits2grams(self, wholeunit):
if self._wholeunits2grams is None:
return None
try:
return self._wholeunits2grams[wholeunit.lower()]
except KeyError:
return None | Python | nomic_cornstack_python_v1 |
function json_date date=none
begin
if not date
begin
return string 1969-12-31T23:59:59
end
return join string T split string date string
end function | def json_date(date=None):
if not date: return '1969-12-31T23:59:59'
return 'T'.join(str(date).split(' ')) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment @Time : 2018/12/6 21:34
comment @Author : lemon_huahua
comment @Email : 204893985@qq.com
comment @File : class_for循环.py
comment s='python13'#8
comment L=[1,0.2,'桃子','旅行者','莉红']#5
comment t=(1,5,6,'hi','how are you')#5
comment d={'name':'katt','age':18,'money':'10w'}#3
comment #练习题:... | # -*- coding: utf-8 -*-
# @Time : 2018/12/6 21:34
# @Author : lemon_huahua
# @Email : 204893985@qq.com
# @File : class_for循环.py
# s='python13'#8
# L=[1,0.2,'桃子','旅行者','莉红']#5
# t=(1,5,6,'hi','how are you')#5
# d={'name':'katt','age':18,'money':'10w'}#3
# #练习题:
# #请利用for循环 依次打印字典d里面的value值
# for a in d.values(... | Python | zaydzuhri_stack_edu_python |
function pc_noutput_items self
begin
return call softbit_msg_sink_f_sptr_pc_noutput_items self
end function | def pc_noutput_items(self):
return _ccsds_swig.softbit_msg_sink_f_sptr_pc_noutput_items(self) | Python | nomic_cornstack_python_v1 |
import json
import socket
import sys
import threading
import modell
set BUFFER_SIZE = 2 ^ 10
set maxSize = 100000
set CLOSING = string Application closing...
set CONNECTION_ABORTED = string Connection aborted
set CONNECTED_PATTERN = string Client connected: {}:{}
set ERROR_ARGUMENTS = string Provide port number as the ... | import json
import socket
import sys
import threading
import modell
BUFFER_SIZE = 2 ** 10
maxSize = 100000
CLOSING = "Application closing..."
CONNECTION_ABORTED = "Connection aborted"
CONNECTED_PATTERN = "Client connected: {}:{}"
ERROR_ARGUMENTS = "Provide port number as the firstcommand line argument"
ERROR_OCCURRED ... | Python | zaydzuhri_stack_edu_python |
import math
import numpy as np
from stl import mesh
function subdivision pt1 pt2 pt3 n
begin
string Convert STL data into unit normal vectors and points on the triangles Input: Triangles (three 3d points) (3 numpy arrays) a number of subdivisions to perform Output: Points on those triangles unit normal vectors points
c... | import math
import numpy as np
from stl import mesh
def subdivision(pt1, pt2, pt3, n):
"""
Convert STL data into unit normal vectors and points on the triangles
Input: Triangles (three 3d points) (3 numpy arrays)
a number of subdivisions to perform
Output: Points on those triangles
unit normal vectors ... | Python | zaydzuhri_stack_edu_python |
comment N = int(raw_input())
set fact = 1
if N < 0
begin
set fact = 0
end
if N > 1
begin
for i in range 1 N + 1
begin
set fact = fact * i
end
end
print fact | #N = int(raw_input())
fact = 1
if N< 0:
fact=0
if N>1:
for i in range(1,N+1):
fact = fact * i
print(fact)
| Python | zaydzuhri_stack_edu_python |
import models.common
import models.skills
import util
class Enemy extends Entity
begin
function __init__ self maxHP name attack_damage
begin
call __init__ maxHP name attack_damage
end function
function calculate_damage_taken self attack_word
begin
raise NotImplementedError
end function
end class
class TriangleEnemy ext... | import models.common
import models.skills
import util
class Enemy(models.common.Entity):
def __init__(self, maxHP, name, attack_damage):
super(Enemy, self).__init__(maxHP, name, attack_damage)
def calculate_damage_taken(self, attack_word):
raise NotImplementedError
class TriangleEn... | Python | zaydzuhri_stack_edu_python |
function testRemoveIssuesFromHotlists_RemoveIssueNotInHotlist self
begin
set issue1 = call MakeTestIssue 789 1 string sum1 string New 111 issue_id=78901
call TestAddIssue issue1
set issue2 = call MakeTestIssue 789 2 string sum2 string New 111 issue_id=78902
call TestAddIssue issue2
set hotlist1 = call CreateHotlist cnx... | def testRemoveIssuesFromHotlists_RemoveIssueNotInHotlist(self):
issue1 = fake.MakeTestIssue(789, 1, 'sum1', 'New', 111, issue_id=78901)
self.services.issue.TestAddIssue(issue1)
issue2 = fake.MakeTestIssue(789, 2, 'sum2', 'New', 111, issue_id=78902)
self.services.issue.TestAddIssue(issue2)
hotlist1 ... | Python | nomic_cornstack_python_v1 |
class TreeNode
begin
function __init__ self val=0 left=none right=none
begin
set val = val
set left = left
set right = right
end function
end class
function find_leaves node result level
begin
if not node
begin
return - 1
end
set left_level = call find_leaves left result level + 1
set right_level = call find_leaves rig... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_leaves(node, result, level):
if not node:
return -1
left_level = find_leaves(node.left, result, level + 1)
right_level = find_leaves(node.right, ... | Python | jtatman_500k |
string 5. Языки Каждый из N школьников некоторой школы знает Mi языков. Определите, какие языки знают все школьники и языки, которые знает хотя бы один из школьников. Входные данные Первая строка входных данных содержит количество школьников N. Далее идет N чисел Mi, после каждого из чисел идет Mi строк, содержащих наз... | """
5. Языки
Каждый из N школьников некоторой школы знает Mi языков. Определите, какие языки знают все школьники и языки, которые знает хотя бы один из школьников.
Входные данные
Первая строка входных данных содержит количество школьников N. Далее идет N чисел Mi, после каждого из чисел идет Mi строк, содержащих на... | Python | zaydzuhri_stack_edu_python |
function makeCircle x y
begin
set canvas = call makeEmptyPicture 400 400
call addOvalFilled canvas x y 50 50 red
return canvas
end function
function bounce
begin
set x = 1
set y = 1
set i = 1
set dx = 10
set dy = - 10
while i < 200
begin
set frame = call makeCircle x y
if x < 0 or x > 350
begin
set dx = - dx
end
if y <... | def makeCircle(x,y):
canvas = makeEmptyPicture(400,400)
addOvalFilled(canvas, x, y, 50, 50, red)
return canvas
def bounce():
x = 1
y = 1
i = 1
dx = 10
dy = -10
while i < 200:
frame = makeCircle(x,y)
if x < 0 or x > 350:
dx = -dx
if y < 0 or y >350:
dy = -dy
x += dx
y ... | Python | zaydzuhri_stack_edu_python |
comment Answer to isLucky
comment https://app.codesignal.com/arcade/intro/level-3/3AdBC97QNuhF6RwsQ
function isLucky n
begin
set n = string n
set length = length n // 2
return sum generator expression integer i for i in n at slice : length : == sum generator expression integer i for i in n at slice length : :
end fun... | # Answer to isLucky
# https://app.codesignal.com/arcade/intro/level-3/3AdBC97QNuhF6RwsQ
def isLucky(n):
n = str(n)
length = len(n)//2
return sum(int(i) for i in n[:length]) == sum(int(i) for i in n[length:])
| Python | zaydzuhri_stack_edu_python |
function random_dataset max_len=20 num=2000 name=string random seed=0
begin
seed seed
comment Only letters are in the base vocabulary
write open string ../data/ { name } .vocab string w join string list ascii_letters
with open string ../data/ { name } .src string w as src ; open string ../data/ { name } .tgt string w ... | def random_dataset(max_len: int = 20, num: int = 2000, name: str = 'random', seed: int = 0) -> None:
random.seed(seed)
# Only letters are in the base vocabulary
open(f'../data/{name}.vocab', 'w').write('\n'.join(list(string.ascii_letters)))
with open(f'../data/{name}.src', 'w') as src, open(f'../data... | Python | nomic_cornstack_python_v1 |
import socket
import threading
class Client extends Thread
begin
function __init__ self host=string 127.0.0.1 port=9999 size=1024
begin
call __init__ self
set host = host
set port = port
set size = size
set tcp = call socket AF_INET SOCK_STREAM
call connect tuple host port
end function
function run self
begin
while tru... | import socket
import threading
class Client(threading.Thread):
def __init__(self, host = '127.0.0.1', port = 9999, size = 1024):
threading.Thread.__init__(self)
self.host = host
self.port = port
self.size = size
self.tcp = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sel... | Python | zaydzuhri_stack_edu_python |
from generator import Pass
function generate_new_pass variantes password
begin
set nodo_password = call Pass password
set nodos_frontera = list
set nodo_visitados = list
for tuple key items in items variantes
begin
for word in items
begin
if word != password
begin
append nodos_frontera call Pass word
end
end
end
set ... | from generator import Pass
def generate_new_pass(variantes, password):
nodo_password = Pass(password)
nodos_frontera = []
nodo_visitados = []
for key, items in variantes.items():
for word in items:
if word != password:
nodos_frontera.append(Pass(word))
... | Python | zaydzuhri_stack_edu_python |
comment noqa: E501 # noqa: E501
function __init__ self line_item_id=none quantity=none
begin
set _line_item_id = none
set _quantity = none
set discriminator = none
if line_item_id is not none
begin
set line_item_id = line_item_id
end
if quantity is not none
begin
set quantity = quantity
end
end function | def __init__(self, line_item_id=None, quantity=None): # noqa: E501 # noqa: E501
self._line_item_id = None
self._quantity = None
self.discriminator = None
if line_item_id is not None:
self.line_item_id = line_item_id
if quantity is not None:
self.quantity... | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
assert initialized msg string Annotation should be initialized.
set world_bbox_str = format string {3:.2f} {4:.2f} {5:.2f} {0:.2f} {1:.2f} {2:.2f} *self.world_bbox
set bbox_str = format string {:0.3f} {:0.3f} {:0.3f} {:0.3f} *self.box
if confidence is not none
begin
return format string {0} ... | def __str__(self):
assert self.initialized, ("Annotation should be initialized.")
world_bbox_str = "{3:.2f} {4:.2f} {5:.2f} {0:.2f} {1:.2f} {2:.2f}".format(
*self.world_bbox
)
bbox_str = "{:0.3f} {:0.3f} {:0.3f} {:0.3f}".format(*self.box)
if self.confidence is not Non... | Python | nomic_cornstack_python_v1 |
import json
comment opening and reading
set file = open string airlines.csv string r
comment finding unique airports
set airports = list
set airport_data = dict
set count = 0
set firstLine = true
for line in file
begin
comment removing header line of file
if firstLine
begin
set firstLine = false
continue
end
append a... | import json
# opening and reading
file = open("airlines.csv",'r')
# finding unique airports
airports = []
airport_data = {}
count = 0
firstLine = True
for line in file:
if firstLine: #removing header line of file
firstLine = False
continue
airports.append(line.split('"')[1])
unique_airp... | Python | zaydzuhri_stack_edu_python |
function test_nrows_gtiff_object self
begin
assert equal call _test_object landsat_gtiff at 1 224
end function | def test_nrows_gtiff_object(self):
self.assertEqual(_test_object(landsat_gtiff)[1], 224) | Python | nomic_cornstack_python_v1 |
function email_an_estimate self estimate_id email attachment=none
begin
set url = base_url + estimate_id + string /email
set json_object = dumps to json email
set data = dict string JSONString json_object
if attachment is not none
begin
set file_list = list
for value in attachment
begin
set attachments = dict string a... | def email_an_estimate(self, estimate_id, email, attachment=None):
url = base_url + estimate_id + '/email'
json_object = dumps(email.to_json())
data = {
'JSONString': json_object
}
if attachment is not None:
file_list = []
for value in attac... | Python | nomic_cornstack_python_v1 |
set data = list string Texas string Blue string Dog
for item in data
begin
print type item
end | data = ["Texas", "Blue", "Dog"]
for item in data:
print(type(item))
| Python | jtatman_500k |
function ensureDetection self
begin
if APs == false
begin
debug string analysis attempted before event detection...
call detect
end
end function | def ensureDetection(self):
if self.APs==False:
self.log.debug("analysis attempted before event detection...")
self.detect() | Python | nomic_cornstack_python_v1 |
class BookShelf
begin
function __init__ self *books
begin
set books = books
end function
function __str__ self
begin
return string BookShelf with { length books } books.
end function
end class
class Book extends BookShelf
begin
function __init__ self name
begin
set name = name
end function
function __str__ self
begin
r... | class BookShelf:
def __init__(self, *books):
self.books = books
def __str__(self):
return f"BookShelf with {len(self.books)} books."
class Book(BookShelf):
def __init__(self, name):
self.name = name
def __str__(self):
return f"Book {self.name}"
book = Book("HP")
book... | Python | zaydzuhri_stack_edu_python |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other):
return not self == other | Python | nomic_cornstack_python_v1 |
comment lista = [1,2,3,4,5,6,7,8,9]
comment for valor in lista:
comment pass
comment nuevo_rango = range(10,20)
comment for valor in nuevo_rango:
comment print(valor)
comment nuevo_rango = range(0,3)
set nombre = list string Karla string Santos string Narciso
set apellido = list string Garcia string Gomez string Holgui... | # lista = [1,2,3,4,5,6,7,8,9]
# for valor in lista:
# pass
# nuevo_rango = range(10,20)
# for valor in nuevo_rango:
# print(valor)
# nuevo_rango = range(0,3)
nombre= ["Karla", "Santos", "Narciso"]
apellido= ["Garcia", "Gomez", "Holguin"]
for completo in range(0,1000000):
print("La vuelta numero... | Python | zaydzuhri_stack_edu_python |
import sys
import heapq
from operator import itemgetter
from collections import deque , defaultdict
from bisect import bisect_left , bisect_right
set input = readline
call setrecursionlimit 10 ^ 7
function sol
begin
set tuple N x = map int split input
if x == 1 or x == 2 * N - 1
begin
print string No
end
else
begin
pri... | import sys
import heapq
from operator import itemgetter
from collections import deque, defaultdict
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
def sol():
N, x = map(int, input().split())
if x == 1 or x == 2 * N - 1:
print('No')
else:
... | Python | zaydzuhri_stack_edu_python |
string Pogo Jump 2 Given an integer list where each number represents the number of hops you can make, determine whether you can reach to the last index starting at index 0. Return True or False
function canJump nums
begin
set x = 1
for y in nums at slice : : - 1
begin
set x = max x - 1 y
if x == 0
begin
return false... | '''
Pogo Jump 2
Given an integer list where each number represents the number of hops you can make, determine whether you can reach to the last index starting at index 0.
Return True or False
'''
def canJump(nums):
x = 1
for y in nums[::-1]:
x = max(x-1,y)
if x == 0:
return False
return True
n... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment dictiteration.py
set dictionary = dict string this string that ; string those string thar ; 23 18 ; none 5 | #! /usr/bin/env python
# dictiteration.py
dictionary = {'this':'that','those':'thar',23:18,None:5}
| Python | zaydzuhri_stack_edu_python |
for i in range n - 2
begin
if max l at i l at i + 2 < min
begin
set min = max l at i l at i + 2
set ans = i
end
end
print ans + 1 min | for i in range(n-2):
if max(l[i],l[i+2]) < min:
min = max(l[i],l[i+2])
ans = i
print(ans+1, min) | Python | zaydzuhri_stack_edu_python |
string Contains CheckerBot class
from typing import Callable , Tuple
from util import Coord
from management import shotfinder
from huntingbot import HuntingBot
class CheckerBot extends HuntingBot
begin
string Shoots to the cell with the statistically highest chance of a ship being there, while only hitting every second... | """Contains CheckerBot class"""
from typing import Callable, Tuple
from ..util import Coord
from ..management import shotfinder
from .huntingbot import HuntingBot
class CheckerBot(HuntingBot):
"""Shoots to the cell with the statistically highest chance
of a ship being there, while only hitting every second ... | Python | zaydzuhri_stack_edu_python |
import functions as fn
comment ask users: single article, or Most read (10 articles)
set bbc_url = string https://www.bbc.com
set instruction = string Please type 'M' for Most Read articles, 'S' for a single article, 'X' to exit:
set resp = string
while upper resp != string X
begin
set resp = input instruction
if uppe... | import functions as fn
# ask users: single article, or Most read (10 articles)
bbc_url = 'https://www.bbc.com'
instruction = "Please type 'M' for Most Read articles, 'S' for a single article, 'X' to exit: "
resp = ''
while resp.upper() != 'X':
resp = input(instruction)
if resp.upper() == 'M':
# most ... | Python | zaydzuhri_stack_edu_python |
comment coding: UTF-8
import math
import matplotlib.pyplot as plt
comment シグモイド関数
function sigmoid x
begin
return 1.0 / 1.0 + exp - x
end function
comment ニューロン
class Neuron
begin
set input_sum = 0.0
set output = 0.0
comment 入力値を加算する
function setInput self cinp
begin
set input_sum = input_sum + inp
end function
comment... | # coding: UTF-8
import math
import matplotlib.pyplot as plt
# シグモイド関数
def sigmoid(x):
return 1.0 / (1.0 + math.exp(-x))
# ニューロン
class Neuron:
input_sum = 0.0
output = 0.0
# 入力値を加算する
def setInput(self, cinp):
self.input_sum += inp
# print(self.input_sum)
# 入力値をシグモイド関数を使って評価
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import os
comment turn off pink warning boxes
import warnings
filter warnings string ignore
is file path string aug_train.csv
function get_aug_train url cached=false
begin
string This function reads in url for aug_train data and writes data to a csv file if cached == False or if c... | import pandas as pd
import numpy as np
import os
# turn off pink warning boxes
import warnings
warnings.filterwarnings("ignore")
os.path.isfile('aug_train.csv')
def get_aug_train(url, cached=False):
'''
This function reads in url for aug_train data and writes data to
a csv file if cached == False or i... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment In[1]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
call magic string matplotlib inline
call magic string load_ext autoreload
call magic string autoreload 2
comment In[2]:
set tuple X Y = call make_circles n_samples=1500 noise=0.09 factor=0.6
set x = X at... | # coding: utf-8
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
get_ipython().magic(u'matplotlib inline')
get_ipython().magic(u'load_ext autoreload')
get_ipython().magic(u'autoreload 2')
# In[2]:
X, Y = datasets.make_circles(n_samples = 1500, noise = 0.09, factor = 0.6)
x ... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function shortestPalindrome2 self s
begin
if not s
begin
return string
end
comment 返回两个单相同的前缀长度
function helper s1 s2
begin
set tmp = 0
for tuple idx val in enumerate zip s1 at slice : : - 1 s2 0
begin
comment print(idx, val)
if val at 0 == val at 1
begin
set tmp = tmp + 1
end
end
return tmp
end... | class Solution:
def shortestPalindrome2(self, s: str) -> str:
if not s:
return ""
# 返回两个单相同的前缀长度
def helper(s1, s2):
tmp = 0
for idx, val in enumerate(zip(s1[::-1], s2), 0):
# print(idx, val)
if val[0] == val[1]:
... | Python | zaydzuhri_stack_edu_python |
import random
import googlesearch
import nltk
import requests
from bs4 import BeautifulSoup
from google.cloud import datastore
from typing import Dict , List
call download string punkt
call download string brown
from nltk.corpus import brown
set sent_tokenizer = load data string tokenizers/punkt/english.pickle
class Co... | import random
import googlesearch
import nltk
import requests
from bs4 import BeautifulSoup
from google.cloud import datastore
from typing import Dict, List
nltk.download('punkt')
nltk.download('brown')
from nltk.corpus import brown
sent_tokenizer = nltk.data.load("tokenizers/punkt/english.pickle")
class Corpus:
... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
function plot_images images titles n_rows n_cols
begin
set tuple fig ax = call subplots
for tuple i img in enumerate images
begin
subplot n_rows n_cols i + 1
image show img
title plt titles at i
end
comment plt.axis("off")
comment plt.title("angle : {}".format(i, str_labels[i]))
comment ... | import matplotlib.pyplot as plt
def plot_images(images, titles, n_rows, n_cols):
fig, ax = plt.subplots()
for i, img in enumerate(images):
plt.subplot(n_rows, n_cols, i+1)
plt.imshow(img)
plt.title(titles[i])
# plt.axis("off")
# plt.title("angle : {}".format(i, ... | Python | zaydzuhri_stack_edu_python |
string Created on Sep 12, 2017 @author: EDWIN
import numpy as np
from random import choice
from numpy import array , dot , random
import operator
import math
from datetime import datetime
from pylab import ylim
import matplotlib.pyplot as plt
set start_time = now
comment Sum the squares of the first 20 odd numbers.
fun... | '''
Created on Sep 12, 2017
@author: EDWIN
'''
import numpy as np
from random import choice
from numpy import array, dot, random
import operator
import math
from datetime import datetime
from pylab import ylim
import matplotlib.pyplot as plt
start_time = datetime.now()
# Sum the squares of the first 20 odd numbers... | Python | zaydzuhri_stack_edu_python |
import sqlite3
from pymystem3 import Mystem
import re
function search str
begin
comment подключаемся к базе данных
set conn = call connect string selskayapravda.db
set answers = list
set c = call cursor
set mystem = call Mystem
set lemSearchStr = join string call lemmatize str at slice : - 1 :
set dataBaseAsk = tup... | import sqlite3
from pymystem3 import Mystem
import re
def search(str):
# подключаемся к базе данных
conn = sqlite3.connect('selskayapravda.db')
answers = []
c = conn.cursor()
mystem = Mystem()
lemSearchStr = ''.join(mystem.lemmatize(str))[:-1]
dataBaseAsk = ('%' + lemSear... | Python | zaydzuhri_stack_edu_python |
function _get_sortgo self
begin
string Get function for sorting GO terms in a list of namedtuples.
if string sortgo in kws
begin
return kws at string sortgo
end
return prt_attr at string sort + string
end function | def _get_sortgo(self):
"""Get function for sorting GO terms in a list of namedtuples."""
if 'sortgo' in self.datobj.kws:
return self.datobj.kws['sortgo']
return self.datobj.grprdflt.gosubdag.prt_attr['sort'] + "\n" | Python | jtatman_500k |
function test_normalize_headers
begin
set headers = list string AllocationTransferAgencyIdentifier string BeginningPeriodOfAvailability string flex_mycol string FLEX_ANOTHER
set mapping = dict string allocationtransferagencyidentifier string ata ; string beginningperiodofavailability string boa
set result = call normal... | def test_normalize_headers():
headers = [
'AllocationTransferAgencyIdentifier', 'BeginningPeriodOfAvailability', 'flex_mycol', 'FLEX_ANOTHER'
]
mapping = {'allocationtransferagencyidentifier': 'ata', 'beginningperiodofavailability': 'boa'}
result = csvReader.normalize_headers(headers, False, ma... | Python | nomic_cornstack_python_v1 |
function __detokenize_translated_sentence__ self sentence_tokens num_vals unk_vals
begin
set id2word = call get_id2word
set num_vals = deque num_vals
set unk_vals = deque unk_vals
comment Convert word IDs to words
set words = list
for word_id in sentence_tokens
begin
set word = get id2word word_id string NAN
if word =... | def __detokenize_translated_sentence__(self, sentence_tokens, num_vals, unk_vals):
id2word = self.target_vocab.get_id2word()
num_vals = deque(num_vals)
unk_vals = deque(unk_vals)
# Convert word IDs to words
words = []
for word_id in sentence_tokens:
word = i... | Python | nomic_cornstack_python_v1 |
function namespace self
begin
return get pulumi self string namespace
end function | def namespace(self) -> Optional[str]:
return pulumi.get(self, "namespace") | Python | nomic_cornstack_python_v1 |
function get_comments self request_id=none project_name=none package_name=none
begin
set url = call _prepare_url request_id project_name package_name
set root = get root parse ET call http_GET url
set root = get root parse ET call http_GET url
set comments = dict
for c in find all string comment
begin
set c = call _co... | def get_comments(self, request_id=None, project_name=None,
package_name=None):
url = self._prepare_url(request_id, project_name, package_name)
root = root = ET.parse(http_GET(url)).getroot()
comments = {}
for c in root.findall('comment'):
c = self._commen... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from statsmodels.nonparametric.smoothers_lowess import lowess
import matplotlib.pyplot as plt
function autocorelation data
begin
comment Multiplicative Decomposition
set result_mul = call seasonal_decompose data at string value model=string multiplicative extrapolate_trend=string ... | import pandas as pd
import numpy as np
from statsmodels.nonparametric.smoothers_lowess import lowess
import matplotlib.pyplot as plt
def autocorelation(data):
# Multiplicative Decomposition
result_mul = seasonal_decompose(data['value'], model='multiplicative', extrapolate_trend='freq')
# Additive Decomp... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
from basic_crawler import BasicCrawler
class MaarivCrawler extends BasicCrawler
begin
function __init__ self
begin
call __init__ string https://www.maariv.co.il/news
set no_topic_news_links = list
set soup = call BeautifulSoup page_html string html.parser
set topic_dict = dict string poli... | from bs4 import BeautifulSoup
from .basic_crawler import BasicCrawler
class MaarivCrawler(BasicCrawler):
def __init__(self):
super(MaarivCrawler, self).__init__("https://www.maariv.co.il/news")
self.no_topic_news_links = []
self.soup = BeautifulSoup(self.page_html, "html.parser")
s... | Python | zaydzuhri_stack_edu_python |
class Print_
begin
function __init__ self
begin
pass
end function
function notify self title message
begin
print title
print message
end function
end class | class Print_:
def __init__(self):
pass
def notify(self, title, message):
print(title)
print(message)
| Python | zaydzuhri_stack_edu_python |
function isConflict self position chiffre
begin
for conflictPos in _conflictPositionDict at position
begin
if conflictPos in _grid and _grid at conflictPos == chiffre
begin
return true
end
end
return false
end function | def isConflict(self, position, chiffre):
for conflictPos in self._conflictPositionDict[position]:
if conflictPos in self._grid and self._grid[conflictPos] == chiffre:
return True
return False | Python | nomic_cornstack_python_v1 |
function dfs graph src vis
begin
global v
global e
set vis at src = 1
set v = v + 1
set e = e + length graph at src
comment print(src,end=" ")
for ng in graph at src
begin
if vis at ng == 0
begin
call dfs graph ng vis
end
end
end function
set t = integer input
for i in range t
begin
set tuple graph n = call makeGraph
s... | def dfs(graph,src,vis):
global v
global e
vis[src]=1
v+=1
e+=len(graph[src])
# print(src,end=" ")
for ng in graph[src]:
if vis[ng]==0:
dfs(graph,ng,vis)
t=int(input())
for i in range(t):
graph,n=makeGraph()
vis=[0]*(n+1)
flag=0
for i i... | Python | zaydzuhri_stack_edu_python |
function get_file_paths_from_directory directory_path
begin
set file_paths = list comprehension join directory_path file for file in list directory directory_path if is file join directory_path file
return file_paths
end function | def get_file_paths_from_directory(directory_path):
file_paths = [join(directory_path, file) for file in listdir(directory_path) if isfile(join(directory_path, file))]
return file_paths | Python | nomic_cornstack_python_v1 |
function teach_classifier self
begin
for i in used_classes
begin
call teach_one_class i
end
set all_words_count = 0
for i in keys words_count
begin
set all_words_count = all_words_count + words_count at i
end
end function | def teach_classifier(self):
for i in self.used_classes:
self.teach_one_class(i)
self.all_words_count = 0
for i in self.words_count.keys():
self.all_words_count += self.words_count[i] | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
set _binding_data = call _sort_membind_info call _get_core_membind_info
end function | def __init__(self):
self._binding_data = CPUInfo._sort_membind_info(self._get_core_membind_info()) | Python | nomic_cornstack_python_v1 |
function wc file_
begin
with open file_ as f
begin
set wc = 0
set chrs = 0
for tuple lc line in enumerate f 1
begin
set words = split line
set wc = wc + length words
set chrs = chrs + length line
end
return string { lc } { wc } { chrs } { file_ }
end
end function | def wc(file_):
with open(file_) as f:
wc = chrs = 0
for lc, line in enumerate(f, 1):
words = line.split()
wc += len(words)
chrs += len(line)
return f'{lc} {wc} {chrs} {file_}' | Python | nomic_cornstack_python_v1 |
function add_sparse_variables self opt_problem
begin
for var in call get_variables
begin
call addVar name lower=lower upper=upper value=value scale=scale
end
return
end function | def add_sparse_variables(self, opt_problem):
for var in self.model.get_variables():
opt_problem.addVar(
var.name,
lower=var.lower,
upper=var.upper,
value=var.value,
scale=var.scale,
)
return | Python | nomic_cornstack_python_v1 |
function checked_download dest url descr=none
begin
if is directory path dest
begin
set realdest = join path dest base name path url
end
else
begin
set realdest = dest
end
end function | def checked_download(dest, url, descr=None):
if os.path.isdir(dest):
realdest = os.path.join(dest, os.path.basename(url))
else:
realdest = dest | Python | nomic_cornstack_python_v1 |
import configparser
import psycopg2
from sql_queries import create_table_queries , drop_table_queries
function drop_tables cur conn
begin
string Deletes pre-existing tables to ensure our tables will be created without the database throwing errors. :param cur: a psycopg2 cursor for the database :param conn: a psycopg2 c... | import configparser
import psycopg2
from sql_queries import create_table_queries, drop_table_queries
def drop_tables(cur, conn):
"""
Deletes pre-existing tables to ensure our tables will be created without the database throwing errors.
:param cur: a psycopg2 cursor for the database
:param conn: a psy... | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
class Solution extends object
begin
function canCompleteCircuit self gas cost
begin
string :type gas: List[int] :type cost: List[int] :rtype: int
set ln = length gas
set delta = map lambda x y -> x - y gas cost
if sum delta < 0
begin
return - 1
end
set ind = 0
while ind < ln
begin
if delta at ind <... | # coding:utf-8
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
ln = len(gas)
delta = map(lambda x,y: x-y, gas, cost)
if sum(delta) < 0:
return -1
ind =... | Python | zaydzuhri_stack_edu_python |
function split_contest_to_targets self ballot_image contest targets
begin
set target_x_pos = list comprehension x at 0 for x in targets
set target_x_range = max target_x_pos - min target_x_pos
set target_y_pos = list comprehension x at 1 for x in targets
set target_y_range = max target_y_pos - min target_y_pos
set tupl... | def split_contest_to_targets(self, ballot_image, contest, targets):
target_x_pos = [x[0] for x in targets]
target_x_range = max(target_x_pos)-min(target_x_pos)
target_y_pos = [x[1] for x in targets]
target_y_range = max(target_y_pos)-min(target_y_pos)
l,u,r,d = contest
t... | Python | nomic_cornstack_python_v1 |
set tuple a b c = map int split input
print a * b // c | a,b,c=map(int,input().split())
print(((a*b)//c))
| Python | zaydzuhri_stack_edu_python |
function is_editing_codelet self
begin
return current_codelet != NULL
end function | def is_editing_codelet(self):
return self.current_codelet != NULL | Python | nomic_cornstack_python_v1 |
function give_exp self physical_key
begin
return call give physical_key
end function | def give_exp(self, physical_key):
return self.give_compo_exp().give(physical_key) | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
comment driver = webdriver.Firefox()
function get_cookie url
begin
set driver = call PhantomJS
get driver url
comment 获取cookie列表
set cookie_list = call get_cookies
comment 格式化打印cookie
set cookie_dict = dictionary
for cookie in cookie_list
begin
set cookie_dict at cookie at string name = c... | from selenium import webdriver
# driver = webdriver.Firefox()
def get_cookie(url):
driver = webdriver.PhantomJS()
driver.get(url)
# 获取cookie列表
cookie_list = driver.get_cookies()
# 格式化打印cookie
cookie_dict = dict()
for cookie in cookie_list:
cookie_dict[cookie['name']] = cookie['valu... | Python | zaydzuhri_stack_edu_python |
import argparse
import sys
import pandas as pd
import numpy as np
set parser = call ArgumentParser
call add_argument string -o string --output help=string Save the output predictions to file. nargs=string ? type=call FileType string w default=stdout
call add_argument string modelfile help=string the model file for pred... | import argparse
import sys
import pandas as pd
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--output", help="Save the output predictions to file.",
nargs="?", type=argparse.FileType('w'), default=sys.stdout)
parser.add_argument("modelfile", help="the model file f... | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ local_ssd_count=none
begin
if local_ssd_count is not none
begin
set __self__ string local_ssd_count local_ssd_count
end
end function | def __init__(__self__, *,
local_ssd_count: Optional[pulumi.Input[int]] = None):
if local_ssd_count is not None:
pulumi.set(__self__, "local_ssd_count", local_ssd_count) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import argparse
import logging
import os
import sys
import urllib.parse
import bs4
set HERE = directory name path real path path __file__
set DEFAULT_ROOT = join path directory name path HERE string _build
call basicConfig format=string [%(name)s] %(levelname)s: %(message)s
set logger = ca... | #!/usr/bin/env python3
import argparse
import logging
import os
import sys
import urllib.parse
import bs4
HERE = os.path.dirname(os.path.realpath(__file__))
DEFAULT_ROOT = os.path.join(os.path.dirname(HERE), '_build')
logging.basicConfig(format='[%(name)s] %(levelname)s: %(message)s')
logger = logging.getLogger('aud... | Python | zaydzuhri_stack_edu_python |
string Partie Core
comment TODO
comment Voir fichier TODO
import random
import cPickle
import os
import operator
import ConfigParser
class Player
begin
string Creation de la classe Player
set score = 0
function __init__ self name=string Snake
begin
string Methode execute a l'instanciation de la classe Player On fixe le... | """
Partie Core
"""
##TODO
#Voir fichier TODO
import random
import cPickle
import os
import operator
import ConfigParser
class Player():
"""
Creation de la classe Player
"""
score = 0
def __init__(self, name="Snake"):
"""
Methode execute a l'instanciation de la classe Player
On fixe le nom du joueur a S... | Python | zaydzuhri_stack_edu_python |
function __init__ self variant_label_loader inferred_zygosities=none output_location=none
begin
comment Check if the inferred zygosities passed in are the same length as label loader
if inferred_zygosities and length inferred_zygosities != length variant_label_loader
begin
raise call RuntimeError string VCFResultWriter... | def __init__(self, variant_label_loader, inferred_zygosities=None, output_location=None):
# Check if the inferred zygosities passed in are the same length as label loader
if inferred_zygosities and (len(inferred_zygosities) != len(variant_label_loader)):
raise RuntimeError(
"... | Python | nomic_cornstack_python_v1 |
function BinarySearch listD key
begin
set low = 0
set high = length listD - 1
set Found = false
while low <= high and not Found
begin
set mid = low + high // 2
if key == listD at mid
begin
set Found = true
end
else
if key > listD at mid
begin
set low = mid + 1
end
else
begin
set high = mid - 1
end
end
if Found == true
... | def BinarySearch(listD, key):
low = 0
high = len(listD) - 1
Found = False
while low<=high and not Found:
mid = (low+high)//2
if key == listD[mid]:
Found = True
elif key>listD[mid]:
low = mid+1
else:
high = mid-1
if Found... | Python | zaydzuhri_stack_edu_python |
import urllib.request
import urllib.parse
import urllib
from django.conf import settings
import json
import math
from random import random
from bisect import bisect_left
from geopy.distance import vincenty
comment helper for making tripexpert API calls.
function tripexpert_api_venues curr_lat curr_long venue_type city
... | import urllib.request
import urllib.parse
import urllib
from django.conf import settings
import json
import math
from random import random
from bisect import bisect_left
from geopy.distance import vincenty
#helper for making tripexpert API calls.
def tripexpert_api_venues(curr_lat, curr_long, venue_type, city):
ve... | Python | zaydzuhri_stack_edu_python |
function reference_nodes_graph_idx self
begin
return node_graph_idx_reference
end function | def reference_nodes_graph_idx(self) -> Dict[str, torch.Tensor]:
return self.node_graph_idx_reference | Python | nomic_cornstack_python_v1 |
from brownie import EmployeePayer , accounts
from web3 import Web3
function deploy_employee_payer
begin
set account = accounts at 0
set account2 = accounts at 1
print string [i]>> Deploying contract...
set employeePayer = call deploy dict string from account ; string value call toWei 50 string ether
print string [i]>> ... | from brownie import EmployeePayer, accounts
from web3 import Web3
def deploy_employee_payer():
account = accounts[0]
account2 = accounts[1]
print("[i]>> Deploying contract...")
employeePayer = EmployeePayer.deploy({"from": account, "value":Web3.toWei(50, "ether")})
print(f"[i]>> Contract deployed... | Python | zaydzuhri_stack_edu_python |
function bound_one bin boxes
begin
set lb = 0
comment rotations
for i in range WDIM DDIM + 1
begin
set lbx = call bound_one_x bin boxes
set lb = max lb lbx
call rotate_problem bin boxes
end
return lb
end function | def bound_one(bin, boxes):
lb = 0
for i in range(WDIM, DDIM + 1): # rotations
lbx = bound_one_x(bin, boxes)
lb = max(lb, lbx)
rotate_problem(bin, boxes)
return lb | Python | nomic_cornstack_python_v1 |
function doStorageAccountChecks self
begin
comment Get storage accounts (either from params.txt or from HDInsight cluster directly)
comment Ref: https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-restrict-outbound-traffic#create-and-configure-a-route-table
call getStorageAccounts self
comment No storage account... | def doStorageAccountChecks(self):
# Get storage accounts (either from params.txt or from HDInsight cluster directly)
# Ref: https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-restrict-outbound-traffic#create-and-configure-a-route-table
getStorageAccounts(self)
# No storage accou... | Python | nomic_cornstack_python_v1 |
function dumps resource encoder=none include_virtual_fields=true **kwargs
begin
comment type: (RT, Optional[Type[OdinEncoder]], bool, Any) -> str
set encoder = call include_virtual_fields __class__ keyword kwargs
if is instance resource tuple Resource ResourceAdapter
begin
set resource = call resource_to_dict resource
... | def dumps(resource, encoder=None, include_virtual_fields=True, **kwargs):
# type: (RT, Optional[Type[OdinEncoder]], bool, Any) -> str
encoder = (encoder or OdinEncoder)(
include_virtual_fields, resource.__class__, **kwargs
)
if isinstance(resource, (Resource, ResourceAdapter)):
resource... | Python | nomic_cornstack_python_v1 |
function get_css self
begin
set css = dict
set print_css = join path theme_dir string css string print.css
if not exists path print_css
begin
comment Fall back to default theme
set print_css = join path THEMES_DIR string default string css string print.css
if not exists path print_css
begin
raise call IOError string C... | def get_css(self):
css = {}
print_css = os.path.join(self.theme_dir, 'css', 'print.css')
if not os.path.exists(print_css):
# Fall back to default theme
print_css = os.path.join(THEMES_DIR, 'default', 'css', 'print.css')
if not os.path.exists(print_css):
... | Python | nomic_cornstack_python_v1 |
import uuid
from html import escape
from reportlab.platypus import SimpleDocTemplate , Paragraph , Spacer
from reportlab.lib.styles import getSampleStyleSheet , ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
call registerFont call TTFont string DejaVuSans string Dej... | import uuid
from html import escape
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('DejaVuSans', 'DejaVuSans.t... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf8 -*-
string • Commonly used items. • Usage: import lib.common as _common • Usage: if _common.isPrime(i): # ... • Author: Arlo Emerson <arloemerson@gmail.com> • License: GNU Lesser General Public License
import inspect
set RED = string [91m
set END = string [0m
set PATH_TO_PLOTS = string ../../... | # -*- coding: utf8 -*-
"""
• Commonly used items.
• Usage: import lib.common as _common
• Usage: if _common.isPrime(i): # ...
• Author: Arlo Emerson <arloemerson@gmail.com>
• License: GNU Lesser General Public License
"""
import inspect
RED = '\033[91m'
END = '\033[0m'
PATH_TO_PLOTS = '../../__rende... | Python | zaydzuhri_stack_edu_python |
function verifyBoxes self boxes object=none
begin
if object is none
begin
set object = portal
end
log string Verifying boxes on %s % call absolute_url relative=1
set box_container = call getBoxContainer object create=1
set existing_boxes = call objectIds
set ttool = call getTool string portal_types
for box in keys boxe... | def verifyBoxes(self, boxes, object=None):
if object is None:
object = self.portal
self.log('Verifying boxes on %s' % object.absolute_url(relative=1))
box_container = self.getBoxContainer(object, create=1)
existing_boxes = box_container.objectIds()
ttool = self.getToo... | Python | nomic_cornstack_python_v1 |
comment Open classif_1.tiff and read it to see where the training data coordinates are
comment then save it to a save file
import numpy as np
from osgeo import gdal
set classif = list string classif_1 string classif_2 string classif_3 string classif_4 string classif_5
function extract filename
begin
set intiffile = fil... | # Open classif_1.tiff and read it to see where the training data coordinates are
# then save it to a save file
import numpy as np
from osgeo import gdal
classif = ["classif_1","classif_2","classif_3","classif_4","classif_5"]
def extract(filename):
intiffile = filename + ".tif"
d5 = gdal.Open(intif... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment coding=utf-8
import sys
import re
comment 功能说明:
comment 关键词匹配,根据码表打标签
comment 支持关键词中 用 空格表示 and的关系
comment 以下是参数######################
comment 要清洗的数据在第几列
set COLUMN = 37
comment 数据文件,必须是立方导出的数据
set FILE_NAME = string sample_min_test.csv
comment 过滤词文件
set FILTER_WORDS = string sick.txt
c... | #!/usr/bin/python
# coding=utf-8
import sys
import re
# 功能说明:
# 关键词匹配,根据码表打标签
# 支持关键词中 用 空格表示 and的关系
#
####################以下是参数######################
COLUMN = 37 # 要清洗的数据在第几列
FILE_NAME = "sample_min_test.csv" # 数据文件,必须是立方导出的数据
FILTER_WORDS = "sick.txt" # 过滤词文件
COLUMN_TOTAL = 42 # 总列数
OUTPUT_FILE = "result.cs... | Python | zaydzuhri_stack_edu_python |
string Prototype(原型) 意图: 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。 适用性: 当要实例化的类是在运行时刻指定时,例如,通过动态装载; 或者为了避免创建一个与产品类层次平行的工厂类层次时; 或者当一个类的实例只能有几个不同状态组合中的一种时。 建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
import copy
class Prototype
begin
function __init__ self
begin
set _objects = dict
end function
function register_object self name obj
... | """
Prototype(原型)
意图:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
适用性:
当要实例化的类是在运行时刻指定时,例如,通过动态装载;
或者为了避免创建一个与产品类层次平行的工厂类层次时;
或者当一个类的实例只能有几个不同状态组合中的一种时。
建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
"""
import copy
class Prototype:
def __init__(self):
self._objects = {}
def register_object(self,name,obj):
"""... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string See: http://deeplearning.net/software/theano/tutorial/examples.html http://deeplearning.net/software/theano/tutorial/modes.html
from __future__ import print_function
import numpy as np
import theano
import theano.tensor as T
comment theano.config.floatX = 'float32'
set rng = random
s... | #!/usr/bin/env python
"""
See:
http://deeplearning.net/software/theano/tutorial/examples.html
http://deeplearning.net/software/theano/tutorial/modes.html
"""
from __future__ import print_function
import numpy as np
import theano
import theano.tensor as T
# theano.config.floatX = 'float32'
rng = np.random
N =... | Python | zaydzuhri_stack_edu_python |
from src.Node import Node
function main
begin
set node_set = set
for i in range 2
begin
add node_set call Node i
end
set main_node = call Node 2 node_set
print main_node
end function
if __name__ == string __main__
begin
call main
end | from src.Node import Node
def main():
node_set = set()
for i in range(2):
node_set.add(Node(i))
main_node = Node(2, node_set)
print(main_node)
if __name__ == '__main__':
main() | Python | zaydzuhri_stack_edu_python |
function collate_minibatch list_of_blobs
begin
set list_of_blobs = sum list_of_blobs list
set Batch = dictionary comprehension key : list for key in list_of_blobs at 0
comment Because roidb consists of entries of variable length, it can't be batch into a tensor.
comment So we keep roidb in the type of "list of ndarray... | def collate_minibatch(list_of_blobs):
list_of_blobs = sum(list_of_blobs, [])
Batch = {key: [] for key in list_of_blobs[0]}
# Because roidb consists of entries of variable length, it can't be batch into a tensor.
# So we keep roidb in the type of "list of ndarray".
list_of_roidb = [blobs.pop('roidb'... | Python | nomic_cornstack_python_v1 |
string Created on Nov 10, 2018 @author: hp840
import unittest
class personValidatorException extends Exception
begin
pass
end class
class personValidator
begin
function validate self personId personName personPhoneNumber personAddress
begin
string Validates a person - verifies if the data format is ok Input: 4 strings ... | '''
Created on Nov 10, 2018
@author: hp840
'''
import unittest
class personValidatorException(Exception):
pass
class personValidator:
def validate(self,personId,personName,personPhoneNumber,personAddress):
'''
Validates a person - verifies if the data format is ok
Input: 4 string... | 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.