Chong's Site book

  • 首页

  • 标签18

  • 分类25

  • 归档33

  • Hexo_docs

  • references

  • markdown_ref

Python-基础(6.2)-time

发表于 2019-04-24 | 分类于 Python , basic , DateTime

time模块— Time access and conversions

Jupter notebook NBViewer传送门
This module provides various time-related functions.

Functions

time.asctime([t])

Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: 'Sun Jun 20 23:21:05 1993'. If t is not provided, the current time as returned by localtime() is used. Locale information is not used by asctime().

1
2
3
4
5
import time
import datetime
print(time.asctime())

print(time.asctime(datetime.datetime.now().timetuple()))
Wed Apr 24 15:34:33 2019
Wed Apr 24 15:34:33 2019

time.ctime([secs])

Convert a time expressed in seconds since the epoch to a string representing local time.
If secs is not provided or None, the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().

1
time.ctime(datetime.datetime.now().timestamp())
'Wed Apr 24 15:36:47 2019'

time.gmtime([secs])

Convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used. Fractions of a second are ignored. See above for a description of the struct_time object. See calendar.timegm() for the inverse of this function.

1
time.gmtime(datetime.datetime.now().timestamp())
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=24, tm_hour=7, tm_min=39, tm_sec=19, tm_wday=2, tm_yday=114, tm_isdst=0)
阅读全文 »

Python-基础(6.1)-datetime and calendar

发表于 2019-04-24 | 分类于 Python , basic , DateTime

主要涉及的模块Modules

Jupter notebook NBViewer传送门

  • datetime Fast implementation of the datetime type. datetime提供操作日期和时间相关的类型
  • calendar Calendar printing functions. calendar模块提供和日历操作及显示打印相关的类
  • time This module provides various functions to manipulate time values. time模块提供了很多方法工具,用来操作时间相关的类型。

datetime模块

模块中包含的类

  • datetime(builtins.object)
    • date
      • datetime
    • time
    • timedelta
    • tzinfo
      • timezone

class datetime.date(year, month, day)

1
2
3
4
5
6
7
代表一个理想化的Gregorian日历中的日期,包括年、月、日等属性。
An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: year, month, and day.
All arguments are required. Arguments may be integers, in the following ranges:

MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year

class methods:

classmethod date.today()

Return the current local date. This is equivalent to date.fromtimestamp(time.time()).

classmethod date.fromtimestamp(timestamp)

Return the local date corresponding to the POSIX timestamp, such as is returned by time.time(). This may raise OverflowError, if the timestamp is out of the range of values supported by the platform C localtime() function, and OSError on localtime() failure. It’s common for this to be restricted to years from 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp().

Changed in version 3.3: Raise OverflowError instead of ValueError if the timestamp is out of the range of values supported by the platform C localtime() function. Raise OSError instead of ValueError on localtime() failure.

阅读全文 »

EBS外币会计核算(一)

发表于 2019-04-23 | 分类于 EBS

外币业务概述

随着我国改革开放的深入,世界经济一体化的进程日益加快,特别是我国已成功地加入了WTO,跨国的各类经济业务的种类不断增加、规模日益扩大。以外币计价和结算的经济业务的比重越来越大。《企业会计制度》第九章分4条,专门对外币业务的定义及核算进行了规范,财政部将在近期颁布有关外币业务的具体会计准则。

1. 外币:是指企业选定的记帐本位币以外的货币。

我国《企业会计制度》第八条规定:

1
2
3
企业的会计核算以人民币为记帐本位币。
业务收支以人民币以外的货币为主的企业,可以选用其中一种货币作为记帐本位币,但是编报的财务会计报告,应当折算为记帐本位币。
在境外设立的中国企业向国内报送的财务会计报告,应当折算为人民币。

注意本章所讲的“外币”与一般意义上的(通常的货币概念中的)外币的区别,一般意义上的外币指外国货币。而会计核算中的“外币”指记帐本位币以外的货币。大多数企业的记帐本位币为人民币,但境外设立的中国企业(如承揽和经营境外工程项目的“外经企业”)及一些从事国际金融业务的金融企业等选择其业务收支使用的主要外国货币如美元作为记帐本位币。如果某企业选择美元作为记帐本位币,则人民币便作为该企业的“外币”。
因此要注意理解是“外币”是相对于企业选定的记帐本位币而言的,“外币≠外国货币”。

2. 外币业务:

《企业会计制度》第一百一十七条规定了外币业务的定义:

1
外币业务,是指以记帐本位币以外的货币进行的款项收付、往来结算等业务。

外币业务的关键是以外币计价,因此要注意理解:

  • “外币业务≠与外国客户进行的交易”,如以人民币为记帐本位币的企业与外国企业进行的以人民币计价结算的经济业务等不属于外币业务;
  • 不能将与国内客户进行的经济业务排除在外币业务之外。

    如:选择人民币为记帐本位币的企业与中国银行之间的美元借款业务、外币兑换业务等都属于外币业务。
    阅读全文 »

Python-基础(6)-Date and Time

发表于 2019-04-23 | 分类于 Python , basic , DateTime

日期和时间 Date and Time


datetime模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from datetime import date 
from datetime import time
from datetime import datetime

> today = date.today()
> print(today)
> 2019-03-04

> print(today.day, today.month, today.year)
> (4, 3, 2019)

> print(today.weekday()) ## returns an integers in the range 0 to 6, where 0 represents Monday and 6 represents Sunday.
> 0

> today = datetime.now()
> print(today)
> 2019-03-04 21:55:56.228000

> time = datetime.time(datetime.now())
> print(time)
> 21:56:16.040000

timedelta类

用于实现date和time对象的计算
This module is used to perform date and time calculations.

1
2
3
4
5
6
7
8
9
from datetime import date 
from datetime import time
from datetime import datetime
from datetime import timedelta

print(timedelta(days=365, hours=5, minutes=1)) # 365 days, 5:01:00
today = datetime.now()
print(today + timedelta(days=60)) # 2019-03-29 18:41:46.720811
print(today - timedelta(days=57)) # 2018-12-02 18:42:36.774421

timedelta object takes the following parameters: days, seconds, microseconds, milliseconds, minutes, hours, weeks.
To find past or future dates, simply use plus or minus sign with the required difference from current date.

日历模块Calendar

Calendar related operations and displaying in formatted way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import calendar

c = calendar.TextCalendar(calendar.MONDAY)
st = c.formatmonth(2017, 1, 0,0)
print(st)

hc = calendar.HTMLCalendar(calendar.MONDAY)
st = hc.formatmonth(2017, 1)
print(st)

#Output
'''
January 2017
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

<table border="0" cellpadding="0" cellspacing="0" class="month">
<tr><th colspan="7" class="month">January 2017</th></tr>
<tr><th class="mon">Mon</th><th class="tue">Tue</th><th class="wed">Wed</th><th class="thu">Thu</th><th class="fri">Fri</th><th class="sat">Sat</th><th class="sun">Sun</th></tr>
<tr><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="sun">1</td></tr>
<tr><td class="mon">2</td><td class="tue">3</td><td class="wed">4</td><td class="thu">5</td><td class="fri">6</td><td class="sat">7</td><td class="sun">8</td></tr>
<tr><td class="mon">9</td><td class="tue">10</td><td class="wed">11</td><td class="thu">12</td><td class="fri">13</td><td class="sat">14</td><td class="sun">15</td></tr>
<tr><td class="mon">16</td><td class="tue">17</td><td class="wed">18</td><td class="thu">19</td><td class="fri">20</td><td class="sat">21</td><td class="sun">22</td></tr>
<tr><td class="mon">23</td><td class="tue">24</td><td class="wed">25</td><td class="thu">26</td><td class="fri">27</td><td class="sat">28</td><td class="sun">29</td></tr>
<tr><td class="mon">30</td><td class="tue">31</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td><td class="noday">&nbsp;</td></tr>
</table>
'''

return HTML code for the calendar in table format. ```Calendar.SUNDAY``` indicates that the first day
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
in the formatted calendar will be Sunday. In the above example, ```Calendar.MONDAY``` is used. Hence, we can see in the output that the first day in the representation is Monday.
#### Iterating through dates of a month
```Python
import calendar

c = calendar.TextCalendar(calendar.MONDAY)
for i in c.itermonthdays(2017, 8):
print(i, end = ' ')
print('')
for name in calendar.month_name:
print(name, end = ' ')
print('')
for day in calendar.day_name:
print(day, end = ' ')
'''
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 0 0 0
January February March April May June July August September October November December
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
'''

Back To Top

Python-基础(5)-Classes

发表于 2019-04-22 | 更新于 2019-04-23 | 分类于 Python , basic , Classes

类 Classes

类的定义 Class Definition

Python是一种面向对象的编程语言。


几乎Python语言中的一切都可以看作一个有自己属性和方法的对象。


而类Class就像一个对象构造器,或者打印机用于创建对象。
A Class is like an object constructor, or a “blueprint” for creating objects..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def test_class():
"""Class definition."""

# Class definitions, like function definitions (def statements) must be executed before they
# have any effect. (You could conceivably place a class definition in a branch of an if
# statement, or inside a function.)

class GreetingClass:
"""Example of the class definition
This class contains two public methods and doesn't contain constructor.
"""
name = 'Bisrat'

def say_hello(self):
"""Class method."""
# The self parameter is a reference to the class itself, and is used to access variables
# that belongs to the class. It does not have to be named self , you can call it
# whatever you like, but it has to be the first parameter of any function in the class.
return 'Hello ' + self.name

def say_goodbye(self):
"""Class method."""
return 'Goodbye ' + self.name

# When a class definition is entered, a new namespace is created, and used as the local scope —
# thus, all assignments to local variables go into this new namespace. In particular, function
# definitions bind the name of the new function here.

# Class instantiation uses function notation. Just pretend that the class object is a
# parameterless function that returns a new instance of the class. For example the following
# code will creates a new instance of the class and assigns this object to the local variable.
# 创建类实例,greeter为实例对象的引用
greeter = GreetingClass()

assert greeter.say_hello() == 'Hello Bisrat'
assert greeter.say_goodbye() == 'Goodbye Bisrat'

>>> print(type(content))
<class 'str'>



类对象 Class Objects

Python是一种面向对象的编程语言。


几乎Python语言中的一切都可以看作一个有自己属性和方法的对象。


所以。。。类本身也是一种对象(Objects)
A Class is like an object constructor, or a “blueprint” for creating objects..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

def test_class_objects():
"""Class Objects.
Class objects support two kinds of operations:
- attribute references
- instantiation.
"""

# ATTRIBUTE REFERENCES use the standard syntax used for all attribute references in
# Python: obj.name. Valid attribute names are all the names that were in the class’s namespace
# when the class object was created. For class MyCounter the following references are valid
# attribute references:

class ComplexNumber:
"""Example of the complex numbers class"""

real = 0
imaginary = 0

def get_real(self):
"""Return real part of complex number."""
return self.real

def get_imaginary(self):
"""Return imaginary part of complex number."""
return self.imaginary

# 并没有创建类实例instance,没有调用类的构造方法。
# 直接通过类引用,调用类对象class object
assert ComplexNumber.real == 0

# __doc__ is also a valid attribute, returning the docstring belonging to the class
assert ComplexNumber.__doc__ == 'Example of the complex numbers class'

# Class attributes can also be assigned to, so you can change the value of
# ComplexNumber.counter by assignment.
ComplexNumber.real = 10
assert ComplexNumber.real == 10

# CLASS INSTANTIATION uses function notation. Just pretend that the class object is a
# parameterless function that returns a new instance of the class. For example
# (assuming the above class):
# 创建实例对象complex_number, 此时创建对象是根据已经改变过的类对象作为创建的模板。
complex_number = ComplexNumber()

assert complex_number.real == 10
assert complex_number.get_real() == 10

# Let's change counter default value back.
ComplexNumber.real = 10
assert ComplexNumber.real == 10

# The instantiation operation (“calling” a class object) creates an empty object. Many classes
# like to create objects with instances customized to a specific initial state. Therefore a
# class may define a special method named __init__(), like this:

class ComplexNumberWithConstructor:
"""Example of the class with constructor"""
def __init__(self, real_part, imaginary_part):
self.real = real_part
self.imaginary = imaginary_part

def get_real(self):
"""Return real part of complex number."""
return self.real

def get_imaginary(self):
"""Return imaginary part of complex number."""
return self.imaginary

complex_number = ComplexNumberWithConstructor(3.0, -4.5)
assert complex_number.real, complex_number.imaginary == (3.0, -4.5)


实例对象 Instance Object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def test_instance_objects():
# DATA ATTRIBUTES need not be declared; like local variables, they spring into existence when
# they are first assigned to. For example, if x is the instance of MyCounter created above,
# the following piece of code will print the value 16, without leaving a trace.

# pylint: disable=too-few-public-methods
class DummyClass:
pass

dummy_instance = DummyClass()

# pylint: disable=attribute-defined-outside-init
dummy_instance.temporary_attribute = 1
assert dummy_instance.temporary_attribute == 1
del dummy_instance.temporary_attribute


方法对象 Method Objects

  • 实例方法(第一个参数是self,自动传递实例对象)
  • 静态方法(没有self参数)
  • 类方法(第一个参数是cls类对象)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class MyCounter:
"""A simple example of the counter class"""
counter = 10

def get_counter(self):
"""Return the counter"""
return self.counter

def increment_counter(self):
"""Increment the counter"""
self.counter += 1
return self.counter


def test_method_objects():
"""Method Objects."""

# object types can have methods as well. For example, list objects have methods called append,

counter = MyCounter()
assert counter.get_counter() == 10

get_counter = counter.get_counter
assert get_counter() == 10



assert counter.get_counter() == 10
assert MyCounter.get_counter(counter) == 10


继承 Inheritance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# pylint: disable=too-few-public-methods
class Person:
"""Example of the base class"""
def __init__(self, name):
self.name = name

def get_name(self):
"""Get person name"""
return self.name


# The syntax for a derived class definition looks like this.
class Employee(Person):

def __init__(self, name, staff_id):
Person.__init__(self, name)
# You may also use super() here in order to avoid explicit using of parent class name:
# >>> super().__init__(name)
self.staff_id = staff_id

def get_full_id(self):
"""Get full employee id"""
return self.get_name() + ', ' + self.staff_id


def test_inheritance():
"""Inheritance."""

# There’s nothing special about instantiation of derived classes: DerivedClassName() creates a
# new instance of the class. Method references are resolved as follows: the corresponding class
# attribute is searched, descending down the chain of base classes if necessary, and the method
# reference is valid if this yields a function object.
person = Person('Bisrat')
employee = Employee('John', 'A23')

assert person.get_name() == 'Bisrat'
assert employee.get_name() == 'John'
assert employee.get_full_id() == 'John, A23'

# Python has two built-in functions that work with inheritance:
#
# - Use isinstance() to check an instance’s type: isinstance(obj, int) will be True only if
# obj.__class__ is int or some class derived from int.
#
# - Use issubclass() to check class inheritance: issubclass(bool, int) is True since bool is
# a subclass of int. However, issubclass(float, int) is False since float is not a subclass
# of int.

assert isinstance(employee, Employee)
assert not isinstance(person, Employee)

assert isinstance(person, Person)
assert isinstance(employee, Person)

assert issubclass(Employee, Person)
assert not issubclass(Person, Employee)


多重继承 Multiple Inheritance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def test_multiple_inheritance():
"""Multiple Inheritance"""
class Clock:
"""Clock class"""

time = '10:17 PM'

def get_time(self):
"""Get current time
Method is hardcoded just for multiple inheritance illustration.
"""
return self.time


class Calendar:
"""Calendar class"""

date = '12/08/2018'

def get_date(self):
"""Get current date
Method is hardcoded just for multiple inheritance illustration.
"""
return self.date

# Python supports a form of multiple inheritance as well. A class definition with multiple
# base classes looks like this.
class CalendarClock(Clock, Calendar):

calendar_clock = CalendarClock()

assert calendar_clock.get_date() == '12/08/2018'
assert calendar_clock.get_time() == '11:23 PM'

Python-基础(4)-Functions

发表于 2019-04-21 | 更新于 2019-04-23 | 分类于 Python , basic , functions

Python Functions

Lambda

1
2
3
4
5
6
7
8
9
>>> fn = lambda x: x**3
>>> fn(2)
8

>>> (lambda x: x**3)(2)
8

>>> (lambda x: [x * _ for _ in range(10)])(3)
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

Declare Function

1
2
3
def fn_name(): ## Where fn_name represents the function name
........
........

Get Function Name

1
2
3
4
5
6
7
8
## First Declare a function 
def fn_name():
.......
.......


>>> fn_name.__name__
'fn_name'

Document a Function

1
2
3
4
5
6
7
8
## Document a function with three single quotes
def check():
'''This function is documented'''
return


>>> check.__doc__
'This function is documented'

Arguments

1
2
3
4
5
6
7
8
9
>>> def multiply(a, b=0): ## b is 0 by default
... return a * b
...
>>> multiply(1, 3) ## 3 * 1
3
>>> multiply(5) ## 5 * 0
0
>>> multiply(5, b=3) ## 5 * 3
15

Generator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def count(start, step):
while True:
yield start
start += step

>>> counter = count(10, 5)
>>> next(counter)
(15)

>>> next(counter) ## Increments by 5 from the previous result
(20)

>>> next(counter)
(25)

>>> next(counter), next(counter), next(counter)
(30, 35, 40)

Decorator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> from functools import wraps

>>> def decorator_func(func):
... @wraps(func)
... def wrapper(*args, **kwargs):
... print("Before calling {}.".format(func.__name__))
... ret = func(*args, **kwargs)
... print("After calling {}.".format(func.__name__))
... return ret
... return wrapper
...
>>> @decorator_func
... def check():
... print("Inside check function.")
...
>>> check()
Before calling check.
Inside check function.
After calling check.

Python-基础(3)-files

发表于 2019-04-21 | 更新于 2019-04-22 | 分类于 Python , basic , files

文件处理

open函数 buildin function

1
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)`

File access modes

1
2
3
4
5
6
7
8
Character	Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)

Read a file

In Python 3, If files do not open in binary mode, the encoding will be determined by
or user's input.
1
2
3
4
5
6
```python
>>> with open("/etc/hosts", encoding="utf-8") as f:
... content = f.read()
...
>>> print(type(content))
<class 'str'>

In python3 binary mode

1
2
3
4
5
>>> with open("/etc/hosts", "rb") as f:
... content = f.read()
...
>>> print(type(content))
<class 'bytes'>

In python2

1
2
3
4
5
6
7
## The content of the file is a byte string, not a Unicode string.
>>> with open("/etc/passwd") as f:
... content = f.read()
>>> print(type(content))
<type 'str'>
>>> print(type(content.decode("utf-8")))
<type 'unicode'>

Write a File

1
2
3
>>> file_content = "Python is great!"
>>> with open("check.txt", "w") as file:
... file.write(file_content)

Copy a file

1
2
3
>>> from distutils.file_util import copy_file
>>> copy_file("a", "b")
('b', 1)

Move a File

1
2
3
>>> from distutils.file_util import move_file
>>> move_file("./a", "./b")
'./b'

Readline

1
2
3
4
5
6
7
8
## If you are not using linux machine try to change the file path to read
>>> with open("/etc/hosts") as f:
... for line in f:
... print(line, end='')
...
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost

Python-基础(2)-number

发表于 2019-04-20 | 更新于 2019-04-22 | 分类于 Python , basic , numbers

Numbers

在Python中一共有三种数字类型:

  • int 整数型 (e.g. 2, 4, 20)
    • bool 布尔 (e.g. False and True, acting like 0 and 1)
  • float 浮点型(e.g. 5.0, 1.6)
  • complex 复数型(e.g. 5+6j, 4-3j)

Basic Functions

1
2
a = pow(2, 3) ## Or: 2 ** 3
b = abs(5) ## <real> = abs(<num>)

Constants

1
from math import e, pi

Trigonometry三角函数

1
from math import cos, acos, sin, asin, tan, atan, degrees, radians

Logarithm对数

1
2
from math import log, log10, log2
<float> = log(<real> [, base]) # Base e, if not specified.

Infinity, nan

1
from math import inf, nan, isinf, isnan

Or:

1
float('inf'), float('nan')

Statistics

1
from statistics import mean, median, variance, pvariance, pstdev

Random

1
2
3
4
5
from random import random, randint, choice, shuffle
<float> = random()
<int> = randint(from_inclusive, to_inclusive)
<el> = choice(<list>)
shuffle(<list>)

Combinatorics

  • Every function returns an iterator.
  • If you want to print the iterator, you need to pass it to the list() function!
1
from itertools import product, combinations, combinations_with_replacement, permutations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> product([0, 1], repeat=3)
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

>>> product('ab', '12')
[('a', '1'), ('a', '2'),
('b', '1'), ('b', '2')]

>>> combinations('abc', 2)
[('a', 'b'), ('a', 'c'), ('b', 'c')]

>>> combinations_with_replacement('abc', 2)
[('a', 'a'), ('a', 'b'), ('a', 'c'),
('b', 'b'), ('b', 'c'),
('c', 'c')]

>>> permutations('abc', 2)
[('a', 'b'), ('a', 'c'),
('b', 'a'), ('b', 'c'),
('c', 'a'), ('c', 'b')]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
 """


def test_integer_numbers():
"""Integer type
Int, or integer, is a whole number, positive or negative,
without decimals, of unlimited length.
"""

positive_integer = 1
negative_integer = -3255522
big_integer = 35656222554887711

assert isinstance(positive_integer, int)
assert isinstance(negative_integer, int)
assert isinstance(big_integer, int)


def test_booleans():
"""Boolean
Booleans represent the truth values False and True. The two objects representing the values
False and True are the only Boolean objects. The Boolean type is a subtype of the integer type,
and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the
exception being that when converted to a string, the strings "False" or "True" are returned,
respectively.
"""

true_boolean = True
false_boolean = False

assert true_boolean
assert not false_boolean

assert isinstance(true_boolean, bool)
assert isinstance(false_boolean, bool)

# Let's try to cast boolean to string.
assert str(true_boolean) == "True"
assert str(false_boolean) == "False"


def test_float_numbers():
"""Float type
Float, or "floating point number" is a number, positive or negative,
containing one or more decimals.
"""

float_number = 7.0
# Another way of declaring float is using float() function.
float_number_via_function = float(7)
float_negative = -35.59

assert float_number == float_number_via_function
assert isinstance(float_number, float)
assert isinstance(float_number_via_function, float)
assert isinstance(float_negative, float)

# Float can also be scientific numbers with an "e" to indicate
# the power of 10.
float_with_small_e = 35e3
float_with_big_e = 12E4

assert float_with_small_e == 35000
assert float_with_big_e == 120000
assert isinstance(12E4, float)
assert isinstance(-87.7e100, float)


def test_complex_numbers():
"""Complex Type"""

complex_number_1 = 5 + 6j
complex_number_2 = 3 - 2j

assert isinstance(complex_number_1, complex)
assert isinstance(complex_number_2, complex)
assert complex_number_1 * complex_number_2 == 27 + 8j


def test_number_operators():
"""Basic operations"""

# Addition.
assert 2 + 4 == 6

# Multiplication.
assert 2 * 4 == 8

# Division always returns a floating point number.
assert 12 / 3 == 4.0
assert 12 / 5 == 2.4
assert 17 / 3 == 5.666666666666667

# Modulo operator returns the remainder of the division.
assert 12 % 3 == 0
assert 13 % 3 == 1

# Floor division discards the fractional part.
assert 17 // 3 == 5

# Raising the number to specific power.
assert 5 ** 2 == 25 # 5 squared
assert 2 ** 7 == 128 # 2 to the power of 7

# There is full support for floating point; operators with
# mixed type operands convert the integer operand to floating point.
assert 4 * 3.75 - 1 == 14.0

Python 基础(1) string

发表于 2019-04-19 | 更新于 2019-04-20 | 分类于 Python , basic , string

飘往NBviewer版本的捷径

Table of Contents

  • 1  string编辑
    • 1.1  修整截断头尾strip()
    • 1.2  右截断、左截断
  • 2  in 和 not in 操作
  • 3  The upper(), lower(), isupper(), islower() string methods
  • 4  string template 字符串模板
  • 5  Pyperclip
  • 6  string编码和解码
    • 6.1  编码(bytes to string)
      • 6.1.1  chr(i) buildin function 将制定整数unicode编码返回对应的字符string
      • 6.1.2  bytes.decode(encoding=”utf-8”, errors=”strict”)
      • 6.1.3  str(object=b’’, encoding=’utf-8’, errors=’strict’) buildin function
    • 6.2  解码(string to bytes)
      • 6.2.1  ord(c) buildin function
      • 6.2.2  str.encode(self, /, encoding=’utf-8’, errors=’strict’) 将string返回默认utf8 unicode字节
      • 6.2.3  class bytes([source[, encoding[, errors]]]) buildin function

string编辑

修整截断头尾strip()

str.strip([chars]) 去掉字符串左右两端的空格,返回字新的字符串对象

1
2
3
4
5
6
'''
Return a copy of the string with leading and trailing whitespace remove.
If chars is given and not None, remove characters in chars instead.
'''
check = ' Everything is fine! '
check.strip()
'Everything is fine!'

如果chars参数指定了,则从字符串两端计算删除指定的 chars 的成员

1
2
#删除字符串两端的[E][e][v][!][ ]
check.strip('Eev! ')
'rything is fin'

右截断、左截断

  • 右删除str.rstrip([chars])
  • 左删除str.lstrip([chars])
阅读全文 »

安装久违的Oracle Developer Suite

发表于 2019-04-09 | 分类于 EBS , Dev

很久没有做EBS的开发了,因为工作需要,也需要准备一套备用的开发环境,需要重新安装一下久违的Oracle Developer Suite。 如今在64位的win10下,貌似也能正常使用。

下载安装 Oracle Developer Suite

去Oracle网站上下载最新版本就好了。

然后下一步下一步,安装完成。

从服务器上复制form库

从服务器$au_top 下将目录forms 和resource 复制到本地开发机器上。

1
2
3
比如
D:\oracle\forms
D:\oracle\resource

设置注册表信息

64位win10的注册表位置有变化,在以下目录下

1
\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\ORACLE\KEY_DevSuiteHome1

  • 修改NLS_LANG 和服务器数据库一致。 EBS一般为 AMERICAN_AMERICA.UTF8。 保持客户段开发机和数据库编码一致能避免代码的乱码问题。

  • 修改FORMS_PATH,添加本地form库信息,如这次我使用的目录D:\oracle\forms\ZHS;D:\oracle\resource;。修改完forms_path之后,formdeverloper打开EBSforms的时候能正常找到引用库,避免错误。

完成

1234
Chong

Chong

33 日志
25 分类
18 标签
GitHub
© 2019 All right reserved