俗话说,“未到苦处,不信神佛”,可我苦苦挣扎着信神信佛也仍在迷茫。世界是什么,我有是什么样的一粒沙子?
在这样的纠结下,我投向某憨憨寻求帮助。“你只不过想得多,又咋又乱”,憨憨如是说。
”当初巴黎公社失败原因是啥?”憨憨问我。
”缺乏科学的(无产阶级)理论的指导?”我底气不足地回答。
”那你现在就去看点科学理论的指导呗,你这个天天学着科学技术却又信神信佛的唯心主义者。“憨憨不屑地说。
后来憨憨发了我她考研用的政治课,我边开始研究起来高大上的马克思主义哲学了。对,哲♂学。
物质认识发展阶段
- 物质就是实物(古代朴素唯物主义)
- 物质就是由粒子构成的物体(机械唯物主义)
- 物质就是一切客观存在(马克思爸爸)
马克思爸爸觉得客观存在的,不管是不是实物,都是物质。非实物,也是物质?非原子构成的也是物质?
—— 人类历史!
意识
- 意识是人脑主观产生的。(唯心主义,在马原当中认为是错的,脱离物质产生不了意识。)
- 意识是人脑的分泌物。(×,混淆“意识”和“物质”,庸俗唯物主义者的理论)
- 意识是物质在人脑中的能动反映。(马爸爸)
马爸爸说的“能动”?:
原项目Theano的github地址:https://github.com/julianser/hed-dlg-truncated
论文地址: https://arxiv.org/abs/1605.06069
首先是对模型ADEM介绍以及对评估模型的学习。 ADEM,short for “automatic dialogue evaluation model”,对话自动评估模型。模型在利用RNN(recurrent neural network,循环神经网络)半监督式(semi-supervised)训练下来评分。
有关RNN的学习就不浪费时间整理已有的东西,重点精力放在我在此项目的总结与感受。有关RNN的开篇学习,我参考了这篇https://blog.csdn.net/zhaojc1995/article/details/80572098,markdown有关数学公式的编辑参考了这篇简书https://www.jianshu.com/p/e74eb43960a1
NLP中重要一环是对“dialogue”的评价,而dialogue中包括reference(人工回复作为“参考”)和candidate(模型给出的答复),基本思路是利用一些评估标准来对比candidate和reference,并给出一个评分。本项目就是基于原有的评估思路上,给定一系列responses,得到一个准确的人工评分。responses要有一定的多样性,包含相关、不相关的,也需要包含连贯性强和连贯性较弱的内容。
为了达到上述的“多样化的responses”,研究人员们采用了4种模型产生的candidate responses。
利用词语的覆盖程度来计算。其中一个最广为使用的当属BLEU和METEOR,两者广泛应用于评价机器翻译的方法当中。但是机器翻译指标与人类评估结果还存在较大差异,尤其在对话系统中,尽管一个对话的responses可以跟reference词语重叠很少(导致Word-Overlap评分很低),但可以被人类评价为一个“好的回复”。
BLEU尽管可以采用n-gram方法来优化评价方式,但在对话评价上有自己的局限性。机器翻译工作中词语选来选去大多不离那些candidate,所以bleu可以很好的被应用。但是在对话当中,与reference词语重叠程度小,也可以是好的回复,这里如果仅以BLEU评分作为评估就显得不合理了。而且回复也需要考虑前后的语境(context)。
Automatic Dialogue Evaluation Model是为了弥补word-overlap metrics的缺陷。而且(1)能够捕捉到语义相似性 (2)挖掘语境和参考回答对于评分模型的作用。
argparse是python用于解析命令行参数和选项的标准模块,类似于linux中的ls指令,后面可以跟着不同的参数选项以实现不同的功能,argparse就可以解析命令行然后执行相应的操作。
使用时需要三步(步骤总结来自于python中argparse模块使用):
1 | def parse_args(): |
os.path.exists()
判断括号里的文件是否存在的意思,括号内的可以是文件路径。而且返回值是Boolean类型。1
2
3def create_experiment(config):
if not os.path.exists(config['exp_folder']):
os.makedirs(config['exp_folder'])
eval()
返回括号里表达式的值
多学了python后对python当中的下划线很感兴趣。不同于c或者java中局限于“命名作用”作用的下划线,python中的下划线在表示特殊含义方面上有着重要作用。
在创建类的时候,也会较易发现def __init__():
,只要有自动补全的IDE,就会默认出现下划线,前后都有。而不同的函数下划线长度还不同(长度为1或为2,前后出现表意也不同)。这边引起了我的好奇。
参考文章:《Python中下划线的5种含义》和The Meaning of Underscores in Python
Intended for internal use. It is defined there. 但是python并不强制要求,而且不像Java,Python对“公共”和“私有”的区分并不那么明显。就像一种提示:
嘿,这其实不是这个类的一个公共接口,最好别管它。
举例如下:
1
2
3
4 class Test:
def __init__(self):
self.foo = 11
self._bar = 23
实例化之后会发生啥呢?
1 | t = Test() |
所以单前导下划线并没有阻止我们访问到方法_bar
但是如果使用通配符从模块中导入名称的话,python不会导入带有单前导下划线名称的方法。(我不确定在python中叫“方法”是否合适,欢迎指摘。)
比如,命名一个my_modelue
有一下代码:1
2
3
4
5
6
7# This is my_module.py:
def external_func():
return 23
def _internal_func():
return 42
此时,如果用通配符*导入所有名称,则Python不会导入有单前导下划线的名称(除非模块定义了覆盖此行为的all列表)1
2
3
4
5from my_module import *
external_func()
23
_internal_func()
NameError: "name '_internal_func' is not defined"
而如果常规导入则不会受此影响:1
2
3
4
5import my_module
my_module.external_func()
23
my_module._internal_func()
42
有时候名称被一个keyword占用了,命名的时候就不得不避开这些Python认定的关键字,下面的例子是用class_
代替class
来表示传递给方法的参数。1
2
3
4
5def make_object(name, class):
SyntaxError: "invalid syntax"
def make_object(name, class_):
pass
其实就是为了避免冲突而采用的。
A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to avoid naming conflicts in subclasses.
这将导致Python解释器重写属性名称避免在子类当中冲突。
这其实也称作 name mangling. 解释器改变变量名称以使得后续扩展类的时候更不容易发生冲突。
例子:1
2
3
4
5class Test:
def __init__(self):
self.foo = 11
self._bar = 23
self.__baz = 23
使用内置的(built-in) dir() 来查看:
1 | t = Test() |
查看列表,查找我们的原始变量foo
,_bar
和 __baz
我们注意到:
self.__baz
而言,情况看来不同。列表中并没有__baz
这个名字的变量 仔细观察,发现有个_Test__baz
的属性。这就是Python解释器所做的名称修饰。 它这样做是为了防止变量在子类中被重写。
而如果创建另一个扩展Test类的类,并尝试重写构造函数中添加的现有属性:
1 | class ExtendedTest(Test): |
foo, _bar, 和 __baz的值会出现在这个ExtendedTest
类的实例上吗? Let’s take a look.
1 | t2 = ExtendedTest() |
得到的AttributeError
? 名称修饰被再次触发了!事实上,这个对象没有__baz属性:
我们可以看到_baz变成_ExtendedTest__baz以防止意外修改:1
2 t2._ExtendedTest__baz
'overridden'
但原来的_Test__baz还在:1
2 t2._Test__baz
42
 双下划线名称修饰对程序员完全透明。下面例子证实:1
2
3
4
5
6
7
8
9
10
11class ManglingTest:
def __init__(self):
self.__mangled = 'hello'
def get_mangled(self):
return self.__mangled
ManglingTest().get_mangled()
'hello'
ManglingTest().__mangled
AttributeError: "'ManglingTest' object has no attribute '__mangled'"
还有另一个例子:1
2
3
4
5
6
7
8
_MangledGlobal__mangled = 23
class MangledGlobal:
def test(self):
return __mangled
MangledGlobal().test()
在这里声明了一个名为_MangledGlobal__mangled
的全局变量。然后在名为MangledGlobal的类的上下文中访问变量。由于名称修饰,我们能够在类的test()方法内,以mangled来引用_MangledGlobalmangled全局变量。
Python解释器自动将名称mangled扩展为_MangledGlobalmangled,因为它以两个下划线字符开头。这表明名称修饰不是专门与类属性关联的。它适用于在类上下文中使用的两个下划线字符开头的任何名称。
如果一个名字同时以双下划线开始和结束,则不会应用名称修饰。 由双下划线前缀和后缀包围的变量不会被Python解释器修改:1
2
3
4
5
6class PrefixPostfixTest:
def __init__(self):
self.__bam__ = 42
PrefixPostfixTest().__bam__
42
但是,Python保留了有双前导和双末尾下划线的名称,用于特殊用途。 这样的例子有,init对象构造函数,或call — 它使得一个对象可以被调用。
但是,Python保留了有双前导和双末尾下划线的名称,用于特殊用途。 这样的例子有,init对象构造函数,或call — 它使得一个对象可以被调用。
有时候独立下划线是用作一个名字,来表示某个变量是临时的或无关紧要的。在下面循环中,我们不需要访问正在运行的索引,可以使用_
来表示它只是一个临时变量1
2
3
for _ in range(32):
'Hello, World.') print(
也可以在拆分(unpacking)表达式中将单个下划线用作“不关心的”变量,以忽略特定的值。 同样,这个含义只是“依照约定”,并不会在Python解释器中触发特殊的行为。 单个下划线仅仅是一个有效的变量名称,会有这个用途而已。
在下面的代码示例中,我们将汽车元组拆分为单独的变量,但我只对颜色和里程值感兴趣。 但是,为了使拆分表达式成功运行,需要将包含在元组中的所有值分配给变量。 在这种情况下,_
作为占位符变量可以派上用场:
1 | 'red', 'auto', 12, 3812.4) car = ( |
除了用作临时变量之外,“_”是大多数Python REPL中的一个特殊变量,它表示由解释器评估的最近一个表达式的结果。
这样比较方便,可以在一个解释器会话中访问先前计算的结果,或者,你是在动态构建多个对象并与它们交互,无需事先给这些对象分配名字:1
2
3
4
5
6
7
8
9
10
11
12
13
1420 + 3
23
_
23
print(_)
23
list()
[]
1) _.append(
2) _.append(
3) _.append(
_
[1, 2, 3]
看到网上一个语言生成模型要使用tensorflow,出了一堆错误。其实是我个人在解释器interpreter里面没有选择对应的tensorflow版本,但乱乱学着别人弄浪费了很多时间。
首先重新安装numpy时出现了
Could not find a version that satisfies the requirement numpy(from versions:) No matching distribution found for numpy
我使用的指令是’ pip install numpy’, 改用 ‘pip3 install numpy’.
解决办法:重新设置环境变量PATH
export PATH=/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin:/bin:/sbin
再 source /etc/profile
题目地址:两个数加和
本人做法:很笨,暴力循环遍历。然后复杂度是O(n2)的两层遍历。而且不熟悉python的一些数组操作。自己真应该多多练习了。
列表list.count(xx)
可以查询里面有xx元素的数量。还有list.index(xx)
返回下标。
字典记录,从而节省了查找索引的步骤。
1 | def twoSum(nums, target): |
升级1
2
3
4
5
6def twoSum(nums, target):
hashmap={}
for i,num in enumerate(nums):
if hashmap.get(target - num) is not None:
return [i,hashmap.get(target - num)]
hashmap[num] = i #这句不能放在if语句之前,解决list中有重复值或target-num=num的情况
As long as people in a society are hungry or out of work or lack the basic skills needed to survive, the use of public resources to support the arts is inappropriate - and, perhaps, even cruel - when one considers all the potential uses of such money.
The speaker asserts that using public resources to support the arts is unjustifiable in a society where some people go without food, jobs and basic survival skills. It might be tempting to agree with the speaker on the basis that art is not a fundamental human need, and that government is not entirely trustworthy when it comes to its motives and methods. However, the speakers overlooks certain economic and other social benefits that accrue when government assumes an active role in supporting the arts.
The implicit rationale behind the speaker’s satement seems to be that cultural enrichment pales in importance compared to food, clothing, and shelter. That the latter needs are more fundamental is indisputable;after all, what starving person would prefer a good painting to even a bad meal? Accordingly, I concede that when it comes to the use of public resources it is entirely appropriate to assign a lower priority to the arts than to these other pressing social problems. Yet, to postpone public arts funding until we completely eliminate unemployment and hunger would be to postpone arts funding forever; any informed person who believes otherwise is envisioning a pure socialist state where the government provides for all of its citizens’ needs - a vision which amounts to fantasy.
It might also be tempting to agree with the speaker on the basis that arts patronage is neither an appropriate nor a necessary function of government. This argument has considerable merit, in three respects. First, it seems ill-conceived to relegate decision and choices about arts funding to a handful of bureaucrats, who are likely to decide based on their quirky notions about art, and whose decisions might be susceptible to influence-peddling. Second, private charity and philanthropy appear to be alive and well today. For example, year after year the Public Broadcasting System is able to survive, and even thrive, on donations from private foundations and individuals. Third, government funding requires tax dollars from our pockets - leaving us with less disposable dollars with which to support the arts directly and more efficiently than any bureaucracy ever could.
On the other hand are two compelling arguments that public support for the arts is desirable, whether or not unemployment and hunger have been eliminated. One such argument is that by allocating public resources to the arts we actually help to solve thses social problems. Consider Canada’s jobs for film-industry workers as a result. The Canadian government also provides various incentives for American production companies to film and produce their movies in Canada. These incentives have sparked a boon for the Canadian economy, thereby stimulating job growth and wealth that can be applied toward education, job training, and social programs. The Canadian example is proof that public arts support can help solve the kinds of social problems with which the speaker is concerned.
A second argument against the speaker’s position has to do with the function and ultimate objectives of art. Art serves to lift the human spirit and to put us more in touch with our feelings, foibles, and fate-in short, with our own humanity. With a heightened sensitivity to the human condition, we become more others-oriented, less self-centered, more giving of ourselves. In other words, we become a more charitable society–more willing to give to those less fortunate than ourselves in the ways with which the speaker is concerned. The speaker might argue, of course, that we do a disservice to others when we lend a helping hand–by enabling them to depend on us to survive. However, at the heart of this specious argument lies a certain coldness and lack of compassion that, in my view, any society should seek to discourage. Besides, the argument leads inexorably to certain political, philosophical, and moral issues that this brief essay cannot begin to address.
In the final analysis, the beneficiaries of public arts funding are not limited to the elitists who stroll through big-city museums and attend symphonies and gallery openings, as the speaker might have us believe. Public resources allocated to the arts create jobs for artists and others whose livelihood depends on a vibrant, rich culture–just the sort of culture that breeds charitable concern for the hungry, the helpless, and the hapless
我想说
但是吧,写出来就变味了。一是我现在英语hold不住中文的论点,词语匮乏。而且写出来不地道。
不堪入目的文章。
Hunger as well as unemployment have always been people’s most concern for thousands of years, no matter what the society they are in. Presumably, the use of public resource to support art is irrational as long as there are people in hunger or out of work, then rapid development of arts is seemingly against people’s will. Nevertheless, arts have witnessed the different status of society, no matter how prosperous or declined the society is, and the truth that arts have been supported by countless people is contradictory to the speakers’ opinion, due to which I’m opposed to the topic and believe the rational existence of arts.
I concede that the speaker is on the correct philosophical side of this issue. After all, the use of money is the lasting solutions to our enduring problems, such as hunger and employment. Proper use of public resources is also the chief means by which we have the probability to get rid of poverty and satisfy our insatiable appetite for better life. Yet, in the very notion of proper use of public resource also lies my first point of contention with the speaker, who illogically presumes that the use of money to support arts is of no help to alleviate the problems of hunger and unemployment. To the contrary, the evidence that arts help dealing with poverty and huger is consolidated and apparent.
The long history of arts shows to us the necessity of higher pursue for life and the basic function arts provide for us – the satisfaction for mental demand. At the same time, people’ demands for arts create the opportunities for others to achieve their goals and make a living by devoting themselves to arts. Despite the fact that arts is in need of public resources to support, arts itself can also be used as public resources and applied to other fields of society. The LIVE AID held in 1985 raised enormous money to helped millions of people in Africa. Singers and groups, representing music arts, were regarded as strong support for people in poverty and even cast a ray of hope to dealing with starvation.
The speakers’ assertion is troubling in two other respects as well. First, no amount of money can completely solve the enduring problems of poverty, unemployment and starvation, for the reason that they stem from the nature of society structure. The use of public resources to support art, if applied to helping people in hunger or out of work, means little to mitigate these problems due to the small percentage that the money account for and the seriousness and large scale the social problem is. At the same time, with slight attention to arts, people will lose the exploration of the unknown for true answers to our questions. Secondly, people who contribute to the society and consist of the different social status vary, which means the demand of them are different as well. The neglection to their demands for arts is another kind of pure cruelty to those people. In short, so-called “the proper use of public resources” is another form of inappropriate use in the name of mitigating social problems.
In sum, the speaker’s assertion that we should invest little or none to arts when hungry or unemployed people exist in society begs the question, because we cannot eliminate the problems of poverty and hunger no matter what the society status is. As for the speaker’s broader assertion, I agree that proper use of money is needed because only when the society is stable can arts be encouraged. Nevertheless, when we purely invest money in those problems, we neglect the diverse needs of our society in the name of relieving the immediate suffering of our dispirited, disadvantaged, and disenfranchised members of society. In the final analysis, given finite economic resources we are forced to strike a balance in how we allocate those resources among competing social objects.
At various times in the geological past, many species have become extinct as a result of natural, rather than human, processes. Thus, there is no justification for society to make extraordinary efforts, especially at a great cost in money and jobs, to save endangered species.
范文:
What are the limits of our duty to save endangered species from extinction? The statement raises a variety of issues about morality, conscience, self-preservation, and economics. On balance, however, I fundamentally agree with the notion that humans need not make “extraordinary” efforts – at the expense of money and jobs – to ensure the preservation of any endangered species.
As I see it, there are three fundamental arguments for imposing on ourselves at least some responsibility to preserve endangered species. The first has to do with culpability. According to this argument, to the extent that endangerment is the result of anthropogenic events such as clear-cutting of forests or poluting of lakes and streams, we humans have a duty to take affirmative measures to protect the species whose survival we’ve placed in jeopardy
The second argument has to do with capability. This argument disregards the extent to which we humans might have contributed to the endangerment of a species. Instead, the argument goes, if we are aware of the danger, know what steps are needed to prevent extinction, and can take those steps, then we are morally obligated to help prevent extinction. This argument would place a very high affirmative duty on humans to protect endangered species.
The third argument is an appeal to self-preservation. The animal kingdom is an intricate matrix of interdependent relationships, in which each species depends on many others for its survival. Severing certain relationships, such as that between a predator and its natural prey, can set into motion a series of extinctions that ultimately might endanger our own survival as a species. While this claim might sound far-fetched to some, environmental experts assure us that in the long run it is a very real possibility.
On the other hand are two compelling arguments against placing a duty on humans to protect endangered species. The first is essentially the Darwinian argument that extinction results from the inexorable process of so-called “natural selection” in which stronger species survive while weaker ones do not. Moreover, we humans are not exempt from the process. Accordingly, if we see fit to eradicate other species in order to facilitate our survival, the so be it. We are only behaving as animals must, Darwin would no doubt assert.
The second argument, and the one that I find most compelling, is an appeal to logic over emotion. It is a scientific fact that thousands of animal species become extinct every year. Many such extinctions are due to natural forces, while others are due to anthropogenic factors. In any event, it is far beyond our ability to save them all. By what standard, then, should we decide which species are worth saving and which ones are not? In my observation, we tend to favor animals with human-like physical characteristics and behaviors. This preference is understandable; after all, dolphins are far more endearing than bugs. But there is no logical justification for such a standard. Accordingly, what makes more sense is to decide based on our own economic self-interest. In other words, the more money and jobs it would cost to save a certain species, the lower priority we should place on doing so.
In sum, the issue of endangered-species protection is a complex one, requiring subjective judgments about moral duty and the comparative value of various life-forms. Thus, there are no easy or certain answers. Yet it is for this very reason I agree that economic self-interest should take precedence over vague notions about moral duty when it comes to saving endangered species. In the final analysis, at a point when it becomes critical for our own survival as a species to save certain others, then we humans will do so if we are fit- in accordance with Darwin’s observed process of natural selection.
The following appeared in a newspaper feature story:
“There is now evidence that the relaxed manner of living in small towns promotes better health and greater longevity than does the hectic pace of life in big cities. Businesses in the small town of Leeville report fewer days of sickleave taken by individual workers than do businesses in the nearby large MasonCity. Furthermore, Leeville has only one physician for its one thousand residents, but in Mason City the proportion of physicians to residents is five times as high. And the average age of Leeville residents is significantly higher than that of Mason City residents. These findings suggest that people seeking longer and healthier lives should consider moving to small communities.”
大体是反对这个论述的,主要攻击点在论据给的不充分。范文:
This news paper story concludes that living in a small town promotes health and longevity. The speaker bases the conclusion on a comparison between the small town of Leeville and nearby Mason City, a larger town. While the argument appears valid enough at first glance, a closer look reveals a few distinct weaknesses.
One initial problem with the argument is that the author draws conclusion about the effect of a town’s size on the health and longevity of its residents but doesn’t really present any evidence. There are a lot of indications that the residents of one town are healthier but the speaker doesn’t indicate why. More specifically, the only evidence presented here is the pace of life. This does very little to establish requisite links.
Next, the author cites the fact that the incidence of sick leave in Leeville is less than in Mason City. This evidence would lend support to the argument only if the portion of local residents employed by local business were nearly the same in both towns, and only if the portion of employees who are local residents were nearly the same in both towns. Of course, in a more densely populated area with more people, the incidence of something like sick leave would be higher. Without offering a per-capita, one cannot come to the conclusion that the rate is higher or lower in either case.
The author also cites the fact that Mason City has five times as many physicians. However, any number of factors besides the health of the town’s residents might explain this disparity. For example, perhaps people in the city are concerned with cosmetic issues rather than health matters. Without ruling out such explanations, these physician-resident ratios prove nothing about the comparative health of Leeville and Mason City residents.
Finally, the author cites the fact that the average age of Leeville residents is higher than that of Mason City residents. However, any number of factors might explain this disparity. For example, perhaps Leeviller is a retirement community, while Mason City attracts younger working people. For that matter, perhaps Leeville is comprised mainly of former Mason City residents whose longevity if attributable chiefly to their former life-style in Mason city. In any event, the author cannot justify the conclusion that this disparity in average age has anything to do with the healthy benefits.
In conclusion, the argument that small-town living promotes good health and longevity based on the examples above is not very persuasive. However, it seems like a sensible one that one should consider trying to strengthen. The argument could be improved if the author provided cleared connections between his example of health and of the causes of such healthy examples. More specifically, if he could prove that there was a very specific attribute in one place or the other that affected health, the argument would be far more convincing.
Practicality is now our great idol, which all powers and talents must serve. Anything that is not obviously practical has little value in today’s world.
In today’s world is practicality our idol – one which all powers and talents must serve? While this claim has considerable merit with respect to most areas of human endeavor – including education, art, and politics – I take exception with the claim when it comes to the direction of scientific research today.
Practicality seems clearly to be the litmus test for education today. Grade-schoolers are learning computer skills right along with reading and writing. Our middle and high school are increasingly cutting arts education, which ostensibly has less practical value than other course work. And more and more college students are majoring in technical fields for the purpose of securing lucrative jobs immediately upon graduation. Admittedly, many college students still advance to graduate-level study; yet the most popular such degree today is the MBA; after all, business administration is fundamentally about practicality and pragmatism – that is, “getting job done” and paying attention to the “bottom line”.
Practicality also dictates what sort of art is produced today. Most new architecture today is driven by, safety, and cost; very few architectural masterpieces find their way past the blue print stage anymore. The content of today’s feature films and music is driven entirely by demographic considerations – that is, by pandering to the interests of 18-35 year olds, who account for most tickets and CD sales. And, the publishing industry today is driven by immediate concern to deliver viable products to marketplace. The glut of how-to books in our bookstores today is evidence that publishers are pandering to our practicality as well. It isn’t that artists no longer create works of high artistic value and integrity. Independent record labels, filmmakers, and publishing houses abound today. It’s just that the independents do not thrive, and they constitute a minuscule segment of the market. In the main, today’s real-estate developers, entertainment moguls, and publishing executives are concerned with practicality and profit, and not with artistic value and integrity.
Practicality is also the overriding concern in contemporary politics. Most politicians seem driven today by their interest in being elected and reelected – that is, in short-term survival – rather than by any sense of mission, or even obligation to their constituency or country. Diplomatic and legal maneuverings and negotiations often appear intended to meet the practical needs of the parties involved – minimizing costs, preserving options, and so forth. Those who would defend the speaker might claim that it is idealists – not pragmatists – who sway the masses, incite revolutions, and make political ideology reality. Consider idealists such as the America’s founders, or Mahatma Gandhi, or Martin Luther King. Had these idealists concerned themselves with short-term survival and immediate needs rather than with their notions of an ideal society, the United States and India might still be British colonies, and African Americans might still be relegated to the backs of buses. Although I concede this point, the plain fact is that such idealists are far fewer in number today.
On the other hand, the claim amounts to an overstatement when it comes to today’s scientific endeavors. In medicine the most common procedures today are cosmetic; these procedures strike me as highly impractical, given the health risks and expense involved. Admittedly, today’s digital revolution serves a host of practical concerns, such as communicating and accessing information more quickly and efficiently. Much of chemical research is also aimed at practicality – at providing convenience enhancing our immediate comfort. Yet, in many other respects scientific research is not driven toward immediate practicality but rather toward broad, long-term objectives: public health, quality of life, and environmental protection.
In sum, practicality may be our idol today when it comes to education, the arts, and politics; but with respect to science I find the claim to be an unfair generalization. Finally, query whether the claim begs the question. After all, practicality amounts to far more than meeting immediate needs; it also embraces long-term planning and prevention aimed at ensuring our future quality of life, and our very survival as a species.
]]>按照实现顺序吧,积累一下。
韩星死亡事件, 来自华盛顿邮报
苛刻粉丝以及国家缺乏对明星心理健康的帮助
Sulli’s(雪莉)death highlighted the huge pressures on K-pop stars, partly exerted by demanding fans, and the lack of mental health support in this country.
女星失去自己的生活
Both women, members of an industry in which female singers are not supposed to date or even live real lives but instead conform to rigid norms, had their private lives intensely examined in public and were the subject of hateful online comments.
雪莉曾经求救
Last year, she took the rare step of speaking out about her mental health issues, saying she had suffered from panic disorder since she was young and also had social phobia.
以及卫报
She also revealed that she was in a relationship at the zenith of her singing career, defying the industry’s carefully crafted image of young female stars as sexually desirable but inexperienced.
彭博社(Bloomberg Businessweek)The Dark Side of K-Pop: Assault, Prostitution, Suicide, and Spycams非常犀利地揭露韩星现状
Promising stars are put through a gruelling training schedule as they pass along the conveyor-belt production of new girl- and boybands. Young stars are subjected to strict controls over their private lives, including bans on dating, restrictions on mobile phone use and an expectation that they will sacrifice their health to achieve the desired image.
No one in K-pop is indispensable**; no idol, no matter how popular, is bigger than the machine.
Government statistics show that sexual assault and harassment are widespread, though fear of stigmatization means few go public with their experiences.
今天看完了这个很久之前下载的小说。这本书有点像那种酸酸涩涩的鸡尾酒,一口下去是不咋有滋味的,甚至难喝,略微感到平淡。但是细细读来会感到它的后劲。
]]>How could George kill Lennie at last? Is the author too crude to set up such an ending or is it just the quintessence of the society? Why while you mean no harm to others but things just turn out to be a mess? Why the little mice die in the hand of the people who love and care them the most? The love and trust between George and lennie are touching; the understanding of life and loneliness of Crooks is pathetic; the death of the innocent is weepy.
It’s not a book about the relationship between men and the nature as the title suggested but related to the emotions and choices of people. Every one has his philosophy, about how to deal with a handy man you don’t want to bother; about how to react when a crude guy want to kill an old man’s disabled dog; about how to protect your life-long friend. I admire George. Though at first I thought he bullied Lennie and I couldn’t understand his action at last at first. When I came to the last chapter I asked myself if I were George, how could I do? To hide Lennie forever? I never guessed George will take the shoot. However this is only he could do. If Curley found Lennie he would not simply shot him. When George decided to end his best companion’s life he had already accepted the truth that Lennie was not at all acceptable in such a dirty world. But I still couldn’t understand one point—why George told Curley that it was Lennie who took the gun?
Lennie uses his special way to protect George and George in turn cautiously protects him. Lennie is so Naïve that he goes against the principles of common people. Though he always says” honest. I am” and he means no harm, he can’t live easily. The world seems unfair. If Lennie were just as big as a common person or even smaller, he would get another kind of treatment. He was not acceptable by others because they are afraid of him, even he is kind indeed. He has power which is not congruent to his childlike heart. This power makes Curley envy and the miserable outcome is ominous. Men are not tolerant because we are afraid.
I’m impressed by the privities between Lennie and George. If we ask ourselves is there anyone that can be so dependable and that you know he will always be on your side? It’s not as cozy as the love of a mother and it not as romantic as the love of a suitor, it is unbelievable.
错的最多的就是每篇的压轴题:6选3,几乎没有全对过,哎呀我的心呀。
大体讲了埃及建筑物的特点,新词frontality,无论材质如何(stone,wooden or metal),都体现这个“正面性”,展示雕塑的姿态。在此基础上探讨了雕塑decorative作用等等……
错题2,事实信息题,根据提问,应该从段落的文句中寻找答案,冒号之后罗列雕塑不受欢迎的原因。
Why did the Egyptians not develop sculpture in which the body turned and twisted through space like classical Greek statuary?
错题14:两个错的选项要根据原文找矛盾,关键地方是功能性评价,重要性等方面,以及性质的对比。
词汇方面:divine pillared(pillar)deity elite depicts
讲了鸟类定位,主要行文方式:罗列一系列的实验并穿插猜测和结论。第一段提出问题以及引出主要的实验研究人员Gustave Kramer
错题25:组织结构题,可知本文应该利用一系列实验去证明“鸟儿在日间和夜间的定位方法”A structured argument about the importance of internal versus external cues for navigation is presented
而是:A number of experiments are described to support the idea that birds use the Sun and the night sky to navigate.
错题28[概要小结]:错因:信息矛盾-没有关注原文“一系列”实验与题中阐述的”in one set”矛盾。
词汇方面:flutter overcast surmise preposterous(荒谬的) versus(prep.与之相对)
一言蔽之:鸟儿叫 = 爸妈给食 + predators
错题37[事实信息题]:根据关键词定位相关段落(第四段)+排除法
错题42[概要小结题]:随缘吧
词汇方面:conceal
难句理解
The hypothesis that begging calls have evolved properties that reduce their potential for attracting predators yields a prediction: baby birds of species that experience high rates of nest predation should produce softer begging signals of higher frequency than nestlings of other species less often victimized by nest predators.
一个关于乞食行为的假说认为,乞食声已经进化出一种避免引起捕食者注意并及时作出预警的特性:比起那些较少受到捕食者捕食的雏鸟相比,被捕食率高的鸟类的雏鸟需要发出更轻柔频率更好的叫声。
错题2[目的题]:仔细听这个student要干什么,梳理脉络
词汇: maxims
题目逻辑关系很清晰,逐点记录即可
错题13[内容主旨]:找到关键词
错题14[内容主旨]:分析原因,(听tapes时记录得不够详细准确)
错题7[特点分析]:folk legends的特点:一定的真实性,错在干扰选项A
They are very imaginative
They are somewhat realistic
从一亩三分地那copy来的,不知道侵犯版权了么。
模板二:
模板二:
模板三:
验证tensorflow能否工作的时候调用1
2
3
4
5import tensorflow as tf
sess = tf.Session()
a = tf.constant(10)
b = tf.constant(12)
sess.run(a+b)
其中对第二行命令,报错AttributeError: module ‘tensorflow’ has no attribute ‘Session’
上网查询,发现原因是这个命令属于低版本的tensorflow,想正常使用的话,应该把import tensorflow as tf
注释掉,然后换成1
2import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
Pycharm中报错,
在开头加上1
2
3import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf
我真的很想骂人了。1
2from tensorflow_core.python.client import device_lib
print(device_lib.list_local_devices())
查看当前可用GPU设备。
第一开始nvidia-smi
指令报错,我真的爆哭。钟哥“冷嘲热讽”地点醒我ge-experience没装等等,让我重新装了之后能够正常使用。他真是个态度差的好男人。
1
2
3from bert import modeling
from bert import optimization
from bert import tokenization
报错,后来发现自己应该pip install bert-tensorflow
并且在pycharm中安装这个bert的package
国际惯例,问候老师。
由于github上的代码基本都是基于tensorflow-1.x版本的,而我最近安装的TF是2.0.0,折腾得筋疲力尽真的不能再让我去降级捯饬这儿玩意儿了。
Luckily,查阅Tensorflow中发现其中有一条The easiest way to automatically apply these renames is to use the v2 upgrade script.
但是实践下来发现还有不少错误。第一开始如果直接在powershell中输入命令tf_upgrade_v2 --infile [文件名].py --outfile [升级后文件名].py
会有DLL错误,回忆之前检测tensorflow-gpu版本检测错误过程当中出现的同样错误,发现是由于自己没有激活tensorflow,
于是先:activate tensorflow-gpu
再使用升级指令。
在计网实验中遇到了些小问题,记录下来。
原因是利用Java开启一个进程后再开启相同进程会抛出这个异常,其中eclipse会提示
Address already in use: NET_Bind
于是上网查询,发现原因是开启服务器后尽管关闭了eclipse,进程仍然没有被终结。解决办法:
netstat -p tcp -ano
查看端口被哪个进程占用taskkill -PID [进程ID] -F
强制终止进程成功解决。
我捯饬了一晚上也不知为啥,试了网上能搜到的代码还是出现相同的情况,但是细(cu)心(xin)的我发现HTTP默认端口为80,可是根据java程序里面的函数反馈信息,发现:
443? 于是百度一下,443端口对应的是Https协议,
网页浏览端口,能提供加密和通过安全端口传输的另一种HTTP。
所以我弄的还是不行喽?再找一份能够实现https代理服务器的代码去。
目前来说主要问题是http代理服务器无法访问得了https协议的网站,4399和哈工大门户网站除外,作为一个懒汉我只能再研究研究参考样例里面的c++语言了
1 | unsigned long _beginthread( |
线程结束
1 | //释放线程空间、释放线程TLS空间、调用ExiteThread结束线程。 |
把这个变量放在前面就好了。
参考网址VS“无法查找或打开PDB文件”
如果还出现无法查找或打开 PDB 文件,原因: 因为符号的加载项没有在你运行项目的那个目录。将缓存符号的目录改为项目运行下的目录。
计网杀我也?代码示例里面的accept函数是:acceptSocket = accept(ProxyServer, NULL, NULL);
但我查询相应的accept发现,根本不能写null,函数原型。1
2
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
]]>sockfd 调用socket函数返回的套接字
addr将对端的套接字地址结构的信息保存在其中
addrlen是套接字地址结构的大小
当然, 如果不关心对端的信息, 可以将addr和addrlen都置为NULL.
It is universally accepted that 在int范围中最大的数为2147483647.在本人设计Ladder这个ADT时,需要记录该梯子上所有猴子中速度最小的,记为这个梯子的最小数。但是应该确保的是,初始化时这个梯子最小速度应该为一个非常非常大的数,即为int范围最大值。
我本人这样写this.minSpeed = 2147483647;
后来查询到,Java中由Integer.MAX_VALUE
表示。不得不叹上一句“这java封装的太好了”。
emsp;查阅可知,可以利用Java封装好的随机正整数生成器。1
2
3
4
5
6
7
8private Direction randomDirection() {
Random ran = new Random();
int dirNumber = ran.nextInt(2); // Random number for [0,1]
if (dirNumber == 0) {
return Direction.LtoR; //If the number is 0, the direction is "LtoR".
}
return Direction.RtoL; // Else, the direction is "RtoL"
}
本人的思路是这样的,在生成一个LadderGenerator,生成public的一个List<Ladder>
,然后大家对这个Ladders操作即可。我设置这个List为静态变量。1
2
3
4
5
6
7
8
9
10
11
12/**
* This is the Ladder generator which produces many Ladders.
*/
public class Ladders {
public static List<Ladder> ladders = new ArrayList<Ladder>();
public static void getLadders(int n) {
for (int i = 1;i <= n; i++) {
ladders.add(new Ladder(i));
}
}
}
在测试时,出了问题1
2
3Ladder l1 = ladders.get(0);
Ladder l2 = ladders.get(1);
Ladder l3 = ladders.get(2);
这时对l1或者其他梯子修改属性,再调用strategy接口中的方法时,会按照未被修改属性的梯子来操作。
并且在该方法中测试l1属性,显示修改过的。但是在具体策略类的方法中就会表现不同?
目前猜测原因:
其中,这个例子很好的演示了这个出人意料的情况的由来。
此外,又学了一招。以往需要访问一个静态变量的时候,需要用[类名].(变量) 的方式访问,比如Client.manyLadders
,而采用静态导入包的方式可以直接访问该包内的静态成员变量。
比如:1
2import static run.Client.manyLadders;
import static run.Client.logger;
本知识点来自于static关键字的四种应用
The Error class describes internal system errors and resource exhaustion situations inside the Java runtime system (e.g., VirtualMachineError, LinkageError) that rarely occur.
内部错误:程序员通常无能为力,一旦发生,想办法让程序优雅的结束 。而对于异常:
The Exception class describes the error caused by your program (e.g. FileNotFoundException, IOException).
异常由于自己程序导致的问题,可以捕获、可以处理。
Error举例:User input errors, Device errors, Physical limitations.
既然Error我们无能为力, 那就转向关注我们能够处理的Exception。
Exception分为unchecked和checked两类,分类如下:
程序员可以通过抛出unchecked exception来声明无法解决,不在自己程序处理能力范围内的异常,而checked exception则是用户所期待的,也是需要程序员去处理的。
如下所示:
根据WZJ老师的建议,可以直接将不符合科学记数法的输入转化为符合要求的数据,也可以Garbage in, garbage out般的Fail Fast,而我本人选择直接抛出异常信息,并且直接让用户重新操作。
值得注意的是,在操作过程中,如果try_catch语句中catch(Exception e)
,那么无论中间有什么自定义exception都会被覆盖,并且不能输出相关的信息。首先,错误样例如下:
如果在总的构造系统中这样catch异常
1 | try { |
则根据文件得到异常信息是这样的:
而如果这样写的话1
2
3
4
5
6
7
8
9try {
······
} catch (NotationFormatException e) {
System.out.println(e.getNumber());
System.out.println("请修改按要求文件后重新读入");
} catch (IOException e) {
System.out.println("IOE EXCEPTION!!!");
e.printStackTrace();
}
则会出现异常的信息:
在实验中要求按照特定代码规范进行走查修改。这里简单学习了Java命名规范。
查看详细信息
除了众所周知的Set不存放重复元素外,两者在contains方法检索元素时差别也巨大!!!
在第一个版本利用graphset元素时,用的是List<Edge<L>> edges
,读取两万数据边的时候就花费10s左右,其中重要一点就是有诸多
1 | if (!edges.contains(e)) { |
利用contains检索的判断语句,而换了之后发现效率大大提升,构造80万的数据也只要1分钟左右,现在考虑把其他List也换成Set!!!
由衷感谢YSC同学的提醒与支持!!!
在实验中要求使用策略模式采用不同读写策略来进行对文本的操作。于是在此复习该设计模式。(本人在实验3和4没有用到此模式)
组成:
类图如下:
读写策略实验提供了多种
要注意,本人默认使用的BufferedReader是Writer的子类,类声明中可以看到其extends Writer
,并不是我以前认为的Buff的子类。
原理:BufferedReader和BufferedWriter出现的目的是为了对FileReader以及FileWriter的读写操作进行增强.原理类似于使用StringBuilder,是把数据先放入他们的一个char数组中,然后再操作char数组。
使用缓冲区的字符流是使用了装饰着模式对FileReader等进行功能上的增强,装饰者模式与继承都可以实现功能上的增强,但是装饰者可以做得更加的灵活,也不会使继承树变得太过复杂。
第一开始采用的读入 BufferedReader 和 BufferedWriter。
注意一下写文件并不会写入空行,整个文件一连串下来非常爆炸。1
2
3
4
5
6
7
8File target = new File("test/file/SocialNetworkCircle.txt");
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(target));
for (String i : info) {
bw.write(i);
}
bw.close();
······
注意:默认为覆盖写入
采用加上写入一换行符试试。bw.write("\n");
!!!在这里发现如果info
为Set<String>
类型,读入后顺序错乱,但是如果用ArrayList
实现,就会按照存入顺序来写入文件,十分美观。
*NOTE:
读入1
2
3
4
5
6String encoding = "UTF-8";
File file = new File(filePath);
if (file.isFile() && file.exists()) { // If the file exists
Path from = Paths.get(filePath);
List<String> lines = Files.readAllLines(from,Charset.forName(encoding));
写入1
2Path from = Paths.get("test/file/SocialNetworkCircle.txt");
Files.write(from,personInfo,Charset.forName("UTF-8"));
Scanner经常被我们用于读取控制台的输入,但是我们只需要将他构造函数中的System.in替换成一个File文件,他就可以变成一个读取文件的Scanner了,Scanner的按行读取方法是nextLine()我们在使用它的时候可以在前面判断它时候hasNextLine()。也是十分方便.如下:1
2
3
4
5
6
7
8
9
10File file = new File(filePath);
if (file.isFile() && file.exists()) { // If the file exists
Scanner s = new Scanner(file);
String lineTxt = null;
while (s.hasNext()) {
lineTxt = s.nextLine();
······
}
s.close();
FileChannel类的使用必须配合一个byteBuffer类使用我们再创建一个FileOutputStream对象之后使用getChannel()方法来创建一条通道,同时我们将要写入的字符串是用getBytes()存在byteBuffer中,翻转byteBuffer使它变为写状态,只要byteBuffe不为空就像FileChannel中写,最后清空bytebuffer完成写操作.
但是这种写入和FileOutputStream都不是分行写入
如果想要加入换行符,需要再写入XX.write("\n".getBytes());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public void channelWrite() throws FileNotFoundException {
FileChannel outChannel = new FileOutputStream(new File("test/file/SocialNetworkCircle.txt")).getChannel();
ByteBuffer byteBuffer = java.nio.ByteBuffer.allocate(1024);
personInfo.addAll(tieInfo);
for(String i :personInfo) {
byteBuffer.put(i.getBytes());
byteBuffer.flip();
while(byteBuffer.hasRemaining()) {
try {
outChannel.write(byteBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
byteBuffer.clear();
}
}
1 | File target = new File("test/file/SocialNetworkCircle.txt"); |
Mutable的类型。
设计新的接口CircularOrbit<L,E>,其中L和E分别代表多轨道系统的中心点物体和轨道物体。可有的操作:
Immutable的ADT。
需要设计rep:1.半径
所设计的表征中心点物体的类。
Immutable的ADT。
实现 ConcreteCircularOrbit<L,E>中的 E,即代表分布在不同轨道上的物 体类 PhysicalObject。可以是接口,也可以是抽象类。 考虑到不同应用中包含不同类型的轨道物体,需从 PhysicalObject 派生子 类型,通过 override 实现 PhysicalObject 中的各个接口方法或抽象方法,也可 根据应用需求来增加子类的特有属性和方法。
API-Application Programming Interface. 何为API→点此了解。
double getObjectDistributionEntropy(CircularOrbit c)
int getLogicalDistance (CircularOrbit c, E e1, E e2)
若两物体无联系,距离无穷大。(Lab1中P3已实现该功能)double getPhysicalDistance (CircularOrbit c, E e1, E e2)
实现可视化
(1) 构造 Track、PhysicalObject 等对象时,请使用 factory method 设计模式。
(2) 构造 ConcreteCircularOrbit 对象时,针对不同应用中所需的不同类型的 L 和 E,使用 abstract factory 或 builder 设计模式。
(3) Iterator设计模式,在遍历各PhysicalObject对象时使用。
(4) 可复用API时遵循façade 设计模式,将所有 API 放置在 helper类CircularOrbitAPIs当中
(5) StellarSystem 应用中使用decorator设计模式
(6) AtomStructure 应用中,请使用 state 和 memento 设计模式管理电子跃迁 的状态,并可进行状态的恢复。意即:可保存电子每次跃迁前后的轨道信息。
继承inheritance.可能涉及到override,较易理解。下面重点分析delegation(委托)
简而言之,delegation是一个对象需要依赖其他的对象所实现功能的行为。
分为Explicit和Implicit两种。
-e.g. theSorter
is delegating functionality to some Comparator
抽象类与多态有关,了解抽象类->为什么使用抽象类?
一个类,一个责任。(下图为反例)
对扩展性的开放,对修改的封闭。
关键技术:抽象
前文
不能强迫客户端依赖于它们 不需要的接口:只提供必需的接口
关键词:隔离
一览Design Patterns的框架
为什么要这种模式:动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
Problem:如何为对象增加不同侧面的特性。
Solution:对每一个特性构造子类,通过委派机制增加到对象上。
- 抽象构件类(Component):给出一个抽象的接口,用以规范准备接收附加责任的对象
- 具体构件类(ConcreteComponent):定义一个具体的准备接受附加责任的类,其必须实现Component接口。
- 装饰者类(Decorator):有一个构件(Conponent)对象的成员变量,并定义一个和抽象构件一致的接口(我们就是通过这个一致的接口中的东西来加东西)。
- 具体装饰者类(Concrete Decoratator):定义给构件对象“贴上”附加责任。
每次想给具体构建类的某个实例加上一点东西的时候,我们做出要加上的东西对应的具体装饰者类,以具体构建类作为构造器的输入参数,然后调用装饰类的方法输出装饰后的结果。注意上述所有的变量的声明都是他们的公共接口。
看decorator模式.其中关键的decorator为material里面添加的内容。如:
1 | class Beef extends Material{ |
外观模式是为了解决类与类之间的依赖关系的,可以将类和类之间的关系配置到配置文件中,而外观模式就是将他们的关系放在一个Facade类中,降低了类类之间的耦合度,该模式中没有涉及到接口。
应用于小的接口,目的是提供一个进行相似工作的接口。详细理解外观模式
例如:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class SystemA {
public void operationA(){
System.out.println("operation a...");
}
}
public class SystemB {
public void operationB() {
System.out.println("operation b...");
}
}
public class SystemC {
public void operationC() {
System.out.println("operation c...");
}
}
facade
1 | public class Facade { |
客户端
1 | public class Client { |
用一句话来表述,状态模式把所研究的对象的行为包装在不同的状态对象里,每一个状态对象都属于一个抽象状态类的一个子类。状态模式的意图是让一个对象在其内部状态改变的时候,其行为也随之改变。
状态模式所涉及到的角色:
详细阅读→状态模式
Also known as “Virtual Constructor”. 工厂方法案例1和工厂方法案例2
应用场景:当client不知道要创建哪个具体类的实例,或者不想在client代码中指明要具体 创建的实例时,用工厂方法。 定义一个用于创建对象的接口,让其子类来决定实例化哪一个类,从而使一个类的实例化延迟到其子类。
开工厂方法就是不想把子类名字暴露,把创建和返回隔离开。在子类实现过程当中不会暴露。
1 | public Track getTrack(int inputRadius) { |
创建的不是一个完整产品,而是“产品族”(遵循 固定搭配规则的多类产品的实例),得到的结果是:多个不同产品的 object,各产品创建过程对client可见,但“搭配”不能改变。
本质上,Abstract Factory是把多类产品的factory method组合在一起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
91abstract class AbstractProductA { // A产品
public abstract void productMethod();
};
abstract class AbstractProductB { // B产品
public abstract void productMethod();
};
abstract class AbstracFactory { // 产品族的抽象工厂
public abstract AbstractProductA createProductA();
public abstract AbstractProductB createProductB();
};
class ProductA1 extends AbstractProductA {
public void productMethod() {
System.out.println("ProductA1");
}
};
class ProductB1 extends AbstractProductB {
public void productMethod() {
System.out.println("Product B1");
}
};
class ProductA2 extends AbstractProductA {
public void productMethod() {
System.out.println("Product A2");
}
};
class ProductB2 extends AbstractProductB {
public void productMethod() {
System.out.println("Product B2");
}
};
class Factory1 extends AbstracFactory {
public AbstractProductA createProductA() {
System.out.println("Factory1");
return new ProductA1();
}
public AbstractProductB createProductB() {
System.out.println("Factory1");
return new ProductB1();
}
};
class Factory2 extends AbstracFactory {
public AbstractProductA createProductA() {
System.out.println("Factory2");
return new ProductA2();
}
public AbstractProductB createProductB() {
System.out.println("Factory2");
return new ProductB2();
}
};
public class Client {
public static void main(String arg[]){
AbstracFactory FAC;
AbstractProductA PA;
AbstractProductB PB;
FAC = new Factory1();
PA = FAC.createProductA();
PA.productMethod();
PB = FAC.createProductB();
PB.productMethod();
System.out.println("----------------");
FAC = new Factory2();
PA = FAC.createProductA();
PA.productMethod();
PB = FAC.createProductB();
PB.productMethod();
}
};
举例:去必胜客点pizza。服务员(director)推荐给你套餐(builder),套餐一:甜甜圈,辣酱和海鲜披萨(concretebuilder),套餐二:薯条,番茄酱和水果披萨(concretebuilder)……而具体的套餐内产品(product)要进行制作(构造):
1 | private String sauce; |
配上一系列set操作,叮,做好了!
设计模式之美:备忘录模式和《java与模式》备忘录模式
意图:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
结构:
橙子说:
Originator发起人角色:记录当前时刻的内部状态,负责定义哪些属于备份范围的状态,负责创建和恢复备忘录数据
Memento备忘录角色:负责存储Originator发起人对象的内部状态,在需要的时候提供发起人需要的内部状态。
Caretaker备忘录管理员角色:对备忘录进行管理、保存和提供备忘录。
构造当中用极复杂的方式实现本来很简单的数据结构。但是便于扩展应用。(后来想想我就是傻,一个Track有啥扩展的?)
assertEquals对double类型测试出错?
查阅资料-看异常中的提醒Use assertEquals(expected, actual, delta) to compare floating-point numbers, 即按照“预期值,真实值,误差值”的格式,只要在这个范围内就算正确。
后来改成这个assertEquals( 2.2, stellarTrack.getRadius(),0.0);
在实验中涉及到对number的处理
大于 10000 的数字按科学记数法表示(例如 1.9885e30 表示1.9885 ∗ 1030,但 e 之前数字的整数部分必 须在 1 到 9 的范围内,e 之后的数字只能是大于 3 的正整 数),小于 10000 的数字直接给出(例如 5912,103.193), 不能用科学计数法。小数点位数不限制。
以本人设计的Stellar(恒星系的中心物体)为例,域如下
1 | private final String name; |
如何根据要求转化为double类型的呢?橙子又说,BigDecimal!this.radius = new BigDecimal(inputRadius).doubleValue(); //转化为科学记数法
发现如果直接用placeObject(Track inputtrack, E object)
就直接能加上物体,而如果先加入轨道的话就不能。
1 | public boolean placeObject(Track t, E object) { |
关键在于我的addTrack:
1 | public boolean addTrack(Track inputTrack) { |
第一开始并没有在objectsOnTrack.put(inputTrack, objects);
和List<E> objects = new ArrayList<E>();
,如果不事先放入一个集合进objectsOnTrack这个map的话,会返回空指针。
在我的SocialNetworkCircle和其父类ConcreteCircularOrbit中都有private final List<Track> tracks; //人际关系,其中radius表示好友所在的轨道级数
然而我在子类方法中调用父类的placeObject,其中会加入新轨道。父类placeObject
代码:
1 | public boolean placeObject(Track t, E object) { |
给的样例中,和中心人物有关的有四对关系,但其中只有两级轨道。一级好友和两级好友。
子类中
1 | Track t = new SocialTrackFactory().getTrack(String.valueOf(distance)); |
第3行为关键,如果注释掉的话每次都会new一个新的track,但是如果加上,只会new两个。猜测这个加入到父类的tracks中而非子类的。
证据:
后来发现objectsOnTrack这个map也有问题,同样的操作会直接对父类的这个成员变量产生影响,唉,索性让我重写父类的方法再ctrl +c/+v。
续:后来得知我的子类的重复定义了父类的成员变量,然后调用一系列方法的时候会被父类成员变量覆盖。
1 | BigDecimal rounded = new BigDecimal(entropy); |
其中entrop
是计算熵的时候用的。
在写星体转动的时候,在position中进行了这样的操作。
1 |
|
就会报错。
纪念第一次通宵写程序。在获取轨道变化前的map时我的画风
1 | for(Track track : objectsOnTrack.keySet()) { |
想着直接把List
1 | for(Track track : objectsOnTrack.keySet()) { |
如此安好!
实验三算过去了,总结的也算一般般吧。一点点进步吧,加油!
]]>于是我剪下了月光
射向我老家的地方
郑州的夜比哈尔滨多了活力与隐隐的躁动,比北京的夜多了些魅惑和妩媚,比商丘多了些大气。
如今,郑州的星星也多了些,大抵是空气得到改善了吧。
我随着颠颠簸簸的机场大巴晃着脑袋,感到4月份的郑州俨然一副夏季整装待发的样子。左座扎着马尾辫的女子低着头刷着抖音,时不时掸去吃在身上的饼干屑;后座一对从哈尔滨回来的男生对着同行女伴绘声绘色地描述着自己的风光往事;隔着过道年轻妈妈的右臂侧枕着约莫2岁的熟睡的儿子,她偶尔也瞥了头地向窗外看去,看这绿城路灯与树影的光影交错。除了随车摇晃的频率,一车的人,无一处相似。
星光与灯光似是漫长黑夜展开中的点点白亮。夜景难忘,难忘的事与深情的回忆都在夜里浮现。
18年夏天,大一暑假宅在北京不亦乐乎。除了夜里跑到对面北京体育大学操场里与大爷大妈们一起跑步,几乎没出过门。
17年夏天,刚刚走出考场就被堂哥开车一路送往商丘高铁站,赶上去往北京的夜班车。爸一路同行,偶尔预测几句我的高考成绩并开始了对我未来教育事业的分析。上了高铁,我则和爸一路默契地枕着高铁的座位默不作声开始了孙家的“休养生息”。爸两年陪读的辛酸不亚于我一路走来的心力交瘁,而现在我终于开始慢慢领悟到于两年中一声不吭地忍耐坏脾气的屁孩儿是一件多么伟大的事。到了北京,姐夫早已叫好了午夜出租。到家凌晨,一身臭汗,一脸痘坑。再来就是我第二天早晨无精打采地听北京出租车司机儿化音碎碎念:“我儿子比你小点儿,今年高中,嘿,这孩儿不争气,中考时都能睡迷糊过头儿……”。那年夏天回龙观依然那么村儿,地铁旁的公交站牌也没有遮阳棚,害得我又黑了几个度。13号线依然那么挤,脚不离地上地铁让人记忆犹新。不过,中央民族大学对面的酸豆角炒饭还是不错的。17年夏天,同学之间流行起了手机狼人杀,我常常光膀子坐在阳台马扎上边洒着杨梅须上的水,边与他们来场“最心机奖”的角逐。
17年夏季的一天夜晚回了老家,重见了发小,那是一个被他们先礼后兵(寒暄加温暖)用啤酒灌晕的夜。17年昏黄交错的夏夜不过是平常的,依然有着老爹四季梅配孜然粉的充满油烟味的夜。
15,16的夜没什么波澜曲折,偶尔穿插生活中的起伏,每夜同样的困乏无力,每夜同样的如山作业,每夜不同的习题和每夜桌前不同的洗好的水果。最怀念那11:00左右一重一轻的上楼声和夹杂着的咳嗽,那是爸回来前的序曲。伴随着对着防盗门插钥匙咯嚓咯嚓的响声,他掂着菜和水果零食回来了。
“为啥这么晚?”我用近乎审讯的语气问。
“打了会儿扑克。”他一脸无奈和“一副小屁孩儿别管老子”的不屑。偶尔他会不那么敷衍地回上“今天斗了会儿地主,赢点小钱儿,买了你爱吃的烧牛肉。” 爸在夜里不那么健谈,总能玩着手机玩着玩着耷拉下头打起呼噜。最怀念周六模考后的夜,他会按时按点地接满一澡池的温水,等我回来大快朵颐后再来场水浴洗礼。夜里会在桌前听见回家路过的三少唱着“我就是我”,不同的曲目代表不同的心情。SYQ则必挎一墨绿色水壶一步一步地回到中行家属院,在门前刷卡或等着别人刷卡。这样看来,中学的夜也不过是平常的充斥生活琐屑的夜。
儿时的夜却是最幻炫的夜。发小(壮哥、HW、LDX)和我干了很多没心没肺的事儿。我们曾找来砖头和废纸,堆成小炉灶开始烧,看谁的黑烟又高又胖,然后看谁在被环卫大妈追打时跑的最快。也曾在建筑楼房的沙堆上挖出一个又一个大坑,看谁的陷阱总不容易被发现,一次我曾经往一个坑里撒泡尿,却自己踩了雷,至此退出挖坑联盟。还曾在夜里在家属院玩捉迷藏,捉到最后就剩我一个傻了吧唧地被野狗追着跑。儿时偶尔会半夜醒来,看堂屋亮着的灯和空空如也的屋子,我就知道爸妈开始了建军大业——深夜麻将场。
09年的中秋节夜里,月亮很亮很大,爸送我和妈去武汉找我姐,正值国庆的商丘有些微凉,我却傻不愣登带了一堆毛衣去武汉热成智障。没有常识不学无术的我不知道长江水变质有多快,离开武汉前我去长江大桥下盛满了一绿茶瓶子的长江水,回到老家打开瓶盖时那“沁人心脾”致人于死地的臭味让我终生难忘。夜里有一次写检讨的时候还舞文弄墨地以“人生如梦,一尊还酹江月”为开头,自以为文采飞扬的检讨书现在重读不过是一地鸡毛,还是土鸡的毛。
08年的夜,奥运会和篇篇被迫写日记的夜,被蚊子咬的夜,还有那随着爸去郊外申甘林带一同捉知了,然后被手电筒照见的孤坟吓得半死的夜。据我妈回忆,我在当时就表现出了“懂得心疼人”的特点,会在夜里11点就催着我爸回去以防第二天休息不好影响上班。可是后来想想,可能是由于我的勇气值用完了急需回家冷静的缘故。
今年冬季的夜,爸回忆,在我两岁的一个夜里,他喝醉回家后看见我在胡同门口雪堆前等着他回来。一激动没抱起来我,却直接对我来个泰山压顶。
“你还记得吗?”他强忍笑意地问。
“不记得,好像不记得小伙伴们咋看我笑话,也不记得如何扑棱手脚也翻不过你压着我的身子。”
小时候不觉得夜有多美多温馨,太过寻常太过平凡了。我会和姐在傍晚夜幕降临前一人两个桌角地把饭桌抬出厨房,然后边尝着爸炒的空心菜,土豆肉丝,焖虾,边端着汤、碗小心翼翼地挪着脚。
小时候小胆儿,最期望睡前能听到爸的呼噜声而非妈讲童话。因为爸的呼噜声总让我觉得这世界上的鬼肯定会先通过声音找我爸,然后放过我。或者早被我爸的呼噜声烦死,然后不来。
长大了,好像不大做噩梦了,也开始觉得爸的呼噜声吵人了,为此还不少在郑州嫌弃我爸,觉得门的隔音效果太差,恨不得在各个漏音的孔里灌满水泥封得严严实实。
后来离开家,想听爸的呼噜声也听不到了。
没在郑州看见过黄河,只在哈尔滨看到过松花江,岸边五光十色的霓虹和对岸萧条无灯火的太阳岛对比鲜明。从防洪纪念塔望去,正好看到浮出水面的沙渚。偶尔晴朗的天,会给皎月登场的机会,却都免不了那“江月年年望相似”的重复感。
大巴依旧颠簸,生活依然继续,心依然疲惫。
那些个再也回不去的夜,再也无法回头的路。
我想我爸了。
]]>爱恨是掌心的沙漠
故事被点了穴遗忘
类(Class)封装了数据和行为,是面向对象的重要组成部分,它是具有相同属性、操作、关系的对象集合的总称。在软件系统运行时,类将被实例化成对象(Object),对象对应于某个具体的事物,是类的实例(Instance)。
类图(Class Diagram)使用出现在系统中的不同类来描述系统的静态结构,它用来描述不同的类以及它们之间的关系。
在UML中,类使用包含类名、属性和操作且带有分隔线的长方形来表示,如定义一个Employee类,它包含属性name、age和email,以及操作modifyInfo(),在UML类图中该类如图1所示:
在UML类图中,类一般由三部分组成:
UML规定属性的表示方式为:可见性 名称:类型 [ = 缺省值 ]
其中:
UML规定操作的表示方式为:可见性 名称(参数列表) [ : 返回类型]
其中:
在类中,操作method1的可见性为public(+),带入了一个Object类型的参数par,返回值为空(void);操作method2的可见性为protected(#),无参数,返回值为String类型;操作method3的可见性为private(-),包含两个参数,其中一个参数为int类型,另一个为int[]类型,返回值为int类型。
在软件系统中,类并不是孤立存在的,类与类之间存在各种关系,对于不同类型的关系,UML提供了不同的表示方式。
关联(Association)关系是类与类之间最常用的一种关系,它是一种结构化关系,用于表示一类对象与另一类对象之间有联系.
默认情况下,关联是双向的。例如:顾客(Customer)购买商品(Product)并拥有商品。
类的关联关系也可以是单向的,单向关联用带箭头的实线表示。
在系统中可能会存在一些类的属性对象类型为该类本身,这种特殊的关联关系称为自关联。例如:一个节点类(Node)的成员又是节点Node类型的对象,如图所示:
了解即可
聚合(Aggregation)关系表示整体与部分的关系。在聚合关系中,成员对象是整体对象的一部分,但是成员对象可以脱离整体对象独立存在。在UML中,聚合关系用带空心菱形的直线表示。
代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class Car {
private Engine engine;
//构造注入
public Car(Engine engine) {
this.engine = engine;
}
//设值注入
public void setEngine(Engine engine) {
this.engine = engine;
}
}
public class Engine {
……
}
组合(Composition)关系也表示类之间整体和部分的关系,但是在组合关系中整体对象可以控制成员对象的生命周期,一旦整体对象不存在,成员对象也将不存在,成员对象与整体对象之间具有同生共死的关系。
泛化(Generalization)关系也就是继承关系,用于描述父类与子类之间的关系,父类又称作基类或超类,子类又称作派生类。在UML中,泛化关系用带空心三角形的直线来表示。
在接口中,通常没有属性,而且所有的操作都是抽象的,只有操作的声明,没有操作的实现。UML中用与类的表示法类似的方式表示接口:
接口之间也可以有与类之间关系类似的继承关系和依赖关系,但是接口和类之间还存在一种实现(Realization)关系,在这种关系中,类实现了接口,类中的操作实现了接口中所声明的操作。在UML中,类与接口之间的实现关系用带空心三角形的虚线来表示:
Those who are dead
Are not dead
They’re just living in my head.
And since i fell
For that spell
I am living there as well
——Coldplay 《42》
致那些失去亲爱的人的人们。
其实想想人们都将往那里走去,“死亡是一座灯塔”。人常说死者离开人世走入记忆,但生者如何依托死者的记忆活着呢?
遇到这种事,想必你没法痛痛快快地宣泄吧?温暖的东西恐怕我不大能写出来了,那种东西在我眼里几乎为骗局。你感受的多,你越觉得累,你觉得精疲力尽走投无路却根本没有柳暗花明。接受吧。
因为那就是生活的真相。
与其说以前生活多美好,只管吃饭只管玩闹,倒不如想想所谓的岁月静好其实是一代又一代人的“负重前行”,只不过大多数人只有“后人乘凉”的享受欲,将那“前人栽树”的前提与责任抛之脑后,最后一人赤手空拳来到新天地时埋怨着世界的不近人情,不有些可笑吗?
我承认我有依赖他人的习惯,我承认自己的懦弱与胆怯。
很多时候我也意识到,只有我边说着话,边兀自重温悲伤的故事。
人们的悲欢大抵不相通,鲁迅早就说过了。不过还是有相通的时候吧,真正的痛苦来自于真正的爱,尽管如此,我还是要去爱,爱那些值得我痛苦的人,爱到不得不重视他们的痛苦,爱到他们的难过也变成我的难过。“重要的不是治愈,而是病痛着活下去。”(加缪)
那人离开了,仿佛处处无此人,又处处皆此人。此人离去,似星火散落四周。
是啊,相处的时间太短,余生太长;是啊,人生太短,遗憾又太长。时隔多日,当我因脑海中那些个人的点点滴滴因时光斑驳至模糊伤怀时,才明白生命中短暂的相遇意义何在。我自认为了解生命,参悟到了生命的真谛——生命就是失去。
三毛也失去了何西,杨绛最后不过一人踽踽独行。
由此说来,你,我,还有他,不过都是天涯倦客,心中惦记那归路,希望回到那些细细碎碎温馨的尘事中。
我们不必留恋所谓过去的好时光,那个时候生活充满艰难危险和迷惘;我们也不必为今天的时代过分沮丧,因为今天,也总有一天会被人们称作是——过去的好时光。
过去的人真笨,过去的人真难。
——刘慈欣《地火》
且将昨日的欢喜悲伤抛去,离开那影影绰绰的回忆,让尘归尘,土归土吧。一切,不都是世界的物质循环吗?
趁天空还明媚,蔚蓝
趁花朵鲜艳
趁眼睛来看一切美好
趁夜幕还没降临
呵 趁现在时流还平静
做你的梦吧 且憩息
等醒来再哭泣
Types, whether built-in or user-defined, can be classified as mutable or immutable
可变类型的对象:提供了可改变其内部数据的值的操作
The objects of a mutable type can be changed: that is, they provide operations which when executed cause the results of other operations on the same object to give different results.
举例:
Creators create new objects of the type.
A creator may take an object as an argument, but not an object of the type being constructed
Producers create new objects
The concat() method of String , for example, is a producer: it takes two strings and produces a new one representing their concatenation.
Observers take objects of the abstract type and return objects of a different type.
The size() method of List , for example, returns an int
Mutators change objects.
The add() method of List , for example, mutates a list by adding an element to the end.
“真是大国重器”呐!
构造器例子
在SC的lab2中构造Vertex。
1 | // TODO constructor |
构造器里面要用this
而不能Vertex.label = name;
根据百度百科
Java接口是一系列方法的声明,是一些方法特征的集合,一个接口只有方法的特征没有方法的实现,因此这些方法可以在不同的地方被不同的类实现,而这些实现可以具有不同的行为(功能)。
两种含义:一,Java接口,Java语言中存在的结构,有特定的语法和结构;二,一个类所具有的方法的特征集合,是一种逻辑上的抽象。前者叫做“Java接口”,后者叫做“接口”。
在外部调用静态方法时,可以使用”类名.方法名”的方式,也可以使用”对象名.方法名”的方式。而实例方法只有后面这种方式。也就是说,调用静态方法可以无需创建对象。
静态方法在访问本类的成员时,只允许访问静态成员(即静态成员变量和静态方法),而不允许访问实例成员变量和实例方法;实例方法则无此限制。
构造器最大的用处就是在创建对象时执行初始化,当创建一个对象时,系统会为这个对象的实例进行默认的初始化。如果想改变这种默认的初始化,就可以通过自定义构造器来实现。例如软件构造实验中需要写一个ConcreteEdgesGraph1
2
3
4
5
6 // TODO constructor
/**
* construct a empty graph
*/
public ConcreteEdgesGraph() {
}
(1)assert [boolean表达式]
如果表达式为true,程序继续执行,若为false则抛出AssertionError,并终止执行。
(2)assert [boolean 表达式:错误表达式(日志)]
如果表达式为true,程序继续执行。如果为false,则程序抛出java.lang.AssertionError,输出[错误信息]。
就是提供一种方法对一个容器对象中的各个元素进行访问,而又不暴露该对象容器的内部细节。详见迭代器
而对应于SC实验中,对边的遍历涉及到迭代器的使用1
2
3
4
5List<Edge> iteratorEdges = new ArrayList<Edge>(edges);
for(Edge i : iteratorEdges) {
if(i.getSource().equals(vertex) || i.getTarget().equals(vertex))
edges.remove(i);
}
简而言之就是可以存在这个东西,如果没有此声明的话会出错-没有实例化。1
2private final String label;
private final Map<String, Integer> toVertex; //声明存在合法变量
对应于以下的实例化1
toVertex = new HashMap<String, Integer>();
Java泛型(generics)是JDK5中引入的一个新特性,泛型提供了编译时类型安全监测机制,该机制允许程序员在编译时检测到非法的类型。
泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。
在软件工程课程里面Poetic WalksP3应用到了泛型。1
2
3
4class Vertex<L> {
private final L label;
private final Map<L, Integer> toVertex; //声明存在合法变量
}
一个好的抽象数据型(ADT)的关键:能否preserves its own invariants
看下面的例子1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public class Tweet {
public String author;
public String text;
public Date timestamp;
/**
* Make a Tweet.
* @param author Twitter user who wrote the tweet
* @param text text of the tweet
* @param timestamp date/time when the tweet was sent
*/
public Tweet(String author, String text, Date timestamp) {
this.author = author;
this.text = text;
this.timestamp = timestamp;
}
}
如何确保Tweet
类是不可变的呢?即一旦建立,相关属性不改变。
威胁之一是客户端能够直接修改这个域。Representation exposure :code outside the class can modify the representation directly.
不过辛亏有private
和final
,官方给出如下解释
The private and public keywords indicate which fields and methods are accessible only within the class and which can be accessed from outside the class. The final keyword also helps by guaranteeing that the fields of this immutable type won’t be reassigned after the object is constructed.
一种策略就是防御式拷贝(defensive copying)。
例如:1
2
3public Date getTimestamp() {
return new Date(timestamp.getTime());
}
值得注意的是,另一种copy a mutable object is clone(),但是有些问题,暂且不谈。
1
2
3
4
5
6
7
8
9
10/** @return a list of 24 inspiring tweets, one per hour today */
public static List<Tweet> tweetEveryHourToday () {
List<Tweet> list = new ArrayList<Tweet>();
Date date = new Date();
for (int i = 0; i < 24; i++) {
date.setHours(i);
list.add(new Tweet("rbmllr", "keep it up! you can do it", date));
}
return list;
}
所以不变性又被破坏了,采用一下策略:1
2
3
4
5public Tweet(String author, String text, Date timestamp) {
this.author = author;
this.text = text;
this.timestamp = new Date(timestamp.getTime());
}
此时,轮到我们的Collections.unmodifiableList()
亮相。但是一个downside就是得到的所谓的immutability只是在runtime,but not at compile time. Java也不会在你试着sort()
这个unmodifiable list的时候警告你,反而抛给你一个冷冰冰的异常。
注意阅读练习里面的array相关的problem
关键不仅仅在于选取两个集合Space,而且在于选取什么的元素为合法,并且怎样将它们对应成抽象的值。
not only choosing the two spaces… but also deciding which rep values are legal, and how to interpret them as abstract values.
比如根据此图,我们得到下面的映射:
以下要点:
·每一个抽象类都对应有原象
·一些抽象类映射前的原象不止一个
·而在集合R中并非所有元素都有映射的象
和实验相关一点,AF就是某个成员变量代表的抽象概念,RI就是对这个成员变量的限制。然而我这个傻子恍然大悟,AF就是”Abstraction functioin”,RI即为” Representation invariant”啊!!!
抽象函数AF:R和A之间映射关系的函数,即如何去解 释R中的每一个值为A中的每一个值。
表示不变性RI:某个具体的“表示”是否是“合法的”
可将RI看作:所有表示值的一个子集,包含了所有合法的表示值
也可将RI看作:一个条件,描述了什么是“合法”的表示
从rep values到其所表示的抽象值之间的映射表示如下
AF: R -> A
同时也可以用R → Boolean
的映射表示是否rep value和一个abstract values之间存在着对应关系。如下图所示
对于表达值(rep value)而言, RI(r) 为真当且仅当r被AF映射。RI(“a”) = true, RI(“ac”) = true, 并且 RI(“acb”) = true, 但 RI(“aa”) = false and RI(“abbc”) = false.
尽管有着不相同类型的rep value space 和相同的rep invariant,我们可以构建出不同的映射。例如“acgg”表示字符串之间的范围,[a-c]和[g-g],所以代表的元素是集合set{a,b,c,g}.
对于client of an abstract data type而言,visible and documented的应该为:abstract value space, creators, observes. 而不可见:abstraction function, rep 和 rep invariant.
Rep invariant is a function from rep values to boolean.
check的特点:
It’s good for an implementer to call
checkRep()
just before returning from a public method of an ADT class.
checkRep()
asserts the rep invariant.
注意,在描述rep invariant and abstraction function的时候,必须注意:
不能仅仅用“域内全员合法”来简简单单概括RI,重要的是explain是如何区分“合法”和“非法”的。
同样的,对于AF而言,仅仅声明“represents a set of charaters”也是不够的。而应该define precisely how the concrete field values are interpreted
而根据同学的解释
Rep exposure:
java中数据类型分为mutable和immutable的,对前者进行的操作可能会改变其内部数据;而对后者的操作不改变其内部值,而是构造新的对象。因此,对于mutable的数据,如果没有良好的保护,意味着client对其的调用可以直接修改内部数据。
An invariant is a property of a program that is always true, for every possible runtime state of the program.
为什么需要不变量? 因为爱情。保持程序的“正确性”,容易发现错误。
SPEC is the abbreviation of the word-specification,规约。client能干什么,不能干什么,输入输出满足的条件将在spec中罗列得清清楚楚。
大致要点
The precondition is an obligation on the client (i.e., the caller of the method). It’s a condition over the state in which the method is invoked.
后置条件 postcondition(后置条件:对开发者的约束,方法结束时必须满足的条件)
The postcondition is an obligation on the implementer of the method.
– Precondition , indicated by the keyword requires
– Postcondition , indicated by the keyword effects
相应于@return
和@param
呢?来看课件讲义:
Parameters are described by @param clauses and results are described by @return and @throws clauses.
Put the preconditions into @param where possible, and postconditions into @return and @throws.
规约的强度S2>=S1 A specification S2 is stronger than or equal to a specification S1 if
多谢橙子的提醒,在poet测试里面需要用到assert断言,而必须要在Eclipse中开启assert选项。详情
Windows -> Preferences ->Java ->Installed JREs ->待使用的JDK ->Edit ->Default VM Arguments文本框中输入:-ea
本人在实验里面经常用到对抛出异常的检测,下面以lab2中Board异常检测为例。Board规定了,应该为”chess”或者”go”类型,而在这里传入”tt”显然会抛出异常的。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public Board(String type) {
if(type == "chess")
N = 8;
else if(type == "go")
N = 19;
else
throw new RuntimeException("Not a game that we'll provide for you");
...
}
/*
* Test for exception
* */
(expected = RuntimeException.class)
public void typeExceptionTest() {
Board board = new Board("tt");
}
overload用同一个方法名字但是输入不同的参数列表,比如本人在实验中构造的函数1
2
3
4
5
6
7
8
9public Vertex(L source,L target, int weight) {
label = source;
toVertex = new HashMap<L, Integer>();
toVertex.put(target, weight);
}
public Vertex(L name) {
this.label = name;
this.toVertex = new HashMap<L, Integer>();
}
Evan的这篇文章很好:Java 何时需要重写hashCode()和equals()
此外override在run time检查,而overload是在compile阶段就进行检查
等价关系(Equivalence Relation):自反、对称、传递
1 | public class Duration { |
其中下列那些等价呢?1
2
3
4Duration d1 = new Duration (1, 2);
Duration d2 = new Duration (1, 3);
Duration d3 = new Duration (0, 62);
Duration d4 = new Duration (1, 2);
等价性:引用等价性和对象等价性
对基本数据类型,使用==判定相等
对对象类型,使用equals.
再看这个例子
1 |
|
结果呢
1 | Duration d1 = new Duration (1, 2); |
答案为true和false。d2的类型是Duration,而o2的类型是Object,在类Duration里面的equals无法对这个o2进行等价判断。而且o2和d1指向并非同一内存空间,因此会返回false。
上述给的例子是overload而非override。1
2
3
4
5
6
7
8
9
10public class Duration extends Object {
// explicit method that we declared:
public boolean equals(Duration that) {
return this.getLength() == that.getLength();
}
// implicit method inherited from Object:
public boolean equals(Object that) {
return this == that;
}
}
equals三件套:(1)是否为空 (2)类型是否相同 (3)根据AF设计相等判断。但是有一弊处:在没有AF情况下判断每个域的等价性,这是不合理的。
hashCode -> memory address!!!
规定一个原则:等价的对象必须有相同的hashCode。(不相等的对象也可以映射为同样的hashCode但性能会变差)
A general rule:
Always override hashCode() when you override equals()
mutable:
对可变类型来说,往往倾向于实现严格的观察等价性(observational equality)。但在某些时候观察等价性可能导致bug甚至可能破坏RI。
immutable类型重写equals和hashCode(),但是mutable类型就不必重写
]]>自修自持莫道此间非彼岸,即心即佛须知东土是西天
羡艳着橙子和钟哥的博客,自己也心痒痒,谁所菜鸡不能有自己的鸡笼?于是乎我也按着教程一步一步地de着bug,学着毫无技术含量的操作。
或许写博客当有中学时代拿着尺子和铅笔一点点打格整理笔记的美感?我挺喜欢手字笔录的方式,但怎奈这越学越深的计算机世界不给你手字笔录的时间让你横平竖直工笔正楷地整理笔记。
《离骚》中有“朝濯发于汤谷兮,夕晞余身兮九阳”,闭目仿佛看见一身高八尺有余形貌昳丽的长发美男于光中背对着你,可瞅瞅我现在满脸油光,痘印未消,面如土色,发型凌乱,眼小无神,体形消瘦······(再说下去我都把我自己说抑郁了)。美男这辈子估计是够呛,或许找个颜值高点的妹子改良基因后能让我儿子当上美男就不错了,我再努努力当上富二代他爹?
一点一点走吧,搭这个博客的时候曾经一度想放弃,为什么那么多的错?那么多的异常?
但是爹一直反对我做事三分钟热度或者半途而废。秉着“吾乃光宗耀祖之孙氏”的信念,忍着不挤额头上痘痘的冲动,我耐着性子开始了以后的博客之路。不过也好,有个能够宣泄的方寸之地······
“是非曲吉祥物”是我和发小一块玩梦幻西游取的第一个人物名字,剑侠客-大唐官府。十多年来,人们走的走,留的留,自己也从任性妄为到忍耐包容的路上自修自持。有些事能够想,有些事只能放,放下那无奈不甘的执念吧。
完善阿里云的信息时跳出密保问题,“你儿时最好的伙伴”,我不假思索地填上cq,可是我们好久好久都没见面了,甚至好久好久都没有说过话了,我们仅存的联系方式就剩下了QQ,我搬了家,他去了外地。但是想一想,人生哪有这么多时间给你感慨呢?孤独的不仅仅是孤单的一人,还有那秋风乍起时望着万家灯火而独自彳亍的异乡客。
不过当个风筝也是好的,虽被一线束缚起来,总不至于落得无处可归,总有人惦记着你,牵扯着你,不肯松手。
可能是经历了一些事吧,我最近竟能在看似千篇一律的生活中活出一瞬间的“幸福感”:雏菊的花又开了些,托福听力又能多听懂些叽里呱啦的词了,洗澡的水温舒服了些······也忘了在哪抄的的这些:
你为什么会爱上人类?他们没有永生,脆弱而匆忙
就因为他们没有永生,害怕死亡,才有那么脆弱和匆忙。我爱上的是那脆弱中的争取和躁动,我爱上的是那随时会失去的短暂和恐慌。
穷且意坚,不堕青云之志。当自强,于人生路上不忘克己复礼。
]]>