code
stringlengths 1
5.19M
| package
stringlengths 1
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
import json
import multiprocessing
import time
import traceback
from RedisQueue.exception.local_exceptions import NumberProcessException
from RedisQueue.redis_connector import RedisPool
# rpop from redis given key as list name
# return rpop result
def single_start(key, pid, func):
"""
read list-key from redis,
pop list element,
call function with popped element as param
:param key: model name defined in tool and model
:param pid: process id
:param func: call model function
"""
print('process start: 【' + str(pid) + '】')
pool = RedisPool()
conn = pool.connector()
while True:
val = conn.brpop(key)
print(pid, val[1])
# do ack
# do persistance work
try:
val_json = json.loads(val[1])
func(val_json)
# do exception work
except:
traceback.print_exc()
# record failed vals
err_json = {"val": val[1], "timestamp": int(round(time.time() * 1000))}
conn.lpush('failed_' + key, json.dumps(err_json))
def start(key: str, func, np: int = 5):
"""
call np number of processes,
do func work, func params read from redis
:param key: model name defined in tool and model
:param func: call model function
:param np: number of processes, default 5
"""
if np < 1:
raise NumberProcessException(np)
return
for i in range(np):
p = multiprocessing.Process(target=single_start, kwargs={"key": key, "pid": i, "func": func})
p.start()
time.sleep(0.5)
|
zzha529-test
|
/zzha529_test-1.16.tar.gz/zzha529_test-1.16/RedisQueue/multi_process.py
|
multi_process.py
|
class NumberProcessException(Exception):
def __init__(self, msg):
self.msg = str(msg) + ' < 1, cannot make such number of processes!'
def __str__(self):
return self.msg
|
zzha529-test
|
/zzha529_test-1.16.tar.gz/zzha529_test-1.16/RedisQueue/exception/local_exceptions.py
|
local_exceptions.py
|
from RedisQueue.multi_process import start
if __name__ == "__main__":
import test_abc
start("zzha529", test_abc.print_json, 4)
|
zzha529-test
|
/zzha529_test-1.16.tar.gz/zzha529_test-1.16/RedisQueueDemo/demo.py
|
demo.py
|
import json
def print_json(in_json: json):
print(in_json.keys())
print(in_json)
|
zzha529-test
|
/zzha529_test-1.16.tar.gz/zzha529_test-1.16/RedisQueueDemo/test_abc.py
|
test_abc.py
|
Copyright (c) 2019 The Python Packaging Authority
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
|
zzhfourth
|
/zzhfourth-0.0.1-py3-none-any.whl/zzhfourth-0.0.1.dist-info/LICENSE.py
|
LICENSE.py
|
name = "example_pkg"
|
zzhfourth
|
/zzhfourth-0.0.1-py3-none-any.whl/example_pkg/__init__.py
|
__init__.py
|
import setuptools
setuptools.setup(name='zzhfun',
version='0.30',
description='zzh model function and data function',
url='https://github.com/FlashSnail/zzhfun',
author='Zzh',
author_email='zzh_0729@foxmail.com',
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 2",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
install_requires=[
'pandas>=0.24.2',
'numpy>=1.16.2',
'xgboost>=0.82', # depency on scipy, however, 1.2.2 is the last version support py2
#'keras>=2.2.4',
'scikit-learn<=0.20.3', #0.20 is the last version support for py2
#'file==0.2.0'
]
)
|
zzhfun
|
/zzhfun-0.30.tar.gz/zzhfun-0.30/setup.py
|
setup.py
|
from distutils.core import setup
setup(
name = 'zzhmodule',
version = '1.4.0',
py_modules = ['zzhmodule'],
author = 'Chou zhonghua',
author_email = '31893592@qq.com',
usl = 'http://www/chouzhonghua.com',
description = 'A simple printer of list',
)
|
zzhmodule
|
/zzhmodule-1.4.0.zip/zzhmodule-1.4.0/setup.py
|
setup.py
|
from setuptools import setup
setup(name='zzhprob-fifth',
version='0.3',
description='Gaussian distributions',
packages=['zzhprob-fifth'],
zip_safe=False)
|
zzhprob-fifth
|
/zzhprob-fifth-0.3.tar.gz/zzhprob-fifth-0.3/setup.py
|
setup.py
|
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
avg = 1.0 * sum(self.data) / len(self.data)
self.mean = avg
return self.mean
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = len(self.data) - 1
else:
n = len(self.data)
mean = self.calculate_mean()
sigma = 0
for d in self.data:
sigma += (d - mean) ** 2
sigma = math.sqrt(sigma / n)
self.stdev = sigma
return self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces = 50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = min(self.data)
max_range = max(self.data)
# calculates the interval between x values
interval = 1.0 * (max_range - min_range) / n_spaces
x = []
y = []
# calculate the x values to visualize
for i in range(n_spaces):
tmp = min_range + interval*i
x.append(tmp)
y.append(self.pdf(tmp))
# make the plots
fig, axes = plt.subplots(2,sharex=True)
fig.subplots_adjust(hspace=.5)
axes[0].hist(self.data, density=True)
axes[0].set_title('Normed Histogram of Data')
axes[0].set_ylabel('Density')
axes[1].plot(x, y)
axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
axes[0].set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev)
|
zzhprob-second
|
/zzhprob_second-0.3-py3-none-any.whl/distributions/Gaussiandistribution.py
|
Gaussiandistribution.py
|
class Distribution:
def __init__(self, mu=0, sigma=1):
""" Generic distribution class for calculating and
visualizing a probability distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
self.mean = mu
self.stdev = sigma
self.data = []
def read_data_file(self, file_name):
"""Function to read in data from a txt file. The txt file should have
one number (float) per line. The numbers are stored in the data attribute.
Args:
file_name (string): name of a file to read from
Returns:
None
"""
with open(file_name) as file:
data_list = []
line = file.readline()
while line:
data_list.append(int(line))
line = file.readline()
file.close()
self.data = data_list
|
zzhprob-second
|
/zzhprob_second-0.3-py3-none-any.whl/distributions/Generaldistribution.py
|
Generaldistribution.py
|
from .Gaussiandistribution import Gaussian
from .Binomialdistribution import Binomial
|
zzhprob-second
|
/zzhprob_second-0.3-py3-none-any.whl/distributions/__init__.py
|
__init__.py
|
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Binomial(Distribution):
""" Binomial distribution class for calculating and
visualizing a Binomial distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats to be extracted from the data file
p (float) representing the probability of an event occurring
n (int) number of trials
TODO: Fill out all functions below
"""
def __init__(self, prob=.5, size=20):
self.n = size
self.p = prob
Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev())
def calculate_mean(self):
"""Function to calculate the mean from p and n
Args:
None
Returns:
float: mean of the data set
"""
self.mean = self.p * self.n
return self.mean
def calculate_stdev(self):
"""Function to calculate the standard deviation from p and n.
Args:
None
Returns:
float: standard deviation of the data set
"""
self.stdev = math.sqrt(self.n * self.p * (1 - self.p))
return self.stdev
def replace_stats_with_data(self):
"""Function to calculate p and n from the data set
Args:
None
Returns:
float: the p value
float: the n value
"""
self.n = len(self.data)
self.p = 1.0 * sum(self.data) / len(self.data)
self.mean = self.calculate_mean()
self.stdev = self.calculate_stdev()
def plot_bar(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n])
plt.title('Bar Chart of Data')
plt.xlabel('outcome')
plt.ylabel('count')
def pdf(self, k):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k)))
b = (self.p ** k) * (1 - self.p) ** (self.n - k)
return a * b
def plot_bar_pdf(self):
"""Function to plot the pdf of the binomial distribution
Args:
None
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
x = []
y = []
# calculate the x values to visualize
for i in range(self.n + 1):
x.append(i)
y.append(self.pdf(i))
# make the plots
plt.bar(x, y)
plt.title('Distribution of Outcomes')
plt.ylabel('Probability')
plt.xlabel('Outcome')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Binomial distributions with equal p
Args:
other (Binomial): Binomial instance
Returns:
Binomial: Binomial distribution
"""
try:
assert self.p == other.p, 'p values are not equal'
except AssertionError as error:
raise
result = Binomial()
result.n = self.n + other.n
result.p = self.p
result.calculate_mean()
result.calculate_stdev()
return result
def __repr__(self):
"""Function to output the characteristics of the Binomial instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}, p {}, n {}".\
format(self.mean, self.stdev, self.p, self.n)
|
zzhprob-second
|
/zzhprob_second-0.3-py3-none-any.whl/distributions/Binomialdistribution.py
|
Binomialdistribution.py
|
from setuptools import setup
setup(name='zzhprob',
version='0.3',
description='Gaussian distributions',
packages=['distributions'],
zip_safe=False)
|
zzhprob
|
/zzhprob-0.3.tar.gz/zzhprob-0.3/setup.py
|
setup.py
|
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
avg = 1.0 * sum(self.data) / len(self.data)
self.mean = avg
return self.mean
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = len(self.data) - 1
else:
n = len(self.data)
mean = self.calculate_mean()
sigma = 0
for d in self.data:
sigma += (d - mean) ** 2
sigma = math.sqrt(sigma / n)
self.stdev = sigma
return self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces = 50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = min(self.data)
max_range = max(self.data)
# calculates the interval between x values
interval = 1.0 * (max_range - min_range) / n_spaces
x = []
y = []
# calculate the x values to visualize
for i in range(n_spaces):
tmp = min_range + interval*i
x.append(tmp)
y.append(self.pdf(tmp))
# make the plots
fig, axes = plt.subplots(2,sharex=True)
fig.subplots_adjust(hspace=.5)
axes[0].hist(self.data, density=True)
axes[0].set_title('Normed Histogram of Data')
axes[0].set_ylabel('Density')
axes[1].plot(x, y)
axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
axes[0].set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev)
|
zzhprob
|
/zzhprob-0.3.tar.gz/zzhprob-0.3/distributions/Gaussiandistribution.py
|
Gaussiandistribution.py
|
class Distribution:
def __init__(self, mu=0, sigma=1):
""" Generic distribution class for calculating and
visualizing a probability distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
self.mean = mu
self.stdev = sigma
self.data = []
def read_data_file(self, file_name):
"""Function to read in data from a txt file. The txt file should have
one number (float) per line. The numbers are stored in the data attribute.
Args:
file_name (string): name of a file to read from
Returns:
None
"""
with open(file_name) as file:
data_list = []
line = file.readline()
while line:
data_list.append(int(line))
line = file.readline()
file.close()
self.data = data_list
|
zzhprob
|
/zzhprob-0.3.tar.gz/zzhprob-0.3/distributions/Generaldistribution.py
|
Generaldistribution.py
|
from .Gaussiandistribution import Gaussian
from .Binomialdistribution import Binomial
|
zzhprob
|
/zzhprob-0.3.tar.gz/zzhprob-0.3/distributions/__init__.py
|
__init__.py
|
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Binomial(Distribution):
""" Binomial distribution class for calculating and
visualizing a Binomial distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats to be extracted from the data file
p (float) representing the probability of an event occurring
n (int) number of trials
TODO: Fill out all functions below
"""
def __init__(self, prob=.5, size=20):
self.n = size
self.p = prob
Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev())
def calculate_mean(self):
"""Function to calculate the mean from p and n
Args:
None
Returns:
float: mean of the data set
"""
self.mean = self.p * self.n
return self.mean
def calculate_stdev(self):
"""Function to calculate the standard deviation from p and n.
Args:
None
Returns:
float: standard deviation of the data set
"""
self.stdev = math.sqrt(self.n * self.p * (1 - self.p))
return self.stdev
def replace_stats_with_data(self):
"""Function to calculate p and n from the data set
Args:
None
Returns:
float: the p value
float: the n value
"""
self.n = len(self.data)
self.p = 1.0 * sum(self.data) / len(self.data)
self.mean = self.calculate_mean()
self.stdev = self.calculate_stdev()
def plot_bar(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n])
plt.title('Bar Chart of Data')
plt.xlabel('outcome')
plt.ylabel('count')
def pdf(self, k):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k)))
b = (self.p ** k) * (1 - self.p) ** (self.n - k)
return a * b
def plot_bar_pdf(self):
"""Function to plot the pdf of the binomial distribution
Args:
None
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
x = []
y = []
# calculate the x values to visualize
for i in range(self.n + 1):
x.append(i)
y.append(self.pdf(i))
# make the plots
plt.bar(x, y)
plt.title('Distribution of Outcomes')
plt.ylabel('Probability')
plt.xlabel('Outcome')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Binomial distributions with equal p
Args:
other (Binomial): Binomial instance
Returns:
Binomial: Binomial distribution
"""
try:
assert self.p == other.p, 'p values are not equal'
except AssertionError as error:
raise
result = Binomial()
result.n = self.n + other.n
result.p = self.p
result.calculate_mean()
result.calculate_stdev()
return result
def __repr__(self):
"""Function to output the characteristics of the Binomial instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}, p {}, n {}".\
format(self.mean, self.stdev, self.p, self.n)
|
zzhprob
|
/zzhprob-0.3.tar.gz/zzhprob-0.3/distributions/Binomialdistribution.py
|
Binomialdistribution.py
|
from setuptools import setup, find_packages
setup(
name='zzhprobm',
version='0.4',
description=('Gaussian distributions'),
author='maxoyed',
author_email='maxoyed@gmail.com',
packages=find_packages(),
include_package_data=True,
platforms="any",
install_requires=['matplotlib==3.3.2']
)
|
zzhprobm
|
/zzhprobm-0.4.tar.gz/zzhprobm-0.4/setup.py
|
setup.py
|
from setuptools import setup
setup(name='zzhprobsecond',
version='0.3',
description='Gaussian distributions',
packages=['distributions'],
zip_safe=False)
|
zzhprobsecond
|
/zzhprobsecond-0.3.tar.gz/zzhprobsecond-0.3/setup.py
|
setup.py
|
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
avg = 1.0 * sum(self.data) / len(self.data)
self.mean = avg
return self.mean
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = len(self.data) - 1
else:
n = len(self.data)
mean = self.calculate_mean()
sigma = 0
for d in self.data:
sigma += (d - mean) ** 2
sigma = math.sqrt(sigma / n)
self.stdev = sigma
return self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces = 50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = min(self.data)
max_range = max(self.data)
# calculates the interval between x values
interval = 1.0 * (max_range - min_range) / n_spaces
x = []
y = []
# calculate the x values to visualize
for i in range(n_spaces):
tmp = min_range + interval*i
x.append(tmp)
y.append(self.pdf(tmp))
# make the plots
fig, axes = plt.subplots(2,sharex=True)
fig.subplots_adjust(hspace=.5)
axes[0].hist(self.data, density=True)
axes[0].set_title('Normed Histogram of Data')
axes[0].set_ylabel('Density')
axes[1].plot(x, y)
axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
axes[0].set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev)
|
zzhprobsecond
|
/zzhprobsecond-0.3.tar.gz/zzhprobsecond-0.3/distributions/Gaussiandistribution.py
|
Gaussiandistribution.py
|
class Distribution:
def __init__(self, mu=0, sigma=1):
""" Generic distribution class for calculating and
visualizing a probability distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
self.mean = mu
self.stdev = sigma
self.data = []
def read_data_file(self, file_name):
"""Function to read in data from a txt file. The txt file should have
one number (float) per line. The numbers are stored in the data attribute.
Args:
file_name (string): name of a file to read from
Returns:
None
"""
with open(file_name) as file:
data_list = []
line = file.readline()
while line:
data_list.append(int(line))
line = file.readline()
file.close()
self.data = data_list
|
zzhprobsecond
|
/zzhprobsecond-0.3.tar.gz/zzhprobsecond-0.3/distributions/Generaldistribution.py
|
Generaldistribution.py
|
from .Gaussiandistribution import Gaussian
from .Binomialdistribution import Binomial
|
zzhprobsecond
|
/zzhprobsecond-0.3.tar.gz/zzhprobsecond-0.3/distributions/__init__.py
|
__init__.py
|
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Binomial(Distribution):
""" Binomial distribution class for calculating and
visualizing a Binomial distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats to be extracted from the data file
p (float) representing the probability of an event occurring
n (int) number of trials
TODO: Fill out all functions below
"""
def __init__(self, prob=.5, size=20):
self.n = size
self.p = prob
Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev())
def calculate_mean(self):
"""Function to calculate the mean from p and n
Args:
None
Returns:
float: mean of the data set
"""
self.mean = self.p * self.n
return self.mean
def calculate_stdev(self):
"""Function to calculate the standard deviation from p and n.
Args:
None
Returns:
float: standard deviation of the data set
"""
self.stdev = math.sqrt(self.n * self.p * (1 - self.p))
return self.stdev
def replace_stats_with_data(self):
"""Function to calculate p and n from the data set
Args:
None
Returns:
float: the p value
float: the n value
"""
self.n = len(self.data)
self.p = 1.0 * sum(self.data) / len(self.data)
self.mean = self.calculate_mean()
self.stdev = self.calculate_stdev()
def plot_bar(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n])
plt.title('Bar Chart of Data')
plt.xlabel('outcome')
plt.ylabel('count')
def pdf(self, k):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k)))
b = (self.p ** k) * (1 - self.p) ** (self.n - k)
return a * b
def plot_bar_pdf(self):
"""Function to plot the pdf of the binomial distribution
Args:
None
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
x = []
y = []
# calculate the x values to visualize
for i in range(self.n + 1):
x.append(i)
y.append(self.pdf(i))
# make the plots
plt.bar(x, y)
plt.title('Distribution of Outcomes')
plt.ylabel('Probability')
plt.xlabel('Outcome')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Binomial distributions with equal p
Args:
other (Binomial): Binomial instance
Returns:
Binomial: Binomial distribution
"""
try:
assert self.p == other.p, 'p values are not equal'
except AssertionError as error:
raise
result = Binomial()
result.n = self.n + other.n
result.p = self.p
result.calculate_mean()
result.calculate_stdev()
return result
def __repr__(self):
"""Function to output the characteristics of the Binomial instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}, p {}, n {}".\
format(self.mean, self.stdev, self.p, self.n)
|
zzhprobsecond
|
/zzhprobsecond-0.3.tar.gz/zzhprobsecond-0.3/distributions/Binomialdistribution.py
|
Binomialdistribution.py
|
# from zzhtestlib import zzhlibone
# import zzhtestlib
#
# zzhtestlib.zzhlibone.run()
def tt():
print("tttt")
|
zzhtestlib
|
/zzhtestlib-1.0.0-py3-none-any.whl/Tool.py
|
Tool.py
|
from setuptools import setup
setup(name='zzhtongjione',
version='0.5',
description='Gaussian distributions',
packages=['distributions'],
zip_safe=False)
|
zzhtongjione
|
/zzhtongjione-0.5.tar.gz/zzhtongjione-0.5/setup.py
|
setup.py
|
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
avg = 1.0 * sum(self.data) / len(self.data)
self.mean = avg
return self.mean
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = len(self.data) - 1
else:
n = len(self.data)
mean = self.calculate_mean()
sigma = 0
for d in self.data:
sigma += (d - mean) ** 2
sigma = math.sqrt(sigma / n)
self.stdev = sigma
return self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces = 50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = min(self.data)
max_range = max(self.data)
# calculates the interval between x values
interval = 1.0 * (max_range - min_range) / n_spaces
x = []
y = []
# calculate the x values to visualize
for i in range(n_spaces):
tmp = min_range + interval*i
x.append(tmp)
y.append(self.pdf(tmp))
# make the plots
fig, axes = plt.subplots(2,sharex=True)
fig.subplots_adjust(hspace=.5)
axes[0].hist(self.data, density=True)
axes[0].set_title('Normed Histogram of Data')
axes[0].set_ylabel('Density')
axes[1].plot(x, y)
axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
axes[0].set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev)
|
zzhtongjione
|
/zzhtongjione-0.5.tar.gz/zzhtongjione-0.5/distributions/Gaussiandistribution.py
|
Gaussiandistribution.py
|
class Distribution:
def __init__(self, mu=0, sigma=1):
""" Generic distribution class for calculating and
visualizing a probability distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
self.mean = mu
self.stdev = sigma
self.data = []
def read_data_file(self, file_name):
"""Function to read in data from a txt file. The txt file should have
one number (float) per line. The numbers are stored in the data attribute.
Args:
file_name (string): name of a file to read from
Returns:
None
"""
with open(file_name) as file:
data_list = []
line = file.readline()
while line:
data_list.append(int(line))
line = file.readline()
file.close()
self.data = data_list
|
zzhtongjione
|
/zzhtongjione-0.5.tar.gz/zzhtongjione-0.5/distributions/Generaldistribution.py
|
Generaldistribution.py
|
from .Gaussiandistribution import Gaussian
from .Binomialdistribution import Binomial
|
zzhtongjione
|
/zzhtongjione-0.5.tar.gz/zzhtongjione-0.5/distributions/__init__.py
|
__init__.py
|
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Binomial(Distribution):
""" Binomial distribution class for calculating and
visualizing a Binomial distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats to be extracted from the data file
p (float) representing the probability of an event occurring
n (int) number of trials
TODO: Fill out all functions below
"""
def __init__(self, prob=.5, size=20):
self.n = size
self.p = prob
Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev())
def calculate_mean(self):
"""Function to calculate the mean from p and n
Args:
None
Returns:
float: mean of the data set
"""
self.mean = self.p * self.n
return self.mean
def calculate_stdev(self):
"""Function to calculate the standard deviation from p and n.
Args:
None
Returns:
float: standard deviation of the data set
"""
self.stdev = math.sqrt(self.n * self.p * (1 - self.p))
return self.stdev
def replace_stats_with_data(self):
"""Function to calculate p and n from the data set
Args:
None
Returns:
float: the p value
float: the n value
"""
self.n = len(self.data)
self.p = 1.0 * sum(self.data) / len(self.data)
self.mean = self.calculate_mean()
self.stdev = self.calculate_stdev()
def plot_bar(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n])
plt.title('Bar Chart of Data')
plt.xlabel('outcome')
plt.ylabel('count')
def pdf(self, k):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k)))
b = (self.p ** k) * (1 - self.p) ** (self.n - k)
return a * b
def plot_bar_pdf(self):
"""Function to plot the pdf of the binomial distribution
Args:
None
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
x = []
y = []
# calculate the x values to visualize
for i in range(self.n + 1):
x.append(i)
y.append(self.pdf(i))
# make the plots
plt.bar(x, y)
plt.title('Distribution of Outcomes')
plt.ylabel('Probability')
plt.xlabel('Outcome')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Binomial distributions with equal p
Args:
other (Binomial): Binomial instance
Returns:
Binomial: Binomial distribution
"""
try:
assert self.p == other.p, 'p values are not equal'
except AssertionError as error:
raise
result = Binomial()
result.n = self.n + other.n
result.p = self.p
result.calculate_mean()
result.calculate_stdev()
return result
def __repr__(self):
"""Function to output the characteristics of the Binomial instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}, p {}, n {}".\
format(self.mean, self.stdev, self.p, self.n)
|
zzhtongjione
|
/zzhtongjione-0.5.tar.gz/zzhtongjione-0.5/distributions/Binomialdistribution.py
|
Binomialdistribution.py
|
# -*- coding: utf-8 -*-
from setuptools import setup
packages = \
['zzip']
package_data = \
{'': ['*']}
setup_kwargs = {
'name': 'zzip',
'version': '0.0.2',
'description': 'Zipper tool for interacting with data',
'long_description': None,
'author': 'Stephen Mizell',
'author_email': 'smizell@gmail.com',
'maintainer': None,
'maintainer_email': None,
'url': None,
'packages': packages,
'package_data': package_data,
'python_requires': '>=3.9,<4.0',
}
setup(**setup_kwargs)
|
zzip
|
/zzip-0.0.2.tar.gz/zzip-0.0.2/setup.py
|
setup.py
|
bb=3
|
zzjjkk
|
/zzjjkk-1.2.3-py3-none-any.whl/kk.py
|
kk.py
|
name=111
def run():
print("this is bao")
if __name__=="__main__":
run()
|
zzjjkk
|
/zzjjkk-1.2.3-py3-none-any.whl/bso/jj.py
|
jj.py
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#############################################
# File Name: setup.py
# Author: LiangjunFeng
# Mail: zhumavip@163.com
# Created Time: 2018-4-16 19:17:34
#############################################
from setuptools import setup, find_packages #这个包没有的可以pip一下
setup(
name = "zzktest", #这里是pip项目发布的名称
version = "2.1.4", #版本号,数值大的会优先被pip
keywords = ("pip", "23333","featureextraction"),
description = "An feature extraction algorithm",
long_description = "An feature extraction algorithm, improve the FastICA",
author = "zjk",
author_email = "1966465337@qq.com",
packages = find_packages(),
include_package_data = True,
platforms = "any",
install_requires = ["numpy"] #这个项目需要的第三方库
)
|
zzktest
|
/zzktest-2.1.4.tar.gz/zzktest-2.1.4/setup.py
|
setup.py
|
print("hello")
|
zzktest
|
/zzktest-2.1.4.tar.gz/zzktest-2.1.4/zjktest/hello.py
|
hello.py
|
ZZlib
=====
Python utils for structure-based computer-aided drug design
|
zzlib
|
/zzlib-0.1.2.tar.gz/zzlib-0.1.2/README.md
|
README.md
|
def test_import():
import zzlib
from zzlib import cls, func, mixin, utils
from zzlib.shell import env, envmgr, pathutils, sandbox, shell, slurm, subprocess
from zzlib.log import logger, liblogger, forcelogger
from zzlib.dl import device
from zzlib.data import pandas
from zzlib.cli import click, typer, progress
from zzlib.bio import seq
|
zzlib
|
/zzlib-0.1.2.tar.gz/zzlib-0.1.2/tests/test_common.py
|
test_common.py
|
# zzlog
Izzy setup for logging in Python
|
zzlog
|
/zzlog-1.0.0.tar.gz/zzlog-1.0.0/README.md
|
README.md
|
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='zzlog',
version='1.0.0',
description='Logging setup made izzy',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/pierre-rouanet/zzlog',
author='Pierre Rouanet',
author_email='pierre.rouanet@gmail.com',
packages=find_packages(exclude=['tests']),
python_requires='>=3.5',
install_requires=[
'python-json-logger',
],
)
|
zzlog
|
/zzlog-1.0.0.tar.gz/zzlog-1.0.0/setup.py
|
setup.py
|
## Project description
Athena is the core SDK for requesting the EnOS API
### Example
#### 1.1 Query
```python
from poseidon import poseidon
appkey = '7b51b354-f200-45a9-a349-40cc97730c5a'
appsecret = '65417473-2da3-40cc-b235-513b9123aefg'
url = 'http://{apim-url}/someservice/v1/tyy?sid=28654780'
req = poseidon.urlopen(appkey, appsecret, url)
print(req)
```
#### 1.2 Header
```python
from poseidon import poseidon
appkey = '7b51b354-f200-45a9-a349-40cc97730c5a'
appsecret = '65417473-2da3-40cc-b235-513b9123aefg'
url = 'http://{apim-url}/someservice/v1/tyy?sid=28654780'
header={}
req = poseidon.urlopen(appkey, appsecret, url, None, header)
print(req)
```
#### 1.3 Body
```python
from poseidon import poseidon
appkey = '7b51b354-f200-45a9-a349-40cc97730c5a'
appsecret = '65417473-2da3-40cc-b235-513b9123aefg'
url = 'http://{apim-url}/someservice/v1/tyy?sid=28654780'
data = {"username": "11111", "password": "11111"}
req = poseidon.urlopen(appkey, appsecret, url, data)
print(req)
```
|
zzltest
|
/zzltest-0.1.5.tar.gz/zzltest-0.1.5/README.md
|
README.md
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
README = f.read()
setup(
name='zzltest',
version='0.1.5',
description='zzl test',
long_description=README,
author='Kid QU',
long_description_content_type='text/markdown',
author_email='kidcrazequ@gmail.com',
url='https://github.com/EnvisionIot',
license='GPLv3',
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Programming Language :: Python :: 3.6",
],
packages=find_packages(),
platforms=['all'],
zip_safe=False,
install_requires=[
'pycryptodome>=3.8.2',
'simplejson>=3.16.0',
],
)
|
zzltest
|
/zzltest-0.1.5.tar.gz/zzltest-0.1.5/setup.py
|
setup.py
|
import hashlib
Q =str
D =int
G =round
e =list
h =None
k =bytes
F =KeyError
w =print
p =hashlib .sha256
import hmac
u =hmac .new
import base64
K =base64 .b64encode
U =base64 .b64decode
import time
B =time .time
from Crypto .PublicKey import RSA
L =RSA .importKey
from Crypto .Cipher import PKCS1_OAEP
t =PKCS1_OAEP .new
from urllib import request ,parse ,error
n =error .URLError
b =request .urlopen
g =request .Request
import ssl
ssl ._create_default_https_context =ssl ._create_unverified_context
import simplejson
c =simplejson .loads
import json
X =json .dumps
m =2 *60 *60 *1000
s =30 *24 *60 *60 *1000
sk ='knoczslufdasvhbivbewnrvuywachsrawqdpzesccknrhhetgmrcwfqfudywbeon'
P =b'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAokFjy0wLMKH0/39hxPN6JYRkMDXzvVIGQh55Keo2LIsP/jRU/yZHT/Vkg34yU9koNjSaacPvooXEoI5eFGuRrsBMrotZ5xfejCrTbGvZqjhnMPBheDmxfflIZzRrF/zoQvF0nIbmGNkxEfROHtDDkgNuGRdthXrNavCgfM2z3LNF83UT9CGpxJWBeKK3pXfYLsQ4f8uyrQRcy2BhKfJ/PKai1mocXYqr07JfQ0XZM4xIzuQ7E4ybNk5IFreDuuhF63wXAi1uonGzqjEYcbC1xT2boNiZORoOQWpAHhSbIRpljmW/uHBvoKZ573PQbbxE62hXv1Z1iVky0dtAV65dXwIDAQAB'
def __OO0000OO0O0O00OOO (O00000O00OO0OOO0O ,O0000OOO000O0O00O ):
O000O000O0O00O000 =[O00000O00OO0OOO0O .split ("-")[1 ],O0000OOO000O0O00O .split ("-")[1 ]]
OO00O0O0OO0O0OO00 =''.join (O000O000O0O00O000 )
return Q (D (OO00O0O0OO0O0OO00 ,16 ))[:6 ]
def __OO0O00O00O0O00O00 (O000O0O0O000OO000 ,O000O0O0OOO0O0OO0 ,O0OO00O0OOOOO00OO ):
O0O00OOO0OO0O00OO =O000O0O0O000OO000 +Q (D (G (B ()*1000 ))+O000O0O0OOO0O0OO0 )
OOOO0O0OO0O0O00O0 =O000O0O0O000OO000 +Q (D (G (B ()*1000 ))+O0OO00O0OOOOO00OO )
O0OO0O00O0000000O =e ()
O0OO0O00O0000000O .append (u (sk .encode ('UTF-8'),O0O00OOO0OO0O00OO .encode ('UTF-8'),p ).hexdigest ())
O0OO0O00O0000000O .append (u (sk .encode ('UTF-8'),OOOO0O0OO0O0O00O0 .encode ('UTF-8'),p ).hexdigest ())
return O0OO0O00O0000000O
def __O0OOO0OOO0000OO0O (O0O000000OOOO0OO0 ,OOOO0O00OOO00O000 ):
O0000OO0O0O0OOOOO =O0O000000OOOO0OO0 +Q (D (G (B ()*1000 ))+OOOO0O00OOO00O000 )
return u (sk .encode ('UTF-8'),O0000OO0O0O0OOOOO .encode ('UTF-8'),p ).hexdigest ()
def __OOO0O00OO0OOO0000 (O0O0O0OOO000OOO00 ,OO00O0O0OO0O0000O ,OO0OOO0000O0O000O ,O00000OO0OOOO0O0O ,O0O0O00O00O0O0O0O ):
OOOO0OO0O00OO0OOO =O0O0O0OOO000OOO00 +'$'+OO00O0O0OO0O0000O +'$'+OO0OOO0000O0O000O +'$'+O00000OO0OOOO0O0O +'$'+O0O0O00O00O0O0O0O
O0OO0O0O00OO00OOO =U (P )
O00O000O00O0000OO =L (O0OO0O0O00OO00OOO )
O00OO0O00OOOO00OO =t (O00O000O00O0000OO )
OOOO0O0000000OOOO =O00OO0O00OOOO00OO .encrypt (OOOO0OO0O00OO0OOO .encode ('UTF-8'))
return K (OOOO0O0000000OOOO ).decode ()
def urlopen (O000OO0O0O0O0O0OO ,O0O000O00OOOOO0OO ,O0O000O0O0O0OOO0O ,data =h ,headers ={}):
OO00O00000O0000OO =__OO0000OO0O0O00OOO (O000OO0O0O0O0O0OO ,O0O000O00OOOOO0OO )
O00000O0O0OO0OO0O =__OO0O00O00O0O00O00 (OO00O00000O0000OO ,m ,s )
OO0OO000O0O0OO00O =__OOO0O00OO0OOO0000 (OO00O00000O0000OO ,O000OO0O0O0O0O0OO ,O0O000O00OOOOO0OO ,O00000O0O0OO0OO0O [0 ],O00000O0O0OO0OO0O [1 ])
if data !=h :
data =X (data )
data =k (data ,'UTF-8')
O0OOOO0OO0OOO0OO0 =g (O0O000O0O0O0OOO0O ,data )
O0OOOO0OO0OOO0OO0 .add_header ('apim-accesstoken',OO0OO000O0O0OO00O )
O0OOOO0OO0OOO0OO0 .add_header ('Content-Type','application/json;charset=utf-8')
O0OOOO0OO0OOO0OO0 .add_header ('User-Agent','Python_enos_api')
for O000OO0O0O0O0O0OO ,OO0OO0O0O00O0O00O in headers .items ():
O0OOOO0OO0OOO0OO0 .add_header (O000OO0O0O0O0O0OO ,OO0OO0O0O00O0O00O )
try :
O0O0OO0O0OOOO00O0 =b (O0OOOO0OO0OOO0OO0 )
O0O000O00OOOOOO0O =O0O0OO0O0OOOO00O0 .read ().decode ('UTF-8')
OOO0O0O0O00OOO00O =c (O0O000O00OOOOOO0O )
try :
OO0O0O0O000OO000O =OOO0O0O0O00OOO00O ['apim_status']
if OO0O0O0O000OO000O ==4011 :
OO0O0O0OO0OOO0OO0 =OOO0O0O0O00OOO00O ['apim_refreshtoken']
OOOO0OOO0OOO0O00O =__O0OOO0OOO0000OO0O (OO00O00000O0000OO ,m )
OO0OO000O0O0OO00O =__OOO0O00OO0OOO0000 (OO00O00000O0000OO ,O000OO0O0O0O0O0OO ,O0O000O00OOOOO0OO ,OOOO0OOO0OOO0O00O ,OO0O0O0OO0OOO0OO0 )
elif OO0O0O0O000OO000O ==4012 :
O00000O0O0OO0OO0O =__OO0O00O00O0O00O00 (OO00O00000O0000OO ,m ,s )
OO0OO000O0O0OO00O =__OOO0O00OO0OOO0000 (OO00O00000O0000OO ,O000OO0O0O0O0O0OO ,O0O000O00OOOOO0OO ,O00000O0O0OO0OO0O [0 ],O00000O0O0OO0OO0O [1 ])
if data !=h :
data =X (data )
data =k (data ,'UTF-8')
O0OOOO0OO0OOO0OO0 =g (O0O000O0O0O0OOO0O ,data )
O0OOOO0OO0OOO0OO0 .add_header ('apim-accesstoken',OO0OO000O0O0OO00O )
O0OOOO0OO0OOO0OO0 .add_header ('Content-Type','application/json;charset=utf-8')
O0OOOO0OO0OOO0OO0 .add_header ('User-Agent','Python_enos_api')
for O000OO0O0O0O0O0OO ,OO0OO0O0O00O0O00O in headers .items ():
O0OOOO0OO0OOO0OO0 .add_header (O000OO0O0O0O0O0OO ,OO0OO0O0O00O0O00O )
O0O0OO0O0OOOO00O0 =b (O0OOOO0OO0OOO0OO0 )
return O0O0OO0O0OOOO00O0 .read ().decode ('UTF-8')
except F :
return OOO0O0O0O00OOO00O
except n as OOO000O00000O0O00 :
w (OOO000O00000O0O00 )
|
zzltest
|
/zzltest-0.1.5.tar.gz/zzltest-0.1.5/posedion/poseidon.py
|
poseidon.py
|
# Example Package
这是我的包
#卸载
pip3 uninstall zzmm
|
zzmm
|
/zzmm-0.0.1.tar.gz/zzmm-0.0.1/README.md
|
README.md
|
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="zzmm",
version="0.0.1",
author="张猛",
author_email="1694349472@qq.com",
description="A small example package",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/pypa/sampleproject",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
|
zzmm
|
/zzmm-0.0.1.tar.gz/zzmm-0.0.1/setup.py
|
setup.py
|
## Pupose
This program parse a .bib file and make new files(index.md, cite.bib) for using zzo theme blog
## Install
You have to install pip before type this command.
```cmd
pip3 install zzo-bibtex-parser
```
## Usage
After install the `zzo-bibtex-parser` package, type this command.
This will generate files in `content/publication/...`
```cmd
zzo --path mybibtex.bib
```
|
zzo-bibtex-parser
|
/zzo-bibtex-parser-1.0.8.tar.gz/zzo-bibtex-parser-1.0.8/README.md
|
README.md
|
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
install_requires = ['bibtexparser==1.1.0']
setuptools.setup(
name="zzo-bibtex-parser",
version="1.0.8",
license="WTFPL",
author="zzossig",
author_email="zzossig@gmail.com",
description="bibtex importer for hugo zzo theme",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/zzossig/zzo-bibtex-parser",
packages=setuptools.find_packages(),
entry_points ={
'console_scripts': [
'zzo = zzo.parser:main'
],
},
classifiers=[
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
install_requires=install_requires,
)
# python setup.py sdist
# pip install twine
# twine upload dist/*
|
zzo-bibtex-parser
|
/zzo-bibtex-parser-1.0.8.tar.gz/zzo-bibtex-parser-1.0.8/setup.py
|
setup.py
|
#!/usr/bin/env python3
import sys
import os
import re
import datetime
import argparse
from time import strptime
import bibtexparser
from bibtexparser.bparser import BibTexParser
from bibtexparser.bwriter import BibTexWriter
from bibtexparser.bibdatabase import BibDatabase
def main():
parse(sys.argv[1:])
def parse(args):
parser = argparse.ArgumentParser(description='zzo-bibtex-parser')
parser.add_argument('--path', required=True, help='bib file path')
args = parser.parse_args()
if args.path == None:
print('You must specify bib file path')
else:
# make list of dictionary for the data
with open(args.path, 'r', encoding='utf8') as bibtex_file:
parser = BibTexParser(common_strings=True)
bib_database = bibtexparser.load(bibtex_file, parser=parser)
for dic in bib_database.entries:
year = '0000'
month = '01'
day = '01'
entry_type = 'misc'
result = ['---']
for key in dic:
# delete { } \ from value
if (key != 'month'):
parsed_dict = re.sub('[{}\\\\]', '', dic[key])
if key != 'file' and key != 'ID' and key != 'urldate' and key != 'language':
if key == 'author':
authors = parsed_dict.split('and')
result.append(f'authors: {authors}')
elif key == 'keywords':
keywords = parsed_dict.split(',')
result.append(f'keywords: {keywords}')
elif key == 'url':
result.append(f'links:\n - name: url\n link: {parsed_dict})')
elif key == 'journal':
result.append(f'publication: "{parsed_dict}"')
elif key == 'year':
year = parsed_dict
elif key == 'month':
month = month_string_to_number(dic[key])
elif key == 'day':
day = parsed_dict
elif key == 'ENTRYTYPE':
doubleQuoteEscape = parsed_dict.replace('"', '\\"')
result.append(f'{key}: "{doubleQuoteEscape}"')
entry_type = doubleQuoteEscape
else:
doubleQuoteEscape = parsed_dict.replace('"', '\\"')
result.append(f'{key}: "{doubleQuoteEscape}"')
result.append(f'enableToc: {False}')
result.append(f'enableWhoami: {True}')
result.append(f'pinned: {True if is_current_year(int(year)) else False}')
result.append(f'publishDate: "{year}-{month}-{day}"')
result.append('---')
# make file
if dic['ID']:
# md file
renamedDir = re.sub(r'(?<!^)(?=[A-Z])', '_', dic['ID']).lower()
filename = f"content/publication/{entry_type}/{renamedDir}/index.md"
listfilename = f"content/publication/{entry_type}/_index.md"
dirname = os.path.dirname(filename)
listdirname = os.path.dirname(listfilename)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(filename, 'w', encoding='utf8') as file:
file.write('\n'.join(result))
if not os.path.exists(listdirname):
os.makedirs(listdirname)
with open(listfilename, 'w', encoding='utf8') as listfile:
listdata = [
'---',
f'title: {entry_type}',
f'date: {datetime.datetime.now()}',
f'description: Publication - {entry_type}',
'---'
]
listfile.write('\n'.join(listdata))
# bib file
db = BibDatabase()
db.entries = [dic]
writer = BibTexWriter()
with open(f"content/publication/{entry_type}/{renamedDir}/cite.bib", 'w', encoding='utf8') as bibfile:
bibfile.write(writer.write(db))
else:
print('There is no ID')
def month_string_to_number(string):
m = {
'jan': "01",
'feb': "02",
'mar': "03",
'apr': "04",
'may': "05",
'jun': "06",
'jul': "07",
'aug': "08",
'sep': "09",
'oct': "10",
'nov': "11",
'dec': "12"
}
s = string.strip()[:3].lower()
try:
out = m[s]
return out
except:
raise ValueError('Not a month')
def is_current_year(year):
now = datetime.datetime.now()
return now.year == year
if __name__ == "__main__":
main()
|
zzo-bibtex-parser
|
/zzo-bibtex-parser-1.0.8.tar.gz/zzo-bibtex-parser-1.0.8/zzo/parser.py
|
parser.py
|
# zzpy
Python3 Utilities
```shell
# pip3 install zzpy -i https://pypi.org/simple
# pip3 install zzpy --upgrade -i https://pypi.org/simple
```
# 待验证
- [ ] zgeo
# 未完成
- [ ] zcaptcha
- [ ] zbrowser
- [ ] zjson
- [ ] zrun
- [ ] ztime
# 已完成
- [x] zrandom
- [x] zconfig
- [x] zfile
- [x] zmongo
- [x] zmysql
- [x] zredis
- [x] zsys
# release log
* 1.1.39: +mongo_download deprecated: mongo_download_collection
* 1.1.23: +mongo_download_collection
* 1.1.18: +area_matcher
* 1.1.16: +dict_extract
* 1.1.9: excel
* 1.1.6: +zfunction.list_or_args; +zredis.publish/listen; zredis.brpop/blpop+safe
* 1.0.20200827: +ES处理zes
* 1.0.20200825: +zfile.download_file
* 1.0.20200824: +zmongo.mongo_collection
* 1.0.20200821.4: 删除ztime无用方法
* 1.0.20200821.3: ztime
* 1.0.20200821:zalioss+url
* 1.0.20200820.10:zalioss+list+delete
* 1.0.20200820.8: 私有库推送
* 1.0.20200817: 重构OssFile,支持oss_url格式,去掉OssFile,新增AliOss
* 1.0.20200812.6: excel->csv
* 1.0.20200812.5: zalioss修复默认配置的bug
* 1.0.20200812.4: +zalioss
* 1.0.20200812.3: zjson.jsondumps cls参数默认值为DateEncoder
* 1.0.20200812.2: zmysql.mysql_iter_table fix default parameters
* 1.0.20200812.1: zmysql.mysql_iter_table+fields
* 1.0.20200812: zmysql+mysql_iter_table
* 1.0.20200723: zmysql.MySQLConfig对MYSQL_URL解析规则问题修复
* 1.0.20200721: ztime+get_month
* 1.0.9: build.sh
* 1.0.8: +get_today, +get_date
* 1.0.7: jsondumps+params
* 1.0.6: +jsondumps
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/README.md
|
README.md
|
from setuptools import setup, find_packages
setup(
name="zzpy",
version="1.1.57",
keywords=["pip", "zzpy", "utils"],
description="Python3 utilities",
long_description="Python3 utilities",
license="MIT Licence",
url="https://github.com/zerocpp/zzpy",
author="zerocpp",
author_email="85642468@qq.com",
packages=find_packages(),
include_package_data=True,
platforms="any",
install_requires=["pymongo", "pymysql",
"redis", "tqdm", "jsonlines", "pandas", "oss2", "openpyxl", "elasticsearch", "Deprecated", "xlrd"]
)
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/setup.py
|
setup.py
|
import unittest
class ZfileTests(unittest.TestCase):
def setUp(self):
import os
super().setUp()
self.root_dir = os.path.join("test", "file")
from zzpy import remove_dir
remove_dir(self.root_dir)
def tearDown(self):
from zzpy import remove_dir
super().tearDown()
remove_dir(self.root_dir)
def test_read_jsonline(self):
from zzpy import read_jsonline
from collections.abc import Generator
import os
# generator
file_path = os.path.join("test", "static", "1.jsonl")
self.assertIsInstance(read_jsonline(file_path), Generator)
# end file without newline
data = []
for i in read_jsonline(file_path):
data.append(i)
self.assertListEqual(data, [{"name": "Zero", "age": 31},
{"name": "Flyoung", "age": 17}])
# generator
file_path = os.path.join("test", "static", "2.jsonl")
self.assertIsInstance(read_jsonline(file_path), Generator)
# end file with newline
data = []
for i in read_jsonline(file_path):
data.append(i)
self.assertListEqual(data, [{"name": "Zero", "age": 31},
{"name": "Flyoung", "age": 17}])
def test_create_and_remove_dir(self):
"""测试文件夹的创建和删除"""
from zzpy import create_dir, remove_dir, init_dir
from zzpy import get_file_name_list_from_dir
import os
# ending without "/"
a_dir = os.path.join(self.root_dir, "a")
b_dir = os.path.join(self.root_dir, "a", "b")
create_dir(b_dir)
self.assertTrue(os.path.exists(b_dir))
init_dir(a_dir)
self.assertTrue(os.path.exists(a_dir))
self.assertFalse(os.path.exists(b_dir))
def test_create_and_remove_dir_ending_with_slash(self):
"""测试文件夹名最后带斜线/的创建和删除"""
from zzpy import create_dir, remove_dir, init_dir
import os
# ending with "/"
a_dir = os.path.join(self.root_dir, "a/")
b_dir = os.path.join(self.root_dir, "a", "b/")
create_dir(b_dir)
self.assertTrue(os.path.exists(b_dir))
init_dir(a_dir)
self.assertTrue(os.path.exists(a_dir))
self.assertFalse(os.path.exists(b_dir))
def test_init_dirs(self):
from zzpy import init_dirs
from zzpy import get_tmp_dir_path
from zzpy import get_work_dir_path
from zzpy import remove_dir
from zzpy import get_file_name_list_from_dir
import os
tmp_dir = get_tmp_dir_path(root_dir=self.root_dir)
work_dir = get_work_dir_path(root_dir=self.root_dir)
self.assertFalse(os.path.exists(self.root_dir))
init_dirs(root_dir=self.root_dir)
self.assertTrue(os.path.exists(self.root_dir))
self.assertTrue(os.path.exists(tmp_dir))
self.assertTrue(os.path.exists(work_dir))
def test_get_file_path_list_from_dir(self):
from zzpy import get_file_path_list_from_dir
from zzpy import write_file
from zzpy import init_dir
import os
# init
a_dir = os.path.join(self.root_dir, "a")
aa_dir = os.path.join(a_dir, "aa")
init_dir(aa_dir)
a10_path = os.path.join(a_dir, "10.txt")
write_file("10.txt", a10_path)
aa11_path = os.path.join(aa_dir, "11.txt")
write_file("11.txt", aa11_path)
b_dir = os.path.join(self.root_dir, "b")
bb_dir = os.path.join(b_dir, "bb")
init_dir(bb_dir)
bb20_path = os.path.join(bb_dir, "20.txt")
write_file("20.txt", bb20_path)
bb21_path = os.path.join(bb_dir, "21.txt")
write_file("21.txt", bb21_path)
c_dir = os.path.join(self.root_dir, "c")
init_dir(c_dir)
c30_path = os.path.join(c_dir, "30.txt")
write_file("30.txt", c30_path)
r_path = os.path.join(self.root_dir, "r.txt")
write_file("r.txt", r_path)
# test
file_path_list = get_file_path_list_from_dir(
self.root_dir)
self.assertSetEqual(set(file_path_list), {
r_path, a10_path, aa11_path, bb20_path, bb21_path, c30_path})
def test_get_file_name_list_from_dir(self):
from zzpy import get_file_name_list_from_dir
from zzpy import write_file
from zzpy import init_dir
import os
# init
a_dir = os.path.join(self.root_dir, "a")
aa_dir = os.path.join(a_dir, "aa")
init_dir(aa_dir)
a10_path = os.path.join(a_dir, "10.txt")
write_file("10.txt", a10_path)
aa11_path = os.path.join(aa_dir, "11.txt")
write_file("11.txt", aa11_path)
b_dir = os.path.join(self.root_dir, "b")
bb_dir = os.path.join(b_dir, "bb")
init_dir(bb_dir)
bb20_path = os.path.join(bb_dir, "20.txt")
write_file("20.txt", bb20_path)
bb21_path = os.path.join(bb_dir, "21.txt")
write_file("21.txt", bb21_path)
c_dir = os.path.join(self.root_dir, "c")
init_dir(c_dir)
c30_path = os.path.join(c_dir, "30.txt")
write_file("30.txt", c30_path)
r_path = os.path.join(self.root_dir, "r.txt")
write_file("r.txt", r_path)
# test
file_path_list = get_file_name_list_from_dir(
self.root_dir)
self.assertSetEqual(set(file_path_list), {
"r.txt", "10.txt", "11.txt", "20.txt", "21.txt", "30.txt"})
def test_get_file_line_count(self):
from zzpy import get_file_line_count
import os
self.assertEqual(get_file_line_count(
os.path.join("test", "static", "1.jsonl")), 2)
self.assertEqual(get_file_line_count(
os.path.join("test", "static", "2.jsonl")), 2)
self.assertNotEqual(get_file_line_count(
os.path.join("test", "static", "3.xls")), 0)
self.assertNotEqual(get_file_line_count(
os.path.join("test", "static", "4.xlsx")), 0)
def test_get_tmp_dir_path(self):
from zzpy import get_tmp_dir_path
import os
self.assertEqual(get_tmp_dir_path(), os.path.join("output", "tmp"))
def test_get_work_dir_path(self):
from zzpy import get_work_dir_path
import os
self.assertEqual(get_work_dir_path(), os.path.join("output", "work"))
def test_write_file_and_read_file_when_dir_not_exist(self):
from zzpy import write_file
from zzpy import read_file
from zzpy import read_bin_file
import os
write_content = "abc"
self.assertFalse(os.path.exists(self.root_dir))
file_path = os.path.join(self.root_dir, f"1.txt")
write_file(content=write_content, file_path=file_path)
self.assertTrue(os.path.exists(file_path))
read_content = read_file(file_path)
self.assertEqual(read_content, write_content)
def test_write_file_and_read_file(self):
from zzpy import write_file
from zzpy import read_file
from zzpy import read_bin_file
import os
# 校验当文件目录不存在时,是否可以写文件
self.assertFalse(os.path.exists(self.root_dir))
for i, write_content in enumerate(("abc", "你好", "abc你好", "你好abc", "こんにちは", "こんにちはzero", "zeroこんにちは", "你好zeroこんにちは", "こんにちはzero你好", "")):
# default encoding
file_path = os.path.join(self.root_dir, f"{i}-default.txt")
write_file(content=write_content, file_path=file_path)
self.assertTrue(os.path.exists(file_path))
read_content = read_file(file_path)
self.assertEqual(read_content, write_content)
# encoding utf8
file_path = os.path.join(self.root_dir, f"{i}-utf8.txt")
write_file(content=write_content,
file_path=file_path, encoding="utf8")
self.assertTrue(os.path.exists(file_path))
read_content = read_file(file_path)
self.assertEqual(read_content, write_content)
# encoding gbk
file_path = os.path.join(self.root_dir, f"{i}-gbk.txt")
write_file(content=write_content,
file_path=file_path, encoding="gbk")
self.assertTrue(os.path.exists(file_path))
read_content = read_file(file_path)
self.assertEqual(read_content, write_content)
def test_get_one_file_path_from_dir_when_no_file(self):
import os
from zzpy import get_one_file_path_from_dir
from zzpy import create_dir
create_dir(os.path.join(self.root_dir, "empty-dir"))
self.assertIsNone(get_one_file_path_from_dir(
os.path.join(self.root_dir, "empty-dir")))
def test_get_one_file_path_from_dir_when_single_file(self):
import os
from zzpy import write_file
from zzpy import get_one_file_path_from_dir
write_file("CONTENT", os.path.join(self.root_dir, "a", "a1.txt"))
self.assertEqual(get_one_file_path_from_dir(os.path.join(self.root_dir, "a")), os.path.join(
self.root_dir, "a", "a1.txt"))
def test_get_one_file_path_from_dir_when_multi_files(self):
import os
from zzpy import write_file
from zzpy import get_one_file_path_from_dir
write_file("CONTENT", os.path.join(self.root_dir, "a", "a1.txt"))
write_file("CONTENT", os.path.join(self.root_dir, "a", "a2.txt"))
self.assertIn(get_one_file_path_from_dir(os.path.join(self.root_dir, "a")), (os.path.join(
self.root_dir, "a", "a1.txt"), os.path.join(self.root_dir, "a", "a2.txt")))
def test_get_one_file_path_from_dir_when_having_dirs_after_file(self):
import os
from zzpy import write_file
from zzpy import get_one_file_path_from_dir
write_file("CONTENT", os.path.join(self.root_dir, "c", "0.txt"))
write_file("CONTENT", os.path.join(self.root_dir, "c", "3", "0.txt"))
write_file("CONTENT", os.path.join(self.root_dir, "c", "1", "0.txt"))
self.assertTrue(get_one_file_path_from_dir(os.path.join(
self.root_dir, "c")), os.path.join(self.root_dir, "c", "0.txt"))
def test_get_one_file_path_from_dir_when_having_dirs_before_file(self):
import os
from zzpy import write_file
from zzpy import get_one_file_path_from_dir
write_file("CONTENT", os.path.join(self.root_dir, "c", "4.txt"))
write_file("CONTENT", os.path.join(self.root_dir, "c", "3", "0.txt"))
write_file("CONTENT", os.path.join(self.root_dir, "c", "1", "0.txt"))
self.assertTrue(get_one_file_path_from_dir(os.path.join(
self.root_dir, "c")), os.path.join(self.root_dir, "c", "4.txt"))
def test_move_file_from_src_dir_when_no_file_in_src(self):
"""当src没有文件时"""
import os
from zzpy import write_file
from zzpy import get_file_path_list_from_dir
from zzpy import move_file_from_src_dir
move_file_from_src_dir(dst_file_path=os.path.join(self.root_dir,
"dst", "1.txt"), src_dir_path=os.path.join(self.root_dir, "src"))
self.assertListEqual(get_file_path_list_from_dir(
os.path.join(self.root_dir, "src")), [])
self.assertListEqual(get_file_path_list_from_dir(
os.path.join(self.root_dir, "dst")), [])
def test_move_file_from_src_dir_when_single_in_src_and_dst_not_exist(self):
"""当src只有一个文件,dst不存在时"""
import os
from zzpy import write_file
from zzpy import get_file_path_list_from_dir
from zzpy import move_file_from_src_dir
write_file("1", os.path.join(self.root_dir, "src", "1.txt"))
move_file_from_src_dir(dst_file_path=os.path.join(self.root_dir,
"dst", "1.txt"), src_dir_path=os.path.join(self.root_dir, "src"))
self.assertListEqual(get_file_path_list_from_dir(
os.path.join(self.root_dir, "src")), [])
self.assertListEqual(get_file_path_list_from_dir(os.path.join(self.root_dir, "dst")), [os.path.join(self.root_dir,
"dst", "1.txt")])
def test_move_file_from_src_dir_when_single_in_src_and_dst_empty(self):
"""当src只有一个文件,dst为空文件夹时"""
import os
from zzpy import write_file
from zzpy import get_file_path_list_from_dir
from zzpy import move_file_from_src_dir
from zzpy import create_dir
write_file("1", os.path.join(self.root_dir, "src", "1.txt"))
create_dir(os.path.join(self.root_dir, "dst"))
move_file_from_src_dir(dst_file_path=os.path.join(self.root_dir,
"dst", "1.txt"), src_dir_path=os.path.join(self.root_dir, "src"))
self.assertListEqual(get_file_path_list_from_dir(
os.path.join(self.root_dir, "src")), [])
self.assertListEqual(get_file_path_list_from_dir(os.path.join(self.root_dir, "dst")), [os.path.join(self.root_dir,
"dst", "1.txt")])
def test_move_file_from_src_dir_when_single_in_src_and_dst_not_empty(self):
"""当src只有一个文件,dst不为空时"""
import os
from zzpy import write_file
from zzpy import get_file_path_list_from_dir
from zzpy import move_file_from_src_dir
from zzpy import create_dir
write_file("1", os.path.join(self.root_dir, "src", "1.txt"))
write_file("2", os.path.join(self.root_dir, "dst", "2.txt"))
move_file_from_src_dir(dst_file_path=os.path.join(self.root_dir,
"dst", "1.txt"), src_dir_path=os.path.join(self.root_dir, "src"))
self.assertListEqual(get_file_path_list_from_dir(
os.path.join(self.root_dir, "src")), [])
self.assertListEqual(get_file_path_list_from_dir(os.path.join(self.root_dir, "dst")), [os.path.join(self.root_dir,
"dst", "1.txt"), os.path.join(self.root_dir, "dst", "2.txt")])
def test_move_file_from_src_dir_when_multi_in_src(self):
"""当src有多个文件时"""
import os
from zzpy import write_file
from zzpy import get_file_path_list_from_dir
from zzpy import move_file_from_src_dir
from zzpy import create_dir
write_file("1", os.path.join(self.root_dir, "src", "1.txt"))
write_file("2", os.path.join(self.root_dir, "src", "2.txt"))
write_file("2", os.path.join(self.root_dir, "dst", "3.txt"))
move_file_from_src_dir(dst_file_path=os.path.join(self.root_dir,
"dst", "0.txt"), src_dir_path=os.path.join(self.root_dir, "src"))
src_pathes = get_file_path_list_from_dir(
os.path.join(self.root_dir, "src"))
self.assertEqual(len(src_pathes), 1)
self.assertIn(src_pathes[0], (os.path.join(
self.root_dir, "src", "1.txt"), os.path.join(self.root_dir, "src", "2.txt")))
dst_pathes = get_file_path_list_from_dir(
os.path.join(self.root_dir, "dst"))
self.assertEqual(len(dst_pathes), 2)
self.assertListEqual(dst_pathes, [os.path.join(
self.root_dir, "dst", "0.txt"), os.path.join(self.root_dir, "dst", "3.txt")])
def test_move_file_from_src_dir_when_src_and_dst_have_same_file(self):
"""当src有多个文件时"""
import os
from zzpy import write_file
from zzpy import get_file_path_list_from_dir
from zzpy import move_file_from_src_dir
from zzpy import read_file
write_file("1", os.path.join(self.root_dir, "src", "1.txt"))
write_file("2", os.path.join(self.root_dir, "dst", "1.txt"))
move_file_from_src_dir(dst_file_path=os.path.join(self.root_dir,
"dst", "1.txt"), src_dir_path=os.path.join(self.root_dir, "src"))
src_pathes = get_file_path_list_from_dir(
os.path.join(self.root_dir, "src"))
self.assertEqual(len(src_pathes), 0)
dst_pathes = get_file_path_list_from_dir(
os.path.join(self.root_dir, "dst"))
self.assertEqual(len(dst_pathes), 1)
dst_path = dst_pathes[0]
self.assertEqual(dst_path, os.path.join(self.root_dir,
"dst", "1.txt"))
self.assertEqual(read_file(dst_path), "1")
def test_normalize_path(self):
import os
from zzpy import windows_else
from zzpy import normalize_path
self.assertEqual(normalize_path(""), windows_else("", ""))
self.assertEqual(normalize_path("."), windows_else(".", "."))
self.assertEqual(normalize_path("./"), windows_else(".\\", "./"))
self.assertEqual(normalize_path(".\\"), windows_else(".\\", "./"))
self.assertEqual(normalize_path("./a"), windows_else(".\\a", "./a"))
self.assertEqual(normalize_path(".\\a"), windows_else(".\\a", "./a"))
self.assertEqual(normalize_path(".."), windows_else("..", ".."))
self.assertEqual(normalize_path("../"), windows_else("..\\", "../"))
self.assertEqual(normalize_path("..\\"), windows_else("..\\", "../"))
self.assertEqual(normalize_path("../a"), windows_else("..\\a", "../a"))
self.assertEqual(normalize_path("..\\a"),
windows_else("..\\a", "../a"))
self.assertEqual(normalize_path("E:/a.txt"),
windows_else("E:a.txt", "E:/a.txt"))
self.assertEqual(normalize_path("E:\\a.txt"),
windows_else("E:a.txt", "E:/a.txt"))
self.assertEqual(normalize_path("E:/x/a.txt"),
windows_else("E:x\\a.txt", "E:/x/a.txt"))
self.assertEqual(normalize_path("E:\\x\\a.txt"),
windows_else("E:x\\a.txt", "E:/x/a.txt"))
self.assertEqual(normalize_path("/a.txt"),
windows_else("/a.txt", "/a.txt"))
self.assertEqual(normalize_path("/x/a.txt"),
windows_else("/x\\a.txt", "/x/a.txt"))
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/test_zfile.py
|
test_zfile.py
|
import unittest
class ZRedisTests(unittest.TestCase):
def setUp(self):
import os
super().setUp()
self.root_dir = os.path.join("test", "file")
from zzpy import remove_dir
remove_dir(self.root_dir)
def tearDown(self):
from zzpy import remove_dir
super().tearDown()
remove_dir(self.root_dir)
def test_redis_decode(self):
from zzpy import redis_decode
self.assertEqual(redis_decode(b"abc"), u"abc")
self.assertEqual(redis_decode("你好".encode("utf8")), u"你好")
self.assertEqual(redis_decode([b"1", "2", 3, u"x".encode("gbk"), u"再见".encode("utf8")]), [
u"1", u"2", 3, u"x", u"再见"])
self.assertEqual(redis_decode(
(b"1", "2", 3, u"再见".encode("utf8"))), (u"1", u"2", 3, u"再见"))
self.assertEqual(redis_decode(
{b"1", "2", 3, u"再见".encode("utf8")}), {u"1", u"2", 3, u"再见"})
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/test_zredis.py
|
test_zredis.py
|
import unittest
class ZMongoTests(unittest.TestCase):
def setUp(self):
import os
super().setUp()
self.root_dir = os.path.join("test", "file")
from zzpy import remove_dir
remove_dir(self.root_dir)
def tearDown(self):
from zzpy import remove_dir
super().tearDown()
remove_dir(self.root_dir)
def test_mongo_config(self):
from zzpy import MongoConfig
self.assertEqual(MongoConfig(url="mongodb://1.2.3.4"),
MongoConfig(host="1.2.3.4", port=27017))
self.assertEqual(MongoConfig(url="mongodb://1.2.3.4/"),
MongoConfig(host="1.2.3.4", port=27017))
self.assertEqual(MongoConfig(url="mongodb://1.2.3.4:5"),
MongoConfig(host="1.2.3.4", port=5))
self.assertEqual(MongoConfig(url="mongodb://1.2.3.4:5/d"),
MongoConfig(host="1.2.3.4", port=5, database="d"))
self.assertEqual(MongoConfig(url="mongodb://1.2.3.4/d"),
MongoConfig(host="1.2.3.4", port=27017, database="d"))
self.assertEqual(MongoConfig(url="mongodb://1.2.3.4/d?"),
MongoConfig(host="1.2.3.4", port=27017, database="d"))
self.assertEqual(MongoConfig(url="mongodb://1.2.3.4:5/d?x=1"),
MongoConfig(host="1.2.3.4", port=5, database="d", param={"x": "1"}))
self.assertEqual(MongoConfig(url="mongodb://1.2.3.4:5/d?x=1&y=2"),
MongoConfig(host="1.2.3.4", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MongoConfig(url="mongodb://localhost"),
MongoConfig(host="localhost", port=27017))
self.assertEqual(MongoConfig(url="mongodb://localhost/"),
MongoConfig(host="localhost", port=27017))
self.assertEqual(MongoConfig(url="mongodb://localhost:5"),
MongoConfig(host="localhost", port=5))
self.assertEqual(MongoConfig(url="mongodb://localhost:5/d"),
MongoConfig(host="localhost", port=5, database="d"))
self.assertEqual(MongoConfig(url="mongodb://localhost/d"),
MongoConfig(host="localhost", port=27017, database="d"))
self.assertEqual(MongoConfig(url="mongodb://localhost/d?"),
MongoConfig(host="localhost", port=27017, database="d"))
self.assertEqual(MongoConfig(url="mongodb://localhost:5/d?x=1"),
MongoConfig(host="localhost", port=5, database="d", param={"x": "1"}))
self.assertEqual(MongoConfig(url="mongodb://localhost:5/d?x=1&y=2"),
MongoConfig(host="localhost", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MongoConfig(url="mongodb://a"),
MongoConfig(host="a", port=27017))
self.assertEqual(MongoConfig(url="mongodb://a/"),
MongoConfig(host="a", port=27017))
self.assertEqual(MongoConfig(url="mongodb://a:5"),
MongoConfig(host="a", port=5))
self.assertEqual(MongoConfig(url="mongodb://a:5/d"),
MongoConfig(host="a", port=5, database="d"))
self.assertEqual(MongoConfig(url="mongodb://a/d"),
MongoConfig(host="a", port=27017, database="d"))
self.assertEqual(MongoConfig(url="mongodb://a/d?"),
MongoConfig(host="a", port=27017, database="d"))
self.assertEqual(MongoConfig(url="mongodb://a:5/d?x=1"),
MongoConfig(host="a", port=5, database="d", param={"x": "1"}))
self.assertEqual(MongoConfig(url="mongodb://a:5/d?x=1&y=2"),
MongoConfig(host="a", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MongoConfig(url="1.2.3.4"),
MongoConfig(host="1.2.3.4", port=27017))
self.assertEqual(MongoConfig(url="1.2.3.4/"),
MongoConfig(host="1.2.3.4", port=27017))
self.assertEqual(MongoConfig(url="1.2.3.4:5"),
MongoConfig(host="1.2.3.4", port=5))
self.assertEqual(MongoConfig(url="1.2.3.4:5/d"),
MongoConfig(host="1.2.3.4", port=5, database="d"))
self.assertEqual(MongoConfig(url="1.2.3.4/d"),
MongoConfig(host="1.2.3.4", port=27017, database="d"))
self.assertEqual(MongoConfig(url="1.2.3.4/d?"),
MongoConfig(host="1.2.3.4", port=27017, database="d"))
self.assertEqual(MongoConfig(url="1.2.3.4:5/d?x=1"),
MongoConfig(host="1.2.3.4", port=5, database="d", param={"x": "1"}))
self.assertEqual(MongoConfig(url="1.2.3.4:5/d?x=1&y=2"),
MongoConfig(host="1.2.3.4", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MongoConfig(url="localhost"),
MongoConfig(host="localhost", port=27017))
self.assertEqual(MongoConfig(url="localhost/"),
MongoConfig(host="localhost", port=27017))
self.assertEqual(MongoConfig(url="localhost:5"),
MongoConfig(host="localhost", port=5))
self.assertEqual(MongoConfig(url="localhost:5/d"),
MongoConfig(host="localhost", port=5, database="d"))
self.assertEqual(MongoConfig(url="localhost/d"),
MongoConfig(host="localhost", port=27017, database="d"))
self.assertEqual(MongoConfig(url="localhost/d?"),
MongoConfig(host="localhost", port=27017, database="d"))
self.assertEqual(MongoConfig(url="localhost:5/d?x=1"),
MongoConfig(host="localhost", port=5, database="d", param={"x": "1"}))
self.assertEqual(MongoConfig(url="localhost:5/d?x=1&y=2"),
MongoConfig(host="localhost", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MongoConfig(url="a"),
MongoConfig(host="a", port=27017))
self.assertEqual(MongoConfig(url="a/"),
MongoConfig(host="a", port=27017))
self.assertEqual(MongoConfig(url="a:5"),
MongoConfig(host="a", port=5))
self.assertEqual(MongoConfig(url="a:5/d"),
MongoConfig(host="a", port=5, database="d"))
self.assertEqual(MongoConfig(url="a/d"),
MongoConfig(host="a", port=27017, database="d"))
self.assertEqual(MongoConfig(url="a/d?"),
MongoConfig(host="a", port=27017, database="d"))
self.assertEqual(MongoConfig(url="a:5/d?x=1"),
MongoConfig(host="a", port=5, database="d", param={"x": "1"}))
self.assertEqual(MongoConfig(url="a:5/d?x=1&y=2"),
MongoConfig(host="a", port=5, database="d", param={"x": "1", "y": "2"}))
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/test_zmongo.py
|
test_zmongo.py
|
import unittest
class ZconfigTests(unittest.TestCase):
def setUp(self):
import os
super().setUp()
self.root_dir = os.path.join("test", "file")
from zzpy import init_dir
init_dir(self.root_dir)
def tearDown(self):
from zzpy import remove_dir
super().tearDown()
remove_dir(self.root_dir)
def test_get_param_none(self):
from zzpy import get_param
key = "UNITTEST_KEY"
value = get_param(key)
self.assertIsNone(value)
def test_get_param_from_default_value(self):
from zzpy import get_param
key = "UNITTEST_KEY"
default_value = "UNITTEST_DEFAULT"
value = get_param(key, default_value=default_value)
self.assertEqual(value, default_value)
def test_get_param_from_default_config_value(self):
from zzpy import get_param
from zzpy import write_file
import os
import json
key = "UNITTEST_KEY"
default_config_path = os.path.join(
self.root_dir, "default-config.json")
default_config_value = "UNITTEST_DEFAULT_CONF"
write_file(json.dumps(
{key: default_config_value}), default_config_path)
default_value = "UNITTEST_DEFAULT"
value = get_param(key, default_value=default_value,
default_config_path=default_config_path, local_config_path=None)
self.assertEqual(value, default_config_value)
def test_get_param_from_local_config_value(self):
from zzpy import get_param
from zzpy import write_file
import os
import json
key = "UNITTEST_KEY"
local_config_path = os.path.join(self.root_dir, "local-config.json")
local_config_value = "UNITTEST_LOCAL_CONF"
write_file(json.dumps({key: local_config_value}), local_config_path)
default_config_path = os.path.join(
self.root_dir, "default-config.json")
default_config_value = "UNITTEST_DEFAULT_CONF"
write_file(json.dumps(
{key: default_config_value}), default_config_path)
default_value = "UNITTEST_DEFAULT"
value = get_param(key, default_value=default_value,
default_config_path=default_config_path, local_config_path=local_config_path)
self.assertEqual(value, local_config_value)
def test_get_param_from_env(self):
from zzpy import get_param
from zzpy import write_file
import os
import json
# init
key = "UNITTEST_KEY"
env_value = "UNITTEST_ENV"
local_config_path = os.path.join(self.root_dir, "local-config.json")
local_config_value = "UNITTEST_LOCAL_CONF"
write_file(json.dumps({key: local_config_value}), local_config_path)
default_config_path = os.path.join(
self.root_dir, "default-config.json")
default_config_value = "UNITTEST_DEFAULT_CONF"
write_file(json.dumps(
{key: default_config_value}), default_config_path)
default_value = "UNITTEST_DEFAULT"
os.environ[key] = env_value
self.assertIn(key, os.environ)
value = get_param(key, default_value=default_value,
default_config_path=default_config_path, local_config_path=local_config_path)
self.assertEqual(value, env_value)
# clean
del os.environ[key]
self.assertNotIn(key, os.environ)
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/test_zconfig.py
|
test_zconfig.py
|
import unittest
class ZGeoTests(unittest.TestCase):
def test_amap_geo_coding(self):
from zzpy import amap_geo_coding
with self.assertRaises(AssertionError):
amap_geo_coding(address="大连市腾讯大厦")
with self.assertRaises(AssertionError):
amap_geo_coding(address="大连市腾讯大厦", api_key="")
with self.assertRaises(Exception):
amap_geo_coding(address="大连市腾讯大厦", api_key="WRONG_API_KEY")
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/test_zgeo.py
|
test_zgeo.py
|
import unittest
class ZMySQLTests(unittest.TestCase):
def setUp(self):
import os
super().setUp()
self.root_dir = os.path.join("test", "file")
from zzpy import remove_dir
remove_dir(self.root_dir)
def tearDown(self):
from zzpy import remove_dir
super().tearDown()
remove_dir(self.root_dir)
def test_MySQLConfig(self):
from zzpy import MySQLConfig
self.assertEqual(MySQLConfig(url="mysql://1.2.3.4"),
MySQLConfig(host="1.2.3.4", port=3306))
self.assertEqual(MySQLConfig(url="mysql://1.2.3.4/"),
MySQLConfig(host="1.2.3.4", port=3306))
self.assertEqual(MySQLConfig(url="mysql://1.2.3.4:5"),
MySQLConfig(host="1.2.3.4", port=5))
self.assertEqual(MySQLConfig(url="mysql://1.2.3.4:5/d"),
MySQLConfig(host="1.2.3.4", port=5, database="d"))
self.assertEqual(MySQLConfig(url="mysql://1.2.3.4/d"),
MySQLConfig(host="1.2.3.4", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="mysql://1.2.3.4/d?"),
MySQLConfig(host="1.2.3.4", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="mysql://1.2.3.4:5/d?x=1"),
MySQLConfig(host="1.2.3.4", port=5, database="d", param={"x": "1"}))
self.assertEqual(MySQLConfig(url="mysql://1.2.3.4:5/d?x=1&y=2"),
MySQLConfig(host="1.2.3.4", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MySQLConfig(url="mysql://localhost"),
MySQLConfig(host="localhost", port=3306))
self.assertEqual(MySQLConfig(url="mysql://localhost/"),
MySQLConfig(host="localhost", port=3306))
self.assertEqual(MySQLConfig(url="mysql://localhost:5"),
MySQLConfig(host="localhost", port=5))
self.assertEqual(MySQLConfig(url="mysql://localhost:5/d"),
MySQLConfig(host="localhost", port=5, database="d"))
self.assertEqual(MySQLConfig(url="mysql://localhost/d"),
MySQLConfig(host="localhost", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="mysql://localhost/d?"),
MySQLConfig(host="localhost", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="mysql://localhost:5/d?x=1"),
MySQLConfig(host="localhost", port=5, database="d", param={"x": "1"}))
self.assertEqual(MySQLConfig(url="mysql://localhost:5/d?x=1&y=2"),
MySQLConfig(host="localhost", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MySQLConfig(url="mysql://a"),
MySQLConfig(host="a", port=3306))
self.assertEqual(MySQLConfig(url="mysql://a/"),
MySQLConfig(host="a", port=3306))
self.assertEqual(MySQLConfig(url="mysql://a:5"),
MySQLConfig(host="a", port=5))
self.assertEqual(MySQLConfig(url="mysql://a:5/d"),
MySQLConfig(host="a", port=5, database="d"))
self.assertEqual(MySQLConfig(url="mysql://a/d"),
MySQLConfig(host="a", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="mysql://a/d?"),
MySQLConfig(host="a", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="mysql://a:5/d?x=1"),
MySQLConfig(host="a", port=5, database="d", param={"x": "1"}))
self.assertEqual(MySQLConfig(url="mysql://a:5/d?x=1&y=2"),
MySQLConfig(host="a", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MySQLConfig(url="1.2.3.4"),
MySQLConfig(host="1.2.3.4", port=3306))
self.assertEqual(MySQLConfig(url="1.2.3.4/"),
MySQLConfig(host="1.2.3.4", port=3306))
self.assertEqual(MySQLConfig(url="1.2.3.4:5"),
MySQLConfig(host="1.2.3.4", port=5))
self.assertEqual(MySQLConfig(url="1.2.3.4:5/d"),
MySQLConfig(host="1.2.3.4", port=5, database="d"))
self.assertEqual(MySQLConfig(url="1.2.3.4/d"),
MySQLConfig(host="1.2.3.4", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="1.2.3.4/d?"),
MySQLConfig(host="1.2.3.4", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="1.2.3.4:5/d?x=1"),
MySQLConfig(host="1.2.3.4", port=5, database="d", param={"x": "1"}))
self.assertEqual(MySQLConfig(url="1.2.3.4:5/d?x=1&y=2"),
MySQLConfig(host="1.2.3.4", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MySQLConfig(url="localhost"),
MySQLConfig(host="localhost", port=3306))
self.assertEqual(MySQLConfig(url="localhost/"),
MySQLConfig(host="localhost", port=3306))
self.assertEqual(MySQLConfig(url="localhost:5"),
MySQLConfig(host="localhost", port=5))
self.assertEqual(MySQLConfig(url="localhost:5/d"),
MySQLConfig(host="localhost", port=5, database="d"))
self.assertEqual(MySQLConfig(url="localhost/d"),
MySQLConfig(host="localhost", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="localhost/d?"),
MySQLConfig(host="localhost", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="localhost:5/d?x=1"),
MySQLConfig(host="localhost", port=5, database="d", param={"x": "1"}))
self.assertEqual(MySQLConfig(url="localhost:5/d?x=1&y=2"),
MySQLConfig(host="localhost", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MySQLConfig(url="a"),
MySQLConfig(host="a", port=3306))
self.assertEqual(MySQLConfig(url="a/"),
MySQLConfig(host="a", port=3306))
self.assertEqual(MySQLConfig(url="a:5"),
MySQLConfig(host="a", port=5))
self.assertEqual(MySQLConfig(url="a:5/d"),
MySQLConfig(host="a", port=5, database="d"))
self.assertEqual(MySQLConfig(url="a/d"),
MySQLConfig(host="a", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="a/d?"),
MySQLConfig(host="a", port=3306, database="d"))
self.assertEqual(MySQLConfig(url="a:5/d?x=1"),
MySQLConfig(host="a", port=5, database="d", param={"x": "1"}))
self.assertEqual(MySQLConfig(url="a:5/d?x=1&y=2"),
MySQLConfig(host="a", port=5, database="d", param={"x": "1", "y": "2"}))
self.assertEqual(MySQLConfig(url="mysql://a.b.c:123/?user=uuuu&password=pppp").to_dict(), {
"host": "a.b.c", "port": 123, "user": "uuuu", "password": "pppp", "param": {"user": "uuuu", "password": "pppp"}, "url": "mysql://a.b.c:123/?user=uuuu&password=pppp"})
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/test_zmysql.py
|
test_zmysql.py
|
import unittest
from zzpy import dict_extract
class TestCase(unittest.TestCase):
def test1(self):
d1 = {
"a": 1, "b": 2, "c": 3
}
d2 = dict_extract(d1, "a")
self.assertDictEqual(d2, {"a": 1})
def test2(self):
d1 = {
"a": 1, "b": 2, "c": 3
}
d2 = dict_extract(d1, "a")
d2["a"] = 0
self.assertEqual(d2["a"], 0)
self.assertEqual(d1["a"], 1)
def test3(self):
d1 = {
"a": 1, "b": 2, "c": 3
}
d2 = dict_extract(d1, "a", "b")
self.assertDictEqual(d2, {"a": 1, "b": 2})
def test4(self):
d1 = {
"a": 1, "b": 2, "c": 3
}
d2 = dict_extract(d1, ("a", "b"))
self.assertDictEqual(d2, {"a": 1, "b": 2})
def test5(self):
d1 = {
"a": 1, "b": 2, "c": 3
}
d2 = dict_extract(d1, {"a", "b"})
self.assertDictEqual(d2, {"a": 1, "b": 2})
def test6(self):
d1 = {
"a": 1, "b": 2, "c": 3
}
d2 = dict_extract(d1, ["a", "b"])
self.assertDictEqual(d2, {"a": 1, "b": 2})
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/zdict/test_dict_extract.py
|
test_dict_extract.py
|
import unittest
class TestCase(unittest.TestCase):
def test(self):
from zzpy import dict_recursive_get
self.assertIsNone(dict_recursive_get({}, key=""))
self.assertIsNone(dict_recursive_get({"k": 1}, key=""))
self.assertEqual(dict_recursive_get({"k": 1, "": 2}, key=""), 2)
self.assertIsNone(dict_recursive_get({"k": 1, "": 2}, key="."))
self.assertEqual(dict_recursive_get({"k": 1, "": {"": 2}}, key="."), 2)
self.assertEqual(dict_recursive_get({"k": 1, "a": {"b": 2}}, key="a.b"), 2)
self.assertEqual(dict_recursive_get({"k": 1, "a": {}}, key="a.b", default_value=3), 3)
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/zdict/test_dict_recursive_get.py
|
test_dict_recursive_get.py
|
import unittest
import datetime
import zzpy as z
class ZjsonJsondumpsTests(unittest.TestCase):
def test_jsondumps_when_empty_dictionary(self):
self.assertEqual(z.jsondumps({}), "{}")
def test_jsondumps_when_empty_string(self):
self.assertEqual(z.jsondumps(""), "\"\"")
def test_jsondumps_when_empty_list(self):
self.assertEqual(z.jsondumps([]), "[]")
def test_jsondumps_when_contains_datetime(self):
test_datetime_str = "2020-07-20 12:00:00"
test_datetime_fmt = "%Y-%m-%d %H:%M:%S"
d = datetime.datetime.strptime(
test_datetime_str, test_datetime_fmt)
expected_value = f'{{"a": 1, "d": "{test_datetime_str}"}}'
self.assertEqual(z.jsondumps({"a": 1, "d": d}),
expected_value)
def test_jsondumps_when_without_datetime(self):
expected_value = f'{{"a": 1, "b": "2"}}'
self.assertEqual(z.jsondumps({"a": 1, "b": "2"}),
expected_value)
def test_jsondumps_with_indent(self):
expected_value = '{\n "k": "v"\n}'
self.assertEqual(z.jsondumps({"k": "v"}, indent=4), expected_value)
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/zjson/test_jsondumps.py
|
test_jsondumps.py
|
import unittest
from zzpy import randhex
import re
class ZRandomRandhexTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_randhex_when_no_parameters(self):
for _ in range(10):
n = randhex()
self.assertIsInstance(n, str)
self.assertEqual(len(n), 1)
self.assertIsNotNone(re.match("^[\dA-F]$", n))
def test_randhex_when_digits_set(self):
for digits in range(1, 100):
n = randhex(digits=digits)
self.assertIsInstance(n, str)
self.assertEqual(len(n), digits)
self.assertIsNotNone(re.match(f"^[\dA-F]{{{digits}}}$", n))
def test_randhex_when_digits_set_0(self):
n = randhex(digits=0)
self.assertIsInstance(n, str)
self.assertEqual(n, "")
def test_randhex_when_prefix_set_true(self):
for digits in range(1, 10):
n = randhex(digits=digits, prefix=True)
self.assertIsInstance(n, str)
self.assertEqual(len(n), 2+digits)
self.assertIsNotNone(re.match(f"^0x[\dA-F]{{{digits}}}$", n))
def test_randhex_when_prefix_set_false(self):
for digits in range(1, 10):
n = randhex(digits=digits, prefix=False)
self.assertIsInstance(n, str)
self.assertEqual(len(n), digits)
self.assertIsNotNone(re.match(f"^[\dA-F]{{{digits}}}$", n))
def test_randhex_when_lower_set_true(self):
digits = 1_000
self.assertIsNotNone(
re.match(f"^[\da-f]{{{digits}}}$", randhex(digits=digits, lower=True)))
self.assertIsNotNone(
re.match(f"^[\da-f]{{{digits}}}$", randhex(digits=digits, prefix=False, lower=True)))
self.assertIsNotNone(re.match(
f"^0x[\da-f]{{{digits}}}$", randhex(digits=digits, prefix=True, lower=True)))
def test_randhex_when_lower_set_false(self):
digits = 1_000
self.assertIsNotNone(
re.match(f"^[\dA-F]{{{digits}}}$", randhex(digits=digits)))
self.assertIsNotNone(
re.match(f"^[\dA-F]{{{digits}}}$", randhex(digits=digits, lower=False)))
self.assertIsNotNone(
re.match(f"^[\dA-F]{{{digits}}}$", randhex(digits=digits, prefix=False, lower=False)))
self.assertIsNotNone(re.match(
f"^0x[\dA-F]{{{digits}}}$", randhex(digits=digits, prefix=True, lower=False)))
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/zrandom/test_randhex.py
|
test_randhex.py
|
import unittest
from zzpy import randint
class ZRandomRandintTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_randint_when_no_parameters(self):
for _ in range(10_000):
n = randint()
self.assertTrue(0 <= n <= 9)
def test_randint_when_only_given_min(self):
for _ in range(10_000):
n = randint(min=5)
self.assertTrue(5 <= n <= 9)
def test_randint_when_only_given_max(self):
for _ in range(10_000):
n = randint(max=5)
self.assertTrue(0 <= n <= 5)
def test_randint_when_given_min_and_max(self):
for _ in range(10_000):
n = randint(min=1, max=5)
self.assertTrue(1 <= n <= 5)
def test_randint_when_min_equals_max(self):
for _ in range(10_000):
n = randint(min=1, max=1)
self.assertEqual(n, 1)
def test_randint_when_min_is_larger_then_max(self):
for _ in range(10_000):
n = randint(min=5, max=1)
self.assertTrue(1 <= n <= 5)
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/zrandom/test_randint.py
|
test_randint.py
|
import unittest
import zzpy as z
def get_month(months=0, separator='-'):
import arrow
return arrow.now().shift(months=months).format(f"YYYY{separator}MM")
class TestCase(unittest.TestCase):
def test_get_month_with_no_parameters(self):
self.assertEqual(z.get_month(), get_month())
def test_get_month_with_days(self):
for offset in range(-1000, 1000):
self.assertEqual(z.get_month(offset), get_month(offset))
self.assertEqual(z.get_month(months=offset),
get_month(months=offset))
self.assertEqual(z.get_month(offset), get_month(offset))
self.assertEqual(z.get_month(months=offset),
get_month(months=offset))
def test_get_month_with_separator(self):
self.assertEqual(z.get_month(), get_month(separator="-"))
self.assertEqual(z.get_month(), z.get_month(separator="-"))
self.assertEqual(z.get_month(separator="-"), get_month(separator="-"))
self.assertEqual(z.get_month(separator="/"), get_month(separator="/"))
def test_get_month_with_days_and_separator(self):
self.assertEqual(z.get_month(), get_month(months=0, separator="-"))
self.assertEqual(z.get_month(), z.get_month(months=0, separator="-"))
self.assertEqual(z.get_month(months=1, separator="*"),
get_month(months=1, separator="*"))
self.assertEqual(z.get_month(months=1, separator="*"),
z.get_month(months=1, separator="*"))
self.assertEqual(z.get_month(months=-1, separator="*"),
get_month(months=-1, separator="*"))
self.assertEqual(z.get_month(months=-1, separator="*"),
z.get_month(months=-1, separator="*"))
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/ztime/test_get_month.py
|
test_get_month.py
|
import unittest
import zzpy as z
def get_now():
import time
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def get_today():
return get_date(days=0, separator='-')
def get_date(days=0, separator='-'):
import time
return time.strftime(f"%Y{separator}%m{separator}%d", time.localtime(time.time()+days*86400))
class TestCase(unittest.TestCase):
def test_get_date_with_no_parameters(self):
self.assertEqual(z.get_date(), get_today())
def test_get_date_with_days(self):
for offset in range(-1000, 1000):
self.assertEqual(z.get_date(offset), get_date(offset))
self.assertEqual(z.get_date(days=offset), get_date(days=offset))
self.assertEqual(z.get_date(offset), get_date(offset))
self.assertEqual(z.get_date(days=offset), get_date(days=offset))
def test_get_date_with_separator(self):
self.assertEqual(z.get_date(), get_date(separator="-"))
self.assertEqual(z.get_date(), z.get_date(separator="-"))
self.assertEqual(z.get_date(separator="-"), get_date(separator="-"))
self.assertEqual(z.get_date(separator="/"), get_date(separator="/"))
def test_get_date_with_days_and_separator(self):
self.assertEqual(z.get_date(), get_date(days=0, separator="-"))
self.assertEqual(z.get_date(), z.get_date(days=0, separator="-"))
self.assertEqual(z.get_date(days=1, separator="*"),
get_date(days=1, separator="*"))
self.assertEqual(z.get_date(days=1, separator="*"),
z.get_date(days=1, separator="*"))
self.assertEqual(z.get_date(days=-1, separator="*"),
get_date(days=-1, separator="*"))
self.assertEqual(z.get_date(days=-1, separator="*"),
z.get_date(days=-1, separator="*"))
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/ztime/test_get_date.py
|
test_get_date.py
|
import unittest
import os
from zzpy import load_matcher, load_matchers, match_area
class TestCase(unittest.TestCase):
def test_load_matcher(self):
def _match(config, area_a, area_b):
return load_matcher(config)(area_a, area_b)
self.assertTrue(_match(config={"pattern_a": "A|B|C", "pattern_b": "A|B|C"}, area_a=(
"A", "B", "C"), area_b=("A", "B", "C")))
self.assertTrue(_match(config={"pattern_a": ".*|.*|.*", "pattern_b": "{province}|{city}|{district}"}, area_a=(
"A", "B", "C"), area_b=("A", "B", "C")))
self.assertFalse(_match(config={"pattern_a": ".*|.*|.*", "pattern_b": "{province}|{city}|{district}"}, area_a=(
"A", "B", "C"), area_b=("A", "B", "D")))
self.assertTrue(_match(config={"pattern_a": ".*|.*|.*", "pattern_b": "{province}|{city}|.*"}, area_a=(
"A", "B", "C"), area_b=("A", "B", "D")))
def test_match_area(self):
mathcers = load_matchers(os.path.join(
"test", "static", "match_config.jsonl"))
def _match(area_a, area_b):
return match_area(mathcers, area_a, area_b)
self.assertTrue(_match(("北京市", "北京市", "东城区"), ("北京市", "北京市", "东城区")))
self.assertTrue(_match(("北京市", "北京市", "东城区"), ("北京市", "北京市", "西城区")))
self.assertFalse(_match(("北京市", "北京市", "东城区"), ("北京市", "XXX", "西城区")))
self.assertTrue(_match(("重庆市", "XXX", "YYY"), ("重庆市", "AAA", "BBB")))
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/zarea_matcher/test_area_matcher.py
|
test_area_matcher.py
|
import unittest
class TestCase(unittest.TestCase):
def test_oss_config(self):
from zzpy import OssConfig
url = "oss://zeros.top/b-bucket?key=kkey&secret=ssecret"
config = OssConfig(url)
self.assertEqual(config.endpoint, f"https://zeros.top")
self.assertEqual(config.bucket, "b-bucket")
self.assertEqual(config.access_key_id, "kkey")
self.assertEqual(config.access_key_secret, "ssecret")
|
zzpy
|
/zzpy-1.1.57.tar.gz/zzpy-1.1.57/test/test_zalioss/test_oss_config.py
|
test_oss_config.py
|
from .databus import *
__doc__ = databus.__doc__
if hasattr(databus, "__all__"):
__all__ = databus.__all__
|
zzq-string-sum
|
/zzq_string_sum-0.4.0-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/databus/__init__.py
|
__init__.py
|
# Databus Client
Databus Client is a Python client for making HTTP requests to the Databus API and retrieving JSON data.
## Installation
You can install Databus Client using pip:
```agsl
pip install databus-client
```
## Usage
#### Get datasheet pack data
```python
from api.apitable_databus_client import DatabusClient
# Initialize the client with the base URL of the Databus API
host_address = "https://integration.vika.ltd"
client = DatabusClient(host_address)
# Make a GET request to fetch the datasheet pack data
datasheet_id = "dstbUhd5coNXQoXFD8"
result = client.get_datasheet_pack(datasheet_id)
if result:
print(result)
else:
print("Request failed.")
```
## develop
```shell
python3 -m venv .env
source ./env/bin/active
pip3 install -r requirements.txt
pip3 install twine
```
## build and publish
```shell
python3 setup.py sdist
twine upload dist/*
```
|
zzq-strings-sum
|
/zzq-strings-sum-0.6.0.tar.gz/zzq-strings-sum-0.6.0/README.md
|
README.md
|
from setuptools import setup, find_packages
with open('README.md', 'r', encoding='utf-8') as f:
long_description = f.read()
setup(
name='zzq-strings-sum',
version='0.6.0',
description='A client for Databus API',
long_description=long_description,
long_description_content_type='text/markdown',
author='zzq',
author_email='zhaozhiqiang@vikadata.com',
package_dir = {"": "src"},
packages = find_packages(where="src"),
install_requires=['requests'],
)
|
zzq-strings-sum
|
/zzq-strings-sum-0.6.0.tar.gz/zzq-strings-sum-0.6.0/setup.py
|
setup.py
|
import requests
import logging
class DatabusClient:
"""
DatabusClient is a client for making HTTP requests to the Databus API.
It provides a simple interface to send GET requests and retrieve JSON data.
Parameters:
host (str): The base URL of the Databus API.
Usage:
host_address = "https://integration.vika.ltd"
client = DatabusClient(host_address)
datasheet_id = "dstbUhd5coNXQoXFD8"
result = client.get_datasheet_pack(datasheet_id)
if result:
print(result)
else:
print("Request failed.")
"""
def __init__(self, host):
"""
Initialize a new DatabusClient instance.
Args:
host (str): The base URL of the Databus API.
"""
self.host = host
self.logger = logging.getLogger("DatabusClient")
self.logger.setLevel(logging.DEBUG)
# Create a console handler for logging
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# Create a formatter and attach it to the handler
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
# Add the console handler to the logger
self.logger.addHandler(ch)
def get_datasheet_pack(self, datasheet_id):
"""
Send a GET request to the Databus API to fetch the datasheet pack data.
Args:
datasheet_id (str): The ID of the datasheet to retrieve.
Returns:
dict or None: A dictionary containing the JSON data from the response,
or None if the request failed.
"""
url = f"{self.host}/databus/get_datasheet_pack/{datasheet_id}"
headers = {'accept': '*/*'}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise an exception if the request is unsuccessful
json_data = response.json()
return json_data
except requests.exceptions.RequestException as e:
self.logger.error(f"Error occurred during the request: {e}")
return None
# Example usage:
if __name__ == "__main__":
# Configure logging to show debug messages
import logging
logging.basicConfig(level=logging.DEBUG)
host_address = "https://integration.vika.ltd"
client = DatabusClient(host_address)
datasheet_id = "dst9zyUXiLDYjowMvz"
result = client.get_datasheet_pack(datasheet_id)
if result:
print("result message", result['message'])
print("result code", result['code'])
else:
print("Request failed.")
|
zzq-strings-sum
|
/zzq-strings-sum-0.6.0.tar.gz/zzq-strings-sum-0.6.0/src/api/apitable_databus_client.py
|
apitable_databus_client.py
|
def functionZZR():
print "ZZR's vivienne"
|
zzr
|
/zzr-1.0.0.tar.gz/zzr-1.0.0/zzr.py
|
zzr.py
|
from distutils.core import setup
setup(
name = 'zzr',
version = '1.0.0',
py_modules = ['zzr'],
author = 'zzr0427',
author_email = 'zzr0427@toki.waseda.jp',
description = 'This is a test program for python learning.'
)
|
zzr
|
/zzr-1.0.0.tar.gz/zzr-1.0.0/setup.py
|
setup.py
|
# zzsn_nlp
#### 介绍
郑州数能软件科技有限公司_自然语言处理
#### 软件架构
软件架构说明
#### 安装教程
1. xxxx
2. xxxx
3. xxxx
#### 使用说明
1. xxxx
2. xxxx
3. xxxx
#### 参与贡献
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
#### 特技
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/README.md
|
README.md
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : setup
# @Author : LiuYan
# @Time : 2021/4/16 10:07
import setuptools
with open('README.md', 'r', encoding='utf-8') as fh:
long_description = fh.read()
setuptools.setup(
name='zzsn_nlp',
version='0.0.1',
author='ygg',
author_email='ygg@zut.edu.cn',
description='zzsn',
long_description=long_description,
url='https://gitee.com/ly_love_ly/zzsn_nlp',
packages=setuptools.find_packages(),
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
)
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/setup.py
|
setup.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/4/16 18:03
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : base_config
# @Author : LiuYan
# @Time : 2021/4/16 18:06
from abc import abstractmethod, ABC
class BaseConfig(ABC):
@abstractmethod
def __init__(self):
super(BaseConfig, self).__init__()
@abstractmethod
def load_config(self):
"""
Add the config you need.
:return: config(YamlDict)
"""
pass
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/config/base_config.py
|
base_config.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/4/16 18:03
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/config/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : base_runner
# @Author : LiuYan
# @Time : 2021/4/19 10:42
from abc import ABC, abstractmethod
class BaseRunner(ABC):
"""
Abstract definition for runner
"""
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _build_config(self):
pass
@abstractmethod
def _build_data(self):
pass
@abstractmethod
def _build_model(self):
pass
@abstractmethod
def _build_loss(self):
pass
@abstractmethod
def _build_optimizer(self):
pass
@abstractmethod
def _build_evaluator(self):
pass
@abstractmethod
def train(self):
pass
@abstractmethod
def _train_epoch(self, epoch: int):
pass
@abstractmethod
def _valid(self, epoch: int):
pass
@abstractmethod
def test(self):
pass
@abstractmethod
def pred(self):
pass
@abstractmethod
def _display_result(self, epoch: int):
pass
@abstractmethod
def _save_checkpoint(self, epoch: int):
pass
@abstractmethod
def _load_checkpoint(self):
pass
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/runner/base_runner.py
|
base_runner.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/4/16 18:04
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/runner/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : base_loss
# @Author : LiuYan
# @Time : 2021/4/19 10:41
from abc import abstractmethod
import torch.nn as nn
class BaseLoss(nn.Module):
def __init__(self, loss_config):
super(BaseLoss, self).__init__()
self._config = loss_config
@abstractmethod
def forward(self, dict_outputs: dict) -> dict:
pass
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/loss/base_loss.py
|
base_loss.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/4/16 18:04
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/loss/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : base_evaluator
# @Author : LiuYan
# @Time : 2021/4/19 10:39
from abc import ABC, abstractmethod
class BaseEvaluator(ABC):
@abstractmethod
def __init__(self):
super(BaseEvaluator, self).__init__()
@abstractmethod
def evaluate(self):
pass
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/evaluation/base_evaluator.py
|
base_evaluator.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/4/16 18:04
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/evaluation/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : base_app
# @Author : LiuYan
# @Time : 2021/4/21 9:30
import json
from flask import Flask, Blueprint, request
from utils.log import logger
app = Flask(__name__)
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/app/base_app.py
|
base_app.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/4/21 9:30
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/app/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : base_data_reader
# @Author : LiuYan
# @Time : 2021/4/19 9:37
from abc import ABC, abstractmethod
class BaseDataReader(ABC):
@abstractmethod
def __init__(self):
super(BaseDataReader, self).__init__()
@abstractmethod
def reade(self):
pass
@abstractmethod
def save(self):
pass
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/data/base_data_reader.py
|
base_data_reader.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : base_data_process
# @Author : LiuYan
# @Time : 2021/4/19 9:37
from abc import ABC, abstractmethod
class BaseDataProcess(ABC):
"""
data processing
"""
@abstractmethod
def __init__(self):
super(BaseDataProcess, self).__init__()
@abstractmethod
def process(self):
pass
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/data/base_data_process.py
|
base_data_process.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : base_data_loader
# @Author : LiuYan
# @Time : 2021/4/19 9:37
from abc import ABC, abstractmethod
class BaseDataLoader(ABC):
@abstractmethod
def __init__(self):
super(BaseDataLoader, self).__init__()
@abstractmethod
def _load_data(self):
"""
load raw data according to data config
:return:
"""
pass
@abstractmethod
def load_train(self):
pass
@abstractmethod
def load_valid(self):
pass
@abstractmethod
def load_test(self):
pass
pass
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/data/base_data_loader.py
|
base_data_loader.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/4/16 18:03
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/data/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : base_model
# @Author : LiuYan
# @Time : 2021/4/19 10:42
from abc import ABC, abstractmethod
import torch.nn as nn
class BaseModel(nn.Module, ABC):
def __init__(self):
super(BaseModel, self).__init__()
@abstractmethod
def forward(self, dict_inputs: dict) -> dict:
pass
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/model/base_model.py
|
base_model.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/4/16 18:04
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/base/model/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : app_test
# @Author : LiuYan
# @Time : 2021/4/22 9:59
import sys
import logging
sys.path.append('../')
from app.test import test_1
from base.app.base_app import *
HOST = '0.0.0.0'
PORT = 7001
DEBUG = False
app.register_blueprint(test_1, url_prefix='/test_1')
@app.route('/')
def hello_world():
app.logger.info('Hello World!')
return 'Hello World!'
if __name__ == '__main__':
app.run(host=HOST, port=PORT, debug=DEBUG)
if __name__ != '__main__':
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
# gunicorn --workers=2 --bind=0.0.0.0:8000 --log-level=debug gunicorn_log:app
# if __name__ != '__main__':
# gunicorn_logger = logging.getLogger('gunicorn.error')
# logging.basicConfig(level=gunicorn_logger.level, handlers=gunicorn_logger.handlers)
# app.logger.handlers = gunicorn_logger.handlers
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/app/app_test.py
|
app_test.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : app_run
# @Author : LiuYan
# @Time : 2021/4/20 20:11
import sys
import logging
sys.path.append('../')
from base.app.base_app import *
from classification.app.f_zp_gp_app import classification_f_zp_gp
from doc_event.app.the_belt_and_road_app import doc_event_br
from doc_similarity.app.doc_sim_app import doc_sim
from sequence.app.digital_recognition_app import seq_digital_recognition
HOST = '0.0.0.0'
PORT = 7000
DEBUG = False
# classification
app.register_blueprint(classification_f_zp_gp, url_prefix='/classification/f_zp_gp')
# doc_event
app.register_blueprint(doc_event_br, url_prefix='/doc_event/br')
# doc_sim
app.register_blueprint(doc_sim, url_prefix='/doc_sim')
# sequence
app.register_blueprint(seq_digital_recognition, url_prefix='/sequence/digital_recognition')
@app.route('/')
def hello_world():
app.logger.info('Hello World!')
return 'Hello World!'
if __name__ == '__main__':
app.run(host=HOST, port=PORT, debug=DEBUG)
if __name__ != '__main__':
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/app/app_run.py
|
app_run.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : test
# @Author : LiuYan
# @Time : 2021/4/22 11:26
from base.app.base_app import *
test_1 = Blueprint('test_1', __name__)
@test_1.route('/test', methods=['GET'])
def test():
# Default route
app.logger.debug('this is a test -> success DEBUG message') # no
app.logger.info('this is a test -> success INFO message') # yes
app.logger.warning('this is a test -> success WARNING message') # yes
app.logger.error('this is a test -> success ERROR message') # yes
app.logger.critical('this is a test -> success CRITICAL message') # yes
logger.info('test -> success!')
return 'test -> success!'
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/app/test.py
|
test.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : app_config
# @Author : LiuYan
# @Time : 2021/4/22 10:51
import os
import multiprocessing
from pathlib import Path
bind = '0.0.0.0:7000' # 绑定ip和端口号
backlog = 512 # 监听队列
# chdir = '/home/zzsn/liuyan/bin' # gunicorn要切换到的目的工作目录
timeout = 30 # 超时
worker_class = 'gevent' # 使用gevent模式,还可以使用sync 模式,默认的是sync模式
# workers = multiprocessing.cpu_count() * 2 + 1 # 进程数 12 * 2 + 1 = 25
workers = 1 # 低资源 3.8G 待测试如何减小
threads = 2 # 指定每个进程开启的线程数
loglevel = 'info' # 日志级别,这个日志级别指的是错误日志的级别,而访问日志的级别无法设置
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"' # 设置gunicorn访问日志格式,错误日志无法设置
"""
其每个选项的含义如下:
h remote address
l '-'
u currently '-', may be user name in future releases
t date of the request
r status line (e.g. ``GET / HTTP/1.1``)
s status
b response length or '-'
f referer
a user agent
T request time in seconds
D request time in microseconds
L request time in decimal seconds
p process ID
"""
_tmp_path = os.path.dirname(os.path.abspath(__file__))
_tmp_path = os.path.join(_tmp_path, 'log')
Path(_tmp_path).mkdir(parents=True, exist_ok=True)
accesslog = os.path.join(_tmp_path, 'gunicorn_access.log') # 访问日志文件
errorlog = os.path.join(_tmp_path, 'gunicorn_info.log') # 错误日志文件
# gunicorn -c app_config.py app_test:app -D --daemon
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/app/app_config.py
|
app_config.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/4/20 20:07
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/app/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/3/29 11:05
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/sequence/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : test_digital_recognition
# @Author : LiuYan
# @Time : 2021/3/31 9:56
from sequence.model.model_pyltp import LTP
from sequence.regular.regular_digital_recognition import RDR
if __name__ == '__main__':
sentence = '一、前 言 国内PPP项目正蓬勃发展,国外“投建营一体化”项目方兴未艾。我国工程承包企业走出国门的时间不长也不短,最早走出国门的施工队伍,基本上都是去执行中国政府对外经援项目,随后,随着国际政治、经济的环境的变化,越来越多的承包企业走出国门,直接参与国际竞争。有的先是给欧美公司作分包开始,然后开始独立参加小项目、单价合同竞争,再到EPC(包括EPC+F)总承包竞争。 近年来国际工程市场变化很大,市场竞争越来越激烈,承包利润越来越薄,承包条件越来越苛刻,承包风险越来越大。在这种新的市场形势下,我国“走出去”时间早、国际经验丰富、实力雄厚的领军承包企业开始探索以投资拉动工程承包甚至转型开展境外投资,向国际工程价值链的高端发展,“投建营一体化”项目运作模式就是这种业务转型升级的重要方式。 与传统承包工程项目相比,“投建营一体化”项目的收益水平更高,但运作模式和交易架构更为复杂,运作难度更大,面临的风险也更高。据统计,中国对外承包100强里尝试做投建营的承包商约占40%左右,其中做成过的不到20%,在做成的里面,只有不到10家目前看是赚到钱而且希望把投建营做成企业战略发展方向。 总得来讲,无论是外国承包商还是中国承包商,有的投建营项目做得比较成功,但大部分投建营项目或多或少存在这样或那样的问题。诚然,投建营一体化(BOT)项目涉足繁多的诸如法律、合同、金融等非常专业的事务,还涉足项目所在国政府更替、政策摆动、合作伙伴各怀鬼胎、行业习惯和技术标准等错综复杂等问题,这些问题交织在一起,往往会把这些项目发起人(特别是对那些总承包企业的牵头人员,他们既充当业主角色,又充当总承包商的角色,即一帮人马,两块牌子)精力、激情和忍耐性消耗殆尽,只剩忧伤。只要全程经历过这事的人,无论项目成功与否,都有“往事不堪回首”之感慨。这进一步说明投建营合同模式确实太不容易,比之前的单价合同模式和EPC总承包合同模式,投建营一体化合同模式不知要难上几个数量级。 “成功的项目都是相似的,不成功的项目各有各的败笔”。柬埔寨甘再水电站项目(BOT合同),堪称是中资企业在境外实施的最成功“投建营一体化”工程项目之一(教科书级的!),对比一带一路倡议的“和平合作、开放包容、互学互鉴、互利共赢”的丝路精神,甘再水电站BOT项目更堪称是两国经济技术合作的经典案例。 本文以甘再水电站BOT项目为例,对境外“投建营一体化”项目的运作要旨、操作流程和核心考量等问题给予整理、汇编,以飨国际工程承包圈子的同仁们,同时也供我国对外承包企业业务转型升级、运作“投建营一体化”项目时借鉴、参考。 二、项目介绍 1、项目背景 甘再水电工程是20世纪60年代由苏联S.J.Jouk水电公司提出并开展规划和设计的,因战火连绵而一直被搁置。进入本世纪后,柬埔寨经过了连年战乱之后处于相对稳定发展的时期,其全国发电量仅为18万千瓦,电价是中国当时的4倍左右,除首都金边外,电力供应主要限于大城市和主要省城,农村无电力供应、依靠燃油灯或电瓶照明度日的状况仍较普遍,仅有8489个村庄(占全国村庄比例的60.3%)约42.7%的居民有电可用。柬埔寨属于电力短缺国家,但却有着丰富的水利资源。 本世纪初,柬埔寨王国颁布实施了私有化电力法,鼓励和推动独立发电商以私有化方式开发柬埔寨水电资源。 2004年6月,柬埔寨王国工业矿业能源部(MIME)代表柬政府,按法律规定程序进行国际招标,要求开发商成立专门的项目公司以BOT方式开发、实施和运行甘再水力发电项目。中国水电建设集团国际工程有限公司(简称水电国际)顺利夺得第一标并获得了该项目的开发权。 该项目得到中柬两国政府高度重视,2005年7月,温家宝总理与洪森总理出席甘再水电站BOT项目备忘录签署仪式;2006年4月8日,两国总理又亲自为该项目象征性开工举行揭牌仪式。 水电国际在2006年2月23日与柬埔寨国家工业矿产能源部、国家电力公司正式签署了《项目实施协议》(IA)、《土地租赁协议》(LA)和《项目购电协议》(PPA)等一系列协议,为此还专门成立了项目公司。2007年9月18日项目正式开工;2011年12月7日,电站8台机组全部投产发电,同一天,甘再水电站BOT(建设一运营一移交)项目(Kamchay Hydroelectric BOT Project)竣工庆典暨PH1发电仪式隆重举行,柬埔寨首相洪森出席并亲手启动PH1首台发电机组。 这标志着甘再水电站已顺利完成建设期土建安装与机电调试运营等建设任务。按照与柬埔寨政府的协议要求,本项目提前三个多月进入商业运行期。2012年8月1日起正式启用商业发电计量(自此运营40年),为柬埔寨经济社会发展提供了强有力的能源保障。 甘再水电站的建成,满足了柬埔寨贡布省和茶胶省全部电力需求,以及首都金边白天40%、夜间100%的电力供应,极大地缓解了柬埔寨国内电力紧张局面,为当地经济发展提供巨大支撑。该项目的主要目标是替代从越南进口电能。工程还有效调节流域内季节性旱涝问题,提高了下游防洪能力,保证下游农田的水利灌溉,减少水土流失,保护生态平衡,改善当地鱼类及野生动物的栖息环境。 在该项目中,中国水电采用有限追索项目融资的模式对项目进行融资:股东投入28%的资本金,采取“项目融资方式”(Project financing)向银行贷款72%。该融资模式以该水电站项目的远期发电收入作为还款抵押,以该项目的资产作为追索,减少了母公司的投资风险。通过有限追索权的项目融资方式,解决了境外项目的资金问题,减少了企业风险,拓宽了融资渠道。这也是中国水电、中国进出口银行和中国出口信用保险公司(以下简称中国信保)在长期合作基础上首次对中资企业境外投资项目所进行的投融资模式的探索创新和实践。 甘再项目受到社会的极大关注并获得的一系列荣誉或嘉奖: 本项目是柬埔寨政府推出的首个国际(引进外资)竞标BOT项目 柬埔寨国内首个投产运营的大型水电站项目 被柬埔寨洪森首相誉为柬埔寨的“三峡工程” 获得柬埔寨政府颁发的最优秀工程奖 获2010年度柬埔寨王国贡布省最优秀工程奖 中国水电首个境外BOT水电站项目 获中国水电股份公司2011年度优质工程奖 获中国电建集团2013年度科技进步二等奖 是中国企业在当时海外投资建设的最大水电站 2013年12月获中国建设工程(境外工程)最高奖——鲁班奖 清华大学出版《中国对外投资项目案例分析:中国进出口银行海外投资项目精选》,甘再水电站作为7个精选案例之一入选。 机械工业出版社《“一带一路”大实践——中国工程企业“走出去”经验与教训》作为首个成功案例收录 香港凤凰卫视《龙行天下》节目组以甘再水电站项目作为中国企业“走出去”的成功范例为主题拍摄专题纪录片 中国中央电视台以《“走出去”,痛苦还是幸福》为题,对中国境外项目进行专题报道,把甘再水电站建设项目作为典型案例 已成为柬埔寨能源矿产部、束埔寨国家电力公司的一个示范教育展示窗口 2、工程介绍 甘再水电站BOT项目位于柬埔寨西南部大象山区的甘再河干流之上。是一个常规的中型水电站项目,水库为多年调节运行模式,总库容6.813亿立方米。电站的总装机容量为19.41万千瓦,年平均发电量为4.98亿度。 项目的主要功能是发电,但同时具备城市供水及灌溉等辅助功能。甘再水电站的建成极大地缓柬埔国内电力紧张的局面,为柬埔寨经济和社会发展提供了强有力的能源保障。除此之外,这座水电站还能够有效调节流域内季节性旱荡问题,提高下游防洪能力保证下游农田的水利灌溉,减少水土流失,保护生态平衡。 甘再水电站设计目标为:运营发电前两年承担柬埔寨首都金边白天80%、晚上100%电量供应;之后承担其电网白天35%左右,夜间80%左右的电量供应。现在金边电网白天容量为550MW,夜间容量为220MW。 总投资:工程动态总投资为2.805亿美元。 特许经营期:44年,其中施工期为4年,商业运营期为40年。 电价:项目前9年为免税期,电价为8.35美分/千瓦・时,中间6年电价为8.696美分/千瓦·时,后25年电价为7.72美分/千瓦・时,平均电价为8.008美分/千瓦・时。超出年平均4.98亿千瓦・时之外的额外电量,EDC承诺以65%的电价水平购买。 股权:国际工程公司拥有100%股权。 融资方式:由项目公司作为货款人的纯项目融资方式。 保险:在中国出口信用保险公司投保海外投资政治保险;柬埔寨政府担保;其他类別商业保险(工程一切险、雇主责任险、机具设备险等)。 EPC承包:国际工程公司为项目EPC总承包商,设计承包商是中国水电工程顾问集团西北勘测设计研究院(福建省水利水电勘测设计院分包大坝设计),采购承包商是国际工程公司保障部,施工承包商是中国水利水电第八工程局。 O&M模式:运营商为国际工程公司,中国水利水电第十工程局负责现场电站运行维护具体工作。 工程内容: 大坝枢纽工程:由碾压混凝土重力坝、坝顶5孔开敞式溢洪道、坝后PH3电站引水发电系统等组成。大坝长593米,高114米,坝顶宽度6.0m,共分为十个坝段。 PHI引水发电系统:由岸塔式进水口、发电引水隧洞、调压室、PHI地面厂房以及安装间、副厂房等组成。 坝后PH3电站引水发电系统包括引水系统和发电厂房。引水系统布置在河道右岸6#挡水坝段,采用一管一机形式。PH3引水建筑物由进水口、渐变段、引水钢管、钢岔管和高压钢支管组成。发电厂房布置在6#挡水坝段下游岸边,厂区主要建筑物有安装场、主机间、副厂房、220kV开关室及主变室等,均沿坝轴线方向直线排列。 下游反调节堰枢纽:由开敞式无闸溢流堰、泄洪冲砂闸、河床贯流机组厂房PH2等组成。 溢洪道:坝顶五孔开敞式溢洪道,布置在河床中段,溢洪道堰顶高程135.00m,共设5孔,每孔净宽12m,中墩宽3.0m,边墩宽3.0m,采用5扇12m×15m弧形钢闸门,相应配5台卷扬机控制闸门启闭。 机组:主厂房(PH1)6万千万立式混流水轮机组3台;副厂房(PH2)2千5百千瓦灯泡式机组4台;第三厂房(PH3)3千2百千万卧式混流水轮机机组1台; 230KV开关站; 10公里的230Kv的双回路输电线路。 设计工程量: 土石方开挖194.5万立方米 洞挖石方14万立方米 骨料料场开挖400万立方米 碾压混凝土152万立方米 常态混凝土25.6万立方米 衬砌混凝土2.04万立方米 固结、帷幕灌浆12.9万立方米 3、项目的意义 首先是解决了目前柬埔寨缺电的状况。甘再项目进入商业运营期之后,可以大部分解决当地人民的生活用电和工业用电问题。其次,它是中柬友谊的一个重要桥梁。通过该项目,中柬友谊得到进一步巩固。第三,这个项目可以为柬埔寨引进一些建筑行业和水电站建设方面的先进理念,使当地工人的技能得到提升。第四,它可以解决当地居民的就业问题。 甘再水电项目的成功实施,更是产生强大的引领示范作用,激发了柬埔寨王国政府加快开发水电资源的热情,此后,采用甘再水电站合作模式启动多个大型水电站项目,仅中国公司就承接了斯登沃代水电站、额勒赛河下游水电站、达岱河水电站、赛桑河下游二号水电站等大型水电项目。 甘再水电站项目将使中柬实现了“双赢”。对柬方来说,将可以获得解决供电紧张问题等实际利益。甘再水电站是柬埔寨最早实现并网发电的大型水电项目,成为政府政绩和改善民生的标志性项目,对柬埔寨调整国家电力及能源结构、缓解供需矛盾、促进基础设施建设和人口就业、交通旅游等方面产生了积极、深远的影响。 通过采用BOT模式极大缓解了柬政府的财政支出压力,降低了政府赤字,且充分调动了项目发起人的主动性和创造性,在确保项目质量的前提下,提高了项目的建设速度,并能够保证项目运营期的效率和服务质量项目。增加了当地政府财政收入,促进了当地劳动力就业。而对中水集团来说,2012年开始进行商业运行后,预计仅用10多年就可以收回投资成本,投资回报率有望超过100%。 作为中资企业在柬埔寨投资的首座电站,甘再水电站不仅树立起以资本投资带动中国标准、中国设计、中国施工、中国装备“走出去”的价值典范,更以其成功实践诠释着中国电建以投资驱动转型升级的示范效应,并将带给中国工程企业以极大的信心,相信中国工程企业也一定可以与“一带一路”沿线国家实现互利共赢。 三、项目主要参与者与合同关系 1、项目参与方: (1)柬埔寨工业、矿产、能源部(MIME): 政府在项目融资中很少直接参与实际运作,但其在项目融资中扮演的角色极其重要,在宏观方面为项目建设提供一种良好的投资环境,在微观方面给予有关的批准和营运特许、提供项目优惠待遇等,具有不可替代的地位。在本项目中,柬埔寨工业、矿产、能源部(Ministry of Industry Mine andEnergy,MIME)代表柬政府,按法律规定程序以国际竞标方式开发和实施柬埔寨甘再水电站BOT项目,并与开发商签订项目实施协议(Implementation Agreement,IA)和土地租赁协议(Land Lease Agreement,LA)。 (2)柬埔寨国家电力管理局(Electricity Authority of Cambodia,EAC):EAC是根据柬埔寨电力法成立的全国电力管理机构,根据柬电力法行使其全国电力的监督和管理职能,并负责规范和监督全国的电力采购程序。 (3)柬埔寨经济与财政部(财经部)(MEF) : 以MEF为主,代表柬政府承诺提供无条件、不可撤销担保。1)承诺在购电方(EDC)无法支付的情况下,由政府支付电费;2)承诺在由于政治、不可抗力事件导致该电站无法实施和运营而被迫中止合同的情况下,柬政府保证从项目公司购买电站设施。柬国会和参议院通过了政府担保,并且于2006年8月日颁布王令,以法律形式予以确认。 (4)购电方(Offtaker)柬埔寨国家电力公司( Electricity du Cambodia,EDC) :由于偿还项目贷款的资金来源主要是依靠项目产品销售或使用后的收入,因此,项目产品的购买者或使用者通过与项目公司签订长期购买合同,保证了项目的市场和现金流量,为项目贷款提供了重要信用保证。所以,它们的资信情况也是能否取得贷款的最重要因素之一。 本项目中的电力购买者是柬埔寨国有公司——柬埔寨国家电力公司(EDC),其与中水国际签订了为期40年照付不议的长期购电协议(Power Purchase Agreement,PPA)。EDC成立于1996年,为政府全资控股公司,负责全国电力的调度,占据了全国电力市场的85%的份额。EDC承担着PPA项下的购电和支付义务,如果EDC不能支付,柬政府承诺支付电费。 (5)项目主办方(或发起人) 中国水电建设集团国际工程有限公司(简称水电国际):项目主办方一般为股本投资人,通过发起组织项目投融资,实现投资项目的综合目标要求。项目主办方的主要职责是负责获取项目所需的政府许可证或批文、直接或间接参与执行合约,并且为项目公司提供一定的信用担保等支持。 中国水电建设集团国际工程有限公司(水电国际),是由中国水利水电建设集团(SINOHYDRO)控股,于2004年12月28日出资组建,当时注册资本为8.3亿人民币(其中股东中水集团,出资6.8亿,占比81.93%),目前注册资金为人民币45亿元。水电国际的前身为中水集团海外事业部,是中国水电国际化经营战略的组织者和实施者,是集合中国水电全系统国际资源的平台和载体,负责整个集团的海外业务,共享集团资质、业绩和形象标识,有全球50%的水利水电建设市场份额。 为整合中国电建海外投资业务和促进结构调整与转型升级,于2012年7月1日按国际工程公司存续分立原则在北京挂牌设立中水电海外投资有限公司(现已更名为“中国电建集团海外投资有限公司”),注册资本为25亿元。中水电海外投资是水电集团专业从事海外投资业务市场开发、项目建设、运营管理与投资风险管理的法人主体,为推动水电国际业务优先发展战略落地做出了突出贡献。以投资为先导,带动海外EPC业务发展,成为中国水电调整结构、转型升级、推动国际业务优先发展的重要平台与载体。在实践中,中水电海外投资公司也探索出一套集投融资、设计、监理、施工为一体的开发模式,有效地带动了水电投融资结构优化和产业升级,促进了水电海外业务产业链向价值链转变。 (6)项目公司SPV,业主单位中国水电甘再水电项目公司(Sinohydro Kamchay Hydroelectric Project Company): 通常情况下是项目发起人/主办方为了项目的实施而注册成立的项目公司,它可以是一个独立的公司,也可以是一个合伙企业或合资企业,还可以是一个信托机构。除了项目发起人的股本金以外,项目公司通常主要靠贷款进行融资。 “中国水电甘再水电项目公司”是由中国水电国际于2006年4月30日在柬境内注册成立的针对该BOT项目的全资项目公司。项目公司于7月3获得当地的注册登记证明,其注册资本金为100万美元。项目公司具体负责项目的设计、建设、运营。以项目公司的名义对外进行融资贷款,并以项目公司名义开展该项目的有关的合同安排。 (7)工程管理单位:甘再水电项目公司工程管理部,经项目公司授权,是本项目的管理方。对外为管理部,行使三大职能:项目管理、技术咨询及施工监理。对内是严格合同意义下的合同第三方管控,便于项目管理和实施。工程管理部由水电工程顾问集团西北勘测设计研究院组建成立,具体管控进度计划、质量安全监督以及同设计单位、施工单位的日常沟通协调工作,对项目公司负责。 (8)贷款人——中国进出口银行: 在项目融资中,贷款人可以是一家或两家商业银行或机构,也可以是多家银行组成的国际银团。也可以是众多的项目债券持有人。通常情况下,参与项目融资的贷款人有商业银行、国际金融组织、保险公司、非金融机构(如租赁公司、财务公司、投资基金等)和一些国家的出口信贷机构。贷款人参与的数目主要根据贷款的规模和项目风险这两个因素决定的。 (9)总承包商——水电国际:在BOT模式下,承包商通常是负责项目的EPC的总承包商。中国水电国际作为该项目的EPC总承包商,与甘再项目公司签订了工程总承包合同(典型的老子看儿子脸色!)。 主要工作分包安排如下: 中水顾问西北院(西北院为国家甲级勘测设计研究单位)和福建院——项目可行性研究编制、项目的设计任务,具体负责设计供图、施工协调、设计变更处理等工作(E) 水电国际——项目永久设备采购(P) 水电8局(8局是具有水利水电工程总承包特级资质)——工程施工建设(C) 水电10局负责项目运营与维护(O/M) 项目设备/原材料供应商——东方电气/哈电 两大主机厂都和中国水电有着良好的合作关系或战略伙伴关系,因而双方可以达成延期付款或者优惠出口信贷的安排,从而成为项目资金的一个重要来源。另外,其它原材料商出于对中国水电的信誉及长期合作的考虑,一般情况下,都会考虑安排优惠条件为该项目提供所需原材料。 2、项目合同关系图 甘再项目的参与方众多,大致可分为5类经济关系: 甘再项目合同关系图 关系一:投资方与柬埔寨政府之间的关系 为开放和吸引电力投资,柬埔寨颁布实施了私有电力法,鼓励和推动独立发电商以私有化方式开发国内水电资源,并决定以国际竞标的BOT方式开发和实施柬埔寨甘再项目。2006年2月23日,水电国际与柬埔寨国家电力公司(EDC)签订了《购电协议》,与柬埔寨工业矿业能源部(MIME)签订的《实施协议》和《土地租赁协议》。这三大协议和政府投资担保构成了东道国合同框架体系。这些协议界定了投资方与柬埔寨政府之间的权利义务关系,是项目运作及项目公司生存的法律基础。 关系二:投资方与项目公司之间的关系 2006年4月30日,国际公司根据柬埔寨公司法在当地独资设立了甘再项目公司,注册资本金100万美元,有效期为99年,经营范围为以BOT方式在柬埔寨开发水电项目业务。甘再项目公司作为投资方代表,是整个项目全面全过程管理、重大决策和对外沟通协调、重大事项披露的核心机构,主要负责项目融资及保险、投资管理和财务税务、工程征地、合同风险管理、参建各方的综合协调管理等工作。 关系三:项目公司与债权人的关系 甘再项目公司于2007年8月31日与中国进出口银行签署了《借款合同》,2007年12月24日中国出口信用保险公司为甘再项目出具了海外投资保险的保单,2008年1月30日,甘再项目公司与中国进出口银行签署了《合同权益质押及担保协议》等。2008年1月31日,中国进出口银行将第一笔项目借款汇入中国水电甘再项目公司账户,为现场施工的顺利实施提供了资金保障,标志着甘再项目融资正式完成。以项目公司作为借款主体负责对外融资,从而成为真正意义上的BOT项目融资运作模式,即有限追索和表外融资,也是中国水电和中国进出口银行、中国出口信用保险公司共同参与完成的项目融资创新模式。该案例编入了银企合作的案例教材。 关系四:项目公司与EPC承包商之间的关系 EPC总承包方(国际公司)是集设计、供货、委托施工承包、统筹管理的综合机构,对投资方负责,与项目公司完成合同周期结算。中水国际作为项目的EPC总承包商和营运商,与项目公司之间签订了工程总承包合同。为优化资源配置,减少决策链条,提高效率,并基于企业整体利益和商业需求考虑,甘再项目EPC总承包方同项目公司现场试行“两块牌子、一套人马”管理体制,双方经济关系以EPC合同得以明确界定。 关系五:EPC总承包方与设计、施工、供货、监理单位之间的关系 甘再项目引入“小业主、大监理、大施工”的管理模式是集团系统背景下投资项目市场化建设管理的客观需要和主要内容。EPC总承包方与业主代表,即甘再项目公司合并办公,机构人员精干、部门高效,主要负责项目计划管理,重大问题决策和项目建设各方协调、协作。业主方精干高效管计划,监理方充分授权抓现场,施工方资源配置控成本,现场合同履约与行政干预适量匹配,有效制衡,转变体制机制“瓶颈”为管理优势、生产要素“短板”为施工强项。 委托施工方(水电八局)是项目的主体建设力量,是工程进度、质量安全、资源优化、成本控制等项目履约的保证机构,与EPC承包商完成合同周期结算。水电八局施工组织和现场管理实力雄厚,能积极主动承担项目建设的绝大部分任务,从而发挥其资源整合和功能优势。中水八局先后独立或参与建设水电工程200多座,总装机14081MW,建设施工经验丰富。可见,本项目EPC总包商及分包商都具有较丰富的行业经验。 项目的设计及可研编制由中国水电工程顾问集团西北勘测设计院负责,该院为国家甲级勘测设计研究单位,设计经验丰富,在本项目上,具体负责设计供图、施工协调、设计变更处理等工作。福建省水利水电勘测设计院分包了大坝设计。 项目工程师由西北院下设咨询公司派出,组成项目管理方(现场称“工程管理部”),经项目公司授权,担当项目工程管理任务,具体管控进度计划、质量安全监督以及同设计单位、施工单位的日常沟通协调工作,对项目公司负责。 项目供货方由国际公司保障部承担,项目部分设备采购、货物仓储、设备及大宗材料运输、有关配套辅助服务等均按市场原则通过经济合同得以实现。 运营维护由水电十局负责。 四、项目里程碑 在前言里提到境外投资项目,尤其是项目融资的项目(Project-Financing Project),其前期工作的复杂程度和困难程度都是难以想象,比之前的单价合同模式和EPC总承包合同模式,投建营一体化合同模式要难上几个数量级,所以凡经历者都有一种不堪回首的感叹。 下图是本项目几个重要里程碑事件,从中也可以看出,大量、复杂的项目开发工作都集中在施工前期。为此,下面就围绕这几个里程碑,介绍一下一个典型的BOT项目前期有哪些工作。 1. 项目的招投标阶段 1) 资格预审 2004年3月,中水国际正式向柬埔寨工业矿产能源部递交了资审文件; 2004年5月19日,中水国际收到柬方发来的通过资审的通知。中水国际随即将项目情况向中国对外承包工程商会国家发改委、中国商务部、进出口银行和中国信用保险公司(以下简称“中信保”)进行汇报。通过资审的单位共有5家公司分别是: (1)中国水电建设集团国际工程有限公司 (2)中国电力技术进出口公司+ 中国国家电力公司联合体; (3)广西投资集团; (4)日本三井公司( Mitsui & Co. Ltd); (5)加拿大Experco International公司。 加拿大公司的预可研对其有利,另1家中国公司已有在柬埔寨成功实施项目的经验,因此这个项目的竞争比较激烈。 2) 投标 2004年6月11日,柬埔寨工业矿产能源部代表柬政府,按法律规定程序对本项目进行国际公开招标,合同模式为BOT; 2004年7月10日,中水国际购买了标书文件; 2004年7月12日,中水国际组建投标团队(由于是首次编制以BOT方式投标的标书文件,国际工程公司组织了由公司海外投资部、中国水电工程顾问集团西北勘测设计研究院及中国水利水电第八工程局组成的团队。BOT项目涉及项目融资、项目设计及建设和建成后的商业运营等多个方面,因此在分工时主要考虑对BOT项目各分项的驾驭能力,并根据各单位的强项进行工作分配,为项目量身定制合作团队)与组织投标,参加了标前会议; 2004年8月15-22日,中水国际组织中国水电西北勘测设计院(设计单位)及中国水电第八工程局(施工单位)项目考察小组(15人组成)对甘再水电站项目进行了现场考察,并收集了大量项目资料(现场考察,尽职调查,内部评审,投资环境研究,风险分析与应对)。在编标期间,投标小组多次集中办公,沟通、交流工作中的问题和体会,相互借鉴,协调步伐,修正偏差,使编标工作得以顺利地完成; 2004年9月-2005年1月,中水国际组织编制了投标文件,进行了设计施工技术专家论证,完成了投标文件的编制工作; 2004年11月18日,中信保为中水国际出具项目海外投资保险兴趣函; 2005年1月10日,进出口银行为中水国际出具项目贷款兴趣函; 2005年1月初,发改委、承包商会和商务部批准了中水国际及中国国家电力公司联合体和广西投资集团公司参加此项目的投标;在工程承包项目投标中,一般只需要国家商务部的投标许可就能参加投标,中标后便可签约。但按当时政策,BOT项目的投标及签约则需要国家发展和改革委员会与商务部的核准以及国家外管局的同意。此外,BOT项目还需要银行的贷款支持函及中国出口信用保险公司的海外投资保险意向书。而在项目所在国,也需要许多政府批文。因此,审批程序要比工程承包项目复杂得多,也困难得多。 2005年1月中旬,商务部为国际工程公司出具了同意参加此项目投标的批准函。中国驻柬埔寨大使馆经济商务参赞处及中国对外承包工程商会也批准了国际工程公司参加此项目的投标申请。 2005年1月17日,中水国际代表向柬方提交了全套投标文件。 3) 评标与决标 2005年1月17日上午,柬埔寨工业矿产能源部部长、柬埔寨评标委员会成员及参加投标的各公司代表在柬埔寨工业矿产能源部会议室进行开标。 只有两家中国公司参加,即中水国际以及中国国电集团公司+中国电力技术进出口公司联营体。而已经通过资审的中国广西投资集团、日本三井公司和加拿大公司没参加投标。 在技术标评比中,中水国际顺利通过了评标委员会的各项初步核査;中国国电集团公司与中国电力技术进出口公司联营体由于被授权人不明确,需要作进一步的澄清。 而根据原招标文件的规定,商务标需要在技术标评估完成以后才能公开,但由于只有两家公司参加投标,在开完技术标后,柬方主动提出建议当场开商务标。两家中资公司同意了柬方的建议。两家中国公司的投标价格都执行了国家发展和改革委员会协调的指导意见。但是柬埔寨评标委员会认为,两家中国公司的电价均超过了柬埔寨的承受范围,因此决定对此标进行评审后再给相关公司发邀请。 最终柬埔寨评标委员会评定中水国际的技术标最优,商务标融资结构基本合理,邀请中水国际直接进行合同谈判。 2005年3月3日,中水国际收到柬方项目评标委员会的“直接进行合同谈判邀请函”。该邀请函指出:中水国际的技术方案对原可行性研究方案进行了非常深入、细致的分析研究,提出了许多切实可行的设计施工优化和替代方案,而且其商务方案的报价结构合理,融资方案切实可行(技术标最优,融资结构基本合理),虽然所报电价过高,难以被柬方接受,但柬方评标委员会认为可以通过直接合同谈判明确设计优化和替代方案,故决定先邀请中水国际于3月16日赴金边进行直接合同谈判以确定设计优化方案和电价。 中水国际将投标情况和开标结果分别向中国驻東埔寨大使馆和经商处、中国对外承包工程商会、中国商务部、中信保、进出口银行和国家发改委作了书面汇报。 2. 项目合同的谈判及签订 1) 第一阶段合同谈判(2005年3月16日-30日) 2005年3月16日,双方谈判小组开始了第一轮的正式合同谈判。柬方谈判人员由工业矿业能源部(MIME)、财政部、国家发展委员会(CDC)、国家电力公司(EIDC)和评标委员会(EC)组成,中水国际谈判小组由设计、施工、商务和融资等方面的专家组成。此外,柬埔寨还专门聘请了印度咨询为他们出谋划策。谈判内容主要涉及技术、商务、法律等方面。由于当时中方没有海外投资的经验,需要在谈边谈边学,因此谈判的过程也是一个学习的过程。 由于投标标价高于柬埔寨政府的底线较多,且电价难以适应柬埔寨国家电力市场的需要,因此如何通过降低总投资以降低电价就成为此次会谈的重点。柬埔寨希望中方能够有一个合理的技术方案来降低总投资,而国际工程公司认为柬埔寨应在各方面给中方优惠条件以降低总投资,从而降低电价。 双方为了各自的利益互不相让,如果柬埔寨给了中方最大的优惠条件,他们的国家利益就将受到一定程度的损害;而中方如果主动降低总投资及电价,国际工程公司的利益也将受损。因此,谈判十分艰难。 为了使谈判顺利进行,中国驻柬埔寨大使馆给予了全力支持。大使亲自约见柬埔寨首相洪森就甘再水电站项目表明中国政府的支持立场。此举对项目的谈判进程起到了关键的推动作用。 谈判内容主要有以下三个方面: (1)技术方面:双方主要对技术方案中的开关站、溢洪道、大坝、主厂房、输变电线路、进场道路和机电设备等几个部分进行了详细的分析和探讨,研究了一些切实可行的技术优化和实施方案,以降低工程造价。双方共同研究决定,将原方案的一个厂房增加为三个厂房,总装机从初始计划的180兆瓦増加到193兆瓦,增加发电量,从而使电价有一定的下降空间。 (2)商务方面:双方对排雷费、库区清理费、征地费、水资源费、环境保护费、营运管理费、融资成本、保险要求和风险安排等方面进行了深入的探讨和研究,明确了双方各自承担的责任和义务。 (3)法律方面:双方认真研究和交流了与该项目有关的投资法、BOT法、税法、公司法和银行法等法律法规,明确了该项目可以最大限度享受的各种最优惠政策,包括免税期、税种、税率和其他优惠条件。 经过两国政府高层的沟通,双方在谈判中各自做出了承受范围内的让步。柬埔寨承担了项目的增值税、排雷任务及对水库清理要求的简化,国际工程公司在土建及机电设备采购等方面做出了一定的优化,双方解释、澄清并优化了技术方案,明确了各自责任和基本商务条件,商签了第一阶段的会议纪要,明确了上述技术谈判的结论,并最终商定工程总投资为280,545,412美元。 2) 第二阶段合同谈判(2005年3月31日一4月6日) 在第一阶段合同谈判的基础上,柬方于2005年3月31日致函邀请中水集团和中水国际领导进行第二阶段的合同谈判。第二阶段的合同谈判主要目的是确定税费结构、优惠政策、最终电价和相关条件。 “或取或付原则”是此次谈判的重中之重。柬埔寨谈判团队开始时只承诺购买中方发出的电量,而没发的电却不予支付。中方坚持按“或取或付原则”申请支付,即按设计的年平均发电量均推至12个月进行支付,除非由于中方的原因发不出电。经过多次谈判,最终柬埔寨同意了此条款。 根据柬埔寨相关法律的规定,在柬埔寨进行水电站项目等基础设施投资可享有最长30年的特许经营期(运营期)。为了保证中方的最大收益,中方谈判团队从多个方游说柬方谈判团队,将项目的特许经营期定为44年,包括4年建设期及40年运行期。这已经突破了柬法律的规定,需要柬埔寨议会的批准和国王的最后签署,形成一个新的法律。 根据柬投资法及BOT法的相关规定,在柬埔寨进行水电站项目等基础设施投资可享有3~9年的利润税免税的优惠政策。为此,中方谈判团队与柬方进行了多轮谈判,最终为甘再水电站项目争取到9年的利润税免税期。 为了保证有足够的还款资金流,中方在谈判中力争梯级电价,即在期间要求较高的电价,还贷完成后再把电价降低,以便中方的资金流合理,并能尽快还银行货款。最终柬埔寨同意了中方的要求,允许了前高后低的电价结构,保证项目有充足的还款资金。 由于柬埔寨比较贫穷,在中国出口信用保险公司的评级中是一个风险较大的国家(按2015年中国出口信用保险的标准,柬埔寨风险评级为7级),签约方的柬埔寨国家电力公司的实力也不是很强大。为保证中方的收益,中方要求柬埔寨出具政府担保,一旦柬埔寨国家电力公司无力支付甘再项目的电费,柬埔寨财政部将有责任替柬埔寨国家电力公司支付相应款项。柬埔寨最终同意并出具了主权担保。 为了预防柬埔寨法律变更带来的风险,中方在实施协议里注明:如果签约后是由柬埔寨法律变更导致项目损失或收益减少,这部分损失或减少的收益将由柬埔寨政府补偿给甘再项目公司。 因此,甘再水电站项目的资金流就是稳定的,这对项目融资十分有利。柬方给出巨大的优惠条件和激励措施,明确电价基础和电价结构,商签了第二阶段的会议纪要。纪要中对这些条件予以确认:1)特许经营期共44年,包括4年施工期和40年商业运营期;2)在“或取或付原则”下,柬埔寨保证年最小购电量为100%的年平均发电量,即4.98亿千瓦・时(投标时电量方案是:柬方保证年最小购电量为4.82亿千瓦・时的95%)。经过专家的反复论证,3个厂房和年平均发电量4.98亿千瓦・时是切实可行的,这就转移了水量不足的风险;3)从电站进入商业运营期开始,前9年为免税期,免税期结束后的利润税税率。 在上述两个阶段的会谈谈判过程中,中水国际始终与中国驻柬埔寨大使馆和经商处、中国商务部、中信保、进出口银行保持密切联系和沟通,上述机构都表示支持中水国际投资开发该项目。 经过柬发改委主席、柬总理、柬副总理兼内阁部长对合同谈判内容的批准,2005年4月27日,柬工业矿产能源部部长向中水国际颁发了中标通知书,该通知书明确指出柬方决定由中水国际以BOT方式投资开该水电站项目,并邀请公司代表进行下一阶段的项目开发协议和售电协议的谈判。 3) 签署项目合作备忘录 2005年7月4日,在昆明举行的大湄公河次流域国家首脑峰会为尽快推动柬埔寨甘再水电站项目的进程,国际工程公司希望在此次会议上,在中柬两国总理的见证下,签订甘再水电站BOT项目投资开发备忘录。为此,国际工程公司上下齐心协力,通过外交部、商务部及中国驻柬埔寨大使馆等方面的高层运作,打消了洪森首相対此项目的疑虑,对甘再水电站项目有了新的定位,同意参加甘再水电站项目备忘录的签字仪式,并要求双方尽快商定未定事宜,促使项目尽快签约。 最后,在中柬两国总理的见证下,柬埔寨工业部和中水国际签订了甘再水电站BOT项目投资开发备忘录,该备忘录明确:中柬两国政府支持中水国际以BOT方式投资开发甘再水电站项目,并要求双方尽快商定未定事宜,促使项目尽快签约。备忘录签订后,中水国际又与柬埔寨工业部、财政部进行了为期两个月的多轮会谈,就原先涉及的所有未定事宜基本达成一致。 项目合作备忘录签订后,国际工程公司又与柬埔寨工业矿产与能源部、财政部进行了为期2个月的多轮会谈,就原先涉及的所有未定事宜基本达成一致。其中最重要的是由于柬埔寨税法的变更,最终电价在保证中方的收益情况下进行了调整,结果如下: 调整后的电价:前9年电价为8.35美分/干瓦・时,中间6年电价为8.66美分/千瓦・时,后25年电价为7.72美分/千瓦・时。 调整后中方的总收益不变,但由于前期电价更高,因此项目的收益率有了一定的提高。 4) 签订项目协议 虽然电价谈判已经确定了最终的电价,但最终的签约过程仍十分困难。主要是由于柬埔寨发展委员会的一些成员对其中一些内容有着自己的看法:首先,不同意出具政府担保;其次,认为融资安排不合理,应该由中国政府提供优惠货款。而中方始终认为,此项目是国际招标项目,是一个标准的BOT项目。洪森首相受此影响,对项目是否以BOT方式建设摇摆不定。为了促使项目能够正式签约,中国驻柬埔寨大使馆直接与洪森首相对话,同时国际工程公司组织人员与柬埔寨发展委员会◇多次沟通,最终双方达成一致,同意签约。 2006年2月23日上午,柬埔寨甘再水电站BOT项目的实施协议、售电协议和土地租赁协议的签字仪式在柬埔寨首都金边隆重举行。出席并见证此签字仪式的有柬埔寨王国副总理宋安阁下、柬埔寨财经部部长吉春阁下、柬埔寨工业矿产能源部部长苏赛阁下、柬埔寨外交部国务秘书龙微撒龙阁下、中国驻東埔寨大使张金风阁下、中国商务部合作司司长吴喜林先生以及柬埔寨王国各部委代表、中国驻柬埔寨大使馆和经商处宫员、华商在柬机构代表、世行和亚行驻柬代表等共计200余人,中国水电建设集团副总经理兼国际工程有限公司董事长刘起涛先生、中国水电建设集团总经理助理兼国际工程有限公司总经理黄保东先生、柬埔寨王国工矿能源部部长苏赛阁下、柬埔寨国家电力公司董事长单金文先生分别代表各方签署了上述协议。 2006年4月8日,在中柬两国总理见证下举行了象征性开工仪式。 3. 项目公司成立及国内审批 2006年4月30日,中水国际全资项目公司(SinohydroKamchay Hydroelectric Project Company)在柬埔寨注册成立(注册资本100万美元,有效期99年),并于2006年7月31日获得最后注册登记证明。 项目公司注册完毕后,向柬政府申请各类许可,同时在国内向进出口银行寻求资金支持,向发改委报批,向外管局提出批准外汇账户的申请,并与出口信用保险公司商讨投保海外投资险事宜。 2006年5月9日,国家外汇管理局北京外汇管理部向中水国际出具了《关于中国水电建设集团国际工程有限公司开立境外外汇账户的批复》:同意中水国际在 Malayan Banking Bhd.( Maybank) Phnom Penh Branch Cambodia开立美元专用账户,有效期至2009年5月。 2006年8月31日,商务部向中水集团颁发了《中国企业境外机构批准证书》,同意中水集团在柬埔寨设立境外机构,即中国水利水电建设集团公司柬埔寨代表处。 2006年10月2日,国家发展和改革委员会向中水集团出具了《关于中国水利水电建设集团公司投资柬埔寨甘再水电站项目核准的批复》:同意中水集团所属中水国际在柬埔寨贡布省以BOT方式独资建设经营甘再水电站项目。 4. 项目融资合同的签署过程 进出口银行自2004年底开始介入该项目,认为该项目适合以有限追索项目融资方式予以支持,并于2005年1月10日为中水国际出具了项目贷款兴趣函。 2005年6月,经进出口银行领导批准,针对该项目组建了大项目小组。同年10月、11月及12月,进出口银行针对柬埔寨方面关于对本项目要求采取优惠贷款利率的要求进行了三次回复,表示该项目是按惯例公开招标的BOT项目,属于一般商业性项目,关于贷款利率条件,应遵循海外投资贷款利率原则执行,如果我国政府确定就该项目给予优惠贷款政策,进出口银行将按照政府意见办理。 2006年4月,进出口银行为该项目出具了有限追索项目融资方式的融资方案以及贷款意向书。 2006年7月,进出口银行联合项目发起人、中信保、项目的法律顾问及技术顾问召开了融资启动会。 2006年8月,中水国际就其投资的柬埔寨甘再BOT水电站项目正式向进出口银行申请总额为20199万美元的项目融资贷款,期限15年。 2006年10月,由进出口银行、中信保、中水国际等人员组成尽职调查小组赴柬埔寨进行实地调査。 2006年12月18、19日,进出口银行和中水国际就柬埔寨甘再水电站项目有关协议进行讨论。谈判的内容主要是关于项目的重点问题以及对主要项目合同的修改问题,涉及投保问题、离岸账户的设置问题、抵押登记问题、还贷储备金等问题。 经过数轮谈判,最终双方就贷款协议和相关保险、担保协议达成了致意见,并正式签署了贷款协议和担保协议。 2007年8月31日与中国进出口银行签署了《借款合同》。 2007年12月24日中国出口信用保险公司为甘再项目出具了海外投资保险的保单。 2008年1月30日,甘再项目公司与中国进出口银行签署了《合同权益质押及担保协议》等。 2008年1月31日,中国进出口银行将第一笔项目借款汇入中国水电甘再项目公司账户,为现场施工的顺利实施提供了资金保障,标志着甘再项目融资正式完成。 从中我们可以看到组织项目融资过程中值得关注的方面:一是贷款银行需提前介入项目的实施程序并参与谈判;二是需利用项目各方的利益点和兴奋点,使其积极参与到项目中,共同组成项目融资的结构体系。 5. 施工 2007年9月18日开始内部施工建设; 2008年1月31日融资关闭; 2011年12月7日,电站竣工,PH1主厂房发电; 2012年3月15日,PH1主厂房3台机组完成试运行,递交COD申请。 6. 商业运营 2012年8月1日,COD,正进入为期40年的商业运营期。 2052年8月1日由甘再项目公司将项目移交给柬埔寨政府。 (未完,待续……) 本案例由霍家杰先生整理编辑,转自微信公号“国际工程承包合同那些事”。'
# sentence = '115.15亿元!中国能建葛洲坝集团 签订印尼水电项目EPC合同 近日,中国能建葛洲坝集团与印尼大丰和顺能源工业有限公司成功签署印尼DATA DIAN 1200MW水电站一期工程项目EPC合同协议,合同金额约合人民币115.15亿元。项目的成功签约是葛洲坝集团积极参与共建“一带一路”、主动与印尼“全球海洋支点”战略高效对接的重要成果,为中印尼在基础设施等重点领域投资与建设注入新动力。 签约现场 该项目位于中印尼“区域综合经济走廊”的北加里曼丹省,陆路直线距离新首都特别行政区约350公里。项目装机容量1200MW,年均发电量7770GWh,主要工程内容包括碾压混凝土重力坝、泄洪建筑物、引水建筑物、进场道路、导流洞、发电厂房等工程的设计、采购、施工、调试和试运行等。 项目位置 项目发挥北加里曼丹省充沛的水能资源优势和加里曼丹岛及周边岛屿丰富的矿产资源,为在丹戎塞洛等地区建设以先进金属冶炼为主导产业的园区提供电力供应,使北加里曼丹省成为印尼的“能源与矿业”门户,促进当地贸易畅通和社会经济发展。 时值新冠肺炎疫情防控的关键时期,中国能建葛洲坝集团坚持一手抓疫情防控、一手抓生产经营,加强外围环境和国际形势的研判,坚定信心,积极作为,创新工作方法,成功推进该项目签约。 印尼是“一带一路”建设的重要支点。葛洲坝集团将坚持共商、共建、共享原则,高质量共建“一带一路”,持续广泛深入参与印尼水利水电、火电、公路、港口航道、工业园区等各领域建设与投资,为增进中印尼友谊和民生改善作出积极贡献。 21亿!中国铁建中标卡塔尔大型高端社区项目 项目概念图 日前,中铁十八局集团成功中标卡塔尔格湾岛第三标段房建及室外工程项目合同,中标金额10.98亿卡塔尔里亚尔,约合人民币21亿元,合同工期28个月。 该项目位于卡塔尔格湾岛,是当地政府重点打造的大型国际化社区珍珠岛的附属工程,包括20栋独立别墅、15幢商住两用住宅楼,1座清真寺和1个俱乐部,以及室外基础设施,是集娱乐、零售、住宅用途为一体的高端社区。 项目业主UDC集团是卡塔尔领先的建筑公司和最具实力的公共持股公司之一,此次中标是双方首次合作,为未来开展多领域深度合作创造了条件。 为推动实现“2030愿景”,卡塔尔政府积极打造高品质宜居地,计划以珍珠岛为核心,开发包括格湾岛在内的辐射区域,丰富均衡国内外投资发展。项目建成后,将吸引大量国内外投资置业,拉动当地经济增长,为卡塔尔的东海岸带来更多的发展活力。 卡塔尔是“一带一路”倡议的重要合作伙伴。自2012年承揽北门项目以来,中铁十八局集团相继承揽了比佛利山庄、卡塔尔世界杯配套项目——绿洲五星级酒店等项目,以科学的管理模式、优质的工程品质、高效的履约能力赢得了当地政府和业主的高度赞誉和好评。'
# model_path = '/data/zutnlp/model/pyltp/ltp_data_v3.4.0'
model_path = '/home/zzsn/liuyan/model/ltp/ltp_data_v3.4.0'
ltp = LTP(model_path=model_path)
rdr = RDR()
# word_list = ltp.cws(sentence=sentence)
word_list, tag_list = ltp.pos(sentence=sentence)
number_list, money_list = rdr.digital_sorting(word_list=word_list, tag_list=tag_list)
print('\n数字个数为: {} \n分别是: {}'.format(len(number_list), ' '.join(number_list)))
print('\n金额个数为: {} \n分别是: {}'.format(len(money_list), ' '.join(money_list)))
# word_list, tag_list = ltp.ner(sentence=sentence)
# word_list, tag_list, arc_list = ltp.parse(sentence=sentence)
# word_list, tag_list, arc_list, role_list = ltp.role_label(sentence=sentence)
ltp.release()
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/sequence/test/test_digital_recognition.py
|
test_digital_recognition.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : __init__.py
# @Author : LiuYan
# @Time : 2021/3/31 9:56
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/sequence/test/__init__.py
|
__init__.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : pyhanlp
# @Author : LiuYan
# @Time : 2021/3/29 17:48
from pyhanlp import *
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/sequence/regular/pyhanlp.py
|
pyhanlp.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : regular_digital_recognition
# @Author : LiuYan
# @Time : 2021/3/31 10:04
import re
class RDR(object):
def __init__(self):
super(RDR, self).__init__()
# 10.98亿 卡塔尔里亚尔
self._end_money = ['元', '磅']
self._end_data = ['年', '月', '日', '天']
def digital_sorting(self, word_list, tag_list) -> [list, list]: # 数字分类/筛选
number_list, money_list = [], []
for index in range(len(word_list)):
if tag_list[index] == 'm' and tag_list[index + 1] == 'q' and word_list[index + 1] not in self._end_data:
result = word_list[index] + word_list[index + 1]
if bool(re.search(r'\d', result)):
if index + 2 < len(tag_list) and tag_list[index + 2] == 'n':
result += word_list[index + 2]
# 判断是否为金额
if result[-1] in self._end_money:
money_list.append(result)
elif len(result) > 6 and result[-6:] == '卡塔尔里亚尔':
money_list.append(result)
else:
number_list.append(result)
# print(result)
number_list, money_list = list(set(number_list)), list(set(money_list))
return [number_list, money_list]
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/sequence/regular/regular_digital_recognition.py
|
regular_digital_recognition.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File : pyltp_demo v3.4.0
# @Author : LiuYan
# @Time : 2021/3/29 15:24
|
zzsn-nlp
|
/zzsn_nlp-0.0.1.tar.gz/zzsn_nlp-0.0.1/sequence/regular/pyltp_demo.py
|
pyltp_demo.py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.