code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function _generate_sketch_matrix rand_h rand_s output_dim
begin
comment Generate a sparse matrix for tensor count sketch
set rand_h = as type rand_h int64
set rand_s = as type rand_s float32
assert ndim == 1 and ndim == 1 and length rand_h == length rand_s
assert all rand_h >= 0 and all rand_h < output_dim
set input_di... | def _generate_sketch_matrix(rand_h, rand_s, output_dim):
# Generate a sparse matrix for tensor count sketch
rand_h = rand_h.astype(np.int64)
rand_s = rand_s.astype(np.float32)
assert (rand_h.ndim == 1 and rand_s.ndim == 1 and len(rand_h) == len(rand_s))
assert (np.all(rand_h >= ... | Python | nomic_cornstack_python_v1 |
function root_init_file_path self
begin
return join path root_directory_path string __init__.py
end function | def root_init_file_path(self):
return os.path.join(self.root_directory_path, "__init__.py") | Python | nomic_cornstack_python_v1 |
function recurse ftp limit dumpdir directory
begin
set path = directory
call cwd path
set files = call nlst
for dirent in files
begin
set fpath = join path path dirent
try
begin
set size = size ftp fpath
if size < limit
begin
if not call download ftp fpath dumpdir
begin
print format string Failed to download {} fpath
e... | def recurse(ftp, limit, dumpdir, directory):
path = directory
ftp.cwd(path)
files = ftp.nlst()
for dirent in files:
fpath = os.path.join(path, dirent)
try:
size = ftp.size(fpath)
if size < limit:
if not download(ftp, fpath, dumpdir):
... | Python | nomic_cornstack_python_v1 |
from PIL import Image
from random import randint
function getColor
begin
set randomColor = random integer 0 4
if randomColor == 0
begin
set color = tuple 150 206 180
end
else
if randomColor == 1
begin
set color = tuple 255 238 173
end
else
if randomColor == 2
begin
set color = tuple 255 111 105
end
else
if randomColor ... | from PIL import Image
from random import randint
def getColor():
randomColor = randint(0, 4)
if randomColor == 0:
color = (150, 206, 180)
elif randomColor == 1:
color = (255, 238, 173)
elif randomColor == 2:
color = (255, 111, 105)
elif randomColor == 3:
color = (255... | Python | zaydzuhri_stack_edu_python |
function _add_symbol self name dim domain attrs
begin
comment Transform the attrs for storage, unpack data
set gdx_attrs = dictionary comprehension format string _gdx_{} k : v for tuple k v in items attrs
set data = _state at name at string data
set elements = _state at name at string elements
comment Erase the cache; ... | def _add_symbol(self, name, dim, domain, attrs):
# Transform the attrs for storage, unpack data
gdx_attrs = {'_gdx_{}'.format(k): v for k, v in attrs.items()}
data = self._state[name]['data']
elements = self._state[name]['elements']
# Erase the cache; this also prevents __getite... | Python | nomic_cornstack_python_v1 |
string Adapted from code by Jean Harb and Pierre Luc Bacon PhD students McGill University
import gym
import numpy as np
from fourrooms import Fourrooms
from scipy.special import expit
from scipy.misc import logsumexp
class Tabular
begin
function __init__ self nstates
begin
set nstates = nstates
end function
function __... | """ Adapted from code by Jean Harb and Pierre Luc Bacon
PhD students McGill University """
import gym
import numpy as np
from fourrooms import Fourrooms
from scipy.special import expit
from scipy.misc import logsumexp
class Tabular:
def __init__(self, nstates):
self.nstates = nstates
def __call_... | Python | zaydzuhri_stack_edu_python |
import datetime
from app import db
class Content extends Model
begin
string Create content table
set __tablename__ = string content
set id = call Column Integer primary_key=true unique=true
set chef_desc = call Column Text
set created_at = call Column DateTime default=now
function __repr__ self
begin
return format stri... | import datetime
from app import db
class Content(db.Model):
"""
Create content table
"""
__tablename__ = 'content'
id = db.Column(db.Integer, primary_key=True, unique=True)
chef_desc = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.datetime.now)
def __repr__(... | Python | zaydzuhri_stack_edu_python |
function _get_path self scope name
begin
return call path scope name
end function | def _get_path(self, scope, name):
return self.translator.path(scope, name) | Python | nomic_cornstack_python_v1 |
comment Band Name Generator Project
import numpy as np
print string Welcome to the Band Name Generator.
set city = input string What's name of the city of grew up in?
set petName = input string What's your pet's name?
print string Your band name could be + city + string + petName + string .
set a = array list 1 2 3
pr... | # Band Name Generator Project
import numpy as np
print("Welcome to the Band Name Generator.")
city = input("What's name of the city of grew up in?\n")
petName = input("What's your pet's name?\n")
print("Your band name could be " + city + " " + petName + ".")
a = np.array([1, 2, 3])
print(a)
| Python | zaydzuhri_stack_edu_python |
string Most arcade-style shooting games report scores as multiples of 10, so let's follow that lead with our scoring. Let's also format the score to include comma separators in large numbers. We'll make this change in Scoreboard:
comment scoreboard.py
function prep_score self
begin
string Turn the score into a rendered... | """
Most arcade-style shooting games report scores as multiples of 10, so let's follow that lead
with our scoring. Let's also format the score to include comma separators in large numbers.
We'll make this change in Scoreboard:
"""
# scoreboard.py
def prep_score(self):
"""Turn the score into a rendered image."""
... | Python | zaydzuhri_stack_edu_python |
import os
call system string shutdown /h | import os
os.system('shutdown /h')
| Python | flytech_python_25k |
function error self table_name key error_message error_stack=none
begin
string Log an error message. The job reservation is replaced with an error entry. if an error occurs, leave an entry describing the problem :param table_name: `database`.`table_name` :param key: the dict of the job's primary key :param error_messag... | def error(self, table_name, key, error_message, error_stack=None):
"""
Log an error message. The job reservation is replaced with an error entry.
if an error occurs, leave an entry describing the problem
:param table_name: `database`.`table_name`
:param key: the dict of the job'... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Created on Sun Feb 14 18:41:51 2016 @author: ronan
import pandas as pd
call set_option string display.mpl_style string default
call figsize 15 5
set na_val = list string ? string ? string ...
set f_names = read csv string ./data/featurenames.txt header=none
set d_set = read csv stri... | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 14 18:41:51 2016
@author: ronan
"""
import pandas as pd
pd.set_option('display.mpl_style', 'default')
figsize(15, 5)
na_val=['?',' ?',' ...']
f_names = pd.read_csv('./data/featurenames.txt',header=None)
d_set = pd.read_csv('./data/DataSet.txt', sep =",",header=None, n... | Python | zaydzuhri_stack_edu_python |
comment 算法导论的第10页,插入排序,数组升序排列。
function insertion_sort_UP A
begin
for j in range 1 length A
begin
set key = A at j
set i = j - 1
while i >= 0 and A at i > key
begin
set A at i + 1 = A at i
set i = i - 1
end
set A at i + 1 = key
end
return A
end function
comment 算法导论的第10页,插入排序,数组降序排列。
function insertion_sort_DOWN A
begi... | #算法导论的第10页,插入排序,数组升序排列。
def insertion_sort_UP(A):
for j in range(1,len(A)):
key = A[j]
i = j - 1
while i>=0 and A[i]>key:
A [i+1] = A[i]
i = i-1
A[i+1] = key
return A
#算法导论的第10页,插入排序,数组降序排列。
def insertion_sort_DOWN(A):
for j in range(1,len(A)):
key = A[j]
i = j - 1
while i>=0 and A[i]<key:
A ... | Python | zaydzuhri_stack_edu_python |
comment Public libraries
import pandas as pd
import os
import sys
insert path 1 string ./Given_Files
comment Private libraries
import homework1
import hazard
import remic
comment Through out the code we use _A to indicate the object has both normal paths and antithetic paths
set tables_file = open string Results/tables... | # Public libraries
import pandas as pd
import os
import sys
sys.path.insert(1,'./Given_Files')
# Private libraries
import homework1
import hazard
import remic
#
# Through out the code we use _A to indicate the object has both normal paths and antithetic paths
#
tables_file = open("Results/tables_latex_format.txt",... | Python | zaydzuhri_stack_edu_python |
function setrange
begin
debug string Entering setrange
call flash format string Setrange gave us '{}' get form string daterange
set daterange = get form string daterange
set session at string daterange = daterange
set daterange_parts = split daterange
set session at string begin_date = call interpret_date daterange_par... | def setrange():
app.logger.debug("Entering setrange")
flask.flash("Setrange gave us '{}'".format(
request.form.get('daterange')))
daterange = request.form.get('daterange')
flask.session['daterange'] = daterange
daterange_parts = daterange.split()
flask.session['begin_date'] = interpret_d... | Python | nomic_cornstack_python_v1 |
function plot_coeff_all_boxplot sto list_OPtype
begin
set list_station = list keys sto
set tuple f axes = call subplots nrows=length list_OPtype ncols=1 sharex=true figsize=tuple 17 length list_OPtype * 5
set sources = list
for s in values sto
begin
set sources = sources + list comprehension a for a in index if a not ... | def plot_coeff_all_boxplot(sto, list_OPtype):
list_station = list(sto.keys())
f, axes = plt.subplots(nrows=len(list_OPtype), ncols=1, sharex=True,
figsize=(17,len(list_OPtype)*5))
sources = []
for s in sto.values():
sources = sources+[a for a i... | Python | nomic_cornstack_python_v1 |
set tup = tuple 1 2 3 4
set tuple a b c d = tup
print string a: a
print string b: b
print string c: c
print string d: d | tup=(1,2,3,4)
a,b,c,d=tup
print("a:",a)
print("b:",b)
print("c:",c)
print("d:",d)
| Python | zaydzuhri_stack_edu_python |
import numpy as np
from keras.layers import Input
from keras.layers.core import Dense , Activation , Flatten
from keras.layers.convolutional import Conv2D , MaxPooling2D
from keras.models import Model
from keras.datasets import fashion_mnist
class LeNet extends object
begin
string "Object Recognition with Gradient-Base... | import numpy as np
from keras.layers import Input
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.models import Model
from keras.datasets import fashion_mnist
class LeNet(object):
'''
"Object Recognition with Gradient-Based Learni... | Python | zaydzuhri_stack_edu_python |
function getData self data_source
begin
if is instance data_source str
begin
try
begin
return eval data_source
end
except tuple NameError SyntaxError
begin
try
begin
set data_f = open data_source string U
set data = read data_f
close data_f
try
begin
return eval data
end
except tuple NameError SyntaxError TypeError
beg... | def getData(self, data_source):
if isinstance(data_source, str):
try:
return eval(data_source)
except (NameError, SyntaxError):
try:
data_f = open(data_source, 'U')
data = data_f.read()
da... | Python | nomic_cornstack_python_v1 |
function verify_pw username password
begin
set credentials = call HtpasswdFile config at string CREDENTIAL_FILE
if not call check_password username password
begin
warning string %s tried to login with wrong password username
return false
end
return true
end function | def verify_pw(username, password):
credentials = HtpasswdFile(app.config["CREDENTIAL_FILE"])
if not credentials.check_password(username, password):
logging.warning("%s tried to login with wrong password", username)
return False
return True | Python | nomic_cornstack_python_v1 |
function process_unknown self root header name
begin
raise call SoapFault string soapenv:Server string No handler for %s % tuple name
end function | def process_unknown(self, root, header, name):
raise SoapFault(u'soapenv:Server', u'No handler for %s' % (name,)) | Python | nomic_cornstack_python_v1 |
comment Column Names
comment Valeurs Foncieres table
set vf_street_num = string No voie
set vf_street_type = string Type de voie
set vf_price_nominal = string Valeur fonciere
set vf_built_area = string Surface reelle bati
set vf_square_meter_price = string prix_m2
set vf_street_name = string Voie
comment Cadastre table... | # Column Names
# Valeurs Foncieres table
vf_street_num = "No voie"
vf_street_type = "Type de voie"
vf_price_nominal = "Valeur fonciere"
vf_built_area = "Surface reelle bati"
vf_square_meter_price = "prix_m2"
vf_street_name = "Voie"
# Cadastre table
cad_street_full = "voie_nom"
cad_street_type = "Type de voie"
cad_stree... | Python | zaydzuhri_stack_edu_python |
function get_players_for_match match_id
begin
set cursor = call cursor
set sql = string SELECT player_id, side, status FROM match_players WHERE match_id = %s
execute cursor sql tuple match_id
set players = call fetchall
close cursor
return players
end function | def get_players_for_match(match_id):
cursor = mysql.connection.cursor()
sql = "SELECT player_id, side, status FROM match_players WHERE match_id = %s"
cursor.execute(sql, (match_id,))
players = cursor.fetchall()
cursor.close()
return players | Python | nomic_cornstack_python_v1 |
import adventure_game.my_utils as utils
comment ROOM 15
set room15_inventory = dict string sword 1
set room15_description = string . . .Room 15. . . You descend further down and enter a room with a small layer of water covering the floor. You see a skeleton lying in the corner of the room with a *sword* still in its bo... | import adventure_game.my_utils as utils
#ROOM 15
room15_inventory = {
"sword": 1
}
room15_description = '''
. . .Room 15. . .
You descend further down and enter a room with a small layer of water
covering the floor. You see a skeleton lying in the corner of the room
with a *sword* s... | Python | zaydzuhri_stack_edu_python |
function add_feat_conf self conf_map
begin
set conf_map at string phase_support_trigger = replace string call text string string
set conf_map at string phase_min = string call text
set conf_map at string phase_max = string call text
end function | def add_feat_conf(self, conf_map):
conf_map['phase_support_trigger'] = str(self.phase_triggers.text()).replace('\n', '')
conf_map['phase_min'] = str(self.phase_min.text())
conf_map['phase_max'] = str(self.phase_max.text()) | Python | nomic_cornstack_python_v1 |
import os
string aFile = open("aws.txt") print(aFile.readline()) print(aFile.read()) aFile.close()
string try: aFile = open("a.txt") print(aFile.readline()) print(aFile.read()) except: print("File Does not exists") finally: aFile.close()
with open string aws.txt as afile
begin
print tell afile
print read line afile
pri... | import os
'''
aFile = open("aws.txt")
print(aFile.readline())
print(aFile.read())
aFile.close()
'''
'''
try:
aFile = open("a.txt")
print(aFile.readline())
print(aFile.read())
except:
print("File Does not exists")
finally:
aFile.close()
'''
with open('aws.txt') as afile:
print(afile.tell(... | Python | zaydzuhri_stack_edu_python |
string create_python_project.project ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Implement ProjectManager which is the main class for manipulating a project :copyright: Copyright 2017 by Nicolas Maurice, see AUTHORS.rst for more details. :license: BSD, see :ref:`license` for more details.
from git import RepositoryManager
from utils... | """
create_python_project.project
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implement ProjectManager which is the main class for manipulating a project
:copyright: Copyright 2017 by Nicolas Maurice, see AUTHORS.rst for more details.
:license: BSD, see :ref:`license` for more details.
"""
from .git import Rep... | Python | zaydzuhri_stack_edu_python |
function help
begin
set text = string DELETE_PROJECT USAGE: %s project [project [project]]... % base name path argv at 0
end function | def help():
text = """
DELETE_PROJECT
USAGE:
%s project [project [project]]...
\n""" % (os.path.basename(sys.argv[0])) | Python | nomic_cornstack_python_v1 |
function _assert_libvirt_calls self mock_libvirt_domain mock_libvirt_open readonly=false
begin
call assert_called_once_with ANY domain at string domain_name
set params = dict string sasl_password domain at string libvirt_sasl_password ; string sasl_username domain at string libvirt_sasl_username ; string uri domain at ... | def _assert_libvirt_calls(self, mock_libvirt_domain, mock_libvirt_open,
readonly=False):
mock_libvirt_domain.assert_called_once_with(
mock.ANY, self.domain['domain_name'])
params = {'sasl_password': self.domain['libvirt_sasl_password'],
'sasl_u... | Python | nomic_cornstack_python_v1 |
comment Exercício Python 061: Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA,
comment mostrando os 10 primeiros termos da progressão usando a estrutura while.
string termo = int(input('Digite o 1 termo: ')) razao = int(input('Digite a razao: ')) decimo = termo + (razao*9) for c in range(termo,decimo+ ... | #Exercício Python 061: Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA,
# mostrando os 10 primeiros termos da progressão usando a estrutura while.
"""termo = int(input('Digite o 1 termo: '))
razao = int(input('Digite a razao: '))
decimo = termo + (razao*9)
for c in range(termo,decimo+ 1 ,razao):... | Python | zaydzuhri_stack_edu_python |
function test_socket self
begin
set s1 = call Socket call Spring
set s2 = call Socket call Spring
comment Something is seriously wrong if this first one doesn't pass...
assert equal s1 s1
assert equal s1 s2
end function | def test_socket(self):
s1 = classes.Socket(classes.Spring())
s2 = classes.Socket(classes.Spring())
## Something is seriously wrong if this first one doesn't pass...
self.assertEqual(s1,s1)
self.assertEqual(s1,s2) | Python | nomic_cornstack_python_v1 |
function format_num self i_num
begin
import locale
for code in tuple string en_GB string en_US string de_DE
begin
try
begin
call setlocale LC_ALL code
return format locale string %d i_num true
end
except any
begin
warning string Could not encode number + code + string + call unicode i_num
end
end
return call unicode i... | def format_num(self, i_num):
import locale
for code in ('en_GB', 'en_US', 'de_DE'):
try:
locale.setlocale(locale.LC_ALL, code)
return locale.format('%d', i_num, True)
except:
self._logger.warning("Could not encode number " + code + ... | Python | nomic_cornstack_python_v1 |
while i < length list1
begin
set my_dict1 = list2 at i
set list list1 at i = list2 at i
set i = i + 1
end
print my_dict1 | while i<len(list1):
my_dict1=[list1[i]]=list2[i]
i+=1
print(my_dict1)
| Python | zaydzuhri_stack_edu_python |
function list_subscribed_workteams NameContains=none NextToken=none MaxResults=none
begin
pass
end function | def list_subscribed_workteams(NameContains=None, NextToken=None, MaxResults=None):
pass | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
set f = open string motor_results.dat string r
set lines = read lines f
close f
set left = list
set right = list
for line in lines
begin
set line = strip line
set tuple l r = split line string
append left - integer l
append right - integer r
end
set time = list comprehension i / 100.0 ... | import matplotlib.pyplot as plt
f = open('motor_results.dat','r')
lines = f.readlines()
f.close()
left = []
right = []
for line in lines:
line = line.strip()
l, r = line.split(' ')
left.append(-int(l))
right.append(-int(r))
time = [(i)/100.0 for i in range(len(left))]
print (left)
plt.plot(time,... | Python | zaydzuhri_stack_edu_python |
string https://leetcode.com/problems/koko-eating-bananas/ Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas... | '''
https://leetcode.com/problems/koko-eating-bananas/
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas.
The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k.
Each hour, she chooses some pile of bananas and eats k bananas ... | Python | zaydzuhri_stack_edu_python |
class Foo extends object
begin
comment 参见Data model ~ 自定义属性访问
comment 显式声明数据成员,避免为每个instance对象创建__dict__和__weakref__,进而避免浪费空间
set __slots__ = tuple string name string age
function __init__ self name age
begin
set name = name
set age = age
end function
function f self
begin
print name age
end function
end class
set foo ... | class Foo(object):
# 参见Data model ~ 自定义属性访问
__slots__ = ('name', 'age') # 显式声明数据成员,避免为每个instance对象创建__dict__和__weakref__,进而避免浪费空间
def __init__(self, name, age):
self.name = name
self.age = age
def f(self):
print(self.name, self.age)
foo = Foo('张三', 28)
foo.f()
foo.name = ... | Python | zaydzuhri_stack_edu_python |
if w in range 0 10
begin
print string yes
end
else
begin
print string no
end | if w in range(0,10):
print("yes")
else:
print("no")
| Python | zaydzuhri_stack_edu_python |
function tmp_img tmpdir
begin
set img_path = join tmpdir string image.jpg
set im = call new string RGB tuple 160 160
save strpath
return img_path
end function | def tmp_img(tmpdir):
img_path = tmpdir.join("image.jpg")
im = Image.new("RGB", (160, 160))
im.save(img_path.strpath)
return img_path | Python | nomic_cornstack_python_v1 |
from abstract_neural_network import AbstractNeuralNetwork
import numpy as np
import layer
import random | from abstract_neural_network import AbstractNeuralNetwork
import numpy as np
import layer
import random
| Python | zaydzuhri_stack_edu_python |
function draw_static_objects self
begin
call draw_anchors
call draw_data_frame_axes
call draw_ground
end function
comment TODO: remove me!
comment plt.show() | def draw_static_objects(self):
self.draw_anchors()
self.draw_data_frame_axes()
self.draw_ground()
# TODO: remove me!
# plt.show() | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from sklearn.utils import shuffle
import pickle
function get_preprocessed_train_val_test_data
begin
set df = read csv string train.csv
set data = call as_matrix
set data = data at tuple slice : : slice 1 : :
set dict = dict string A 0 ; string C 1 ; string G 2 ; string T 3
se... | import pandas as pd
import numpy as np
from sklearn.utils import shuffle
import pickle
def get_preprocessed_train_val_test_data():
df = pd.read_csv('train.csv')
data = df.as_matrix()
data = data[:,1:]
dict = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
seq_data = []
label_data = []
for rna_seq, label i... | Python | zaydzuhri_stack_edu_python |
function validate self value
begin
raise call NotImplementedError string %s is an internal or organizational parameter, and is not intended to be used. % name
end function | def validate(self, value):
raise NotImplementedError("%s is an internal or organizational parameter, and is not intended to be used."%self.name) | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
set total_files = list 90 180 270 360 450
set acc_list = list 94 96 97 98 99
plot total_files acc_list
x label string Total Files
y label string Accuracy (%)
show | import matplotlib.pyplot as plt
total_files = [90, 180, 270, 360, 450]
acc_list = [94, 96, 97, 98, 99]
plt.plot(total_files, acc_list)
plt.xlabel("Total Files")
plt.ylabel('Accuracy (%)')
plt.show() | Python | zaydzuhri_stack_edu_python |
comment The loop will run until the game finishes
while gameRunning
begin
comment for every word in the phrase
for word in wordsInPhrase
begin
comment for every letter in that word
for letter in word
begin
comment if that letter has been guessed (we use .lower() here to make sure that uppercase and lowercase letters ar... | # The loop will run until the game finishes
while gameRunning:
# for every word in the phrase
for word in wordsInPhrase:
# for every letter in that word
for letter in word:
# if that letter has been guessed (we use .lower() here to make sure that uppercase and lowercase letters are ... | Python | zaydzuhri_stack_edu_python |
function __lt__ self other
begin
return pathCost < pathCost
end function | def __lt__(self, other):
return self.pathCost < other.pathCost | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Wed Jun 29 16:09:35 2016 @author: Administrator
import pandas as pd
comment 餐饮菜品盈利数据
set dish_profit = string demo/data/catering_dish_profit.xls
set data = call read_excel dish_profit index_col=string 菜品名
set data = copy data at string 盈利
sort data ascending=false
import ... | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 29 16:09:35 2016
@author: Administrator
"""
import pandas as pd
dish_profit = 'demo/data/catering_dish_profit.xls' #餐饮菜品盈利数据
data=pd.read_excel(dish_profit, index_col=u'菜品名')
data=data[u'盈利'].copy()
data.sort(ascending = False)
import matplotlib.pylab as plt
plt.rcPara... | Python | zaydzuhri_stack_edu_python |
comment msg ='Welcome to Python 101: Split and Join'
comment csv = 'Eric,John,Michael,Terry,Graham'
comment friends_list = ['Eric','John','Michael','Terry','Graham']
comment print(msg.split()) #changes a string into a list
comment print(csv.split(','))#changes a string into ta list by ','
comment print(' '.join(friends... | # msg ='Welcome to Python 101: Split and Join'
# csv = 'Eric,John,Michael,Terry,Graham'
# friends_list = ['Eric','John','Michael','Terry','Graham']
# print(msg.split()) #changes a string into a list
# print(csv.split(','))#changes a string into ta list by ','
# print(' '.join(friends_list)) #changes a list into a stri... | Python | zaydzuhri_stack_edu_python |
comment imports
comment all of them
from tkinter import *
comment FunCTIONS
comment clasSes
comment And StuFF
class Circle
begin
function __init__ self x y r
begin
set x = x
set y = y
set r = r
end function
function render self
begin
call create_oval x - r y - r x + r y + r
end function
end class
comment Main
comment C... | # imports
# all of them
from tkinter import *
# FunCTIONS
# clasSes
# And StuFF
class Circle:
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
def render(self):
canvas.create_oval(self.x - self.r, self.y -
self.r, self.x + self.r, self... | Python | zaydzuhri_stack_edu_python |
from Equation import Equation
from LinearProblem import LinearProblem
import random
import itertools
class RandomSolver
begin
global VECTORS
set VECTORS = 100
global ITERATIONS
set ITERATIONS = 100
decorator staticmethod
function solve lp
begin
comment Encontrar valores limite de las variables
set randLimits = list
fo... | from Equation import Equation
from LinearProblem import LinearProblem
import random
import itertools
class RandomSolver():
global VECTORS
VECTORS = 100
global ITERATIONS
ITERATIONS = 100
@staticmethod
def solve(lp):
#Encontrar valores limite de las variables
randLimits = []
for i in range(0, lp.nvars)... | Python | zaydzuhri_stack_edu_python |
import csv
import traceback
from sys import exit
from os import chdir
from glob import glob
from copy import deepcopy
from random import shuffle
set CARD_PATH = string /var/patient_cards
function catch_exc func
begin
function wrapper *args **kwargs
begin
try
begin
return call func *args keyword kwargs
end
except any
be... | import csv
import traceback
from sys import exit
from os import chdir
from glob import glob
from copy import deepcopy
from random import shuffle
CARD_PATH = "/var/patient_cards"
def catch_exc(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
t... | Python | zaydzuhri_stack_edu_python |
function is_motorcycle self
begin
if wheels == 2
begin
return true
end
else
begin
return false
end
end function | def is_motorcycle(self):
if self.wheels == 2:
return True
else:
return False | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
comment Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
comment Only one letter can be changed at a time
comment Each transformed word must exist in the word list. Note that beginWord i... | # -*- coding:utf-8 -*-
#
# Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
#
#
# Only one letter can be changed at a time
# Each transformed word must exist in the word list. Note that beginWord is not a transf... | Python | zaydzuhri_stack_edu_python |
function safe_request fct
begin
string Return json messages instead of raising errors
function inner *args **kwargs
begin
string decorator
try
begin
set _data = call fct *args keyword kwargs
end
except ConnectionError as error
begin
return dict string error string error ; string status 404
end
if ok
begin
if content
be... | def safe_request(fct):
''' Return json messages instead of raising errors '''
def inner(*args, **kwargs):
''' decorator '''
try:
_data = fct(*args, **kwargs)
except requests.exceptions.ConnectionError as error:
return {'error': str(error), 'status': 404}
... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Задание 22.4 Создать функцию send_and_parse_show_command. Параметры функции: * device_dict - словарь с параметрами подключения к одному устройству * command - команда, которую надо выполнить * templates_path - путь к каталогу с шаблонами TextFSM * index - имя индекс файла, значение ... | # -*- coding: utf-8 -*-
"""
Задание 22.4
Создать функцию send_and_parse_show_command.
Параметры функции:
* device_dict - словарь с параметрами подключения к одному устройству
* command - команда, которую надо выполнить
* templates_path - путь к каталогу с шаблонами TextFSM
* index - имя индекс файла, значение по умол... | Python | zaydzuhri_stack_edu_python |
function __init__ self path
begin
comment Metadata Definition
set metadata = read csv path nrows=5 header=none
set subject = string loc at tuple 0 0
set base_date = call date
if loc at tuple 4 0 != string Unknown Line
begin
set valid_measurements = string loc at tuple 4 0
end
else
begin
set metadata = read csv path nro... | def __init__(self, path):
# Metadata Definition
metadata = pd.read_csv(path, nrows=5, header=None)
self.subject = str(metadata.loc[0, 0])
base_date = dt.datetime.strptime(metadata.loc[2, 0], '%d.%m.%Y').date()
if metadata.loc[4, 0] != 'Unknown Line':
self.valid_measu... | Python | nomic_cornstack_python_v1 |
string This example demonstrates how to use MSXML to load transform XML using XSLT
import win32com.client
set input_xml = string <foo> <bar> <beer/> </bar> <beer/> </foo>
function load_xml_string s
begin
set dom = call Dispatch string Microsoft.XMLDOM
set validateOnParse = 0
call loadXML s
if call parseError != 0
begin... | """
This example demonstrates how to use MSXML to load transform XML using XSLT
"""
import win32com.client
input_xml = """
<foo>
<bar>
<beer/>
</bar>
<beer/>
</foo>
"""
def load_xml_string( s ) :
dom = win32com.client.Dispatch("Microsoft.XMLDOM")
dom.validateOnParse = 0
dom.loadXM... | Python | zaydzuhri_stack_edu_python |
function read_speaker_data_from_file data_path find_min_max_p=true
begin
with open data_path string r as fp
begin
set d = read fp
end
set d = eval d
if find_min_max_p
begin
set all_lengths = list chain *d.values()
set lmin = min all_lengths
set lmax = max all_lengths
end
end function | def read_speaker_data_from_file(data_path, find_min_max_p=True):
with open(data_path, 'r') as fp:
d = fp.read()
d = eval(d)
if find_min_max_p:
all_lengths = list(itertools.chain(*d.values()))
lmin = min(all_lengths)
lmax = max(all_lengths) | Python | nomic_cornstack_python_v1 |
function plot_concatenated dataframe title=string x=none y=none err=none xlabel=none ylabel=none points=true line=true errors=true hover=true width=800 height=300 journal=none file_id_level=0 hdr_level=none axis=1 mean_end=string _mean std_end=string _std cycle_end=string cycle_index legend_title=string cell-type mark... | def plot_concatenated(
dataframe,
title="",
x=None,
y=None,
err=None,
xlabel=None,
ylabel=None,
points=True,
line=True,
errors=True,
hover=True,
width=800,
height=300,
journal=None,
file_id_level=0,
hdr_level=None,
axis=1,
mean_end="_mean",
std... | Python | nomic_cornstack_python_v1 |
string The Hamming distance.
function distance string1 string2
begin
string Return the number of positions where the symbols are different.
if length string1 != length string2
begin
raise call ValueError string1 string2
end
return sum generator expression 1 for tuple sym1 sym2 in zip string1 string2 if sym1 != sym2
end... | """The Hamming distance."""
def distance(string1, string2):
"""Return the number of positions where the symbols are different."""
if len(string1) != len(string2):
raise ValueError(string1, string2)
return sum(1 for sym1, sym2 in zip(string1, string2) if sym1 != sym2)
| Python | zaydzuhri_stack_edu_python |
import sys
function sort **kwargs
begin
string SORT User Commands SORT NAME sort - sorts files SYNOPSIS sort [FILE] DESCRIPTION sort sorts FILEs by the given option. Default is alphebetically with blank lines followed by capital letters, then lowercase below them. EXAMPLE sort file.txt
if string params in kwargs
begin
... | import sys
def sort (**kwargs):
"""
SORT User Commands SORT
NAME
sort - sorts files
SYNOPSIS
sort [FILE]
DESCRIPTION
sort sorts FILEs by the given option. Default is alphebetically with blank
lines followed by capital le... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Nov 2 10:40:25 2016 @author: ansohn
from tpot import TPOT
import numpy as np
import pandas as pd
import time
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestClassifier
set input_data = string /home/ansohn/Python/data/cgem... | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 2 10:40:25 2016
@author: ansohn
"""
from tpot import TPOT
import numpy as np
import pandas as pd
import time
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestClassifier
input_data = '/home/ansohn/Python/data/cgems/CGEMS-p... | Python | zaydzuhri_stack_edu_python |
function perspective_blockdev_shutdown params
begin
set bdev_s = params at 0
set bdev = call FromDict bdev_s
if bdev is none
begin
raise call ValueError string can't unserialize data!
end
return call BlockdevShutdown bdev
end function | def perspective_blockdev_shutdown(params):
bdev_s = params[0]
bdev = objects.Disk.FromDict(bdev_s)
if bdev is None:
raise ValueError("can't unserialize data!")
return backend.BlockdevShutdown(bdev) | Python | nomic_cornstack_python_v1 |
comment in checks if one string is part of another string.
comment Using in results in a boolean expression
comment Write contains function
function contains big_string little_string
begin
comment If little_string in big_string
if little_string in big_string
begin
comment Return True
return true
end
comment Return Fals... | # in checks if one string is part of another string.
# Using in results in a boolean expression
# Write contains function
def contains(big_string, little_string):
# If little_string in big_string
if(little_string in big_string):
# Return True
return True
# Return False
return False
# Write common_lett... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string Computing GC Content
from helpers.data import parse_FASTA
function get_GC DNA
begin
string Returns DNA string and GC content of that string. /!\ GC content is given as a percentage rather than a fraction. /! Input: - DNA: string of DNA nucleotides Output: - DNA: string of DNA nucleot... | #!/usr/bin/env python
'''
Computing GC Content
'''
from helpers.data import parse_FASTA
def get_GC(DNA):
'''
Returns DNA string and GC content of that string.
/!\ GC content is given as a percentage rather than a fraction. /!\
Input:
- DNA: string of DNA nucleotides
Output:
... | Python | zaydzuhri_stack_edu_python |
comment Problem description: https://contest.yandex.ru/contest/19036/problems/B/
comment Solution complexity: time - O(NlogN), space - O(N).
comment Solution:
comment 1) As the problem states, there are N alarms, which ring every X minutes after
comment their starting time. Therefore, if an alarm starts ringing at some... | # Problem description: https://contest.yandex.ru/contest/19036/problems/B/
# Solution complexity: time - O(NlogN), space - O(N).
# Solution:
# 1) As the problem states, there are N alarms, which ring every X minutes after
# their starting time. Therefore, if an alarm starts ringing at some time ti,
# then it wil... | Python | zaydzuhri_stack_edu_python |
function destination_service_name self
begin
return get pulumi self string destination_service_name
end function | def destination_service_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "destination_service_name") | Python | nomic_cornstack_python_v1 |
function generate_cluster_movie dataDir stimulus_information wholeTraces_allTrials_video
begin
print string Generating cluster movie...
comment Directory for where to save the cluster movie
set selected_movie_dir = join path dataDir string cluster.sima
set mov_xDim = call shape wholeTraces_allTrials_video at 1 at 1
set... | def generate_cluster_movie(dataDir, stimulus_information,
wholeTraces_allTrials_video):
print('Generating cluster movie...\n')
# Directory for where to save the cluster movie
selected_movie_dir = os.path.join(dataDir,'cluster.sima')
mov_xDim = np.shape(wholeTraces_allTrials_v... | Python | nomic_cornstack_python_v1 |
import urllib2
import json
comment <- PASTE YOUR BOT'S TOKEN HERE
set BOT_TOKEN = string
comment <- ROOM ID WHERE THE MESSAGE WILL BE POSTED
set OPS_TEAM_SPACE = string
comment <- ROOM ID WHERE DEBUG MESSAGE WILL BE POSTED
set CHATOPS_SPACE = string
set HEADERS = dict string Content-type string application/json; cha... | import urllib2
import json
BOT_TOKEN = "" # <- PASTE YOUR BOT'S TOKEN HERE
OPS_TEAM_SPACE = "" # <- ROOM ID WHERE THE MESSAGE WILL BE POSTED
CHATOPS_SPACE = "" # <- ROOM ID WHERE DEBUG MESSAGE WILL BE POSTED
HEADERS = {"Content-type" : "application/json; charset=utf-8",
"Authorization" : "Bearer %s" % BOT... | Python | zaydzuhri_stack_edu_python |
function get_parts self
begin
set parts = list
set start_byte = 0
for i in range 1 total + 1
begin
set end_byte = start_byte + part_size
if end_byte >= file_size - 1
begin
set end_byte = file_size
end
append parts dict string part i ; string offset start_byte ; string limit end_byte
set start_byte = end_byte
end
retur... | def get_parts(self):
parts = []
start_byte = 0
for i in range(1, self.total + 1):
end_byte = start_byte + self.part_size
if end_byte >= self.file_size - 1:
end_byte = self.file_size
parts.append({
'part': i,
'off... | Python | nomic_cornstack_python_v1 |
function get_mae a b
begin
return mean np absolute array a - array b
end function | def get_mae(a, b):
return np.mean(abs(np.array(a) - np.array(b))) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[6]:
import webbrowser
import pyttsx3
from fuzzywuzzy import fuzz
import tkinter as tk
from tkinter import *
set p = call Tk
set s = call init
set rate = call getProperty string rate
call setProperty string rate 125
set data1 = open string ques.txt string r+
... | #!/usr/bin/env python
# coding: utf-8
# In[6]:
import webbrowser
import pyttsx3
from fuzzywuzzy import fuzz
import tkinter as tk
from tkinter import *
p = tk.Tk()
s = pyttsx3.init()
rate = s.getProperty('rate')
s.setProperty('rate', 125)
data1 = open(r'ques.txt', 'r+')
data2 = open(r'ans.txt', 'r+')
predic = []
answ... | Python | zaydzuhri_stack_edu_python |
function _chol_loggausspdf2 X mu cov
begin
set tuple D N = shape
comment DxN
set X = X - mu
comment DxD
set U = call cholesky cov
set Q = call solve U X
set q = sum Q ^ 2 axis=0
set log_det = sum log call diag U
return - 0.5 * D * _LOG_2PI + q - log_det
end function | def _chol_loggausspdf2(X, mu, cov):
D, N = X.shape
X = X - mu # DxN
U = np.linalg.cholesky(cov) # DxD
Q = np.linalg.solve(U, X)
q = np.sum(Q ** 2, axis=0)
log_det = np.sum(np.log(np.diag(U)))
return -0.5 * (D * _LOG_2PI + q) - log_det | Python | nomic_cornstack_python_v1 |
from os import listdir
from os.path import exists , join
from faasmcli.util.env import FAASM_DATA_DIR
comment Reads are sequences of indexed nucleotides and are the input to the mapper
comment Not sure what the best source is so far, but have found some examples
comment Genome data can be found at ftp://ftp-trace.ncbi.... | from os import listdir
from os.path import exists, join
from faasmcli.util.env import FAASM_DATA_DIR
# Reads are sequences of indexed nucleotides and are the input to the mapper
# Not sure what the best source is so far, but have found some examples
# Genome data can be found at ftp://ftp-trace.ncbi.nih.gov/genomes
... | Python | zaydzuhri_stack_edu_python |
import os
import chardet
function getFileNames
begin
set dir = list directory string D:\Recommender System\Generated Data\type_info_body
return dir
end function
comment with open('D:\\sampleRecom\\data\\recom_new_ps\\train\\methodbody_lessthan4_part1.txt', 'rb') as f:
comment result = chardet.detect(f.read()) # or read... | import os
import chardet
def getFileNames():
dir = os.listdir("D:\\Recommender System\\Generated Data\\type_info_body")
return dir
#with open('D:\\sampleRecom\\data\\recom_new_ps\\train\\methodbody_lessthan4_part1.txt', 'rb') as f:
#result = chardet.detect(f.read()) # or readline if the file is large
dir... | Python | zaydzuhri_stack_edu_python |
comment --------------- Python 26 ---------------
comment ---- Kontrola toka - range() funkcija ---
comment Funkcija range() koristi paremetre (start), (stop), (step)
comment Parametar (stop)
for n in range 12
begin
comment Rezultat: 01234567891011
print n end=string
end
print string
comment Parametri (start), (stop)
f... | # --------------- Python 26 ---------------
# ---- Kontrola toka - range() funkcija ---
# Funkcija range() koristi paremetre (start), (stop), (step)
# Parametar (stop)
for n in range (12):
print(n, end="") # Rezultat: 01234567891011
print('\r')
# Parametri (start), (stop)
for m in range (6, 12):
print(m, ... | Python | zaydzuhri_stack_edu_python |
comment pylint: disable=unused-argument
function get_repo repo root=none **kwargs
begin
return call _get_repo_info repo root=root
end function | def get_repo(repo, root=None, **kwargs): # pylint: disable=unused-argument
return _get_repo_info(repo, root=root) | Python | nomic_cornstack_python_v1 |
function parse_upload_date upload_date
begin
return call parse_date upload_date
end function | def parse_upload_date(upload_date):
return parse_date(upload_date) | Python | nomic_cornstack_python_v1 |
function attest_android_key att_stmt att_obj auth_data client_data_hash
begin
if length x5c == 0
begin
raise call AttestationError string Must have at least 1 X509 certificate
end
set credential_certificate = call load_der_x509_certificate x5c at 0 call default_backend
set cred_cert_pk = call public_key
if not is insta... | def attest_android_key(
att_stmt: AndroidKeyAttestationStatement, att_obj: AttestationObject,
auth_data: bytes,
client_data_hash: bytes) -> Tuple[AttestationType, TrustedPath]:
if len(att_stmt.x5c) == 0:
raise AttestationError('Must have at least 1 X509 certificate')
credential_... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as pyplot
function discharge
begin
set Vi = 5.0
set R = 3
set C = 2
set time = array range 0 15 0.1
set Vdischarge = Vi * exp - time / R * C
set Cdischarge = Vdischarge / R
plot time Vdischarge
plot time Cdischarge
show
end function
function charge
begin
set Vin = 5.0
set tim... | import numpy as np
import matplotlib.pyplot as pyplot
def discharge():
Vi = 5.0
R = 3
C = 2
time = np.arange(0, 15, 0.1)
Vdischarge = Vi * np.exp(-time / (R * C));
Cdischarge = Vdischarge / R;
pyplot.plot(time, Vdischarge);
pyplot.plot(time, Cdischarge);
pyplot.show()
def charge():
Vin = 5.0
time = np.ar... | Python | zaydzuhri_stack_edu_python |
comment Creating and removing sheets
import openpyxl as xl
set wb = call Workbook string example_2.xlsx
print sheetnames
comment Add sheet
comment This creates a new Workbook Object
call create_sheet
print sheetnames
comment Create a sheet with a specific name and location
call create_sheet index=0 title=string First S... | # Creating and removing sheets
import openpyxl as xl
wb = xl.Workbook('example_2.xlsx')
print(wb.sheetnames)
# Add sheet
# This creates a new Workbook Object
wb.create_sheet()
print(wb.sheetnames)
# Create a sheet with a specific name and location
wb.create_sheet(index=0, title='First Sheet')
print(wb... | Python | zaydzuhri_stack_edu_python |
function tilecode in1 in2 tileIndices
begin
string write your tilecoder here (5 lines or so)
for i in range 0 numTilings
begin
set offset = i * 0.6 / numTilings
set in1index = integer 10 * in1 + offset / 6.0
set in2index = integer 10 * in2 + offset / 6.0
set tileIndices at i = integer 121 * i + 11 * in2index + in1index... | def tilecode(in1,in2,tileIndices):
" write your tilecoder here (5 lines or so)"
for i in range (0, numTilings):
offset = i*0.6/numTilings
in1index = int((10*(in1+offset)/6.0))
in2index = int((10*(in2+offset)/6.0))
tileIndices[i] = int((121*i)+(11*in2index)+in1index)
... | Python | zaydzuhri_stack_edu_python |
comment 1-2 匹配由单个空格分割的任意单词对,也就是姓和名
import re
function p1_2 str
begin
string >>> p1_2('Alex Ryan') Alex Ryan >>> p1_2('2gether forever') 0 >>> p1_2('Thomas Muller') Thomas Muller
set patt = string ^[a-zA-Z]+ [a-zA-Z]+$
set i = match patt str
if i is not none
begin
print call group
end
else
begin
print string 0
end
end f... | # 1-2 匹配由单个空格分割的任意单词对,也就是姓和名
import re
def p1_2(str):
"""
>>> p1_2('Alex Ryan')
Alex Ryan
>>> p1_2('2gether forever')
0
>>> p1_2('Thomas Muller')
Thomas Muller
"""
patt = '^[a-zA-Z]+ [a-zA-Z]+$'
i = re.match(patt, str)
if i is not None:
print(i.group())
else:
... | Python | zaydzuhri_stack_edu_python |
function _tileIteratorInfo self **kwargs
begin
set maxWidth = get get kwargs string output dict string maxWidth
set maxHeight = get get kwargs string output dict string maxHeight
if maxWidth is not none and not is instance maxWidth integer_types or maxWidth < 0 or maxHeight is not none and not is instance maxHeight int... | def _tileIteratorInfo(self, **kwargs):
maxWidth = kwargs.get('output', {}).get('maxWidth')
maxHeight = kwargs.get('output', {}).get('maxHeight')
if ((maxWidth is not None and
(not isinstance(maxWidth, six.integer_types) or maxWidth < 0)) or
(maxHeight is not None ... | Python | nomic_cornstack_python_v1 |
function read_dmask_csv fpath
begin
comment -load csv data-
assert ends with fpath string .dmask.csv msg string File suffix must be .dmask.csv
with open fpath as rf
begin
set lines = call splitlines
end
comment extract layers, channels and columns of interest
set dmask_dict = ordered dictionary
for tuple l_idx line in ... | def read_dmask_csv(fpath):
# -load csv data-
assert fpath.endswith('.dmask.csv'), 'File suffix must be .dmask.csv'
with open(fpath) as rf:
lines = rf.read().splitlines()
# extract layers, channels and columns of interest
dmask_dict = OrderedDict()
for l_idx, line in enumerate(lines):
... | Python | nomic_cornstack_python_v1 |
import socket
import pickle
set s = call socket AF_INET SOCK_DGRAM
call bind tuple string 0.0.0.0 5555
set tuple buff addr = call recvfrom 50
set info = loads buff
print string Received the tuple (s,start,length)
set string = info at 0
set start = info at 1
set length = info at 2
call sendto dumps string at slice start... | import socket
import pickle
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(("0.0.0.0",5555))
buff,addr = s.recvfrom(50)
info = pickle.loads(buff)
print("Received the tuple (s,start,length)")
string = info[0]
start = info[1]
length = info[2]
s.sendto(pickle.dumps(string[start:start+length]),addr)
| Python | zaydzuhri_stack_edu_python |
function test_labels_get self
begin
pass
end function | def test_labels_get(self):
pass | Python | nomic_cornstack_python_v1 |
comment -*- coding:UTF-8 -*-
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import numpy as np
import random
string 函数说明:加载数据 Parameters: 无 Returns: dataMat - 数据列表 labelMat - 标签列表 Author: Jack Cui Blog: http://blog.csdn.net/c406495762 Zhihu: https://www.zhihu.com/people/Jack--Cui/ Mo... | # -*- coding:UTF-8 -*-
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import numpy as np
import random
"""
函数说明:加载数据
Parameters:
无
Returns:
dataMat - 数据列表
labelMat - 标签列表
Author:
Jack Cui
Blog:
http://blog.csdn.net/c406495762
Zhihu:
https://www.zhihu.com/people/Jack--Cui/
Mod... | Python | zaydzuhri_stack_edu_python |
function get_project path project_name=none
begin
comment environment = Environment.from_env_file(path)
comment config_path = get_config_path_from_options(path, dict(), environment)
comment project = compose_get_project(path, config_path, project_name=project_name)
set options = dict string --file list string docker-co... | def get_project(path, project_name=None):
# environment = Environment.from_env_file(path)
# config_path = get_config_path_from_options(path, dict(), environment)
# project = compose_get_project(path, config_path, project_name=project_name)
options = {
'--file': ['docker-compose.json'],
'... | Python | nomic_cornstack_python_v1 |
function pop_message self
begin
try
begin
set result = get messages
end
except Empty
begin
return none
end
try else
begin
return call Message body=call getBody subject=call getBody sender=call getFrom
end
end function | def pop_message(self):
try:
result = self.messages.get()
except Queue.Empty:
return None
else:
return Message(body=result.getBody(), subject=result.getBody(), sender=result.getFrom()) | Python | nomic_cornstack_python_v1 |
from tkinter import *
import tkinter as tk
import Tk_Final_Drill_Func
string This will create and place the app widgets and buttons and the database will be created if one doesnt already exist
function load_gui self
begin
comment create an entry text box and a source button and set to a default string
set srcEntryBox =... | from tkinter import *
import tkinter as tk
import Tk_Final_Drill_Func
""" This will create and place the app
widgets and buttons and the database
will be created if one doesnt already exist
"""
def load_gui(self):
# create an entry text box and a source button and set to a default string
s... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
set Base = call declarative_base
class Folders extends Base
begin
set __tablename__ = string folders
set folder_id = call Column Integer primar... | #!/usr/bin/env python3
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Folders(Base):
__tablename__ = "folders"
folder_id = Column(Integer, primary_key=True, nullable=False, aut... | Python | zaydzuhri_stack_edu_python |
function GetTemperatureMap
begin
set collection = call ImageCollection TEMPERATURE_COLLECTION_ID
comment .map(CreateTimeBand)
set collection = select collection string LST_Day_1km
set fit = call subtract call Image 273.15
return call getMapId dict string min string 0 ; string max string 40 ; string palette string 0000f... | def GetTemperatureMap():
collection = ee.ImageCollection(TEMPERATURE_COLLECTION_ID)
collection = collection.select('LST_Day_1km')#.map(CreateTimeBand)
fit = collection.median().toFloat().multiply(ee.Image(0.02)).subtract(ee.Image(273.15))
return fit.getMapId({
'min': '0',
'max': '40',
'palette':'0... | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
comment Load an color image in grayscale
set img1 = call imread string axis_small.jpg IMREAD_COLOR
set img2 = call imread string axis_small.jpg IMREAD_GRAYSCALE
set img3 = call imread string axis_small.jpg IMREAD_UNCHANGED
image show string Axis Color img1
image show string Axis Gray img2
... | import numpy as np
import cv2
# Load an color image in grayscale
img1 = cv2.imread('axis_small.jpg',cv2.IMREAD_COLOR)
img2 = cv2.imread('axis_small.jpg',cv2.IMREAD_GRAYSCALE)
img3 = cv2.imread('axis_small.jpg',cv2.IMREAD_UNCHANGED)
cv2.imshow('Axis Color',img1)
cv2.imshow('Axis Gray',img2)
cv2.imshow('Axis No Chang... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler , HTTPServer
import sys | #!/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import sys | Python | zaydzuhri_stack_edu_python |
function process_aggregate_vulnerability aggregate_vulnerability
begin
set agg_vuln_to_vuln_id = call gen_empty_agg_vuln_to_vuln_ids
if aggregate_vulnerability is not none
begin
set agg_vuln_df = call DataFrame aggregate_vulnerability
comment init agg_vuln_to_vuln_id to allow numba to compile later functions
comment vu... | def process_aggregate_vulnerability(aggregate_vulnerability):
agg_vuln_to_vuln_id = gen_empty_agg_vuln_to_vuln_ids()
if aggregate_vulnerability is not None:
agg_vuln_df = pd.DataFrame(aggregate_vulnerability)
# init agg_vuln_to_vuln_id to allow numba to compile later functions
# vulner... | Python | nomic_cornstack_python_v1 |
function start_message self trainer
begin
comment initialize the flags of notifier
set flags_batch = list
set flags_epoch = list
set details = dict
comment calculate the batch status updates frequency - only 10 edits per epoch (avoid spam)
set iteration_update_freq = max _epoch_size // batch_size // 10 1
set details... | def start_message(self, trainer):
# initialize the flags of notifier
self.notifier.flags_batch = []
self.notifier.flags_epoch = []
self.details = {}
# calculate the batch status updates frequency - only 10 edits per epoch (avoid spam)
self.iteration_update_freq = max(tra... | Python | nomic_cornstack_python_v1 |
function __init__ self *args
begin
pass
end function | def __init__(self,*args):
pass | Python | nomic_cornstack_python_v1 |
import torch
from torch import nn , optim
import torch.autograd as autograd
import torch.utils.data
import numpy as np
from torch.nn import functional as F
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import os
import pandas as pd
from torch.autograd import Variable
from math import sqrt
from ... | import torch
from torch import nn, optim
import torch.autograd as autograd
import torch.utils.data
import numpy as np
from torch.nn import functional as F
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import os
import pandas as pd
from torch.autograd import Variable
from math import sqrt
from s... | 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.