小编ajm*_*tin的帖子

记录器配置以记录到文件并打印到stdout

我正在使用Python的日志记录模块将一些调试字符串记录到一个非常好的文件中.现在另外,我想使用这个模块也将字符串打印到stdout.我该怎么做呢?为了将我的字符串记录到文件,我使用以下代码:

import logging
import logging.handlers
logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler(
    LOGFILE, maxBytes=(1048576*5), backupCount=7
)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
Run Code Online (Sandbox Code Playgroud)

然后调用一个记录器函数

logger.debug("I am written to the file")
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

python logging stdout file

310
推荐指数
7
解决办法
21万
查看次数

用于将CamelCase转换为java中的camel_case的正则表达式

我明白了为什么使用正则表达式的字符串转换一样没有给出所需的输出FooBarFoo_Bar这反而给了Foo_Bar_.我可以用String.substring做一些事情substring(0, string.length() - 2)或者只是替换掉最后一个字符,但我认为这种情况有更好的解决方案.

这是代码:

String regex = "([A-Z][a-z]+)";
String replacement = "$1_";

"CamelCaseToSomethingElse".replaceAll(regex, replacement); 

/*
outputs: Camel_Case_To_Something_Else_
desired output: Camel_Case_To_Something_Else
*/
Run Code Online (Sandbox Code Playgroud)

问题:寻找更简洁的方法来获得所需的输出?

java regex string

72
推荐指数
5
解决办法
6万
查看次数

优化阵列压缩

假设我有一个数组 k = [1 2 0 0 5 4 0]

我可以按如下方式计算掩码 m = k > 0 = [1 1 0 0 1 1 0]

仅使用掩码m和以下操作

  1. 向左/向右移动
  2. 和/或
  3. 加/减/乘

我可以将k压缩成以下内容 [1 2 5 4]

这是我目前的做法(MATLAB伪代码):

function out = compact( in )
    d = in
    for i = 1:size(in, 2) %do (# of items in in) passes
        m = d > 0
        %shift left, pad w/ 0 on right
        ml = [m(2:end) 0] % shift
        dl = [d(2:end) 0] % shift

        %if …
Run Code Online (Sandbox Code Playgroud)

algorithm matlab sse simd

22
推荐指数
2
解决办法
2936
查看次数

递归与迭代图遍历中的内存利用率

我已经看了一些像Heapy这样的常用工具来衡量每种遍历技术使用了多少内存,但我不知道他们是否给了我正确的结果.这是给出上下文的一些代码.

代码只是测量图中唯一节点的数量.提供了两种遍历技术.count_bfscount_dfs

import sys
from guppy import hpy
class Graph:
    def __init__(self, key):
        self.key = key       #unique id for a vertex 
        self.connections = []
        self.visited = False 

def count_bfs(start):
    parents = [start]
    children = []
    count = 0
    while parents:
        for ind in parents:
            if not ind.visited:
                count += 1
                ind.visited = True
                for child in ind.connections:
                        children.append(child)

        parents = children
        children = []
    return count

def count_dfs(start):
    if not start.visited:
          start.visited = True
    else: …
Run Code Online (Sandbox Code Playgroud)

python memory iteration recursion stack

7
推荐指数
1
解决办法
883
查看次数

评论块与emacs中的明星

需要执行哪些设置和命令才能在emacs中执行此类注释:

  /**
   * 
   * something here
   */
Run Code Online (Sandbox Code Playgroud)

谢谢.

emacs comments

6
推荐指数
1
解决办法
2050
查看次数

找到两个排序数组的交集,在某些情况下需要少于O(m + n)个比较

这是在两个数组的O(m+n)位置mn长度中执行此操作的一种方法:

import random

def comm_seq(arr_1, arr_2):
    if len(arr_1) == 0 or len(arr_2) == 0:
        return []

    m = len(arr_1) - 1
    n = len(arr_2) - 1

    if arr_1[m] == arr_2[n]:
        return comm_seq(arr_1[:-1], arr_2[:-1]) + [arr_1[m]]

    elif arr_1[m] < arr_2[n]:
        return comm_seq(arr_1, arr_2[:-1])

    elif arr_1[m] > arr_2[n]:
        return comm_seq(arr_1[:-1], arr_2)


if __name__ == "__main__":
    arr_1 = [random.randrange(0,5) for _ in xrange(10)]
    arr_2 = [random.randrange(0,5) for _ in xrange(10)]
    arr_1.sort()
    arr_2.sort()
    print comm_seq(arr_1, arr_2)
Run Code Online (Sandbox Code Playgroud)

有些技术在某些情况下使用的O(m+n) …

python algorithm performance

5
推荐指数
2
解决办法
1753
查看次数

使用带有类指针的qsort()

我正在使用内置函数qsort()来对class item指针向量进行排序.

class item {
int value;
vector<char> c;
...
...
};

//Declaration of vector
vector<item*> items;

//Function Call
qsort(&items, items.size(), sizeof(item*), value_sort);

int value_sort(const void* a, const void* b)
{
item* pa = *(item**) a;
item* pb = *(item**) b;

if (pb->value < pa->value)
    return 1;
else if (pa->value < pb->value)
    return -1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)

在调试器模式下,指针既不指向pa也不pb指向有效位置.由class items指向的所有数据成员集合papb包含垃圾值.我哪里弄错了?我也不确定双指针的用法.

谢谢.

c++ pointers std visual-studio-2010 qsort

4
推荐指数
1
解决办法
7135
查看次数

通过附加向量在方案中突变向量

我不知道Scheme中向量的底层实现,因此不知道如何编写 vector-append!

原型:

(define (vector-append! vect . vects)
  ; definition here 
  )
Run Code Online (Sandbox Code Playgroud)

PS首选使用向量列表,因为vector-ref是一个恒定时间操作[src]

scheme functional-programming vector mit-scheme

4
推荐指数
1
解决办法
963
查看次数

类初始化时的解引用变量

这是我初始化类字典的代码:

class Directory:
    def __init__(self, **kwds):
        self.__dict__.update(kwds)
obj = Directory(name=dict())
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,密钥是name,并且可以使用:obj.__dict__.['name']或访问 obj.name

Q1.如何使用键值作为变量的值来初始化类字典?

代码应该看起来像:

name = 'bin'
obj = Directory(name=dict()) #here I want the variable `name` to be replaced by its value i.e. `bin`
Run Code Online (Sandbox Code Playgroud)

问.还有其他最佳实施方法吗?(可能是__slots__)

谢谢!

python dictionary

3
推荐指数
1
解决办法
1007
查看次数

通过Python中的子类扩展类型

这是从Learning Python第4版中提取的.它的功能是使用list子类设置.但我不明白第5行list.__init__([]),请帮忙.即使我注释掉这行代码,代码也能正常工作.为什么?

### file: setsubclass.py

class Set(list):
    def __init__(self, value = []):      # Constructor
        list.__init__([])                # Customizes list 
        self.concat(value)               # Copies mutable defaults

    def intersect(self, other):          # other is any sequence
        res = []                         # self is the subject
        for x in self:
            if x in other:               # Pick common items
                res.append(x)
        return Set(res)                  # Return a new Set

    def union(self, other):              # other is any sequence
        res = Set(self)                  # Copy me and my list
        res.concat(other)
        return …
Run Code Online (Sandbox Code Playgroud)

python

3
推荐指数
1
解决办法
174
查看次数

在两个进程之间共享资源

我想知道在Python中两个进程之间共享队列(资源)所遵循的最佳实践。这是每个进程正在做的事情:

Process_1:从流式API连续获取数据(JSON格式)

Process_2:是一个守护程序(类似于Sander Marechal的代码),它将数据(一次一个)提交到数据库中

因此,Process_1(或Producer)将一个数据单元放到此共享资源上,而Process_2(或Consumer)将在此共享资源中轮询任何新的数据单元,并将它们存储在DB中(如果有)。

我想到了一些选择:

  • 使用泡菜(缺点:酸洗和去酸洗的额外开销)
  • 通过stdoutProcess_1到stdinProcess_2 传递数据(缺点:无,但不确定如何通过守护程序实现)
  • 使用库中的pool对象multiprocessing(缺点:不确定如何将其编码为一个进程是守护程序)

我想要在这方面实践最佳的解决方案,并附上一些代码:)。谢谢。

python producer-consumer shared-resource

2
推荐指数
1
解决办法
3384
查看次数

比较两个字符串C++

你能简单地比较两个字符串string1==string2吗?

void ex_file_licensing::compare_license(const std::string &reference,
                                        const std::string &result)
{
    if (reference == result)
        cout << "It's the same" << endl;
    else 
        cout << "It's diffrent" << endl;
    return;
}
Run Code Online (Sandbox Code Playgroud)

如果是,此代码将正常工作或我应该进行一些修改.

感谢大家

c++ string

1
推荐指数
2
解决办法
1万
查看次数