小编avi*_*avi的帖子

在switch中使用break语句

以下是在switch中使用break语句的给定示例:

let numberSymbol: Character = "?"  // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "?", "?", "?":
    possibleIntegerValue = 1
case "2", "?", "?", "?":
    possibleIntegerValue = 2
case "3", "?", "?", "?":
    possibleIntegerValue = 3
case "4", "?", "?", "?":
    possibleIntegerValue = 4
default:
    break
}
if let integerValue = possibleIntegerValue {
    println("The integer value of \(numberSymbol) is \(integerValue).")
} else {
    println("An integer value could not be found for \(numberSymbol).")
} …
Run Code Online (Sandbox Code Playgroud)

break switch-statement swift

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

比较python中的两个大型列表

我有一个包含大约400个单词的列表.另一个列表列表,其中每个列表包含大约150,000个单词.这份清单有20个这样的清单.

现在我想看看这150,000个单词列表中出现的400个单词中有多少个.我也想从这400个单词中知道一个单词,在150k单词列表中出现多少次,这些单词中出现的最多,多少次等等.

我能想到的唯一解决方案是多项式时间解决方案.这是一个非常糟糕的解决方案,并且会很慢:

for one_list in list_of_150kwords:
    for key in 400_words:
        for word in one_list:
            if key == word:
                # count this word
                # do other stuff
Run Code Online (Sandbox Code Playgroud)

这是一个非常丑陋和糟糕的解决方案,但我想不出更好.我通过将这些列表转换为NumPy数组来尝试使用NumPy:

list_of_150kwords = numpy.array(list_of_150kwords)
...
Run Code Online (Sandbox Code Playgroud)

但我仍觉得它很慢.还有其他方法吗?还是任何图书馆?

python performance numpy list

15
推荐指数
1
解决办法
4595
查看次数

使用CSS创建抽象

我不确定这是正确的标题,如果不是,请随时更改它.我不是母语为英语的人,所以我会尽力在图片的帮助下解释:

在此输入图像描述

让我们假设,我有一个普通的HTML文件.该文件使用按钮并使用一些UI库(如Yahoo Pure).但是我没有使用Pure的类,而是使用我自己的类,让我们调用它myButton,然后使用Pure CSS(或任何其他类).但是怎么样?

在这里,我试图创建一个抽象层,以便我的css文件可以使用一些不同的UI库(无论是bootstrap,纯粹还是基础),代码仍然可以工作.

如果没有这个解决方案,我会这样做(我的初始代码是):

<html>
    <head>
        <link rel="stylesheet" href="http://yahoo-pure.com/pure-min.css">
    </head>
    <body>
        <button class="pure-button" type="button">Some Button</button>
    </body>
</html> 
Run Code Online (Sandbox Code Playgroud)

然后如果我改变主意并决定使用bootstrap:

<html>
    <head>
        <link rel="stylesheet" href="http://twitter-bootstrap.com/bootstrap.css">
    </head>
    <body>
        <button class="btn" type="button">Some Button</button>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

所以我必须在这里做两个更改,一个是源css文件(不是大问题)和按钮类(如果代码很大则是一个非常大的问题).(想象一下,如果我正在使用网格和其他东西,我必须做出的改变)

如果我能做这样的事情怎么办?

<html>
    <head>
        <link rel="stylesheet" href="my-magic-stylesheet.css">
    </head>
    <body>
        <button class="myButton" type="button">Some button</button>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

因此,当我想从Bootstrap切换到Pure时,我只在内部进行更改my-magic-stylesheet.css并且它仍然可以工作.我的HTML文件引用my-magic-stylesheet.css并且my-magic-stylesheet.css可以引用我指定的任何库.

我想到的一个解决方案是,这很简单,我编写了一个python脚本.首先,我记下不同的类及其各自的UI库.然后我将编写一个CSS,我将使用泛型类名称myButton.然后我将这个css作为另一个输入提供给我的脚本,其名称为UI库.该脚本将运行css文件并相应地进行更改.(例如,更改myButtonbtn如果另一个输入到脚本bootstrap)

但有没有更好的方法呢?可能没有使用python脚本?或者您想到的任何解决方案?我也是LESS/SASS等CSS工具的新手.我可以用它们来解决我的问题吗?

html css html5 css3 twitter-bootstrap

9
推荐指数
1
解决办法
451
查看次数

如何使箭头键在MIT Scheme解释器中工作?

我从明安装MIT计划在这里运行的优胜美地在我的笔记本电脑.我可以scheme从终端获得解释器,但我的箭头键似乎都没有工作.对于任何打字错误,我做了我不能回去纠正它.我必须使用退格键或重新输入整个内容.

左箭头打印 ^[[D

右箭头打印 ^[[C

向上箭头打印 ^[[A

向下箭头打印 ^[[B

这是一个截图:

screnshot在工作中显示箭头键,而不是

macos terminal mit-scheme

9
推荐指数
1
解决办法
1403
查看次数

如何使用 MOSS 脚本?

我正在尝试在 Mac OS X 上运行 MOSS,但我不知道自己犯了什么错误。我不确定我是否正确运行命令。我将此文件下载为“苔藓”,授予此执行权限并尝试运行以下命令:

./moss -l python -c "Assignment 1" -d assignment1/
Run Code Online (Sandbox Code Playgroud)

我得到了回应

Checking files . . . 
OK
Run Code Online (Sandbox Code Playgroud)

这是错误的。assignment1 目录有 4 个 python 脚本。两个文件完全相似,一个我重新排列了代码,另一个我更改了变量名称。

我已经发送了注册电子邮件,但没有收到任何回复。所以我使用默认用户 ID 运行代码。

我还尝试通过发送每个 python 文件而不是在目录上运行来运行它,但我仍然得到相同的响应。

./moss -l python -c "Assignment 1" 1.py 2.py 3.py 4.py
Run Code Online (Sandbox Code Playgroud)

perl

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

如何在Tornado中设置“安全”和“ httponly” cookie?

我有一个使用Google Oauth 2.0身份验证的Tornado应用程序,获取电子邮件并将其设置在cookie中。现在,我不希望其他任何人访问此Cookie,复制值并在我的应用程序上获取其他用户的详细信息。所以我要制作这个cookie httponlysecurecookie。但是,当我将这些作为参数传递时,它无法设置Cookie:

self.set_secure_cookie('trakr', email, secure=True, httponly=True)
Run Code Online (Sandbox Code Playgroud)

我正在起诉Tornado 3.2.2和Python 2.7.5。

由于它无法设置Cookie,因此会一直重定向到Google身份验证页面。这是我的代码:

class GAuthLoginHandler(BaseHandler, tornado.auth.GoogleOAuth2Mixin):
    @tornado.gen.coroutine
    def get(self):
        if self.get_current_user():
            self.redirect('/products')
            return

        if self.get_argument('code', False):
            user = yield self.get_authenticated_user(redirect_uri=settings.google_redirect_url,
                code=self.get_argument('code'))
            if not user:
                self.clear_all_cookies() 
                raise tornado.web.HTTPError(500, 'Google authentication failed')

            access_token = str(user['access_token'])
            http_client = self.get_auth_http_client()
            response =  yield http_client.fetch('https://www.googleapis.com/oauth2/v1/userinfo?access_token='+access_token)
            user = json.loads(response.body)
            self.set_secure_cookie('trakr', user['email'], secure=True, httponly=True)
            self.redirect(self.get_argument("next", "/products"))
            return

        elif self.get_secure_cookie('trakr'):
            self.redirect('/products')
            return

        else:
            yield self.authorize_redirect(
                redirect_uri=settings.google_redirect_url,
                client_id=self.settings['google_oauth']['key'],
                scope=['email'],
                response_type='code',
                extra_params={'approval_prompt': 'auto'})
Run Code Online (Sandbox Code Playgroud)

当我删除securehttponly参数时,代码工作正常。如果我只是发送 …

python cookies tornado

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

带有Python的HTTPS服务器

我已经用python编写了一个简单的Web服务器和客户端,以下是我的代码。我要实现HTTPS,因为我正在使用标准SSL库。我正在使用Python 2.7.3。我生成了证书文件并对其进行了自签名。所以我有.crt和.key文件,可以用它们来绑定套接字。

当我从浏览器中浏览证书时,出现异常错误,即证书是自签名的,必须将其添加到异常中。然后就可以了。

我的服务器代码:

import BaseHTTPServer
import urlparse
import urllib 
import SocketServer
import threading
import ssl

HOST_NAME = 'localhost'
PORT_NUMBER = 8089


class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_GET(self):

        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        if self.path == '/get/':
            self.wfile.write('On /get/')
            return
        self.wfile.write('On root')
        return    

    def do_POST(self):
        pass

class ThreadedHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    pass


if __name__ == '__main__':
    httpd = BaseHTTPServer.HTTPServer((HOST_NAME, PORT_NUMBER), Handler)
    httpd.socket = ssl.wrap_socket (httpd.socket, keyfile='my_key.key', certfile='my_cert.crt', server_side=True)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        httpd.server_close()
    print "Server Stopped - %s:%s" % …
Run Code Online (Sandbox Code Playgroud)

python ssl webserver python-requests

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

如何使用Python请求在Amazon S3上执行"PUT"

我正在尝试使用Python请求将文件上传到Amazon S3(Python是v2.7.9,请求是v2.7).遵循完美运行的curl命令:

curl --request PUT --upload-file img.png https://mybucket-dev.s3.amazonaws.com/6b89e187-26fa-11e5-a04f-a45e60d45b53?Signature=Ow%3D&Expires=1436595966&AWSAccessKeyId=AQ
Run Code Online (Sandbox Code Playgroud)

但是当我对请求做同样的事情时,它就失败了.这是我尝试过的:

url = https://mybucket-dev.s3.amazonaws.com/6b89e187-26fa-11e5-a04f-a45e60d45b53?Signature=Ow%3D&Expires=1436595966&AWSAccessKeyId=AQ
requests.put(url, files={'file': base64_encoded_image})
requests.put(url, files={'upload_file': base64_encoded_image})
Run Code Online (Sandbox Code Playgroud)

它失败了403,我得到的回应是:

<Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
Run Code Online (Sandbox Code Playgroud)

然后我以详细模式运行curl:

* Hostname was NOT found in DNS cache
*   Trying 54.231.168.134...
* Connected to mybucket-dev.s3.amazonaws.com (54.231.168.134) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
* Server certificate: *.s3.amazonaws.com
* Server certificate: VeriSign Class 3 Secure Server CA - G3
* Server …
Run Code Online (Sandbox Code Playgroud)

python curl amazon-s3 amazon-web-services python-requests

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

Python记录器格式化不是格式化字符串

以下为 的内容mylogger.py

def get_logger(name='my_super_logger'):
    log = logging.getLogger(name)
    log.setLevel(logging.DEBUG)
    formatter = logging.Formatter(fmt='%(asctime)s %(name)s %(message)s',
                                  datefmt='%m/%d/%Y %I:%M:%S %p')
    if not len(log.handlers):
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        ch.setFormatter(formatter)
        log.addHandler(ch)
    # print(id(log))
    return log
Run Code Online (Sandbox Code Playgroud)

以下是内容myscript.py

from mylogger import get_logger

_logger = get_logger()

_logger.info('trying info')
_logger.debug('trying debug')
Run Code Online (Sandbox Code Playgroud)

然而我面临两个问题。它打印日志两次并且格式化程序每次都不起作用:

09/18/2015 09:59:54 PM my_super_logger trying info 
INFO:my_super_logger:trying info 
09/18/2015 09:59:54 PM my_super_logger trying debug 
DEBUG:my_super_logger:trying debug 
Run Code Online (Sandbox Code Playgroud)

我的代码到底有什么问题get_logger

我需要自定义格式。但是我发现,如果不添加处理程序,我就无法添加formatter. 这就是我添加的原因StreamHandler这个答案if中提到了阻止的原因。如果没有它,我会打印重复的日志消息。

python logging python-2.7

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

发送带有机械化和请求的POST。

我正在尝试使用机械化发送POST,但是我的代码有时无法正常工作(我知道为什么)。我已经使用机械化,斜纹布和要求。机械化和斜纹化处理有效,而对请求不起作用。可能是我做错了。

我的机械化代码。以下作品:

#!/usr/bin/env python
import sys
import urllib
import mechanize
from mechanize import ParseResponse, urlopen, urljoin
response = urlopen(url)
forms = ParseResponse(response, backwards_compat=False)
form = forms[0]
form["username"] = "avi"
form["password"] = "stackoverflow"
urlopen(form.click())
Run Code Online (Sandbox Code Playgroud)

我的斜纹代码。它也可以工作:

import os
import twill
from twill.commands import *
out = open(os.devnull,"w")
twill.set_output(out)
go(url)
formvalue("1", "username", "avi")
formvalue("1", "password", "stackoverflow")
submit()
go(url2) #some protected page
content = show()
print 'content is',content[:100]
Run Code Online (Sandbox Code Playgroud)

据我了解,机械化或斜纹首先获取页面,填写表格并发送表格。但是这里的问题是,有时目标页面显示随机页面,没有任何形式。在那种情况下,我会得到一个错误,显然是因为没有表格可以显示。我不想处理此错误,因为我已经知道帖子的网址。即使显示了一些随机页面,我单击下一步后,也会加载相同的表单。POST网址的所有字段均保持不变。所以我想直接发送POST请求,因为我已经知道了所需的所有细节。这是我的代码,基于

browser = mechanize.Browser()
parameters = {"username" : "avi",
          "password" : "stackoverflow",
         }  
data …
Run Code Online (Sandbox Code Playgroud)

python csrf twill python-requests mechanize-python

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