repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
geekosphere/zgeist | test/routes/test_frontend.py | Python | agpl-3.0 | 715 | 0.005594 | """
Test Frontend
"""
import json
from nose.tools import *
from datetime import date | time
from zg.error import NotFound |
from zg.objects import Item, Tag
from zg.objects.event import EventRecorder
from zg.app import app
def test_index():
with app.test_client() as client:
rv = client.get('/')
assert_in('/upload', rv.headers['Location'])
def test_upload():
with app.test_client() as client:
rv = client.get... |
midokura/python-midonetclient | script/remove-tags.py | Python | apache-2.0 | 519 | 0.009634 | #!/usr/bin/env python
from midonetclient.api import MidonetApi
import sys
def main():
mn_uri = 'http://localhost:8081'
my_laptop = 'c1b9eb8a-c83b-43d3-b7b8-8613f921dbe7'
mc = MidonetApi(mn_uri, 'admin', 'password')
bridges = mc.get_bridges({'tenant_id': my_laptop})
for bridge in bridges:
pr... | print("Deleting tag: %s" % tag.get_tag())
tag.delet | e()
if __name__ == '__main__':
main()
|
papedaniel/oioioi | oioioi/gamification/profile.py | Python | gpl-3.0 | 1,330 | 0.002256 | from django.template.loader import render_to_string
from oioioi.base.menu import OrderedRegistry
from oioioi.gamification.friends import UserFriends
profile_registry = OrderedRegistry()
def profile_section(order):
""" Decorator for registering profile view sections.
The decorat | ed function is passed the request and shown user.
It may return a string, a TemplateResponse or HttpResponseRedirect.
"""
return profile_registry.register_decorator(order)
@profile_section(order=80)
def friend_finder_section( | request, user):
if user != request.user:
return ''
return render_to_string('gamification/profile/invite-friends.html')
@profile_section(order=90)
def invite_list_section(request, user):
if user != request.user:
return ''
requests = UserFriends(user).requests_for_me\
.sele... |
Accent-/WasedaU_Library | wine.py | Python | mit | 1,004 | 0.004202 | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import json
import tim | e
def keys(filename):
with open(filename) as f:
secret_keys = json.load(f)
return secret_keys
def access_listpage(secret_keys, driver):
driver.get("https://wine.wul.waseda.ac.jp/patroninfo*jpn")
time.sleep(5)
elem = | driver.find_element_by_name("extpatid")
elem.send_keys(secret_keys["user"])
elem2 = driver.find_element_by_name("extpatpw")
elem2.send_keys(secret_keys["pw"])
submit = driver.find_element_by_link_text("送信")
submit.click()
time.sleep(5)
list_all = driver.find_element_by_partial_lin... |
MOA-2011/enigma2-plugin-extensions-openwebif | plugin/controllers/views/ajax/satellites.py | Python | gpl-2.0 | 5,571 | 0.013104 | #!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatib... | rs/views/ajax/satellites.tmpl'
__CHEETAH_srcLastModified__ = 'Fri Aug 1 18:30:05 2014'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'
if __CHEETAH_versionTuple__ < | RequiredCheetahVersionTuple:
raise AssertionError(
'This template was compiled with Cheetah version'
' %s. Templates compiled before version %s must be recompiled.'%(
__CHEETAH_version__, RequiredCheetahVersion))
##################################################
## CLASSES
class satellites(T... |
werkzeuge/gimp-plugins-simplest | bdfix.py | Python | mit | 2,693 | 0.025871 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# см. также http://habrahabr.ru/post/135863/
# "Как написать дополнение для GIMP на языке Python"
# Импортируем необходимые модули
from gimpfu import *
## fix
def bdfix(image, drawable, w0, c0, w1, c1):
# for Undo
pdb.gimp_context_push()
pdb.gimp_image_undo_group_start(... | Регистрируем функцию в PDB
register(
"python-fu-bdfix", # Имя регистрируемой функции
"Добавление рамки к изображению", # Информация о дополнении
"Помещает вокруг изображения рамку", # Короткое описание выполняемых скриптом дейст | вий
"Александр Лубягин", # Информация об авторе
"Александр Лубягин", # Информация о правах
"15.01.2015", # Дата изготовления
"Добавить рамку", # Название пункта меню, с помощью которого дополнение будет запускаться
"*", # Типы изображений, с которыми работает дополнение
[
(PF_IMAGE, "image", "Исходное изо... |
kalaspuff/tomodachi | tomodachi/envelope/__init__.py | Python | mit | 1,527 | 0.00262 | from typing import Any, Dict, Tuple, U | nion
__cached_defs: Dict[str, Any] = {}
def __getattr__(name: str) -> Any:
import importlib # noqa # isort:skip
if name in __cached_defs:
return __cached_defs[name]
if name == "JsonBase":
module = importlib.import_module(".json_bas | e", "tomodachi.envelope")
elif name == "ProtobufBase":
try:
module = importlib.import_module(".protobuf_base", "tomodachi.envelope")
except Exception: # pragma: no cover
class ProtobufBase(object):
@classmethod
def validate(cls, **kwargs: Any... |
hail-is/hail | hail/python/hailtop/__init__.py | Python | mit | 332 | 0.003012 | _VE | RSION = None
def version() -> str:
global _VERSION
if _VERSION is None:
import pkg_resources # pylint: disable=import-outside-toplevel
_VERSION = pkg_resources.resource_string(__name__, 'hail_version').decode().strip()
return _VERSION
def pip_version() -> str:
return vers | ion().split('-')[0]
|
OpenDaisy/daisy-api | daisy/search/api/v0_1/search.py | Python | apache-2.0 | 13,617 | 0 | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | olicy.Enforcer()
self.gateway = daisy.gateway.Gateway(
es_api=self.es_api,
policy_enforcer=self.policy)
self.plugins = plugins or []
def search(self, req, query, index, doc_type=None, fie | lds=None, offset=0,
limit=10):
if fields is None:
fields = []
try:
search_repo = self.gateway.get_catalog_search_repo(req.context)
result = search_repo.search(index,
doc_type,
... |
rebost/django | django/conf/project_template/project_name/settings.py | Python | bsd-3-clause | 5,206 | 0.001537 | # Django settings for {{ project_name }} project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '',... | # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices ... | tems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make s... |
Rudde/pyroscope | pyroscope/pyroscope/controllers/error.py | Python | gpl-2.0 | 1,655 | 0.001813 | import cgi
from paste.urlparser import PkgResourcesParser
from pylons import request
from pylons.controllers.util import forward
from pylons.middleware import error_document_template
from webhelpers.html.builder import literal
from pyroscope.lib.base import BaseController
class ErrorController(BaseController):
... | eturn page
def img(self, id):
"""Serve Pylons' stock images"""
return self._ser | ve_file('/'.join(['media/img', id]))
def style(self, id):
"""Serve Pylons' stock stylesheets"""
return self._serve_file('/'.join(['media/style', id]))
def _serve_file(self, path):
""" Call Paste's FileApp (a WSGI application) to serve the file
at the specified path
... |
anhstudios/swganh | data/scripts/templates/object/draft_schematic/droid/component/shared_advanced_droid_frame.py | Python | mit | 465 | 0.047312 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR | EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/droid/component/shared_advanced_droid_frame.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICAT | IONS ####
return result |
markruys/gw2pvo | gw2pvo/pvo_api.py | Python | mit | 3,200 | 0.005 | import logging
import time
import requests
__author__ = "Mark Ruys"
__copyright__ = "Copyright 2017, Mark Ruys"
__license__ = "MIT"
__email__ = "mark@paracas.nl"
class PVOutputApi:
def __init__(self, system_id, api_key):
self.m_system_id = system_id
self.m_api_key = api_key
def add_status(se... | }
if temperature is not None:
payload['v5'] = temperature
if voltage is not None:
payload['v6'] = voltage
self | .call("https://pvoutput.org/service/r2/addstatus.jsp", payload)
def add_day(self, data, temperatures):
# Send day data in batches of 30.
for chunk in [ data[i:i + 30] for i in range(0, len(data), 30) ]:
readings = []
for reading in chunk:
dt = reading['dt']... |
xenoxaos/pithos | pithos/pithosconfig.py | Python | gpl-3.0 | 2,682 | 0.008576 | # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*-
### BEGIN LICENSE
# Copyright (C) 2010-2012 Kevin Mehall <km@kevinmehall.net>
#This program is free software: you can redistribute it and/or modify it
#under the terms of the GNU General Public License version 3, as published
#by the Free Software Foundation... | opy of the GNU General Public License along
#with this program. If not, see <http://www.gnu.org/licenses/>.
### END LICENSE |
# where your project will head for your data (for instance, images and ui files)
# by default, this is data, relative your trunk layout
__pithos_data_directory__ = 'data/'
__license__ = 'GPL-3'
VERSION = '1.1.1'
import os
class project_path_not_found(Exception):
pass
ui_files = {
'about': 'AboutPithosDial... |
cbednarski/ifs-python | ifs/source/nginx.py | Python | isc | 644 | 0 | version = '1.10.0'
version_cmd = 'nginx -v'
depends = ['buil | d-essential', 'libpcre3-dev', 'zlib1g-dev', 'libssl-dev']
download_url = 'http://nginx.org/download/nginx-VERSION.tar.gz'
install_script = """
tar -xzf nginx-VERSION.tar.gz
cd nginx-VERSION/
./configure \
--with-http_ssl_module \
--with-http_auth_request_module \
| --prefix=/etc/nginx \
--conf-path=/etc/nginx/nginx.conf \
--sbin-path=/usr/sbin/nginx \
--pid-path=/var/run/nginx.pid \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log
make
make install
mkdir -p /etc/nginx/sites-enabled
chmod -R 0700 /etc/nginx
"""
|
its-dirg/Flask-pyoidc | tests/test_redirect_uri_config.py | Python | apache-2.0 | 1,687 | 0.003557 | import pytest
from flask_pyoidc.redirect_uri_config import RedirectUriConfig
class TestRedirectUriConfig(object):
LEGACY_CONFIG = {'SERVER_NAME': 'example.com', 'PREFERRED_URL_SCHEME': ' | http'}
def test_legacy_config_defaults(self):
config = RedirectUriConfig.from_config(self.LEGACY_CONFIG)
assert config.endpoint == 'redirect_uri'
assert config.full_uri == 'http://example.com/redirect_uri'
def test_legacy_config_endpoint(self):
config = RedirectUriConfig.from_c... | LEGACY_CONFIG})
assert config.endpoint == 'foo'
def test_legacy_config_domain(self):
config = {
'OIDC_REDIRECT_DOMAIN': 'other.example.com:6000', # should be preferred over SERVER_NAME
**self.LEGACY_CONFIG
}
redirect_uri_config = RedirectUriConfig.from_confi... |
wmles/scholarium | Scholien/migrations/0002_auto_20170225_1111.py | Python | bsd-2-clause | 552 | 0.001812 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-02-25 11:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Scholien', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... | migrations.RemoveField(
model_name='artikel',
name | ='titel',
),
]
|
Laurawly/tvm-1 | tests/python/driver/tvmc/test_model.py | Python | apache-2.0 | 2,481 | 0.000806 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apach | e License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on... |
# under the License.
import pytest
import os
from os import path
from tvm.driver import tvmc
from tvm.driver.tvmc.model import TVMCModel, TVMCPackage, TVMCResult
from tvm.runtime.module import BenchmarkResult
def test_tvmc_workflow(keras_simple):
pytest.importorskip("tensorflow")
tvmc_model = tvmc.load(ke... |
Sarvatt/backports | lib/bpgpg.py | Python | gpl-2.0 | 625 | 0.008 | import subprocess | , os
class GpgError(Exception):
pass
class ExecutionError(GpgError):
def __init__(self, errcode):
self.error_code = errcode
def sign(input_file, extra_args=[]):
cmd = ['gpg', '--sign']
cmd.extend(extra_args)
cmd.append(input_file)
process = subprocess.Popen(cmd,
... | universal_newlines=True)
stdout = process.communicate()[0]
process.wait()
if process.returncode != 0:
raise ExecutionError(process.returncode)
return stdout
|
gmfrasca/pointstreak-groupme | psgroupme/util/encode_strings.py | Python | gpl-3.0 | 337 | 0 | def encode_strings(data):
if isinstance(data, str):
| return str(data)
elif isinstance(data, list):
return [encode_strings(x) for x in data]
elif isinstance(data, dict):
res = {}
for k, v in data.items():
res[encode_strings(k)] = | encode_strings(v)
return res
return data
|
cr/fxos-certsuite | web-platform-tests/tests/eventsource/resources/cors-cookie.py | Python | mpl-2.0 | 1,220 | 0.003279 | from datetime import datetime
def main(request, response):
last_event_id = request.headers.get("Last-Event-Id", "")
ident = request.GET.first('ident', "test")
cookie = "COOKIE" if ident in request.cookies else "NO_COOKIE"
origin = request.GET.first('origin', request.headers["origin"])
credentials =... | ders.append(("Content-Type", "text/event-stream"))
response.set_cookie(ident, "COOKIE")
data = "id: 1\nretry: 200\ndata: first %s\n\n" % cookie
elif last_event_id == '1':
headers.append(("Content-Type", "text/event-stream"))
long_long_time_ago = datetime.now().repl | ace(year=2001, month=7, day=27)
response.set_cookie(ident, "COOKIE", expires=long_long_time_ago)
data = "id: 2\ndata: second %s\n\n" % cookie
else:
headers.append(("Content-Type", "stop"))
data = "data: " + last_event_id + cookie + "\n\n";
return headers, data
|
openspending/os-conductor | conductor/app.py | Python | mit | 1,606 | 0.004359 | import os
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '../.env')
load_dotenv(dotenv_path)
# pylama:ignore=E402
from flask import Flask
from flask.ext.cors import CORS
from flask.ext.session import Session
from werkzeug.contrib.fixers import ProxyFix
from raven.contrib.flask i... | .init_app(app)
# Register blueprints
logger.info("Creating Datastore Blueprint")
app.register_blueprint(datastore.create(), url_prefix='/datastore/')
logger.info("Creating Package Blueprint")
app.register_blueprint(package.create(), url_prefix='/package/')
logger.info("Creating Authentication B... | ')
logger.info("Creating Users Blueprint")
app.register_blueprint(user.create(), url_prefix='/user/')
logger.info("Creating Search Blueprint")
app.register_blueprint(search.create(), url_prefix='/search/')
# Return application
return app
|
eric-stanley/NewsBlur | apps/profile/urls.py | Python | mit | 1,662 | 0.006017 | from django.conf.urls import *
from apps.profile import views
urlpatterns = patterns('',
url(r'^get_preferences?/?', views.get_preference),
url(r'^set_preference/?', views.set_preference),
url(r'^set_account_settings/?', views.set_account_settings),
url(r'^get_view_setting/?', views.get_view_setting),
... | rl(r'^activities/?', views.load_activities, name='profile-activities'),
url(r'^payment_hi | story/?', views.payment_history, name='profile-payment-history'),
url(r'^cancel_premium/?', views.cancel_premium, name='profile-cancel-premium'),
url(r'^refund_premium/?', views.refund_premium, name='profile-refund-premium'),
url(r'^upgrade_premium/?', views.upgrade_premium, name='profile-upgrade-premium'),... |
mistercrunch/airflow | airflow/providers/microsoft/azure/hooks/fileshare.py | Python | apache-2.0 | 13,121 | 0.002439 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | tr, directory_name: Optional[str] = None, **kwargs
) -> list:
"""
Return the list of directories and files stored on a Azure File Share.
:param share_name: Name of the share.
:type share_name: str
:param directory_name: Name of the directory.
:type | directory_name: str
:param kwargs: Optional keyword arguments that
`FileService.list_directories_and_files()` takes.
:type kwargs: object
:return: A list of files and directories
:rtype: list
"""
return self.get_conn().list_directories_and_files(share_name, d... |
erick84/uip-iiiq2016-prog3 | laboratorio3/Juanelcallado/Juan.py | Python | mit | 284 | 0.007042 | print("hola me llamo juan")
a = 'ofi'
b = 'chilea'
c = 'Mmm'
d = 'me da igual'
bandera = True
carac = input()
if carac.endswith('?'): |
print(a)
elif carac.isupper():
print (b)
elif carac.isalnum():
print(d)
else:
| print(c)
|
planetlab/NodeManager | plugins/sliverauth.py | Python | bsd-3-clause | 5,118 | 0.016999 | #!/usr/bin/python -tt
# vim:set ts=4 sw=4 expandtab:
#
# NodeManager plugin for creating credentials in slivers
# (*) empower slivers to make API calls throught hmac
# (*) also create a ssh key - used by the OMF resource controller
# for authenticating itself with its Experiment Controller
# in order to avoid spam... | th):
keyfile = '%s/key' % path
if (tools.replace_file_with_string(keyfile,hmac,chmod=0400)):
logger.log ("sliverauth: (o | ver)wrote hmac into %s " % keyfile)
# create the key if needed and returns the key contents
def generate_sshkey (sliver):
# initial version was storing stuff in the sliver directly
# keyfile="/vservers/%s/home/%s/.ssh/id_rsa"%(sliver['name'],sliver['name'])
# we're now storing this in the same place as the authori... |
qiyuangong/Machine_Learning_in_Action_QYG | 03_ID3/treePlotter.py | Python | mit | 3,229 | 0.001548 | import matplotlib
import matplotlib.pyplot as plt
decisionNoe = dict(boxstyle="sawtooth", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")
def plotNoe(nodeTxt, centerPt, parentPt, nodeType):
createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction',
... | oe)
secondDict = myTree[firstStr]
plotTree.yoff = plotTree.yoff - 1.0 / plotTree.totalD
for key in secondDict.keys(): |
if type(secondDict[key]).__name__ == 'dict':
plotTree(secondDict[key], cntrPt, str(key))
else:
plotTree.xoff = plotTree.xoff + 1.0 / plotTree.totalW
plotNoe(secondDict[key], (plotTree.xoff, plotTree.yoff), cntrPt, leafNode)
plotMidText((plotTree.xoff, plo... |
matclayton/OpenSocial-Python | tests/run_online_tests.py | Python | apache-2.0 | 1,350 | 0.004444 | #!/usr/bin/python
#
# Copyright (C) 2007, 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | ing permissions and
# limitations under the License.
__author__ = 'davidbyttow@google.com (David Byttow)'
import module_test_runner
import opensocial_tests.orkut_test
import opensocial_tests.myspace_test
import opensocial_tests.partuza_test
import opensocial_tests.oauth_test
import opensocial_tests.google_sandbox_t... | ():
test_runner = module_test_runner.ModuleTestRunner()
test_runner.modules = [
opensocial_tests.orkut_test,
opensocial_tests.myspace_test,
opensocial_tests.myspace09_test,
opensocial_tests.partuza_test,
opensocial_tests.oauth_test,
opensocial_tests.google... |
AEDA-Solutions/matweb | backend/Models/Sala/RespostaListar.py | Python | mit | 224 | 0.026786 | from Framework.Resposta impo | rt Resposta
from Models.Sala.Sala import Sala as ModelSala
class RespostaListar(Resposta):
def __init__(self,salas):
self.corpo = []
for sala in salas:
self.corpo.append(ModelSa | la(sala))
|
ojii/django-nani | hvad/tests/fieldtranslator.py | Python | bsd-3-clause | 971 | 0.00309 | # -*- coding: utf-8 -*-
from hv | ad.fieldtranslator import translate
from hvad.test_utils.testcase import NaniTestCase
from testproject.app.models import Related
class FieldtranslatorTests(NaniTestCase):
def test_simple(self):
INPUT = 'normal__shared_field' |
query_string, joins = translate(INPUT, Related)
self.assertEqual(query_string, INPUT)
self.assertEqual(joins, ['normal__translations__language_code'])
def test_query_bit(self):
INPUT = 'normal__shared_field__exact'
query_string, joins = translate(INPUT, Related)
... |
inkenbrandt/Snake_Valley | untitled1.py | Python | gpl-2.0 | 205 | 0.009756 | # -*- coding: utf | -8 -*-
"""
Created on Mon Jul 13 09:11:25 2015
@author: paulinkenbrandt
"""
import py_compile
py_compile.compile("C:\\Users\\PAULINKENBRANDT\\Documents\\GitHub\\Snak | e_Valley\\snake.py") |
roycem90/python-o365 | tests/test_attachment.py | Python | apache-2.0 | 1,812 | 0.032561 | from O365 import attachment
import unittest
import json
import base64
from random import randint
att_rep = open('attachment.json','r').read()
att_j = json.loads(att_r | ep)
class TestAttachment (unittest.TestCase):
def setUp(self):
self.att = attachment.Attachment(att_j['value'][0])
def test_isType(self):
| self.assertTrue(self.att.isType('txt'))
def test_getType(self):
self.assertEqual(self.att.getType(),'.txt')
def test_save(self):
name = self.att.json['Name']
name1 = self.newFileName(name)
self.att.json['Name'] = name1
self.assertTrue(self.att.save('/tmp'))
with open('/tmp/'+name1,'r') as ins:
f = in... |
adrn/MDM | mdm/triand.py | Python | mit | 1,923 | 0.00416 | # coding: utf-8
""" TriAnd RR Lyrae """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Standard library
import os, sys
from datetime import datetime, timedelta
# Third-party
import astropy.coordinates as coord
import astropy.units as u
from astropy.io import ascii
f... | ='rhjd0'))
RRLyr_stds2['ra'] = [coord.Angle(x, unit=u.hour).degree for x in RRLyr_stds2['ra_str']]
RRLyr_stds2['dec'] = [coord.Angle(x, unit=u.degree).degree for x in RRLyr_stds2['dec_str']]
standards = join(RRLyr_stds1, RRLyr_stds2, join_type='outer')
all_stars = join(stars, RRLyr_stds1, join_type='outer')
all_stars ... | ars, RRLyr_stds2, join_type='outer')
triand_stars = stars |
exepulveda/swfc | python/clustering_ga.py | Python | gpl-3.0 | 15,844 | 0.02796 | import sys
import logging
import collections
import math
import sys
sys.path += ['..']
import clusteringlib as cl
import numpy as np
from deap import algorithms
from deap import base
from deap import creator
from deap import tools
from copy import deepcopy
from cluster_utils import fix_weights
class CentroidIndiv... | for i in range(self.NC):
for j in range(self.ND): |
if not(self.min_values[j] <= self.centroid[i,j] <= self.max_values[j]):
print(i,j,self.centroid[i,j],self.min_values[j],self.max_values[j])
assert False, "PROBLEM 2222"
def __deepcopy__(self,memo):
return self.clone()
def clo... |
outini/sandcrawler | libraries/sc_systems.py | Python | gpl-3.0 | 6,623 | 0.002265 | # -*- coding: iso-latin-1 -*-
"""
systems specifics for sandcrawler
"""
__docformat__ = 'restructuredtext en'
__author__ = "Denis 'jawa' Pompilio"
__credits__ = "Denis 'jawa' Pompilio"
__license__ = "GPLv3"
__maintainer__ = "Denis 'jawa' Pompilio"
__email__ = "denis.pompilio@gmail.com"
__status__ = "Development"
impo... | s if found
try:
__import__(module)
return sys.modules[module]
except ImportError:
LOG.log_d("module '%s' not found" % (module))
return None
def retriev_attrs_and_methods(self, modules_list):
""" retrieve a | ttributes and methods from each module """
for mod in modules_list:
LOG.log_d("importing from %s" % (mod.__name__))
for attr in dir(mod):
# import everything but builtins and privates
if attr[0:2] == "__":
continue
modu... |
franek/weboob | modules/attilasub/__init__.py | Python | agpl-3.0 | 802 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Julien Veyssier
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | blic License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
from .backend import AttilasubBacke | nd
__all__ = ['AttilasubBackend']
|
liuguoyaolgy/Stock | m_wangge.py | Python | gpl-2.0 | 13,472 | 0.017862 |
import tushare as ts
from m_load_update_data import load
import m_draw
import matplotlib.pyplot as plt
import string
import m_smtp
import datetime
price = ''
class cw_dsp():
def __init__(self):
self.bishu=0.0
self.buyamt=0.0
self.buyprice=0.0
class CW():
def __init__(self):
se... | cw.jycnt += 1
return
if 4 == cw.bili and 5 == cwno:
print('amtdiff:',cw.bili,date,round(cw.C5.buyprice,2),'->',round(price,2),round(cw.C5.bishu*price*100-cw.C5.buyamt))
cw.bili -= 1
| cw.remainder_Amt += cw.C5.bishu*price*100
cw.C5.bishu = 0.0
cw.C5.buyamt = 0.0
cw.C5.buyprice = 0.0
cw.jycnt += 1
return
if 5 == cw.bili and 6 == cwno:
print('amtdiff:',cw.bili,date,round(cw.C6.buyprice,2),'->',round(price,2),round(cw.C... |
Saevon/AnkiHelpers | kana.py | Python | mit | 7,233 | 0.003811 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from jcconv import kata2hira, hira2kata
from itertools import chain
from printable import PrintableDict, PrintableList
__by_vowels = PrintableDict(**{
u'ア': u'ワラヤャマハナタサカアァ',
u'イ': u'リミヒニちシキイィ',
u'ウ': u'ルユュムフヌツスクウゥ',
... | ef __is_katakana(char):
return char in KATAKANA
def is_katakana(string):
for char in string:
if not __is_katakana(char):
return False
return True
def __is_h | iragana(char):
return char in HIRAGANA
def is_hiragana(string):
for char in string:
if not __is_hiragana(char):
return False
return True
def __is_kana(char):
return char in KANA
def is_kana(string):
for char in string:
if not __is_kana(char):
return False
... |
westurner/i3wm-formula | tests/test_i3wm-formula.py | Python | bsd-3-clause | 407 | 0.004914 | #!/usr/bin/env python
# -*- codi | ng: utf-8 -*-
"""
test_i3wm-formula
----------------------------------
Tests for `i3wm-formula` module.
"""
import unittest
fro | m i3wm-formula import i3wm-formula
class TestI3wm-formula(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main() |
benkonrath/transip-api | transip/service/webhosting.py | Python | mit | 2,545 | 0.00275 | """
Implementation of the WebhostingService API endpoint
"""
from transip.client import MODE_RW, Client
class WebhostingService(Client):
"""
Transip_WebhostingService
"""
def __init__(self, *args, **kwargs):
super().__init__('WebhostingService', *args, **kwargs)
def get_webhosting_domain... | ostingService::modifyMailBox
"""
return self._simple_request('modifyMailB | ox', domain, mailbox, mode=MODE_RW)
def delete_mailbox(self, domain, mailbox):
"""
Transip_WebhostingService::deleteMailBox
"""
return self._simple_request('deleteMailBox', domain, mailbox, mode=MODE_RW)
def create_mail_forward(self, domain, mailforward):
"""
Tr... |
Orav/kbengine | kbe/src/lib/python/Lib/test/test_zipimport.py | Python | lgpl-3.0 | 18,625 | 0.000859 | import sys
import os
import marshal
import importlib.util
import struct
import time
import unittest
from test import support
from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED
import zipimport
import linecache
import doctest
import inspect
import io
from traceback import extract_tb, extr... | badtime_pyc[7] ^= 0x02
files = {TESTMOD + ".py": (NOW, test_src),
TESTMOD + pyc_ext: (NOW, badtime_pyc)}
self.doTest(".py", files, TESTMOD)
def testPackage(self):
packdir = TESTPACK + os.sep
files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
... | ef testDeepPackage(self):
packdir = TESTPACK + os.sep
packdir2 = packdir + TESTPACK2 + os.sep
files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}
... |
daviferreira/leticiastallone.com | leticiastallone/blog/migrations/0001_initial.py | Python | mit | 1,393 | 0.006461 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Post'
db.create_table(u'blog_post', (
(u'id', self.gf('django.db.models.fields.A... | e'}),
u'id': ('django | .db.models.fields.AutoField', [], {'primary_key': 'True'}),
'tags': ('django.db.models.fields.TextField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '60'})
}
}
complete_apps = ['blog'] |
1024inc/django-rq | django_rq/management/commands/rqenqueue.py | Python | mit | 1,223 | 0 | from distutils.version import LooseVersion
from django.core.management.base import BaseCommand
from django.utils.version import | get_version
from django_rq import get_queue
class Command(BaseCommand):
"""
Queue a function with the given arguments.
"""
help = __doc__
args = '<function arg arg ...>'
def add_arguments(self, parser):
parser.add_argument('--queue', '-q', dest='queue', default='default',
... | 'Specify the queue [default]')
parser.add_argument('--timeout', '-t', type=int, dest='timeout',
help='A timeout in seconds')
if LooseVersion(get_version()) >= LooseVersion('1.9'):
parser.add_argument('args', nargs='*')
def handle(self, *args, **options):
... |
enigmampc/catalyst | catalyst/exchange/exchange_errors.py | Python | apache-2.0 | 10,006 | 0 | import sys
import traceback
from catalyst.errors import ZiplineError
def silent_except_hook(exctype, excvalue, exctraceback):
if exctype in [PricingDataBeforeTradingError, PricingDataNotLoadedError,
SymbolNotFoundOnExchange, NoDataAvailableOnExchange,
ExchangeAuthEmpty]:
... | , exctraceback)
sy | s.excepthook = silent_except_hook
class ExchangeRequestError(ZiplineError):
msg = (
'Request failed: {error}'
).strip()
class ExchangeRequestErrorTooManyAttempts(ZiplineError):
msg = (
'Request failed: {error}, giving up after {attempts} attempts'
).strip()
class ExchangeBarDataErr... |
yancz1989/cancer | scan.py | Python | mit | 2,610 | 0.012261 | # -*- coding: utf-8 -*-
# @Author: yancz1989
# @Date: 2017-01-17 23:43:18
# @Last Modified by: yancz1989
# @Last Modified time: 2017-02-22 20:33:29
import utilities as util
from utilities import parse_image_file, filterBoxes, voxel_2_world, mkdir
import numpy as np
import os
import json
import sys
from PIL import I... | ext(f)[0]
numpyImage, numpyOrigin, numpySpacing = (
util.load_itk_image(
os.path.join(root, f)))
for z in range(numpyImage.shape[0]):
patch = numpyImage[z, 0:512, 0:512]
patch = util.normalizePlanes(patch)
im = | Image.fromarray(patch * 255).convert('L')
output_filename = (
subset + "-" + key + "-" + str(z) + "-scan.bmp")
print(subset + '/' + output_filename)
im.save(os.path.join(
output_dir, output_filename))
jsobjs.append({
"image_path": subset + ... |
unifispot/unifispot-free | manage.py | Python | mit | 510 | 0.001961 | #! flask/bin/python
from os.path import abspath
fr | om flask import current_app
from flask.ext.script import Manager
from flask.ext.assets import ManageAssets
from flask.ext.migrate import Migrate, MigrateCommand
from bluespot import create_app
from bluespot.extensions import db
| app = create_app(mode='development')
manager = Manager(app)
manager.add_command('assets', ManageAssets())
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
manager.run()
#app.run(host='0.0.0.0',debug = True)
|
adamatus/boldsim | benchmark/benchmark.py | Python | gpl-2.0 | 17,981 | 0.010344 | #!/usr/bin/env python
import numpy as np
import boldsim.sim as sim
import timeit
import argparse
parser = argparse.ArgumentParser(description='Run BOLDsim benchmarks.',
epilog='By default no benchmarks will be run, so make sure to specify one!')
parser.add_argument('-a', '--all', acti... | ,
setup=setup)
run_test('Wholebrain [64x64x32], 200 TRs',
'noise = sim.phys | noise(nscan=200, |
Bedrock02/General-Coding | Sorting/mergesort.py | Python | mit | 1,720 | 0.05 | #!/usr/bin/env python2.7
#Author:Steven Jimenez
#Subject: Python Programming
#HW 1
#Merge Sort that Calls a non-recursive function to sort lists
def mergesort(a):
#if singleton return singleton
if len(a)==1:
return a
#find mindpoint of list
n = len(a)/2
#split the list into sorted halves. left-... | ))
#If one of the lists are empty, send the non empty list to the new list
if len(lft):
sorted.extend(lft);
if len(rgt):
sorted.extend(rgt)
return sorted
#Merge Sort that calls a recursive function to sort list
def mergesort2(a):
#If list is a singleton return singleton
if len(a)==1:
return... | n(a)/2
#Divide current list into two halves and call function to sort
left = mergesort2(a[:n])
right = mergesort2(a[n:])
#Bring together the new sorted lists
return mergelists2(left,right)
def mergelists2(lft,rgt):
#If one list is empty return the other
if lft == []:
return rgt
if r... |
liqd/adhocracy4 | adhocracy4/comments/serializers.py | Python | agpl-3.0 | 7,379 | 0 | import warnings
from django.conf import settings
from django.utils.translation import gettext as _
from rest_framework import serializers
from rest_framework.utils import model_meta
from .models import Comment
class CommentSerializer(serializers.ModelSerializer):
"""Attention: This class is deprecated, use
... | gory')
})
return data
def get_user_name(self, obj):
"""
Don't show username if comment is marked removed or censored
"""
if(obj.is_censored or obj.is_removed):
return _('unknown user')
return str(obj.creator.username)
def get_user_pro... | ttributeError:
return ''
def get_is_moderator(self, obj):
return obj.project.has_moderator(obj.creator)
def get_is_deleted(self, obj):
"""
Returns true is one of the flags is set
"""
return (obj.is_censored or obj.is_removed)
def get_ratings(self, comme... |
SCPR/kpcc_backroom_handshakes | election_registrar/migrations/0006_election_election_kpcc_page.py | Python | mit | 544 | 0.001838 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-03-07 20:43
from __future__ import uni | code_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('election_registrar', '0005_auto_20170307_1104'),
]
operations = [
migrations.AddField(
model_name='election',
name='election_kpcc_page',
f... | .URLField(blank=True, max_length=1024, null=True, verbose_name=b'URL on KPCC.org hosting results'),
),
]
|
pablocarderam/genetargeter | gRNAScores/azimuth/models/DNN.py | Python | mit | 3,012 | 0.001328 | # from copy import deepcopy
#
# import numpy as np
# import theanets
#
# # from ke | ras.wrappers import scikit_learn
# from scipy.stats import spearmanr
# from sklearn.model_selection import StratifiedKFold
# from sklearn.preprocessing import LabelEncoder
#
# from .. import predict
#
#
# def DNN_on_fold(train, test, y_all, X, learn_options):
# y = np.array(y_all[learn_options["DNN target variable... | num_hidden_layers = [1] # , 2, 3]
# num_units = [2] # , 5, 8, 10, 15, 20, 25, 30, 40, 50, 60]
# accuracies = np.zeros((len(num_hidden_layers), len(num_units)))
# best_score = None
# best_model = None
#
# for i, hl in enumerate(num_hidden_layers):
# for j, nu in enumerate(num_units):
# ... |
pbs/thespian | setup.py | Python | unlicense | 630 | 0.001587 | from setuptools import setup, find_packages
def get_dependencies(filename):
dependencies = []
with open("REQUIREMENTS") as f:
dependencies = f.read().splitlines()
return dependencies
setup(
na | me="thespian",
version="0.0.1",
packages=find_packages('src'),
package_dir={'': 'src'},
install_requires=get_dependencies("REQUIREMENTS"),
package_data={
'': ['*.txt'],
},
# metadata for upload to PyPI
author="Radu Ciorba",
author_email="radu.ciorba@3pillarglobal.com",
de... | rocessing based Actor Model",
url="http://github.com/pbs/thespian",
)
|
greggian/TapdIn | django/db/backends/postgresql/client.py | Python | apache-2.0 | 795 | 0.002516 | import os
import sys
from django.db.backends import BaseDatabaseClient
class DatabaseClient(BaseDatabaseClient):
executable_name = 'psql'
def runshell(self):
settings_dict = self.connection.s | ettings_dict
args = [self.executable_name]
if settings_dict['DATABASE_USER']:
args += ["-U", settings_dict['DATABASE_USER']]
if settings_dict['DATABASE_HOST']:
args.extend(["-h", settings_dict['DATABASE_HOST']])
if settings_dict['DATABASE_PORT']:
... | ame == 'nt':
sys.exit(os.system(" ".join(args)))
else:
os.execvp(self.executable_name, args)
|
vel21ripn/nDPI | python/ndpi.py | Python | lgpl-3.0 | 40,747 | 0.001767 | """
file: ndpi.py
This file is part of nfstream.
Copyright (C) 2019-20 - nfstream.org
nfstream is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later versi... | f enum {
NDPI_NO_RISK = 0,
NDPI_URL_POSSIBLE_XSS,
NDPI_URL_POSSIBLE_SQL_INJECTION,
NDPI_URL_POSSIBLE_R | CE_INJECTION,
NDPI_BINARY_APPLICATION_TRANSFER,
NDPI_KNOWN_PROTOCOL_ON_NON_STANDARD_PORT,
NDPI_TLS_SELFSIGNED_CERTIFICATE,
NDPI_TLS_OBSOLETE_VERSION,
NDPI_TLS_WEAK_CIPHER,
NDPI_TLS_CERTIFICATE_EXPIRED,
NDPI_TLS_CERTIFICATE_MISMATCH,
NDPI_HTTP_SUSPICIOUS_USER_AGENT,
NDPI_HTTP_NUMERIC_IP_HOST,
NDPI_HT... |
minhphung171093/OpenERP_V8 | openerp/addons/google_spreadsheet/google_spreadsheet.py | Python | agpl-3.0 | 5,617 | 0.003205 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2012 OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General... | _id, context=None):
access_token = self.get_access_token(cr, uid, scope='https://spreadsheets.google.com/feeds', context=context)
fields = self.pool.get(model).fields_view_get(cr, uid, view_id=view_id, view_type='tree')
doc = etree.XML(fields.get('arch') | )
display_fields = []
for node in doc.xpath("//field"):
if node.get('modifiers'):
modifiers = simplejson.loads(node.get('modifiers'))
if not modifiers.get('invisible') and not modifiers.get('tree_invisible'):
display_fields.append(node.get(... |
widoptimization-willett/feature-extraction | feature_extraction/measurements/__init__.py | Python | apache-2.0 | 885 | 0.030508 | from collections import defaultdict
from ..util import AttributeDict
class Measurement(object):
"""
A generic feature measurement.
Attributes
----------
default_options
Can be set by subclasses to set default option values
"""
default_options = {}
def __init__(self, options=None):
"""
When initializin... | sed to internal algorithms as `self.options`.
Parameters
----------
options : dict
A dict of options for this measurement.
"""
self.options = AttributeDict()
self.options.update(self.default_options or {})
self.options.update(options or {})
from .pixelaverage import PixelAverage
from .texture_haralic... | uler_number import EulerNumber
# from .caffenet import Caffenet
|
daneos/Tango-RedPitaya | src/rp_board/service.py | Python | gpl-2.0 | 875 | 0.049143 | # This file should go to /usr/lib/python2.7/site-packages/PyRedPitaya/ directory on the device's SD card
import rpyc
import os
from raw_memory import BoardRawMemory
class MyService(rpyc.Service):
def on_connect(self):
print | "CONNECTION"
self._mem = BoardRawMemory()
self._conn._config.update(dict(
allow_all_attrs = True,
allow_pickle = False,
allow_getattr = True,
allow_setattr = True,
allow_delattr = True,
import_custom_exceptions = True,
instantiate_custom_exceptions = True,
instantiate_oldstyle_exceptions = ... | # this allows to execute commands on server
def exposed_run_command(self, cmd):
return os.popen(cmd).read()
if __name__=="__main__":
from rpyc.utils.server import ThreadedServer
print 'START SERVER'
t = ThreadedServer(MyService, port = 18861)
t.start()
|
mark-burnett/lsf-python | tests/test_request.py | Python | gpl-3.0 | 376 | 0 | import lsf
import unittest
class RequestTests(unittest.TestCase):
def test_submit_to_default_que | ue(self):
job = lsf.submit('ls')
self.assertGreater(job.job_id, 0)
def test_submit_to_illegal_q | ueue(self):
with self.assertRaises(lsf.exceptions.LSFBindingException):
lsf.submit('ls', options={'queue': 'nonexistantqueuefortesting'})
|
sam-m888/addons-source | PhpGedView/phpgedview.gpr.py | Python | gpl-2.0 | 1,398 | 0.02289 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2007 Martin Hawlisch
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) ... | You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
register(TOOL,
id = 'PhpGedView',
name = _("PhpGedView"),
description = _("Do... | include_in_listing = False,
status = UNSTABLE,
fname = 'phpgedviewconnector.py',
authors = ["Martin Hawlisch"],
authors_email = ["martin.hawlisch@gmx.de"],
category = TOOL_UTILS,
toolclass = 'PHPGedViewConnector',
optionclass = 'phpGedViewImporter',
... |
wgnet/webium | examples/8_finds.py | Python | apache-2.0 | 368 | 0 | from selenium.webdriver.common.by import By
from webium import BasePage, Finds
class LinksPage(BasePage):
l | inks = Finds(by=By. | TAG_NAME, value='a')
def __init__(self):
super(LinksPage, self).__init__(url='http://wargaming.net')
if __name__ == '__main__':
page = LinksPage()
page.open()
print('Number of links: ' + str(len(page.links)))
|
JburkeRSAC/PizzaCat-Web | threat_recon_to_CSV.py | Python | mit | 2,231 | 0.017929 | import urllib
from urllib2 import urlopen, quote
import urllib2
import json
import time
import datetime
import csv
import unicodedata
import sys
timestring = time.time()
formatted_timestring = datetime.datetime.fromtimestamp(timestring).strftime('%Y_%m_%d')
search = sys.argv[1]
api_key = 'YOUR_API_KEY'
def query_th... | e('utf-8')
comment = item["Comment"]
comment2 = unicodedata.normalize('NFKD', comment).encode('ascii','ignore')
confidence = str(item["Confidence"]).decode('utf-8')
indicatorwriter.writerow([indicator,reference,source,killchain,first_seen,last_seen,attribution,process_type,rrname,rdata,r... | country,tags,comment2,confidence])
lenresults = str(len(results))
print csv_file_name
#print lenresults +' records added to CSV'
|
skangas/zombieswtf | scripts/network/packets/client.py | Python | gpl-3.0 | 2,495 | 0.022044 | # -*- coding: utf-8 -*-
########################################################################
# Copyright (C) 2011 The Unknown Horizons Team <team@unknown-horizons.org>
########################################################################
# This file is part of ZombiesWTF.
#
# ZombiesWTF is free software: you can... | he
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ###################################################
from horizons.network.packets import *
class cmd_creategame(packet):
de... | mapname = mapname
self.maxplayers = maxplayers
self.playername = playername
packetlist.append(cmd_creategame)
#-------------------------------------------------------------------------------
class cmd_listgames(packet):
def __init__(self, clientver, mapname = None, maxplayers = None):
self.clientv... |
zzragida/PythonExamples | MemberShip/db/base.py | Python | mit | 2,027 | 0.009867 | # -*- coding:utf-8 -*-
import unittest
from datetime import datetime
from datetime import timedelta
from SQLRelay import PySQLRClient
SQLRELAY_HOST = 'localhost'
SQLRELAY_PORT = 9002
SQLRELAY_USER = 'sqlruser'
SQLRELAY_PASS = 'sqlrpass'
SQLRELAY_DEBUG = False
class SQLRelayTestCase(unittest.TestCase):
"""Base ... | device_platform,
service_platform,
facebook_id = 0,
| facebook_email = None,
facebook_phone = None,
status = 1):
self.cur.prepareQuery('CALL member_info(:app_id, :udid, :device_platform, :service_platform, :facebook_id, :facebook_email, :facebook_phone, :status)')
self.cur.inputBind('app_id', app_i... |
CentechMTL/TableauDeBord | app/experiment/migrations/0005_auto_20160330_1625.py | Python | gpl-3.0 | 919 | 0.003264 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependen | cies = [
('experiment', '0004_auto_20150727_1405'),
]
operations = [
migrations.AlterField(
model_name='customerexperiment',
name='experiment_description',
field=models.TextField(max_length=1024, verbose_name='Experiment description'),
),
migr... | ame='test_subject_count',
field=models.PositiveIntegerField(default=0, verbose_name='Number of test participants'),
),
migrations.AlterField(
model_name='customerexperiment',
name='test_subject_description',
field=models.TextField(max_length=512, verbose_n... |
Naburimannu/libtcodpy-tutorial | components.py | Python | bsd-3-clause | 4,487 | 0 | """
Simple entity system: any renderable Object can have
a number of Components attached.
"""
import math
import algebra
class Object:
"""
This is a generic object: the player, a monster, an item, the stairs...
It's always represented by a character on screen.
"""
def __init__(self, pos, char, nam... | fighter
self._ensure_ownership(fighter)
self.ai = ai
self._ensure_ownership(ai)
self.item = item
self._ensure_ownership(item)
self.equipment = equipment
self. | _ensure_ownership(equipment)
@property
def x(self):
return self.pos.x
@property
def y(self):
return self.pos.y
def _ensure_ownership(self, component):
if (component):
component.set_owner(self)
def distance_to(self, other):
"""
Return the di... |
mchristopher/PokemonGo-DesktopMap | app/pylibs/osx64/Cryptodome/PublicKey/RSA.py | Python | mit | 28,324 | 0.001024 | # ===================================================================
#
# Copyright (c) 2016, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributio... | generate_probable_prime, COMPOSITE)
from Cryptodome.PublicKey import (_expand_subject_public_key_info,
_create_subject_public_key_info,
_extract_subject_public_key_info)
class RsaKey(object):
"""Class defining an actual RSA key.
:undocumented: __... | **kwargs):
"""Build an RSA key.
:Keywords:
n : integer
The modulus.
e : integer
The public exponent.
d : integer
The private exponent. Only required for private keys.
p : integer
The first factor of the modulus. On... |
MediffRobotics/DeepRobotics | DeepRobSite/DeepRobSite/wsgi.py | Python | gpl-3.0 | 399 | 0 | """
WSGI config for DeepRobSite project.
It exposes the WSGI callable as a module- | level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DeepRobSite.settings")
application = get_wsgi_applica | tion()
|
callowayproject/django-staff | staff/settings.py | Python | apache-2.0 | 436 | 0.002294 | from dja | ngo.conf import settings
DEFAULT_SETTINGS = {
'PHOTO_STORAGE': settings.DEFAULT_FILE_STORAGE,
'ORDERING': ('last_name', 'first_name'),
}
USER_SETTINGS = DEFAULT_SETTINGS.copy()
if hasattr(settings, 'STAFF_ORDERING'):
USER_SETTINGS['ORDERING'] = settings.STAFF_ORDERING
if hasattr(set | tings, 'STAFF_PHOTO_STORAGE'):
USER_SETTINGS['PHOTO_STORAGE'] = settings.STAFF_PHOTO_STORAGE
globals().update(USER_SETTINGS) |
LouvainVerificationLab/pynusmv | pynusmv/utils.py | Python | lgpl-3.0 | 22,573 | 0.002614 | """
The :mod:`pynusmv.utils` module contains some secondary functions and classes
used by PyNuSMV internals.
"""
__all__ = ['PointerWrapper', 'fixpoint', 'update', 'StdioFile','writeonly',
'indexed']
from pynusmv_lower_interface.nusmv.utils import utils
from pynusmv.init import _register_wrapper
class ... | output"""
ret = StdioFile("(standard output)", "w")
ret._ptr = utils.stdio_stdout()
ret._isspecial = True
return ret
@staticmethod
def stderr():
"""standard error"""
ret = StdioFile("(standard error)", "w")
ret._ptr = utils.stdio_stderr()
ret._is... | elf):
"""Opens the file"""
if not self._isspecial:
self._ptr = utils.stdio_fopen(self._fname, self._mode)
return self
def __exit__(self, exception_type, exception_value, trace):
"""Makes sure the file is closed"""
if self._ptr is not None and not self._isspecial:... |
indygreg/lua-protobuf | setup.py | Python | apache-2.0 | 1,098 | 0.030055 | # Copyright 2010 Gregory Szorc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | r the License.
from setuptools import setup, find_packages
setup(
name = 'lua-protobuf',
version = '0.0.1',
packages = [ 'lua_protobuf' ],
scripts = ['protoc-gen-lua'],
install_requires = [ 'protobuf>=2.3.0' ],
author = 'Gregory Szorc',
autho... | 'http://github.com/indygreg/lua-protobuf'
)
|
mvaled/sentry | src/sentry/south_migrations/0408_identity_provider_external_id.py | Python | bsd-3-clause | 105,752 | 0.00799 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from sentry.utils.query import RangeQuerySetWrapperWithProgressBar
class Migration(DataMigration):
# Flag to indicate if this migration is too risky
... | eignKey', [], {'to': "orm['sentry.User']", 'null': 'True'})
},
'sentry.apiapplication': {
'Meta': {'object_name': ' | ApiApplication'},
'allowed_origins': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'client_id': ('django.db.models.fields.CharField', [], {'default': "'7659033185d64a589638801d051ec5fa77cdbd017cbe4b6a84bea5d474b31e70'", 'unique': 'True', 'max_length': '64'}),
... |
ajdavis/mongo-mockup-db | docs/conf.py | Python | apache-2.0 | 8,880 | 0.00518 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# mongo-mockup-db documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in th... | ended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by de... | sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# Theme gratefully vendored from CPython source.
html_theme = "pydoctheme"
html_theme_path = ["."]
h... |
foursquare/pants | contrib/python/src/python/pants/contrib/python/checks/tasks/checkstyle/trailing_whitespace.py | Python | apache-2.0 | 2,252 | 0.010657 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import tokenize
from builtins import range
from collections import defaultdict... | en_end[0]):
exception_ranges[line].append((0, sys.maxsize))
exception_ranges[token_end[0]].append((0, token_end[1]))
return exception_ranges
def __init__(self, *args, **kw):
super(TrailingWhitespace, self).__init__(*args, **kw)
self._exception_map = self.build_exception_map(self.pyt... | p.get(line_number, ()):
if start <= exception_start and exception_end <= end:
return True
return False
def nits(self):
for line_number, line in self.python_file.enumerate():
stripped_line = line.rstrip()
if stripped_line != line and not self.has_exception(line_number,
len(... |
imiric/ork | ork/task.py | Python | mit | 1,945 | 0 | import importlib
import functools
import multiprocessing as mp
from .brokers import get_broker
from .config import load_config
_TASK_NAME_PREFIX = 'ork'
def task(name=''):
def _outer_wrapper(wrapped_task):
def delay(*args, **kwargs):
task_name = '{}:{}'.format(
_TASK_NAME_P... | ped_task)
def _wrapper(*args, **kwargs):
return | wrapped_task(*args, **kwargs)
return _wrapper
return _outer_wrapper
class Task:
def __init__(self, name, broker, task=None, *args, **kwargs):
self.name = name
self._broker = broker
self._task = task
self._process = mp.Process(target=self._work, args=args, kwargs=kwargs... |
ciechowoj/haste-format | make_data_t.py | Python | mit | 5,303 | 0.014332 | #!/usr/bin/python3
from itertools import *
KINDS = ['unorm', 'snorm', 'uint', 'sint', 'float']
PRECS = [8, 16, 32, 64]
def value(kind, prec, ndim):
ikind = KINDS.index(kind)
iprec = PRECS.index(prec)
index = ikind * len(PRECS) + iprec
return index << 16 | KINDS.index(kind) << 12 | iprec << 8 | (ndim - 1) << 10 ... | data_t_cpp.write("\n")
data_t_cpp.write("data_t unorm8(size_t components) {\n")
data_t_cpp.write("\tswitch(components) {\n")
| data_t_cpp.write("\t\tcase 1: return data_t::unorm8x1;\n")
data_t_cpp.write("\t\tcase 2: return data_t::unorm8x2;\n")
data_t_cpp.write("\t\tcase 3: return data_t::unorm8x3;\n")
data_t_cpp.write("\t\tcase 4: return data_t::unorm8x4;\n")
data_t_cpp.write("\t\tdefault: return data_t::unorm8x4;\n")
data_t_cpp.write("\t}\n"... |
ayiis/python | pcap_usage.py | Python | mit | 2,503 | 0.003638 | # -*- coding:utf-8 -*-
import socket
import time
import struct
from struct import pack
import traceback
import rand | om
import pcap
import q
def checksum(tcp_header):
s = 0
for i in range(0, len(tcp_header), 2):
w = (tcp_header[i] << 8) + (tcp_header[i + | 1])
s = s + w
s = (s >> 16) + (s & 0xffff)
s = ~s & 0xffff
return s
def pPacket(source_address, source_port, remote_address, remote_port):
get_ipheader = lambda iph_checksum: pack("!BBHHHBBH4s4s", 69, 0, 40, 0, 0, 64, 6, iph_checksum, source_address, remote_address)
ip_header = get_iphea... |
itielshwartz/BackendApi | lib/pyasn1_modules/rfc3447.py | Python | apache-2.0 | 1,399 | 0.00143 | #
# PKCS#1 syntax
#
# ASN.1 source from:
# ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.asn
#
# Sample captures could be obtained with "openssl genrsa" command
#
from pyasn1_modules.rfc2437 import *
class OtherPrimeInfo(univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('pri... | 1', univ.Integer()),
| namedtype.NamedType('exponent2', univ.Integer()),
namedtype.NamedType('coefficient', univ.Integer()),
namedtype.OptionalNamedType('otherPrimeInfos', OtherPrimeInfos())
)
|
ondra-novak/chromium.src | tools/telemetry/telemetry/core/backends/chrome/tracing_backend_unittest.py | Python | bsd-3-clause | 2,594 | 0.004626 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import cStringIO
import json
import logging
import unittest
from telemetry.core import util
from telemetry.timeline import model
from telemetry.timeline imp... | '"args": {"name": "Browser"},'
'"pid": | 5, "ph": "M"}',
'{"name": "thread_name",'
'"args": {"name": "CrBrowserMain"},'
'"pid": 5, "tid": 32578, "ph": "M"}']))
timeline_model = model.TimelineModel(ri)
self.assertEquals(timeline_model.browser_process.pid, 5)
|
zubair-arbi/dota-world | dota_world/settings.py | Python | mit | 8,644 | 0.001157 | """
Django settings for dota_world project.
Generated by 'django-admin startproject' using Django 1.11.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import... | UNT_EMAIL_CONFIRMATION_EMAIL = False
ACCOUNT_EMAIL_CONFIRMATION_REQUIRED = False
ACCOUNT_OPEN_SIGNUP = False |
# AUTHENTICATION_BACKENDS = {
# "account.auth_backends.EmailAuthenticationBackend"
# }
# Specified in seconds. Enable caching by setting this to a value greater than 0.
RESPONSE_CACHE_TTL = 60 * 60
# ------------------------------
# Email configuration
DEFAULT_FROM_EMAIL = 'DotaWorld <noreply@mydomain.com>'
#... |
CroissanceCommune/autonomie | autonomie/forms/holiday.py | Python | gpl-3.0 | 2,323 | 0.000864 | # -*- coding: utf-8 -*-
# * Copyright (C) 2012-2013 Croissance Commune
# * Authors:
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
# * Pettier Gabriel;
# * TJEBBES Gaston <g.t@majerti.fr>
#
# This file is part of Autonomie : Progiciel de gestion de CAE.
#
# Autonomie is... | = colander.Invalid(form,
u"La date de début doit précéder la date de fin")
exc['start_date'] = u"Doit précéder la date de fin"
raise exc
class HolidaySchema(colander.MappingSchema):
start_date = colander.SchemaNode(colander.Date | (), title=u"Date de début")
end_date = colander.SchemaNode(colander.Date(), title=u"Date de fin")
class HolidaysList(colander.SequenceSchema):
holiday = HolidaySchema(title=u"Période", validator=date_validator)
class HolidaysSchema(colander.MappingSchema):
holidays = HolidaysList(title=u"",
... |
AnalogJ/lexicon | lexicon/providers/aliyun.py | Python | mit | 8,095 | 0.001482 | """Module provider for Aliyun"""
import base64
import datetime
import hmac
import logging
import random
import sys
import time
from hashlib import sha1
import requests
from six.moves import urllib
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = ... | ecordId"],
"type": resource["Type"],
"name": self._full_name(resource["RR"]),
"ttl": resource["TTL"],
"content": resource["Value"],
}
)
LOGGER.debug("list_records: %s", p | rocessed_records)
return processed_records
# Create or update a record.
def _update_record(self, identifier, rtype=None, name=None, content=None):
resources = self._list_records(rtype, name, None)
for record in resources:
if (
rtype == record["type"]
... |
sudoes/UTEM-Vote | config.py | Python | mit | 105 | 0 | class Config(object | ):
DEBUG = False
TESTING = False
class DevConfig(Config | ):
DEBUG = False
|
Jortolsa/l10n-spain | l10n_es_aeat_mod303/models/mod303.py | Python | agpl-3.0 | 7,898 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | Resultado", readonly=True,
help="Atribuible a la Administración [66] - Cuotas a compensar [67] + "
"Regularización anual [68]""")
previous_result = fields.Float(
string="[70] A deducir",
help="Resultado d | e la anterior o anteriores declaraciones del mismo "
"concepto, ejercicio y periodo",
states={'done': [('readonly', True)]})
resultado_liquidacion = fields.Float(
string="[71] Result. liquidación", readonly=True)
result_type = fields.Selection(
selection=[('I', 'A ingresar')... |
jiadaizhao/LeetCode | 0101-0200/0199-Binary Tree Right Side View/0199-Binary Tree Right Side View.py | Python | mit | 493 | 0.004057 | # Definition f | or a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if root is None:
return []
level = [root]
result = []
while lev... | |
FTAsr/STS | monolingual-word-aligner/wordSim.py | Python | mit | 2,728 | 0.008431 | from config import *
################################################################################
def loadPPDB(ppdbFileName = '../monolingual-word-aligner/ppdb-1.0-xxxl-lexical.extended.synonyms.uniquepairs'):
global ppdbSim
global ppdbDict
count = 0
ppdbFile = open(ppdbFileName, 'r')
fo... | (tokens[0], tokens[1])] = ppdbSim
count += 1
################################################################################
################################################################################
def presentInPPDB(word1, word2):
global ppdbDict
if (word1.lower(), word2.lower()) in ppdbDi... | ###############################################################################
##############################################################################################################################
def wordRelatedness(word1, pos1, word2, pos2):
global stemmer
global ppdbSim
global punctuations
... |
theKono/mobile-push | tests/factories/topic.py | Python | apache-2.0 | 422 | 0.00237 | #!/usr/bin/env python
# standard li | brary imports
# third party related imports
import factory
# local library imports
from mobile_push.db import Session, Topic
class TopicFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta(object):
model = Topic
sqlalchemy_session = Session
name = factory.Sequence(lambda n: 'topic-%... | n: 'topic-arn-%s' % n)
|
andrevmatos/Librix-ThinClient | src/__init__.py | Python | gpl-2.0 | 777 | 0.005148 | #!/usr/bin/env python3
#
#
#
# This file is part of librix-thinclient.
#
# librix-thinclient is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lice | nse as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# librix-thinclient is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
#
# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with librix-thinclient. If not, see <http://www.gnu.org/licenses/>.
__all__ = [
'ui',
'lib',
'daemon',
'modules',
]
|
thatneat/petl | petl/test/transform/test_basics.py | Python | mit | 17,148 | 0.000058 | from __future__ import absolute_import, print_function, division
from petl.test.helpers import ieq
from petl.util import expr, empty, coalesce
from petl.transform.basics import cut, cat, addfield, rowslice, h | ead, tail, \
cutout, skipcomments, annex, addrownumbers, addcolumn, \
addfieldusingcontext, movefield, stack
def test_cut():
table = (('foo', 'bar', 'baz'),
('A', 1, 2),
('B', '2', '3.4'),
(u'B', u'3', u'7.8 | ', True),
('D', 'xyz', 9.0),
('E', None))
cut1 = cut(table, 'foo')
expectation = (('foo',),
('A',),
('B',),
(u'B',),
('D',),
('E',))
ieq(expectation, cut1)
cut2 = cut(table, 'foo', ... |
pretix/django-formset-js | example/example/urls.py | Python | bsd-2-clause | 147 | 0.006803 | from | django.conf.urls import patterns, include, url
import example.views
urlpatterns = patterns('',
url(r | '^$', example.views.formset_view),
)
|
synthicity/activitysim | activitysim/estimation/larch/auto_ownership.py | Python | agpl-3.0 | 1,942 | 0.00103 | import os
import numpy as np
import pandas as pd
import yaml
from typing import Collection
from larch.util import Dict
from .simple_simulate import simple_simulate_data
from .general import (
remove_apostrophes,
apply_coefficients,
dict_of_linear_utility_from_spec,
)
from larch import Model, DataFrames, P... | ide_choice"] >= 0]
m = Model()
# One of the alternatives is coded as 0, so
# we need to explicitly initialize the MNL nesting graph
# and set to root_id to a value other than zero.
m.initialize_graph(alternative_codes=altcodes, root_id=99)
m.utility_co = dict_of_linear_utility | _from_spec(
spec, "Label", dict(zip(altnames, altcodes)),
)
apply_coefficients(coefficients, m)
d = DataFrames(co=chooser_data, av=True, alt_codes=altcodes, alt_names=altnames,)
m.dataservice = d
m.choice_co_code = "override_choice"
if return_data:
return (
m,
... |
lupyuen/RaspberryPiImage | usr/share/pyshared/ajenti/plugins/main/controls_inputs.py | Python | apache-2.0 | 3,085 | 0 | import calendar
import datetime
import os
import time
from ajenti.api import *
from ajenti.ui import p, UIElement, on
@p('value', default='', bindtypes=[str, unicode, int, long])
@p('readonly', type=bool, default=False)
@p('type', default='text')
@plugin
class TextBox (UIElement):
typeid = 'textbox'
@p('value'... | if self.value:
return datetime.fromtimestamp(self.value)
@dateobject.setter
def dateobject__set(self, value):
if value:
self.value = calendar.timeg | m(value.timetuple())
else:
self.value = None
@p('value', default='', bindtypes=[str, unicode])
@p('icon', default=None)
@p('placeholder', default=None)
@plugin
class Editable (UIElement):
typeid = 'editable'
@p('text', default='')
@p('value', default=False, bindtypes=[bool])
@plugin
class Ch... |
ostree/plaso | tests/parsers/olecf_plugins/test_lib.py | Python | apache-2.0 | 2,117 | 0.001889 | # -*- coding: utf-8 -*-
"""OLECF plugin related functions and classes for testing."""
import pyolecf
from plaso.engine import single_process
from tests.parsers import test_lib
class OleCfPluginTestCase(test_lib.ParserTestCase):
"""The unit test case for OLE CF based plugins."""
def _OpenOleCfFile(self, path, ... | th: The path to the OLE CF test file.
codepage: Optional codepage. The default is cp1252.
"""
file_entry = self._GetTestFileEntryFromPath([path])
file_object = file_entry.GetFileObject()
olecf_file = pyolecf.file()
olecf_file.set_ascii_codepage(codepage)
olecf_file.open_file_object(file_... | nt generator.
Args:
path: The path to the OLE CF test file.
plugin_object: The plugin object that is used to extract an event
generator.
knowledge_base_values: optional dict containing the knowledge base
values. The default is None.
Returns:
... |
usc-isi-i2/etk | etk/unit_tests/test_language_identification_extractor.py | Python | mit | 1,687 | 0.001778 | import unittest
from etk.extractors.language_identification_extractor import LanguageIdentificationExtractor
class TestLanguageIdentificationExtractor(unittest.TestCase):
def test_langid(self):
extractor = LanguageIdentificationExtractor()
text_en = "langid.py comes pre-trained on 97 languages (I... | iven)"
result_en = extractor.extract(text_en, "LANGID")
self.assertEqual(result_en[0].value, "en")
text_es = "Hola Mundo"
result_es = extractor.extract(text_es, "LANGID")
self.assertEqual(result_es[0].value, "es")
text_de = "Ein, zwei, drei, vier"
result_de = ex... | nknown = extractor.extract(text_unknown, "LANGID")
self.assertEqual(result_unknown[0].value, "en")
def test_langdetect(self):
extractor = LanguageIdentificationExtractor()
text_en = "langdetect supports 55 languages out of the box (ISO 639-1 codes)"
result_en = extractor.extract(te... |
sunze/py_flask | venv/lib/python3.4/site-packages/celery/tests/security/test_serialization.py | Python | mit | 2,252 | 0 | from __future__ import absolute_import
import os
import base64
from kombu.serialization import registry
from celery.exceptions import SecurityError
from celery.security.serialization import SecureSerializer, register_auth
from celery.security.certificate import Certificate, CertStore
from celery.security.key import ... | s2 = self._get_s(KEY1, CERT1, [])
self.assertRaises(SecurityError,
s1.deserialize, s1.serialize('foo'))
self.assertRaises(SecurityError,
s2.deseri | alize, s2.serialize('foo'))
def test_self_send(self):
s1 = self._get_s(KEY1, CERT1, [CERT1])
s2 = self._get_s(KEY1, CERT1, [CERT1])
self.assertEqual(s2.deserialize(s1.serialize('foo')), 'foo')
def test_separate_ends(self):
s1 = self._get_s(KEY1, CERT1, [CERT2])
s2 = sel... |
aequitas/home-assistant | homeassistant/components/ambiclimate/climate.py | Python | apache-2.0 | 7,406 | 0 | """Support for Ambiclimate ac."""
import asyncio
import logging
import ambiclimate
import voluptuous as vol
from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (
SUPPORT_TARGET_TEMPERATURE,
SUPPORT_ON_OFF, STATE_HEAT)
from homeassistant.const import AT... | ATTR_TEMPERATURE,
STATE_OFF, TEMP_CELSIUS)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import (ATTR_VALUE, CONF_CLIENT_ID, CONF_CLIENT_SECRET,
DOMAIN | , SERVICE_COMFORT_FEEDBACK, SERVICE_COMFORT_MODE,
SERVICE_TEMPERATURE_MODE, STORAGE_KEY, STORAGE_VERSION)
_LOGGER = logging.getLogger(__name__)
SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE |
SUPPORT_ON_OFF)
SEND_COMFORT_FEEDBACK_SCHEMA = vol.Schema({
vol.Required(ATTR_NAME): c... |
SymbiFlow/symbolator | nucanvas/cairo_backend.py | Python | mit | 13,085 | 0.021629 | # -*- coding: utf-8 -*-
# Copyright © 2017 Kevin Thibedeau
# Distributed under the terms of the MIT license
import os
import math
import gi
import cairo
from .shapes import *
try:
import pango
import pangocairo
use_pygobject = False
except ImportError:
gi.require_version('Pango', '1.0')
from gi.repository... | self)
elif isinstance(shape, GroupShape):
c.save()
c.translate(*sha | pe._pos)
if 'scale' in shape.options:
c.scale(shape.options['scale'], shape.options['scale'])
if 'angle' in shape.options:
c.rotate(math.radians(shape.options['angle']))
for s in shape.shapes:
self.draw_shape(s)
c.restore()
elif isinstance(shape, TextShape):
x... |
rmk135/objects | tests/typing/selector.py | Python | bsd-3-clause | 1,159 | 0.001726 | from typing import Any
from dependency_injector import providers
# Test 1: to check the return t | ype
provider1 = providers.Selector(
lambda: 'a',
a=providers.Factory(object),
b=providers.Factory(object),
)
var1: Any = provider1()
# Test 2: to check the provided instance interface
provider2 = providers.Selector(
lambda: 'a',
a=providers.Factory(object),
b=providers.Factory(object),
)
provid... | .provided['item']
method_caller2: providers.MethodCaller = provider2.provided.method.call(123, arg=324)
# Test3 to check the getattr
provider3 = providers.Selector(
lambda: 'a',
a=providers.Factory(object),
b=providers.Factory(object),
)
attr3: providers.Provider = provider3.a
# Test 4: to check the retur... |
marbl/MetaCompass | workflows/pilon_paired.py | Python | artistic-2.0 | 1,045 | 0.023923 | """
DESCRIPTION
"""
#__author__ = "Victoria Cepeda
#configfile: expand("config.json",
ruleorder: pilon_contigs
rule all:
input:
sixth=expand('{outdir}/error | _correction/contigs.pil | on.fasta',outdir=config['outdir'])
rule pilon_contigs:
input:
contigs='%s/assembly/contigs.fasta'%(config['outdir']),
sam = "%s/error_correction/sorted.bam"%(config['outdir'])
output:
pilonctg='%s/error_correction/contigs.pilon.fasta'%(config['outdir'])
params:
memory="%d... |
citruz/beacontools | beacontools/packet_types/__init__.py | Python | mit | 427 | 0.004684 | """Packets supported by the parser."""
from .eddystone import EddystoneUIDFrame, EddystoneURLFrame, EddystoneEncryptedTLMFrame, \
EddystoneTLMFrame, EddystoneEIDFrame
from .ibeacon im | port IBeaconAdvertisement
from .estimote import EstimoteTelemetryFrameA, EstimoteTelemetryFrameB, EstimoteNearable
from .controlj imp | ort CJMonitorAdvertisement
from .exposure_notification import ExposureNotificationFrame
|
vargax/RAPfSC | RAPfSC/modelo.py | Python | gpl-2.0 | 12,512 | 0.007942 | # -*- coding: utf-8 -*-
import itertools
import pythoncom
import win32com.client as com
__author__ = 'cvargasc'
# Una intersección es un SignalController, tiene carriles de entrada, salida, cruces y semáforos.
class Interseccion:
# ------------------------
# Constructor
# ------------------------
# In... | # todos los cruces son compatibles
def __calcularGrupos(self):
print " ++ Calculando las combinaciones posibles de cruces..."
combinaciones = []
for i in range(1,len(self.cruces)):
#print " +++ Generando las combinaciones de "+str(i | )+" cruces..."
combinaciones.extend(itertools.combinations(self.cruces,i))
print " +++ Se generaron "+str(len(combinaciones))+" grupos de cruces posibles..."
i = 0
for combinacion in combinaciones:
if self.__grupoCompatible(combinacion):
self.grupos[i] = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.