给定一个类型类,其中应根据返回类型执行实例选择:
case class Monoid[A](m0: A) // We only care about the zero here
implicit def s[T] : Monoid[Set[T]] = Monoid(Set.empty[T])
implicit def l[T] : Monoid[List[T]] = Monoid(List.empty[T])
def mzero[A](implicit m: Monoid[A]) : A = m.m0
Run Code Online (Sandbox Code Playgroud)
为什么Scala(2.11.6)无法解析正确的实例:
scala> mzero : List[Int]
<console>:24: error: ambiguous implicit values:
both method s of type [T]=> Monoid[Set[T]]
and method l of type [T]=> Monoid[List[T]]
match expected type Monoid[A]
mzero : List[Int]
^
Run Code Online (Sandbox Code Playgroud)
当它有没有问题,使用时发现基于返回类型的隐式隐函数(我们在这里重新定义它为我来说明它是多么相似mzero)
def i[A](implicit a : A) : …
Run Code Online (Sandbox Code Playgroud) 在我从一名前员工继承的许多脚本中,我一直看到这种模式:
if (true $SOME_VAR)&>/dev/null; then
...
fi
Run Code Online (Sandbox Code Playgroud)
或者这个
(true $SOME_VAR)&>/dev/null || SOME_VAR="..."
Run Code Online (Sandbox Code Playgroud)
人工页面true
说它总是返回true,因此我一直在想,这些检查有什么意义?在第一种情况下,then
部件始终执行,在第二种情况下,从不执行右手部件.
在大多数tensorflow教程中,作者使用通道最后维度排序,例如
input_layer = tf.reshape(features, [-1, 28, 28, 1])
Run Code Online (Sandbox Code Playgroud)
最后一位代表通道数(https://www.tensorflow.org/tutorials/layers).习惯了Theano和Numpy(都使用C-ordering,即row-major),我发现这很尴尬.此外,在已经读取文档上在tensorflow内存布局方案,我估计信道最后一个布局会造成更多的高速缓存未命中,因为卷积是在各个信道进行的,而在后沟道排序这些信道的线性存储器混合,有效地将缓存缩小N(其中N是通道数),这在3D和4D卷积中效率特别低.我弄错了吗?
PS
我发现了一个密切相关的线程(Tensorflow 3通道颜色输入顺序).接受回答的作者声明TF默认使用row-major,但鉴于我到目前为止发现的所有教程都显示了频道最后的排序,我发现这种说法具有误导性.
我一直在尝试创建一个服务器进程,该进程从客户端进程异步接收输入文件路径和输出路径。服务器执行一些依赖于数据库的转换,但为了简单起见,我们假设它只是将所有内容都设为大写。这是服务器的一个玩具示例:
import asyncio
import aiofiles as aiof
import logging
import sys
ADDRESS = ("localhost", 10000)
logging.basicConfig(level=logging.DEBUG,
format="%(name)s: %(message)s",
stream=sys.stderr)
log = logging.getLogger("main")
loop = asyncio.get_event_loop()
async def server(reader, writer):
log = logging.getLogger("process at {}:{}".format(*ADDRESS))
paths = await reader.read()
in_fp, out_fp = paths.splitlines()
log.debug("connection accepted")
log.debug("processing file {!r}, writing output to {!r}".format(in_fp, out_fp))
async with aiof.open(in_fp, loop=loop) as inp, aiof.open(out_fp, "w", loop=loop) as out:
async for line in inp:
out.write(line.upper())
out.flush()
writer.write(b"done")
await writer.drain()
log.debug("closing")
writer.close()
return
factory = asyncio.start_server(server, *ADDRESS) …
Run Code Online (Sandbox Code Playgroud) 我有一个collections
模块的计数器.总结所有计数的最佳方法是什么?
例如,我有:
my_counter = Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1})
Run Code Online (Sandbox Code Playgroud)
并希望获得7
返回的值.据我所知,该功能sum
用于将多个计数器添加到一起.
嗯,这似乎很容易,但我在网上找不到一个参考.在C中,我们可以创建一个空字符char
数组,n
如下所示:
char arr[n] = "";
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在Cython中做同样的事情时
cdef char arr[n] = ""
Run Code Online (Sandbox Code Playgroud)
我得到这个编译错误:
Error compiling Cython file:
------------------------------------------------------------
...
cdef char a[n] = ""
^
------------------------------------------------------------
Syntax error in C variable declaration
Run Code Online (Sandbox Code Playgroud)
显然,Cython不允许以这种方式声明数组,但还有其他选择吗?我不想手动设置数组中的每个项目,也就是说我不是在寻找这样的东西
cdef char a[10]
for i in range(0, 10, 1):
a[i] = b"\0"
Run Code Online (Sandbox Code Playgroud) 我正在创建几个类来将它们用作状态标志(这更像是一个练习,虽然我将在实际项目中使用它们),就像我们None
在Python中使用一样,即
... some_var is None ...
Run Code Online (Sandbox Code Playgroud)
NoneType
有几个特殊属性,最重要的是它是一个单例,即NoneType
在任何解释器会话期间不能有多个实例,并且它的实例(None
对象)是不可变的.我想出了两种可能的方法来在纯Python中实现一些类似的行为,我很想知道从架构的角度来看哪一个看起来更好.
我们的想法是拥有一个产生不可变类的元类.禁止这些类具有实例.
class FlagMetaClass(type):
def __setattr__(self, *args, **kwargs):
raise TypeError("{} class is immutable".format(self))
def __delattr__(self, *args, **kwargs):
self.__setattr__()
def __repr__(self):
return self.__name__
class BaseFlag(object):
__metaclass__ = FlagMetaClass
def __init__(self):
raise TypeError("Can't create {} instances".format(type(self)))
def __repr__(self):
return str(type(self))
class SomeFlag(BaseFlag):
pass
Run Code Online (Sandbox Code Playgroud)
我们得到了理想的行为
a = BaseFlag
a is BaseFlag # -> True
a is SomeFlag # -> False
Run Code Online (Sandbox Code Playgroud)
显然,任何在这些类上设置属性的尝试都将失败(当然有几种黑客可以克服这个问题,但直接的方法是关闭的).类本身是在命名空间中加载的唯一对象.
class FlagMetaClass(type):
_instances = {}
def __call__(cls): …
Run Code Online (Sandbox Code Playgroud) 假设我们已经[(a1, b1), (a2, b2), ... , (an, bn)]
根据起始位置和长度排序了一系列间隔.我们希望统一所有相交的间隔.这是一个包含至少2个隔离区间组的小样本数据集:
from random import randint
def gen_interval(min, max):
return sorted((randint(min, max), randint(min, max)))
sample = sorted([gen_interval(0, 100) for _ in xrange(5)] +
[gen_interval(101, 200) for _ in xrange(5)],
key=lambda (a, b): (a, b - a))
Run Code Online (Sandbox Code Playgroud)
还有一些我们需要检查交叉和延长间隔的函数.
def intersects(interval1, interval2):
a1, b1 = interval1
a2, b2 = interval2
return (a1 <= a2 <= b1) or (a1 <= b2 <= b1)
def extend(interval1, interval2):
a1, b1 = interval1
a2, b2 = interval2
return …
Run Code Online (Sandbox Code Playgroud) 我正在将我的R
一些东西移到Python
,因此我必须使用pandas.DataFrame
s。有几件事我想优化。
假设我们有一张桌子
key value
abc 1
abc 2
abd 1
Run Code Online (Sandbox Code Playgroud)
我们想要得到一个 form 的字典{key -> list[values]}
。这是我现在完成这项工作的方法。
from pandas import DataFrame
from StringIO import StringIO
def get_dict(df):
"""
:param df:
:type df: DataFrame
"""
def f(accum, row):
"""
:param accum:
:type accum: dict
"""
key, value = row[1]
return accum.setdefault(key, []).append(value) or accum
return reduce(f, df.iterrows(), {})
table = StringIO("key\tvalue\nabc\t1\nabc\t2\nabd\t1")
parsed_table = [row.rstrip().split("\t") for row in table]
df = DataFrame(parsed_table[1:], columns=parsed_table[0])
result = get_dict(df) …
Run Code Online (Sandbox Code Playgroud) 我们应该如何用 Python 编写文件,同时保持功能纯粹?通常我会做这样的事情
from typing import Iterable
from io import IOBase
def transform_input(input_lines: Iterable[str]) -> Iterable[str]: ...
def print_pack(input_lines: Iterable[str], output: IOBase) -> None:
for line in input_lines:
print(line, file=output)
def main(*args, **kwargs):
# Somehow we get a bunch iterables with strings and a list of output streams
packs_of_input = ... # Iterable[Iterable[str]]
output_streams = ... # Iterable[IOBase]
packs_to_print = map(transform_input, packs_of_input)
for pack, output_stream in zip(packs_to_print, output_streams):
print_pack(pack, output_stream)
Run Code Online (Sandbox Code Playgroud)
我们可以for
用这样的东西替换 -loop
list(map(lambda pack_stream: print_pack(*pack_stream), zip(packs_to_print, output_streams))
Run Code Online (Sandbox Code Playgroud)
但这只会让打印看起来像是功能性完成的。问题是这 …
python ×7
algorithm ×1
asynchronous ×1
bash ×1
c ×1
conditional ×1
counter ×1
cython ×1
dataframe ×1
if-statement ×1
implicit ×1
io ×1
memory ×1
metaclass ×1
nonetype ×1
numpy ×1
pandas ×1
python-2.7 ×1
python-3.5 ×1
python-3.x ×1
r ×1
reduce ×1
return-type ×1
scala ×1
scalaz ×1
tensorflow ×1