小编tij*_*jko的帖子

pygame mainloop中的扭曲客户端?

我正在尝试使用pygame-clients运行一个扭曲的服务器:

class ChatClientProtocol(LineReceiver):
    def lineReceived(self,line):
        print (line)

class ChatClient(ClientFactory):
    def __init__(self):
        self.protocol = ChatClientProtocol

def main():
    flag = 0
    default_screen()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
               return
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                pos = pygame.mouse.get_pos()
                # some rect.collidepoint(pos) rest of loop... 
Run Code Online (Sandbox Code Playgroud)

这是服务器:

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor

class Chat(LineReceiver):
    def __init__(self, users, players):
        self.users = users
        self.name …
Run Code Online (Sandbox Code Playgroud)

python program-entry-point pygame twisted

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

Valgrind读取大小无效1

对于我的生活,我无法解决为什么我得到一个invalid read size of 1这个代码片段,我很确定它与我有关虐待char *url pointer...

char *extractURL(char request[])
{
char *space = malloc(sizeof(char *));
space = strchr(request, ' ')+1;
char *hostend = malloc(sizeof(char *));
hostend = strchr(request, '\r');
int length = hostend - space;
if (length > 0)
{
    printf("Mallocing %d bytes for url\n.", length+1);
    char *url = (char *)malloc((length+1)*sizeof(char));
    url = '\0';
    strncat(url, space, length);
    return url;
}
//else we have hit an error so return NULL
return NULL;    
}
Run Code Online (Sandbox Code Playgroud)

我得到的valgrind错误是:

==4156== Invalid …
Run Code Online (Sandbox Code Playgroud)

c valgrind

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

sqlite从事务转换到保存点

SQLite的应用程序目前使用事务 - 既可以回滚也可以提高性能.我正在考虑用保存点替换所有交易.其原因是,应用程序是多线程的(是的,sqlite配置是线程安全的),并且在某些情况下,事务可能由两个线程在同一时间开始(在同一分贝).

  1. 有理由不这样做吗?
  2. 我需要注意哪些陷阱?
  3. 难道我只是代替BEGIN,COMMIT,ROLLBACKSAVEPOINT xyz,RELEASE SAVEPOINT xyz,ROLLBACK TO SAVEPOINT xyz

sql sqlite multithreading transactions savepoints

5
推荐指数
1
解决办法
2150
查看次数

贪心算法和硬币算法?

我一直致力于项目Euler的一些问题/练习,希望练习/学习一些最佳算法和使用python编程习语.

我遇到了一个问题,要求找到所有使用至少两个值总和为100的独特组合.在研究这个问题时,我遇到了人们提到硬币问题和贪婪算法,这就是这个问题的意义所在.

我之前听说过贪婪的算法,但从未理解或使用它.我以为我会尝试一下.我仍然不确定这是否是正确的做法.

def greedy(amount):
    combos = {}
    ways = {}
    denominations = [1,5,10,25]
    ## work backwards? ##
    denominations.reverse()
    for i in denominations:
    ## check to see current denominations maximum use ##
        v = amount / i
        k = amount % i
    ## grab the remainder in a variable and use this in a while loop ##
        ways.update({i:v})
    ## update dictionarys ##
        combos.update({i:ways})
        while k != 0:
            for j in denominations:
                if j <= k:
                    n = k/j
                    k = …
Run Code Online (Sandbox Code Playgroud)

python algorithm optimization

5
推荐指数
1
解决办法
8167
查看次数

Tkinter.在方法冻结窗口之后?

我有一个简单的聊天客户端,我试图将其Tkinter作为界面使用.我的问题是,当为聊天输入/输出运行mainloopwith 时.after,窗口会冻结并阻塞,直到收到另一条消息.

class Client(Frame):

    def __init__(self, **kwargs):
        Frame.__init__(self, Tk())
        self.pack()

        self.lb = Listbox(self, width=100, height=30)
        self.lb.pack()

        self.show_data = self.lb.after(1000, self.chat_handle)

        self.entry = Entry(self)
        self.entry.bind('<Return>', self.input_handle)
        self.entry.pack(side=BOTTOM, fill=X)

    def input_handle(self, event):
        msg = self.entry.get()
        self.entry.delete(0, 'end')
        new_msg = 'privmsg %s :' % self.channel + msg + '\r\n'
        self.client.sendall(new_msg)
        self.lb.insert(END, self.nick + ' | ' + msg)

    def chat_handle(self):
        try:
            self.data = self.client.recvfrom(1024)
        except socket.error:
            self.lb.insert(END, "Bad Connection!")
            return
        if self.data and len(self.data[0]) > 0:
            self.lb.insert(END, …
Run Code Online (Sandbox Code Playgroud)

python sockets events tkinter

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

通用netlink中的策略和属性的概念是什么?

我是netlink编程新手.我正在编写一个generic netlink用于创建netlink协议族的程序.我在互联网上搜索了很多文档,我发现了一些"属性和策略",就像定义一个netlink家庭一样.

我对这些事情感到很困惑.

我发现了关于属性的轰鸣声 linux/netlink.h

 <------- NLA_HDRLEN ------> <-- NLA_ALIGN(payload)-->
+---------------------------+- - -+- - - - - - - - - -+- - -+
|        Header             | Pad |    Payload        | Pad | 
|   (struct nlattr)         | ing |                   | ing |
+---------------------------+- - -+- - - - - - - - - -+- - -+
 <-------------------- nlattr->nla_len -------------->
Run Code Online (Sandbox Code Playgroud)

政策是一系列nla_policy结构.我的问题是:

  1. 标题和属性之间有什么关系?请解释"属性".
  2. 什么是政策,需要什么,为什么我们为此使用数组?

我找到了一些关于"它定义属性类型"的政策,
这是什么意思?我的意思是"属性类型的含义是什么?"

这可能是一个无意义的问题,但我完全感到困惑.我一直试图了解这些事情超过三天,请帮助我.

谢谢..

linux kernel module netlink

5
推荐指数
1
解决办法
2384
查看次数

嵌入式 Python 段错误

我的多线程应用程序在调用PyImport_ImportModule("my_module").

BT 将发布在底部。

一些背景:

  1. 我的应用程序创建许多派生 C++ 类的多个实例,并运行基类的Run()函数,该函数使用虚拟方法来确定要执行的操作。
  2. 一个派生类使用 Python 类, (模块Grasp_Behavior)中的(类)grasp_behavior
  3. 经过大量阅读我已经使用Python API来实现(2)(下面摘录)
  4. 我生成了该类的 2 个实例,并“并行”运行它们(python interpr 并不是真正并行运行)
  5. 我尝试生成该类的另一个实例,段错误位于PyImport_ImportModule

我的想法是,也许我不能在同一个解释器中两次导入模块。但我不知道如何检查它。我想我需要看看是否grasp_behavior在字典中,但我不知道是哪一个,也许我得到了__main__模块的字典?

但我可能是错的,任何建议都会非常有帮助!

在构造函数中:

//Check if Python is Initialized, otherwise initialize it
if(!Py_IsInitialized())
{
    std::cout << "[GraspBehavior] InitPython: Initializing the Python Interpreter" << std::endl;
    Py_Initialize();
    PyEval_InitThreads(); //Initialize Python thread ability
    PyEval_ReleaseLock(); //Release the implicit lock on the Python GIL
}

// --- Handle Imports ----

PyObject * pModule = PyImport_ImportModule("grasp_behavior"); …
Run Code Online (Sandbox Code Playgroud)

c++ python multithreading embedding segmentation-fault

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

插入sqlite3值时Python TypeError?

我一直在学习使用sqlite3和python.现在,我有一个功能,它会在互联网上查找该词的定义.然后我尝试将该单词存储在一个表中,并将定义存储到另一个表中,该表通过外键链接在一起.

像这样:

#! /usr/bin/env python
import mechanize
from BeautifulSoup import BeautifulSoup
import sys
import sqlite3

def dictionary(word):
    br = mechanize.Browser()
    response = br.open('http://www.dictionary.reference.com')
    br.select_form(nr=0)
    br.form['q'] = word 
    br.submit()
    definition = BeautifulSoup(br.response().read())
    trans = definition.findAll('td',{'class':'td3n2'})
    fin = [i.text for i in trans]
    query = {}
    word_count = 1
    def_count = 1
    for i in fin: 
        query[fin.index(i)] = i
    con = sqlite3.connect('vocab.db')
    with con:
        spot = con.cursor()
        spot.execute("SELECT * FROM Words")
        rows = spot.fetchall()
        for row in rows:
            word_count += 1
        spot.execute("INSERT …
Run Code Online (Sandbox Code Playgroud)

python sqlite typeerror

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

用元组切片进行Python字符串插值?

我正在使用python2.7,我想知道使用元组进行pythons字符串插值的原因是什么.TypeErrors在做这么少的代码时,我开始陷入困境:

def show(self):
    self.score()
    print "Player has %s and total %d." % (self.player,self.player_total)
    print "Dealer has %s showing." % self.dealer[:2]
Run Code Online (Sandbox Code Playgroud)

打印:

Player has ('diamond', 'ten', 'diamond', 'eight') and total 18
Traceback (most recent call last):
File "trial.py", line 43, in <module>
    Blackjack().player_options()
  File "trial.py", line 30, in player_options
    self.show()
  File "trial.py", line 27, in show
    print "Dealer has %s showing." % (self.dealer[:2])
TypeError: not all arguments converted during string formatting
Run Code Online (Sandbox Code Playgroud)

所以我发现我需要更改错误来自的第四行,以此:

print "Dealer has %s %s showing." % …
Run Code Online (Sandbox Code Playgroud)

python tuples string-interpolation

4
推荐指数
2
解决办法
1376
查看次数

如何使用 CloudFormation 向 CloudFront 分配提供备用域名 (CNAME)?

我努力了:

"Aliases": ["www.samplewebsite.com","samplewebsite.com"]

但我收到此错误:

Property validation failure: [Encountered unsupported properties in {/DistributionConfig/Origins/0}: [Aliases]]

amazon-web-services amazon-cloudfront aws-cloudformation

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