code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import matplotlib
call use string Agg
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.offsetbox import AnnotationBbox
from modelaje import modelo
print string Listo
function horario modelo
begin
set colores = dict 0 string red ; 1 string blue ; 2 string green ; 3 string grey ; 4 str... | import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.offsetbox import AnnotationBbox
from modelaje import modelo
print("Listo")
def horario(modelo):
colores = {0: "red", 1: "blue", 2: "green", 3: "grey", 4: "yellow", 5: "purple"}
fig... | Python | zaydzuhri_stack_edu_python |
function make_int_object_list self
begin
from libtbx import easy_pickle as ep
if grid_search_path == none
begin
set int_dir = call set_base_dir string integration true
end
else
begin
set int_dir = grid_search_path
end
set img_objects = list
comment Inspect integration folder for image objects
for tuple root dirs files... | def make_int_object_list(self):
from libtbx import easy_pickle as ep
if self.params.cctbx.selection.select_only.grid_search_path == None:
int_dir = misc.set_base_dir('integration', True)
else:
int_dir = self.params.cctbx.selection.select_only.grid_search_path
img_objects = []
# Inspec... | Python | nomic_cornstack_python_v1 |
function getAttributes self
begin
pass
end function | def getAttributes(self):
pass | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template , url_for , redirect
from student import Student
set app = call Flask __name__
set eiPhyoThein = call Student name=string Ei Phyo Thein
set mayThuHnin = call Student name=string May Thu Hnin
set thiriSan = call Student name=string Thiri San
set students = list eiPhyoThein mayTh... | from flask import Flask, render_template,url_for,redirect
from student import Student
app=Flask(__name__)
eiPhyoThein=Student(name="Ei Phyo Thein")
mayThuHnin=Student(name="May Thu Hnin")
thiriSan=Student(name="Thiri San")
students=[eiPhyoThein,mayThuHnin,thiriSan]
@app.route('/')
@app.route('/students',methods=["G... | Python | zaydzuhri_stack_edu_python |
comment Global Keyword
set total = 0
function count
begin
global total
set total = total + 1
return total
end function
comment Puts total into the global context
comment - Better to use paramters instead of global keyword
comment nonlocal keyword
function outer
begin
set x = string local
function inner
begin
nonlocal x... | # Global Keyword
total = 0
def count():
global total
total += 1
return total
# Puts total into the global context
# - Better to use paramters instead of global keyword
# nonlocal keyword
def outer():
x = 'local'
def inner():
nonlocal x
x = 'nonlocal'
| Python | zaydzuhri_stack_edu_python |
import requests
set login_url = string https://ringzer0team.com/login
set target_url = string https://ringzer0team.com/challenges/5
set data = dict string username string zwhubuntu ; string password string ************************
set password = string
set s = call session
set r = post login_url data=data | import requests
login_url = 'https://ringzer0team.com/login'
target_url = 'https://ringzer0team.com/challenges/5'
data = {'username': 'zwhubuntu', 'password': '************************'}
password = ''
s = requests.session()
r = s.post(login_url, data=data) | Python | zaydzuhri_stack_edu_python |
string Write a function nestingdepth(s) that takes as input a string s and computes the maximum nesting depth of brackets. if s has properly nested brackets. If the string is not properly matched, your function should return -1. Hint: Use the function matched() from the practice assignment. Here are some examples to sh... | '''
Write a function nestingdepth(s) that takes as input a string s and computes the maximum nesting depth of brackets.
if s has properly nested brackets. If the string is not properly matched, your function should return -1.
Hint: Use the function matched() from the practice assignment.
Here are some examples to sho... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import cv2 as cv
import sys
import time
import matplotlib.pyplot as plot
class AStar
begin
function compute self
begin
set c = set
set o = set
set cameFrom = dict
set gScore = dict
set gScore at start_cell = 0
set fScore = dict
set fScore at start_cell = call heuristic start_cell
add o start_cell
... | import numpy as np
import cv2 as cv
import sys
import time
import matplotlib.pyplot as plot
class AStar:
def compute(self):
self.c = set()
self.o = set()
self.cameFrom = {}
gScore={}
gScore[self.start_cell] = 0
fScore = {}
fScore[self.start_cell] = self.heur... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import string
import time
comment Definitions
comment Update word frequencies with the next word.
function update_freq word Words weight=1
begin
set output = Words
set found = false
for x in Words
begin
if x at 0 == word
begin
set x at 1 = x at 1 + weight
set found = true
break
en... | import numpy as np
import pandas as pd
import string
import time
## Definitions
# Update word frequencies with the next word.
def update_freq(word, Words, weight=1):
output = Words
found = False
for x in Words:
if x[0] == word:
x[1] = x[1] + weight
found = True
... | Python | zaydzuhri_stack_edu_python |
comment Problem statement :
comment Accept number from user and display factors of that number.
comment Input : 12 Output : 1 2 3 4 | #Problem statement :
#Accept number from user and display factors of that number.
#Input : 12 Output : 1 2 3 4
| Python | zaydzuhri_stack_edu_python |
function terminate_connection self volume connector
begin
debug call _ string enter: terminate_connection: volume %(vol)s with connector %(conn)s % dict string vol string volume ; string conn string connector
set vol_name = volume at string name
set initiator_name = connector at string initiator
set host_name = call _g... | def terminate_connection(self, volume, connector):
LOG.debug(_('enter: terminate_connection: volume %(vol)s with '
'connector %(conn)s') % {'vol': str(volume),
'conn': str(connector)})
vol_name = volume['name']
initiator_name = connector['initiator']
... | Python | nomic_cornstack_python_v1 |
comment n spaced string
comment red blue green =>der eulb neerg
comment first line testcases
comment second line n spaced strings
set test = integer input
while test > 0
begin
set arr = split input
for i in range length arr
begin
set temp = list arr at i
reverse temp
set arr at i = join string temp
end
print arr
set t... | #n spaced string
# red blue green =>der eulb neerg
#first line testcases
#second line n spaced strings
test=int(input())
while(test>0):
arr=input().split()
for i in range(len(arr)):
temp=list(arr[i])
temp.reverse()
arr[i]=''.join(temp)
print(arr)
test-=1 | Python | zaydzuhri_stack_edu_python |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
function __eq__ self other
begin
return call compare self other
end function | def __eq__(self, other):
return ForgotPassword.compare(self, other) | Python | nomic_cornstack_python_v1 |
function predict self data_dict label_dict phases=list string test
begin
set loaders = call init_loaders_predict data_dict label_dict
set loss_dict = call init_loss_dict phases=phases
set performance_dict = call init_performance_dict phases=phases
train model false
with no grad
begin
set output_dict_dict = dict
for ph... | def predict(self, data_dict, label_dict, phases=["test"]):
loaders = self.init_loaders_predict(data_dict, label_dict)
loss_dict = self.init_loss_dict(phases=phases)
performance_dict = self.init_performance_dict(phases=phases)
self.model.train(False)
with torch.no_grad():
... | Python | nomic_cornstack_python_v1 |
function on_actionSession_Speaker_triggered self
begin
set p0 = call isChecked
call setSessionSpeaker p0
end function | def on_actionSession_Speaker_triggered(self):
p0 = self.actionSession_Speaker.isChecked()
menus.setSessionSpeaker(p0) | Python | nomic_cornstack_python_v1 |
import sys
set text_file = open string 123.txt string r
set lines = split read text_file string ,
close text_file
function changeststus
begin
set file = open string 123.txt string w
set i = 1
for line in lines
begin
write file join string line
if i < length lines
begin
write file string ,
set i = i + 1
end
end
end fun... | import sys
text_file = open("123.txt", "r")
lines = text_file.read().split(",")
text_file.close()
def changeststus():
file = open("123.txt","w")
i=1
for line in lines:
file.write(" ".join(line))
if i < len(lines):
file.write(",")
i += 1
for x in range(... | Python | zaydzuhri_stack_edu_python |
function parse_file arguments
begin
set file = call open_file file
set results = list
call parse_lines file results
call print_results_as_yaml results arguments
end function | def parse_file(arguments):
file = open_file(arguments.file)
results = []
parse_lines(file, results)
print_results_as_yaml(results, arguments) | Python | nomic_cornstack_python_v1 |
import selenium.webdriver as webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
import os
from six.moves.urllib.parse import urlparse
from bs4 import BeautifulSoup
import urllib.request
import time
comment Being honest IDK how many of these imports are actually needed.
comment Create a refera... | import selenium.webdriver as webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
import os
from six.moves.urllib.parse import urlparse
from bs4 import BeautifulSoup
import urllib.request
import time
#Being honest IDK how many of these imports are actually needed.
#Create a referal ... | Python | zaydzuhri_stack_edu_python |
function _compute_correlations self data
begin
set mappings = mappings_
set tuple n_channels n_times = shape
comment get the predictions
set y_pred = dot T
set y_pred = reshape y_pred tuple n_times length picks n_resample order=string F
comment pool them using median
comment XXX: weird that original implementation sort... | def _compute_correlations(self, data):
mappings = self.mappings_
n_channels, n_times = data.shape
# get the predictions
y_pred = data.T.dot(mappings.T)
y_pred = y_pred.reshape((n_times, len(self.picks),
self.n_resample), order='F')
# pool... | Python | nomic_cornstack_python_v1 |
async function consume_audio track
begin
set writer = none
try
begin
while true
begin
set frame = await call recv
if writer is none
begin
set writer = open AUDIO_OUTPUT_PATH string wb
call setnchannels channels
call setframerate sample_rate
call setsampwidth sample_width
end
call writeframes data
end
end
finally
begin
... | async def consume_audio(track):
writer = None
try:
while True:
frame = await track.recv()
if writer is None:
writer = wave.open(AUDIO_OUTPUT_PATH, 'wb')
writer.setnchannels(frame.channels)
writer.setframerate(frame.sample_rate)
... | Python | nomic_cornstack_python_v1 |
class Node extends object
begin
string A node in the suffix tree. suffix_node the index of a node with a matching suffix, representing a suffix link. -1 indicates this node has no suffix link.
function __init__ self
begin
set suffix_node = - 1
end function
function __repr__ self
begin
return string Node(suffix link: %d... | class Node(object):
"""A node in the suffix tree.
suffix_node
the index of a node with a matching suffix, representing a suffix link.
-1 indicates this node has no suffix link.
"""
def __init__(self):
self.suffix_node = -1
def __repr__(self):
retu... | Python | zaydzuhri_stack_edu_python |
comment Here we compare other cmd-line parsing libraries.
comment the alternative to argparse lib are docopt and click
comment for argparse --->
comment import argparse
comment parser = argparse.ArgumentParser()
comment subparser = parser.add_subparsers()
comment hello_parser = subparser.add_parser('hello')
comment goo... | #Here we compare other cmd-line parsing libraries.
#the alternative to argparse lib are docopt and click
##for argparse --->
#import argparse
#parser = argparse.ArgumentParser()
#subparser = parser.add_subparsers()
#hello_parser = subparser.add_parser('hello')
#goodbye_parser = subparser.add_parser('goodbye')
#--> now... | Python | zaydzuhri_stack_edu_python |
import traceback
import sys | import traceback
import sys
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string @author: Eraguzin This is a GUI designed to communicate with board IO-1733-1 Rev A, with a HV5523 -> HV3418 SPI control chain Through an LTC6820 pair of chips to minimize the lines on the cable. This script uses an FT2323H board: https://www.adafruit.com/product/2264 To generate the... | # -*- coding: utf-8 -*-
"""
@author: Eraguzin
This is a GUI designed to communicate with board IO-1733-1 Rev A, with a HV5523 -> HV3418 SPI control chain
Through an LTC6820 pair of chips to minimize the lines on the cable. This script uses an FT2323H board:
https://www.adafruit.com/product/2264
To generate the S... | Python | zaydzuhri_stack_edu_python |
from appium import webdriver
import time
set driver = call Remote string http://127.0.0.1:4723/wd/hub desired_caps
comment 定义事件
function click_id ele
begin
call click
end function
comment 找不到id的就用xpath
function click_xpath ele
begin
call click
end function
function send_id ele keys
begin
call send_keys keys
end functio... | from appium import webdriver
import time
driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
#定义事件
def click_id(ele):
driver.find_element_by_id(ele).click()
#找不到id的就用xpath
def click_xpath(ele):
driver.find_element_by_xpath(ele).click()
def send_id(ele,keys):
driver.find_element_by_id(e... | Python | zaydzuhri_stack_edu_python |
import logging
from base.base_page import BasePage
from utilities.custom_logger import create_custom_logger
class PopulationPage extends BasePage
begin
string Specialization of the BasePage that is specialized to the Population page on the Avida-ED website.
comment Logger
set log = call create_custom_logger DEBUG
comme... | import logging
from base.base_page import BasePage
from utilities.custom_logger import create_custom_logger
class PopulationPage(BasePage):
"""
Specialization of the BasePage that is specialized to the Population page
on the Avida-ED website.
"""
# Logger
log = create_custom_logger(logging.D... | Python | zaydzuhri_stack_edu_python |
if km > 80
begin
set velocidade_extra = km - 80
set multa = velocidade + extra * 5
print format string Você está a {0} km acima do limite, sua multa é de {1} reais velocidade_extra multa
end
else
begin
print string Não foi multado
end | if km>80:
velocidade_extra = km - 80
multa = velocidade+extra * 5
print ('Você está a {0} km acima do limite, sua multa é de {1} reais'.format(velocidade_extra , multa))
else:
print('Não foi multado')
| Python | zaydzuhri_stack_edu_python |
function deploy tag num names
begin
set len = 0
call echo string *** DEPLOYMENT IS INITIATED
for name in names
begin
set len = len + 1
end
if num == len
begin
for name in names
begin
try
begin
set response_container = run tag name=name detach=true
set container_id = id
set index = call slice 12
call echo string Contain... | def deploy(tag,num, names):
len=0
click.echo('*** DEPLOYMENT IS INITIATED\n')
for name in names:
len+=1
if (num==len):
for name in names:
try:
response_container = client.containers.run(tag, name=name, detach=True)
container_id = response_contai... | Python | nomic_cornstack_python_v1 |
function makeZDecisionImage key useCenterPoints pointLocations baseFilename=string crop
begin
set creatingImage = false
set generateDiagnostic = true
comment print "number of adjacencies for plane to plane", numProcessed, "total number", len(zEdges)
comment print "number of adjacencies processed for plane to plane", nu... | def makeZDecisionImage(key, useCenterPoints, pointLocations, baseFilename="crop"):
creatingImage = False
generateDiagnostic = True
#print "number of adjacencies for plane to plane", numProcessed, "total number", len(zEdges)
#print "number of adjacencies processed for plane to plane", numProcessed, "t... | Python | nomic_cornstack_python_v1 |
function create_user self email password=none **extra_fields
begin
comment We set last login in the past so we know which users has logged in once
set last_login_date = replace call datetime 1970 1 1 tzinfo=utc
if not email
begin
raise call ValueError string The given email must be set
end
set email = call normalize_em... | def create_user(self, email, password=None, **extra_fields):
# We set last login in the past so we know which users has logged in once
last_login_date = datetime(1970, 1, 1).replace(tzinfo=timezone.utc)
if not email:
raise ValueError('The given email must be set')
email = ... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu May 28 13:09:45 2020 @author: lx
comment 自编码网络 #########################################
comment 用于查看与修改当前数据读取路径
import os
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import pandas as pd
import numpy as np
import matplotlib... | # -*- coding: utf-8 -*-
"""
Created on Thu May 28 13:09:45 2020
@author: lx
"""
################################### 自编码网络 #########################################
import os #用于查看与修改当前数据读取路径
import tensorflow as tf
from tensorflow import keras
from tensorflow.ker... | Python | zaydzuhri_stack_edu_python |
function default_test self tables_and_test_values
begin
comment pre-conditions
comment validate sandbox tables don't exist yet
set tables_created_at_setup = list
for values_list in tables_and_test_values
begin
set rule_setup_creation_list = get values_list string tables_created_on_setup list
extend tables_created_at_s... | def default_test(self, tables_and_test_values):
# pre-conditions
# validate sandbox tables don't exist yet
tables_created_at_setup = []
for values_list in tables_and_test_values:
rule_setup_creation_list = values_list.get(
'tables_creat... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import sys
function parse filename
begin
set fo = open filename string r
while true
begin
set line = read line fo
if not line
begin
break
end
if starts with line string //
begin
continue
end
set items = split strip line string string
if length items < 2
begin
continue
end
if not items at 0
begi... | #!/usr/bin/python
import sys
def parse(filename):
fo = open(filename, "r")
while True:
line = fo.readline()
if not line:
break;
if line.startswith('//'):
continue
items = line.strip("\r\n").split('\t')
if len(items) < 2:
continue
if not items[0]:
continue
if not items[1]:
continue
... | Python | zaydzuhri_stack_edu_python |
import argparse
import sys
function main
begin
set parser = call ArgumentParser description=string Filter SNP positions by call quality and min. coverage. Awaits filenames for M, P .vcf files, and M, P .sam files.
call add_argument string snps type=str help=string paths to .vcf files with M, P SNPs and to corresponding... | import argparse
import sys
def main():
parser = argparse.ArgumentParser(description='Filter SNP positions by call quality and min. coverage. Awaits filenames for M, P .vcf files, and M, P .sam files.')
parser.add_argument('snps', type=str, help='paths to .vcf files with M, P SNPs and to corresponding .sam file... | Python | zaydzuhri_stack_edu_python |
function _find_server account servername=none
begin
set servers = list comprehension s for s in call resources if string server in provides
set servers = list comprehension s for s in call resources if string server in provides
comment If servername specified find and return it
if servername is not none
begin
for serve... | def _find_server(account, servername=None):
servers = servers = [s for s in account.resources() if 'server' in s.provides]
# If servername specified find and return it
if servername is not None:
for server in servers:
if server.name == servername:
return server.connect()
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import sys
function r_regression X_train y_train lamda variance
begin
set wRR = dot dot y_train
return wRR
end function
function a_learning lamda variance X_train X_test
begin
set covariance = call inv lamda * call eye shape at 1 + 1 / variance * dot X_train
set indices = list range shape at 0
set ac... | import numpy as np
import sys
def r_regression(X_train, y_train, lamda, variance):
wRR = (np.linalg.inv(lamda*np.eye(X_train.shape[1]) + (X_train.T).dot(X_train))).dot((X_train.T).dot(y_train))
return wRR
def a_learning(lamda, variance, X_train, X_test):
covariance = np.linalg.inv(lamda * np.eye(X... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
set fn = open string all_names.txt string r
set out = open string all_names2.txt string w
set names = list
for line in fn
begin
set tuple offset iname name = split line string |
append names tuple name iname
end | #!/usr/bin/python
fn = open('all_names.txt', 'r')
out = open('all_names2.txt', 'w')
names = []
for line in fn:
(offset,iname,name)=line.split("|")
names.append((name,iname)) | Python | zaydzuhri_stack_edu_python |
function sc_build_zones self
begin
set build_zones = unique
return build_zones
end function | def sc_build_zones(self):
build_zones = self._pras_build_zones['region'].unique()
return build_zones | Python | nomic_cornstack_python_v1 |
function _quatm q1 q0
begin
set tuple w0 x0 y0 z0 = q0
set tuple w1 x1 y1 z1 = q1
return call FloatTensor list - x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0 x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0 - x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0 x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0
end function | def _quatm(q1, q0):
w0, x0, y0, z0 = q0
w1, x1, y1, z1 = q1
return torch.cuda.FloatTensor([
-x1*x0 - y1*y0 - z1*z0 + w1*w0,
x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0,
]) | Python | nomic_cornstack_python_v1 |
function get_port_rxrate self iface
begin
skip string Method is not supported by Iperf TG
end function | def get_port_rxrate(self, iface):
pytest.skip("Method is not supported by Iperf TG") | Python | nomic_cornstack_python_v1 |
function variants store institute_obj case_obj variants_query page=1 per_page=50
begin
set variant_count = count variants_query
set skip_count = per_page * max page - 1 0
set more_variants = if expression variant_count > skip_count + per_page then true else false
set variant_res = call limit per_page
set genome_build =... | def variants(store, institute_obj, case_obj, variants_query, page=1, per_page=50):
variant_count = variants_query.count()
skip_count = per_page * max(page - 1, 0)
more_variants = True if variant_count > (skip_count + per_page) else False
variant_res = variants_query.skip(skip_count).limit(per_page)
... | Python | nomic_cornstack_python_v1 |
function update team_member_id
begin
set content = json
try
begin
if content at string type == string Player
begin
set member = call Player content at string first_name content at string last_name content at string member_num content at string annual_salary content at string contract_years_length content at string last... | def update(team_member_id):
content = request.json
try:
if content["type"] == 'Player':
member = Player(content['first_name'], content['last_name'], content['member_num'],
content['annual_salary'], content['contract_years_length'],
co... | Python | nomic_cornstack_python_v1 |
from math import ceil | from math import ceil
| Python | zaydzuhri_stack_edu_python |
comment Copyright Pololu Corporation. For more information, see https://www.pololu.com/
import smbus
import struct
import time
class AStar
begin
function __init__ self
begin
set bus = call SMBus 1
comment cumulative number of errors
set errors = 0
comment result of the last operation - gets reset at the beginning of th... | # Copyright Pololu Corporation. For more information, see https://www.pololu.com/
import smbus
import struct
import time
class AStar:
def __init__(self):
self.bus = smbus.SMBus(1)
self.errors = 0 #cumulative number of errors
self.error = 0 #result of the last operation - gets reset at the beginning of... | Python | zaydzuhri_stack_edu_python |
function volume_present name bricks stripe=false replica=false device_vg=false transport=string tcp start=false force=false arbiter=false
begin
string Ensure that the volume exists name name of the volume bricks list of brick paths replica replica count for volume arbiter use every third brick as arbiter (metadata only... | def volume_present(name, bricks, stripe=False, replica=False, device_vg=False,
transport='tcp', start=False, force=False, arbiter=False):
'''
Ensure that the volume exists
name
name of the volume
bricks
list of brick paths
replica
replica count for volum... | Python | jtatman_500k |
function __init__ self width height title
begin
call __init__ width height title
set shape_list = none
set matrix = grid ROW_COUNT COLUMN_COUNT
call set_background_color BLACK
set color_frequency = 0.4
call recreate_grid
end function | def __init__(self, width, height, title):
super().__init__(width, height, title)
self.shape_list = None
self.matrix = Grid(ROW_COUNT, COLUMN_COUNT)
arcade.set_background_color(arcade.color.BLACK)
self.color_frequency = 0.4
self.recreate_grid() | Python | nomic_cornstack_python_v1 |
function is_economical n
begin
function fac x
begin
set ans = list
set i = 2
while x != 1
begin
if x % i == 0
begin
append ans i
set x = x / i
end
else
begin
set i = i + 1
end
end
set count = 0
for j in set ans
begin
set count = count + if expression count ans j > 1 then length string j + length string count ans j els... | def is_economical(n):
def fac(x):
ans = []
i = 2
while x != 1:
if x % i == 0:
ans.append(i)
x /= i
else: i += 1
count = 0
for j in set(ans): count += ((len(str(j)) + len(str(ans.count(j))))
if ans.count(j) > 1 else len(str(j)))
return count
... | Python | zaydzuhri_stack_edu_python |
import math
import os
from sklearn.utils import shuffle
import numpy as np
class CNN_Inputparser
begin
function read_data self prot_name_file
begin
set base_name = call splitext prot_name_file at 0
if exists path base_name + string .cnn_train_windows.npy and exists path base_name + string .cnn_train_one_hots.npy and ex... | import math
import os
from sklearn.utils import shuffle
import numpy as np
class CNN_Inputparser:
def read_data(self, prot_name_file):
base_name = os.path.splitext(prot_name_file)[0]
if os.path.exists(base_name + ".cnn_train_windows.npy") and os.path.exists(base_name + ".cnn_t... | Python | zaydzuhri_stack_edu_python |
function ciclosBreakContinue
begin
set continuar = 1
comment while continuar == 1:
while true
begin
set numero = integer input string Ingrese un numero:
if numero % 2 == 0
begin
print string El numero es par
continue
end
print string Si vino a esta linea es porque el numero no fue par
set continuar = integer input stri... | def ciclosBreakContinue ():
continuar = 1
while True:#while continuar == 1:
numero = int(input("Ingrese un numero: "))
if (numero % 2 == 0):
print ("El numero es par")
continue
print ("Si vino a esta linea es porque el numero no fue par")
continua... | Python | zaydzuhri_stack_edu_python |
comment -*-coding:utf8-*-#
set __author__ = string play4fun
string create time:15-10-24 下午5:22
import cv2
import numpy as np
from matplotlib import pyplot as plt
set img = call imread string ../data/home.jpg 0
comment create a mask
set mask = zeros shape at slice : 2 : uint8
set mask at tuple slice 100 : 300 : slice... | #-*-coding:utf8-*-#
__author__ = 'play4fun'
"""
create time:15-10-24 下午5:22
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('../data/home.jpg',0)
# create a mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 100:400] = 255
masked_img = cv2.bitwise_and(img,img,mask = ma... | Python | zaydzuhri_stack_edu_python |
function solution n words
begin
set answer = list
set check_word = list
set person_count = 1
set word_count = 0
set last_word = string
for i in words
begin
if length i == 1
begin
append answer person_count
append answer word_count
break
end
if i in check_word
begin
append answer person_count
append answer word_count... | def solution(n, words):
answer = []
check_word = []
person_count = 1
word_count = 0
last_word = ''
for i in words:
if len(i) == 1:
answer.append(person_count)
answer.append(word_count)
break
if i in check_word:
answer.append(person_... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
set foo = string hi | #!/usr/bin/env python
foo = 'hi'
| Python | zaydzuhri_stack_edu_python |
function palindrome
begin
set value = 0
comment 3digits
for n1 in range 100 1000
begin
comment 3digits
for n2 in range 100 1000
begin
set pal_digit = n1 * n2
comment convert to string to perform indexing
set string_chk = string pal_digit
if string_chk == string_chk at slice : : - 1
begin
if pal_digit > value
begin
se... | def palindrome():
value=0
for n1 in range(100,1000): #3digits
for n2 in range(100,1000): #3digits
pal_digit = n1*n2
string_chk = str(pal_digit) #convert to string to perform indexing
if string_chk == string_chk[::-1]:
if pal_digit>value:
... | Python | nomic_cornstack_python_v1 |
comment https://www.interviewbit.com/problems/kth-manhattan-distance-neighbourhood/
class Solution
begin
comment @param A : integer
comment @param B : list of list of integers
comment @return a list of list of integers
function solve self A B
begin
set n = length B
set m = length B at 0
set dp = list comprehension list... | #https://www.interviewbit.com/problems/kth-manhattan-distance-neighbourhood/
class Solution:
# @param A : integer
# @param B : list of list of integers
# @return a list of list of integers
def solve(self, A, B):
n = len(B)
m = len(B[0])
dp = [[B[i][j] for j in range(m)] for i in ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Author: Lynne Raynor Description: Library for locating QR codes in images and performing a perspective transform -----------
import numpy as np
import matplotlib.pyplot as plt
import cv2
import transform
function cornerHarris_demo val image
begin
set thresh = val
comment Detector pa... | # -*- coding: utf-8 -*-
"""
Author: Lynne Raynor
Description: Library for locating QR codes in images and performing a
perspective transform
-----------
"""
import numpy as np
import matplotlib.pyplot as plt
import cv2
import transform
def cornerHarris_demo(val, image):
thresh = val
# Dete... | Python | zaydzuhri_stack_edu_python |
function find_lucky lst
begin
comment Your code here
set occurrences = dict
comment count number of occurrences for each num in list
for n in lst
begin
if n in occurrences
begin
set occurrences at n = occurrences at n + 1
end
else
begin
set occurrences at n = 1
end
end
comment add all nums that are possible lucky numb... | def find_lucky(lst):
# Your code here
occurrences = {}
# count number of occurrences for each num in list
for n in lst:
if n in occurrences:
occurrences[n] += 1
else:
occurrences[n] = 1
# add all nums that are possible lucky numbers to a candidates list
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
function addNumbers numOne=1 numTwo=1
begin
return numOne + numTwo
end function | #!/usr/bin/python
def addNumbers(numOne=1, numTwo=1):
return numOne + numTwo
| Python | zaydzuhri_stack_edu_python |
comment Thomas Fiorilla, fork of Anthony Tiongson
comment Anthony's genetic algorithm turned into a class
import AStarEval
import random
import copy
import board
import evaluate
import time
class Genetic
begin
function __init__ self board
begin
set puzzle = deep copy board
end function
function run self eval iterations... | # Thomas Fiorilla, fork of Anthony Tiongson
# Anthony's genetic algorithm turned into a class
import AStarEval
import random
import copy
import board
import evaluate
import time
class Genetic:
def __init__(self, board):
self.puzzle = copy.deepcopy(board)
def run(self, eval, iterations):
start = time.time()
... | Python | zaydzuhri_stack_edu_python |
function crossword_solution
begin
import os
set input_f = join path directory name path real path path __file__ string downloadable_input.txt
with open input_f string r as f
begin
set s = strip read f
end
return call solution s
end function | def crossword_solution() -> int:
import os
input_f = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'downloadable_input.txt')
with open(input_f, 'r') as f:
s = f.read().strip()
return solution(s) | Python | nomic_cornstack_python_v1 |
function register self measurement_class callback
begin
string Call the ``callback`` with any new values of ``measurement_class`` received.
add callbacks at call name_from_class measurement_class callback
end function | def register(self, measurement_class, callback):
"""Call the ``callback`` with any new values of ``measurement_class``
received.
"""
self.callbacks[Measurement.name_from_class(measurement_class)
].add(callback) | Python | jtatman_500k |
function test_reset_server_state_fails_as_user self
begin
with assert raises Forbidden
begin
call reset_state id
end
end function | def test_reset_server_state_fails_as_user(self):
with self.assertRaises(Forbidden):
self.servers_client.reset_state(self.server.id) | Python | nomic_cornstack_python_v1 |
function get_v_lan_df_primary file_name primary
begin
set v_lan_df = read csv file_name
return reset index reset index loc at v_lan_df at string primary_port == primary drop=true drop=true
end function | def get_v_lan_df_primary(file_name, primary):
v_lan_df = pd.read_csv(file_name)
return v_lan_df.loc[
v_lan_df['primary_port'] == primary
].reset_index(drop=True).reset_index(drop=True) | Python | nomic_cornstack_python_v1 |
function send_error self conn msg
begin
print string ERROR PLACEHOLDER
return
end function | def send_error(self, conn, msg):
print("ERROR PLACEHOLDER")
return | Python | nomic_cornstack_python_v1 |
import json
from codecs import open as copen
function get_data fname
begin
set inp = call copen fname encoding=string utf-8
set data = read inp
set data = loads data
close inp
return data
end function
function get_nice_data jdata
begin
set texts = list
set opinions = list
for q in jdata
begin
append texts q at string... | import json
from codecs import open as copen
def get_data(fname):
inp = copen(fname, encoding='utf-8')
data = inp.read()
data = json.loads(data)
inp.close()
return data
def get_nice_data(jdata):
texts = []
opinions = []
for q in jdata:
texts.append(q['text'])
curop = [... | Python | zaydzuhri_stack_edu_python |
import requests , json
from __output__ import say
from __input__ import inp
from __recognise__ import recognise
comment from __ML__ import wml
import geocoder
function weather text
begin
set li = split lower text string
if string in not in li
begin
comment wml(li)
set x = call here
info x
return
end
set pos = index li ... | import requests, json
from __output__ import say
from __input__ import inp
from __recognise__ import recognise
#from __ML__ import wml
import geocoder
def weather(text):
li=text.lower().split(' ')
if 'in' not in li:
#wml(li)
x=here()
info(x)
return
pos=li.index('in')
if ... | Python | zaydzuhri_stack_edu_python |
function __print_cmap_plot self x y data
begin
set crange = parameters at string color_scale_range
set ncolors = parameters at string n_colors at 0
set increment = decimal crange at 1 - crange at 0 / decimal ncolors - 2
set cbounds = list array range crange at 0 crange at 1 + increment increment
set main_render = call ... | def __print_cmap_plot(self,x,y,data):
crange = self.parameters["color_scale_range"]
ncolors = self.parameters["n_colors"][0]
increment = float(crange[1] - crange[0]) / float(ncolors-2)
cbounds = list(np.arange(crange[0],crange[1] + increment, increment ))
self.m... | Python | nomic_cornstack_python_v1 |
function pick_roc_thresholds roc_for_threshold_fn min_threshold max_threshold num_points=32
begin
function add_threshold threshold
begin
string Calculate the ROC point and add to list.
append rocs tuple call roc_for_threshold_fn threshold threshold
sort rocs
end function
function compare_2_points x1 x2
begin
string Com... | def pick_roc_thresholds(roc_for_threshold_fn, min_threshold, max_threshold, num_points=32):
def add_threshold(threshold):
"Calculate the ROC point and add to list."
rocs.append((roc_for_threshold_fn(threshold), threshold))
rocs.sort()
def compare_2_points(x1, x2):
"Compare 2 ROC... | Python | nomic_cornstack_python_v1 |
import pygame
import pygame.camera
from pygame.locals import *
import sys
set tuple scr_w scr_h = tuple 1280 720
set tuple M N = tuple 3 4
set tuple rw rh = tuple scr_w // M scr_h // N
set list_blackrect = list
set list_remove = list
function open_camera frame_size=tuple 1280 720 mode=string RGB
begin
call init
set l... | import pygame
import pygame.camera
from pygame.locals import *
import sys
scr_w, scr_h = 1280, 720
M,N = 3,4
rw, rh = scr_w//M, scr_h//N
list_blackrect = []
list_remove = []
def open_camera( frame_size=(1280,720),mode='RGB'):
pygame.camera.init()
list_cameras = pygame.camera.list_cameras()
p... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
from pyalgotrade.barfeed import csvfeed
from backtesting.data_sources import dbc
class ITFDatabaseFeed extends GenericBarFeed
begin
function __init__ self frequency timezone=none maxLen=none
begin
call __init__ frequency timezone maxLen
end function
function read_data self instrument
begin
set conne... | import pandas as pd
from pyalgotrade.barfeed import csvfeed
from backtesting.data_sources import dbc
class ITFDatabaseFeed(csvfeed.GenericBarFeed):
def __init__(self, frequency, timezone=None, maxLen=None):
super(ITFDatabaseFeed, self).__init__(frequency, timezone, maxLen)
def read_data(self, instr... | Python | zaydzuhri_stack_edu_python |
import unittest
import collections
class Solution
begin
function ladderLength self beginWord endWord wordList
begin
if not endWord in wordList or not wordList
begin
return 0
end
set combo_dict = default dictionary list
set L = length beginWord
for word in wordList
begin
for i in range L
begin
set k = word at slice : i... | import unittest
import collections
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList) -> int:
if (not endWord in wordList) or not wordList:
return 0
combo_dict = collections.defaultdict(list)
L = len(beginWord)
for ... | Python | zaydzuhri_stack_edu_python |
function SetCallbackUserData self _arg
begin
return call itkVTKImageImportIUS2_SetCallbackUserData self _arg
end function | def SetCallbackUserData(self, _arg: 'void *') -> "void":
return _itkVTKImageImportPython.itkVTKImageImportIUS2_SetCallbackUserData(self, _arg) | Python | nomic_cornstack_python_v1 |
function solution n
begin
set size = n + 1
set matrix = list comprehension list comprehension 0 for _ in range size for _ in range size
set matrix at 0 at 0 = 1
for prev in range 1 size
begin
for left in range 0 size
begin
set matrix at prev at left = matrix at prev - 1 at left
if left >= prev
begin
set matrix at prev ... | def solution(n):
size = n + 1
matrix = [[0 for _ in range(size)] for _ in range(size)]
matrix[0][0] = 1
for prev in range(1, size):
for left in range(0, size):
matrix[prev][left] = matrix[prev - 1][left]
if left >= prev:
matrix[prev][left] += matrix[prev -... | Python | zaydzuhri_stack_edu_python |
function _fe_check_phishing_similarity_words self sample
begin
set result = ordered dictionary
for key in _similarity_words
begin
set result at key + string _lev_1 = 0
for word in sample at string fqdn_words
begin
if distance word key == 1
begin
set result at key + string _lev_1 = 1
end
end
end
return result
end functi... | def _fe_check_phishing_similarity_words(self, sample):
result = OrderedDict()
for key in self._similarity_words:
result[key + "_lev_1"] = 0
for word in sample['fqdn_words']:
if distance(word, key) == 1:
result[key + "_lev_1"] = 1
ret... | Python | nomic_cornstack_python_v1 |
function _csr_to_delta_csr self other block_size n_samples n_history
begin
comment set the component data structures to point to those of other
set data = data
set indices = indices
set indptr = indptr
set shape = shape
comment populate the deltas vector with default values
set deltas = array range shape at 0
comment u... | def _csr_to_delta_csr(self, other, block_size, n_samples, n_history):
# set the component data structures to point to those of other
self.data = other.data
self.indices = other.indices
self.indptr = other.indptr
self.shape = other.shape
# populate the deltas vector with ... | Python | nomic_cornstack_python_v1 |
function IsVisible self
begin
set callResult = call _Call string IsVisible
if callResult is none
begin
return none
end
return callResult
end function | def IsVisible(self):
callResult = self._Call("IsVisible", )
if callResult is None:
return None
return callResult | Python | nomic_cornstack_python_v1 |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other):
return not self == other | Python | nomic_cornstack_python_v1 |
function testNewRatingCalculation self
begin
comment use products[2] to avoid counting new vote from testRate() test
set test_product_id = products at 2
set new_rating_vote = 5
set url_get = call composeUrl string rating test_product_id
set url_post = call composeUrl string rating
set url_recollect = call composeUrl st... | def testNewRatingCalculation(self):
# use products[2] to avoid counting new vote from testRate() test
test_product_id = TestEndpoints.products[2]
new_rating_vote = 5
url_get = TestEndpoints.composeUrl("rating", test_product_id)
url_post = TestEndpoints.composeUrl("rating")
... | Python | nomic_cornstack_python_v1 |
comment _*_ coding:utf-8 _*_
comment when m=1, n=10000 , exceeding time
import math
import time
set start = call clock
function isPrime x
begin
set end = integer square root x + 1
for i in call xrange 2 end
begin
if x % i == 0
begin
return false
end
end
return true
end function
set tuple primes number = tuple list 2 3
... | # _*_ coding:utf-8 _*_
import math # when m=1, n=10000 , exceeding time
import time
start = time.clock()
def isPrime(x):
end = int(math.sqrt(x))+1
for i in xrange(2, end):
if x % i == 0:
return False
return True
primes, number = [2], 3
# numbers = raw_input().split(' ')
numbers = [1... | Python | zaydzuhri_stack_edu_python |
function render self
begin
set value = string *
if value_from > min or value_to < max
begin
set value = string %d-%d % tuple integer value_from integer value_to
end
if integer seq != 1
begin
set value = value + string /%d % integer seq
end
return value
end function | def render(self):
value = '*'
if self.value_from > self.slice.min or self.value_to < self.slice.max:
value = "%d-%d" % (int(self.value_from), int(self.value_to))
if int(self.seq) != 1:
value += "/%d" % (int(self.seq))
return value | Python | nomic_cornstack_python_v1 |
function bound_subject self
begin
return get pulumi self string bound_subject
end function | def bound_subject(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "bound_subject") | Python | nomic_cornstack_python_v1 |
comment 1장 말뭉치와 워드넷 - 두 개의 구별되는 동의어 집합을 선택하고 워드넷을 사용해 상위어와 하위어 개념 탐색
comment 라이브러리 import 및 synset 초기화
from nltk.corpus import wordnet as wn
set woman = call synset string woman.n.01
set bed = call synset string bed.n.01
comment 동의어 집합 출력, 루트 노드에서 synset까지의 경로를 포함하는 집합의 리스트 얻기
print call hypernyms
set woman_paths = cal... | # 1장 말뭉치와 워드넷 - 두 개의 구별되는 동의어 집합을 선택하고 워드넷을 사용해 상위어와 하위어 개념 탐색
# 라이브러리 import 및 synset 초기화
from nltk.corpus import wordnet as wn
woman = wn.synset('woman.n.01')
bed = wn.synset('bed.n.01')
# 동의어 집합 출력, 루트 노드에서 synset까지의 경로를 포함하는 집합의 리스트 얻기
print(woman.hypernyms())
woman_paths = woman.hypernym_paths()
# root에서부터의 경로 출... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import matplotlib.pyplot as plt
set incomes = list
set calls = list
set infile = open string scatter.txt string r
set lines = read lines infile
close infile
for line in lines
begin
set a = split line string
if integer a at 0 == - 1
begin
set ndat = tuple integer a at 0 integer a at 1
end... | #!/usr/bin/env python3
import matplotlib.pyplot as plt
incomes=[]
calls=[]
infile =open("scatter.txt","r")
lines=infile.readlines()
infile.close()
for line in lines:
a=line.split(" ")
if int(a[0]) == -1:
ndat = int(a[0]),int(a[1])
else:
incomes.append(int(a[0]))
calls.append(int(a[1... | Python | zaydzuhri_stack_edu_python |
function plotIIRNotchFilterResponse numerator denominator f_samp
begin
comment Calculate the frequency response
set tuple freq response = call freqz numerator denominator fs=f_samp
comment Create plot
set tuple IIRNotchFilterResponse tuple IIR_ax1 IIR_ax2 = call subplots 2 1
call suptitle string IIR Notch Filter Freque... | def plotIIRNotchFilterResponse(numerator, denominator, f_samp):
# Calculate the frequency response
freq, response = freqz(numerator, denominator, fs=f_samp)
# Create plot
IIRNotchFilterResponse, (IIR_ax1, IIR_ax2) = plt.subplots(2, 1)
plt.suptitle("IIR Notch Filter Frequency Response")
plt.xla... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Mar 29 19:05:53 2016 @author: wxt
string Problem 79: A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th characters; the expect... | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 19:05:53 2016
@author: wxt
"""
"""
Problem 79:
A common security method used for online banking is to ask the user for three
random characters from a passcode. For example, if the passcode was 531278, they
may ask for the 2nd, 3rd, and 5th characters; the expected re... | Python | zaydzuhri_stack_edu_python |
for i in a
begin
print a at i
end | for i in a:
print(a[i])
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import scipy as sc
from minepy import MINE
function delete_constant df
begin
set columns = columns
set non_constant_columns = list comprehension column for column in columns if max != min
return df at non_constant_columns
end function
function delete_nan df
begin
set null_num = su... | import pandas as pd
import numpy as np
import scipy as sc
from minepy import MINE
def delete_constant(df):
columns = df.columns
non_constant_columns = [column for column in columns if df[column].max() != df[column].min()]
return df[non_constant_columns]
def delete_nan(df):
null_num = df.isnull().sum... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
string Calculate different Metrics This file provides functions to calculate various metrics related to the game of cricket. It is divided in the following sections: Sections: 1. Batsmen Metrics - Hard Hitting Ability 2. Bowler Metrics 3. Match Metrics
string Section I: Batting Metrics
function hard... | import pandas as pd
"""
Calculate different Metrics
This file provides functions to calculate various metrics
related to the game of cricket.
It is divided in the following sections:
Sections:
1. Batsmen Metrics
- Hard Hitting Ability
2. Bowler Metrics
3. Match Metrics
"""
"""
Section I: Batting Metrics
"""
... | Python | zaydzuhri_stack_edu_python |
string DICTIONARIES
set trial = dictionary
comment trial['one']='uno'
print trial
set trial = dict string two string dos ; string three string thres ; string four string quathros
set trial at string one = string uno
print trial
print trial at string one
comment you need the kay for the in operator, the value wont work
... | """DICTIONARIES"""
trial=dict()
# trial['one']='uno'
print(trial)
trial = {'two':'dos','three':'thres','four':'quathros'}
trial['one']='uno'
print(trial)
print(trial['one'])
#you need the kay for the in operator, the value wont work
def messing(trial):
vals = trial.values()
if 'one' in trial and 'thres' in va... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set name = string
set address = string
set coordinates = list
set weatherHours = list
set currentHour = 0
end function | def __init__(self):
self.name = ""
self.address = ""
self.coordinates = []
self.weatherHours = []
self.currentHour = 0 | Python | nomic_cornstack_python_v1 |
comment this method implement addintion of two number
function add x y
begin
return x + y
end function
comment this method implement subtraction of two number
function subtract x y
begin
return x - y
end function
comment this method implement multiplication of two number
function multiply x y
begin
return x * y
end fun... | # this method implement addintion of two number
def add(x,y):
return x + y
# this method implement subtraction of two number
def subtract(x,y):
return x -y
# this method implement multiplication of two number
def multiply(x,y):
return x * y
# this method implement Division of two number
def divide(x, y):
... | Python | zaydzuhri_stack_edu_python |
function SetOutputParametersFromImage self image
begin
return call itkResampleImageFilterVIUC3VIUC3_SetOutputParametersFromImage self image
end function | def SetOutputParametersFromImage(self, image: 'itkImageBase3') -> "void":
return _itkResampleImageFilterPython.itkResampleImageFilterVIUC3VIUC3_SetOutputParametersFromImage(self, image) | Python | nomic_cornstack_python_v1 |
function dim self
begin
return ndim
end function | def dim(self):
return self._counts.ndim | Python | nomic_cornstack_python_v1 |
comment Write a program in Python to check if a sequence is a Palindrome.
function palindrome a
begin
set n = length a
if n == 1
begin
print string Enter digit keeping space.
end
else
begin
set b = a at slice : : - 1
if a == b
begin
print string Penlindrome
end
else
begin
print string Not Palindrome
end
end
end funct... | # Write a program in Python to check if a sequence is a Palindrome.
def palindrome(a):
n = len(a)
if n == 1:
print("Enter digit keeping space.")
else:
b = a[::-1]
if a == b:
print("Penlindrome")
else:
print("Not Palindrome")
a = list(map(int,input("I... | Python | zaydzuhri_stack_edu_python |
from html.parser import HTMLParser
import urllib.request
import os
set readData = false
set filename = string
class MyHTMLParser extends HTMLParser
begin
function handle_starttag self tag attrs
begin
if tag == string p or tag == string div
begin
if attrs
begin
set attr_name = list comprehension x at 1 for x in attrs a... | from html.parser import HTMLParser
import urllib.request
import os
readData = False
filename = ""
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
if tag == "p" or tag == "div":
if(attrs):
attr_name = [x[1] for x in attrs][0]
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Table extends QWidget
begin
function __init__ self
begin
call __init__
call initUI
end function
function initUI self
begin
call setWindowTitle string QTableWidg... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Table(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("QTableWidget例子")
self.... | Python | zaydzuhri_stack_edu_python |
function test_entities__get_bound_schema_field__1 address_book
begin
set field = call get_bound_schema_field address_book address_book_entity call getRawField string title
assert address_book == context
assert string title == __name__
assert is instance field TextLine
end function | def test_entities__get_bound_schema_field__1(address_book):
field = get_bound_schema_field(address_book, address_book_entity,
address_book_entity.getRawField('title'))
assert address_book == field.context
assert 'title' == field.__name__
assert isinstance(field, zope.s... | Python | nomic_cornstack_python_v1 |
comment python script um den gradienten der Abstandsfunktion zu berechnen. Die Abstandsfunktion bezieht sich auf die Punkte (den nächsten) und nicht die Linie
import numpy as np
import matplotlib.pyplot as plt
import math
comment Number of legs
set N = 4
comment Number of measurements
set M = 10
comment Measurement poi... | #python script um den gradienten der Abstandsfunktion zu berechnen. Die Abstandsfunktion bezieht sich auf die Punkte (den nächsten) und nicht die Linie
import numpy as np
import matplotlib.pyplot as plt
import math
# Number of legs
N = 4
# Number of measurements
M = 10
# Measurement points
rc = [(np.ra... | Python | zaydzuhri_stack_edu_python |
function store self obs act rew next_obs done
begin
set transition = call store obs act rew next_obs done
if transition
begin
set sum_tree at tree_ptr = max_priority ^ alpha
set min_tree at tree_ptr = max_priority ^ alpha
set tree_ptr = tree_ptr + 1 % max_size
end
return transition
end function | def store(
self,
obs: np.ndarray,
act: int,
rew: float,
next_obs: np.ndarray,
done: bool,
) -> Tuple[np.ndarray, np.ndarray, float, np.ndarray, bool]:
transition = super().store(obs, act, rew, next_obs, done)
if transition:
se... | Python | nomic_cornstack_python_v1 |
function index vec base
begin
set index = 0
for i in range length vec
begin
set index = index + vec at i * base ^ i
end
return integer index
end function | def index(vec, base):
index = 0
for i in range(len(vec)):
index += (vec[i]*(base**i))
return int(index) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.