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 |
|---|---|---|---|---|---|---|---|---|
rolando-contrib/scrapy | scrapy/http/headers.py | Python | bsd-3-clause | 2,738 | 0.000365 | import six
from w3lib.http import headers_dict_to_raw
from scrapy.utils.datatypes import CaselessDict
from scrapy.utils.python import to_unicode
class Headers(CaselessDict):
"""Case insensitive http headers dictionary"""
def __init__(self, seq=None, encoding='utf-8'):
self.encoding = encoding
... | value):
lst = self.getlist(key)
lst.extend(self.normvalue(value))
self[key] = lst
def items(self):
return list(self.iteritems())
def iteritems(self):
return ((k, self.getlist(k)) for k in self.keys())
def values(self):
return [self[k] for | k in self.keys()]
def to_string(self):
return headers_dict_to_raw(self)
def to_unicode_dict(self):
""" Return headers as a CaselessDict with unicode keys
and unicode values. Multiple values are joined with ','.
"""
return CaselessDict(
(to_unicode(key, enco... |
rvalyi/l10n-brazil | l10n_br_base/tools/misc.py | Python | agpl-3.0 | 531 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Renato Lima - Akretion
# Copyright (C) 2015 Luis Felipe Mileo - KMEE
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
import re
import string
def p | unctuation_rm(string_value):
tmp_value = (
re.sub('[%s]' % re.escape(string.punctuation), '', s | tring_value or ''))
return tmp_value
def calc_price_ratio(price_gross, amount_calc, amount_total):
if amount_total:
return price_gross * amount_calc / amount_total
else:
return 0.0
|
jtara1/MiscScripts | misc_scripts/images_to_pdf.py | Python | apache-2.0 | 1,706 | 0.000586 | from fpdf import FPDF
import os
import glob
import PIL
from PIL import Image
import click
__doc__ = """
saves each image in a di | rectory on a page of a newly created PDF
"""
letter_width_inches = 8.5
letter_height_inches = 11
def images_to_pdf(path, offset_coords=(-5, 0), ext='.png'):
path = os.path.abspath(path)
image_files = glob.glob(os.path.join(path, "*"))
image_files = sorted(image_files,
... | s[0]).size
pdf = FPDF(format=size)
# add a page containing a single image for each image
for image in image_files:
print(image)
img_size = Image.open(image).size
pdf.add_page(orientation='Portrait')
pdf.image(image,
x=offset_coords[0],
... |
hazelnusse/sympy-old | sympy/matrices/__init__.py | Python | bsd-3-clause | 312 | 0.003205 | """A m | odule that handles matrices.
Includes functions for fast creating ma | trices like zero, one/eye, random matrix etc.
"""
from matrices import Matrix, SMatrix, zero, zeronm, zeros, one, ones, eye, \
hessian, randMatrix, GramSchmidt, wronskian, casoratian, \
list2numpy, matrix2numpy, DeferredVector
|
duncan-r/SHIP | ship/utils/tools/openchannel.py | Python | mit | 9,571 | 0.001881 | """
Summary:
Contains methods for calculating characteristics of open channel flow.
Currently only used to calculate conveyance for a channel section.
Author:
Duncan Runnacles
Created:
01 Apr 2016
Copyright:
Duncan Runnacles 2016
TODO:
Updates:
"""
import math
import... | x2 = section[0][i - 1]
y1 = section[1][i]
y2 = section[1][i - 1]
n = section[2][i - 1]
miny, maxy, same_val = utilfunc.findMax(y1, y2)
# Water level lower than min elevation so no K
if depth < miny:
addToPanel(0, 0, 0)
... | the top of the x/y triangle. Reduce x by the same factor as
# we're reducing y.
if depth < maxy:
height2 = depth - miny
width = width * (height2 / height)
height = height2
maxy = depth
# If ... |
markeldigital/design-system | vendor/ruby/2.0.0/gems/pygments.rb-0.6.3/vendor/pygments-main/tests/run.py | Python | mit | 951 | 0.001052 | # -*- coding: utf-8 -*-
"""
Pygments unit tests
~~~~~~~~~~~~~~~~~~
Usage::
python run.py [testfile ...]
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import print_function
import sys, os
# only find tests... | try:
import nose
except ImportError:
print('nose is required to run the Pygments test suite')
sys.exit(1)
try:
# make sure the current source is first on sys.path
sys.path.insert(0, '..')
import pygments
except SyntaxError as err:
print('Syntax error: %s' % err)
sys.exit(1)
except Impor... | nd Pygments to test: %s' % err)
sys.exit(1)
else:
print('Pygments %s test suite running (Python %s)...' %
(pygments.__version__, sys.version.split()[0]))
nose.main()
|
kxgames/glooey | glooey/drawing/stencil.py | Python | mit | 1,948 | 0.002567 | #!/usr/bin/env python3
from pyglet.gl import *
from pyglet.graphics import Group, OrderedGroup
from glooey.helpers import *
class StencilGroup(Group):
def __init__(self, parent=None):
Group.__init__(self, parent)
def set_state(self):
glEnable(GL_STENCIL_TEST)
glClear(GL_DEPTH_BUFFER_... | unset_state(self):
glDisable(GL_STENCIL_TEST)
class StencilMask(OrderedGroup):
def __init__(self, parent=None, order=0):
super().__init__(order, parent)
def set_state(self):
# Disable writing the to color or depth buffers.
| glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE)
glDepthMask(GL_FALSE)
glStencilFunc(GL_NEVER, 1, 0xFF)
glStencilOp(GL_REPLACE, GL_KEEP, GL_KEEP)
glStencilMask(0xFF)
def unset_state(self):
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)
glDepthMask(GL_TRUE... |
ShySec/scrimmage-scoreboard | web2py/gluon/packages/dal/pydal/base.py | Python | gpl-2.0 | 48,012 | 0.005811 | # -*- coding: utf-8 -*-
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
|
This file contains the DAL support for many relational databases, including:
- SQLite & SpatiaLite
- MySQL
- Postg... | >>> james.update_record(name='Jim')
<Row {'id': 1, 'name': 'Jim'}>
### u | pdate multiple records by query
>>> db(person.name.like('J%')).update(name='James')
1
### delete records by query
>>> db(person.name.lower() == 'jim').delete()
0
### retrieve multiple records (rows)
>>> people = db(person).select(orderby=person.name,
... groupby=person.name, limitby=(0... |
simonz05/pack-command | misc/bench.py | Python | mit | 1,564 | 0.003839 | # -*- coding: utf-8 -*-
import pack_command
import pack_command_python
import timeit
import cProfile
import pstats
import pycallgraph
def format_time(seconds):
v = seconds
if v * 1000 * 1000 * 1000 < 1000:
scale = u'ns'
v = int(round(v*1000*1000*1000))
elif v * 1000 * 1000 < 1000:
... |
pack_command_python.pack_command("ZADD", "foo", 136919834 | 1, 10000)
if profile:
pr = cProfile.Profile()
pr.enable()
if graph:
pycallgraph.start_trace()
if timer:
for name, t in (("Python", runitp), ("cython", runit)):
res = timeit.Timer(t).repeat(sample, number)
min_run = min(res)
per_loop = min_run/number
print u'{}'.format... |
GH1995/tools | archives/Python_江老师给的代码/chapter09/total_ordering_student.py | Python | gpl-3.0 | 777 | 0.018945 | #total_ordering_student.py
import functools
@functools.total_ordering
class Student:
def __init__(self, firstname, lastname): #姓和名
self.firstname = firstname
self.lastname = lastname
def __eq__(self, other): #判断姓名是否一致
return ((self.lastname.lower(), | self.firstname.lower()) ==
(other.lastname.lower(), other.firstname.lower()))
def __lt__(self, other): #self姓名<other姓名
return ((self.lastname.lower(), self.firstname.lower()) <
(other.lastname.lower(), other.first | name.lower()))
#测试代码
if __name__ == '__main__':
s1 = Student('Mary','Clinton')
s2 = Student('Mary','Clinton')
s3 = Student('Charlie','Clinton')
print(s1==s2)
print(s1>s3)
|
openstack/octavia | octavia/db/migration/alembic_migrations/versions/4c094013699a_update_load_balancer_amphora.py | Python | apache-2.0 | 1,475 | 0 | # Copyright 2014 Rackspace
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTI... | cific language governing permissions and limitations
# under the License.
'''update load balancer amphora relationship
Revision ID: 4c094013699a
Revises: 35dee79d5865
Create Date: 2014-09-15 14:42:44.875448
'''
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '4... |
mouckatron/Martyr2MegaProjectList | text/piglatin.py | Python | mit | 638 | 0.018809 | #! /usr/bin/python2.7
import os
import re
import sys
# some static resources
vowels = set(('a','e','i','o','u','A','E','I','O','U'))
#vowel_re
consonant_re = re.compile(r'([bcdfghjklmnpqrstvwxyzBCDFGHJKLMN | PQRSTVWXYZ]+)([a-zA-Z]*)(.*)?')
# input
original = sys.stdin.read()
# output
piglatin = []
# loop over the words and change them to pig latin
for word in original.split():
# there are different rules if it starts with a | vowel
if word[0] in vowels:
piglatin.append(word+'way')
else:
piglatin.append(consonant_re.sub(r'\2\1ay\3', word))
# output the translated text
sys.stdout.write(' '.join(piglatin)) |
Phelimb/atlas | mykatlas/atlas_main.py | Python | mit | 8,067 | 0.001735 | #! /usr/bin/env python
from __future__ import print_function
import os
import sys
import logging
import argparse
sys.path.append(
os.path.realpath(
os.path.join(
os.path.dirname(__file__),
"..")))
from mykatlas.version import __version__
from mykatlas.base import ArgumentParserWi... | rt sequ | ence_or_binary_parser_mixin
from mykatlas.base import probe_set_mixin
from mykatlas.base import force_mixin
from mykatlas.base import genotyping_mixin
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logger = logging.getLogger(__name__)
DEFAULT_KMER_SIZE = os.environ.get("KMER_SIZE", 31)
def run_subtool... |
graycarl/moon | moon/mac.py | Python | mit | 340 | 0 | # -*- coding: utf-8 -*-
from os import system
|
def alert(msg, title=u'通知'):
"""
osascript -e 'display notification "Lorem ipsum dolor sit amet"
with title "Title"'
"""
cmd = u"osascript -e 'display notification \"%s\" with title " \
u"\"%s\"'" % (m | sg, title)
print cmd
system(cmd.encode("utf-8"))
|
HydrelioxGitHub/home-assistant | homeassistant/components/notify/rocketchat.py | Python | apache-2.0 | 2,514 | 0 | """
Rocket.Chat notification service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/notify.rocketchat/
"""
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
CONF_URL, CON... | A) or {}
resp = self._server.chat | _post_message(
message, channel=self._room, **data)
if resp.status_code == 200:
success = resp.json()["success"]
if not success:
_LOGGER.error("Unable to post Rocket.Chat message")
else:
_LOGGER.error("Incorrect status code when posting mes... |
52osworld/RealBoard4088 | software/rtthread_examples/examples/6_media_mp3/rtconfig.py | Python | gpl-2.0 | 3,433 | 0.014565 | import os
# toolchains options
ARCH='arm'
CPU='cortex-m4'
CROSS_TOOL='keil'
# get setting from environment.
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
# cross_tool provides the cross compiler
# EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR
if CROSS_TOOL == 'g... | thumb '
LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rtthread-lpc40x.map,-cref,-u,Reset_Handler -T lpc40xx_rom.ld'
CPATH = ''
LPATH = ''
if BUILD == 'debug':
CFLAGS += ' -O0 -gdwarf-2'
AFLAGS += ' -gdwarf-2'
else:
CFLAGS += ' -O2'
POST_ACTIO | N = OBJCPY + ' -O ihex $TARGET rtthread.hex\n' + SIZE + ' $TARGET \n'
elif PLATFORM == 'armcc':
# toolchains
CC = 'armcc'
AS = 'armasm'
AR = 'armar'
LINK = 'armlink'
TARGET_EXT = 'axf'
DEVICE = ' --device DARMSTM'
CFLAGS = DEVICE + ' --apcs=interwork'
AFLAGS = DEVICE
LFLAGS = D... |
marshallmcdonnell/interactive_plotting | Traits/manual/minimal.py | Python | mit | 167 | 0.011976 | #!/usr/b | in/env python
# minimal.py --- Minimal example of using traits.
from traits.api import HasTraits, Float
class P | erson(HasTraits):
weight = Float(150.0)
|
olethanh/django-phpbb | phpbb/views.py | Python | gpl-3.0 | 5,332 | 0.005627 | # -*- coding: utf-8 -*-
# This file is part of django-phpbb, integration between Django and phpBB
# Copyright (C) 2007-2008 Maciej Bliziński
#
# django-phpbb 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; e... | ts?",
'page_list': range(1, paginator.num_pages + 1),
}, [phpbb_config_context])
return render_to_respo | nse("phpbb/topic_detail.html", {
'object': t,
'posts': page.object_list,
}, context_instance=c)
def unanswered(request):
topics = PhpbbTopic.objects.filter(topic_replies = 0)
c = RequestContext(request, {}, [phpbb_config_context])
return render_to_response(
"phpbb/unans... |
rolisz/walter_waiter | lower.py | Python | mit | 203 | 0.004926 | #! /usr/bin/python
impo | rt event
import nxt.locator
import nxt.motor as motor
brick = nxt.locator.find_one_brick()
height_motor = | motor.Motor(brick, motor.PORT_A)
height_motor.turn(127, 5000, brake=False) |
vmojzis/sepolicy_analysis | sepolicyanalysis/security_related.py | Python | gpl-3.0 | 2,061 | 0.022804 | # (C) Copyright 2016 Vit Mojzis, vmojzis@redhat.com
#
# This program is distributed under the terms of the GNU General Public License
#
# 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 v... | t([x.strip() for x in line[9:].split(",")])
if line.startswith("types=="):
types = set([x.strip() for x in line[6:].split(",")])
if line.startswith("exclude="):
exclude = set([x.strip() for x in line[8:].split(",")])
#all types given in "types=" are treated as domains !
domain_grouping = group... | = domain_grouping.get(name, None)
if group:
groups.add(group)
#get types corresponding to given packages
domains, resources = grouping.get_types(groups)
domains = domains | types
# remove excluded types
domains = domains - exclude
resources = resources - exclude
return domains, resources
exc... |
TathagataChakraborti/resource-conflicts | PLANROB-2015/seq-sat-lama/Python-2.5.2/Doc/tools/prechm.py | Python | mit | 17,381 | 0.014556 | """
Makes the necesary files to convert from plain html of
Python 1.5 and 1.5.x Documentation to
Microsoft HTML Help format version 1.1
Doesn't change the html's docs.
by hernan.foffani@iname.com
no copyright and no responsabilities.
modified by Dale Nagata for Python 1.5.2
Renamed fr... | Book('dist','Distributing Python Modules', 'dist', 'index'),
],
'2.1.1':
[
Book('.', 'Main page', 'index'),
Book('.', | 'Global Module Index', 'modindex'),
Book('tut','Tutorial','tut','node2'),
Book('lib','Library Reference','lib','contents','genindex'),
Book('ref','Language Reference','ref','contents','genindex'),
Book('mac','Macintosh Reference','mac','contents','genindex'),
Book('ext','Extendin... |
pombredanne/PyMISP | examples/create_events.py | Python | bsd-2-clause | 1,138 | 0.004394 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from keys import misp_url, misp_key
import argparse
# For python2 & 3 compat, a bit dirty, but it seems to be the least bad one
try:
input = raw_input
except NameError:
pass
def init(url, key):
return PyMISP(url, key, True, 'json', ... | r.add_argument("-i", "--info", help="Used to populate the event info field if no event ID supplied.")
parser.add_argument("-a", "--analysis", type=int, help="The analysis level of the | newly created event, if applicatble. [0-2]")
parser.add_argument("-t", "--threat", type=int, help="The threat level ID of the newly created event, if applicatble. [1-4]")
args = parser.parse_args()
misp = init(misp_url, misp_key)
event = misp.new_event(args.distrib, args.threat, args.analysis, args.i... |
veltzer/demos-python | src/examples/short/networking/socket_reuseaddr.py | Python | gpl-3.0 | 427 | 0 | #!/usr/bin/env python
"""
This example shows that python suffers from some problem of
not being able to reuse sockets even though the socket.SO_REUSEADDR
is used...
"""
import socket
while True:
adr = ('localhost', 8080)
s = socket.socket(soc | ket.AF_INET, socket.SOCK_STREAM)
s.bind(adr)
| s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.listen(15)
s.accept()
s.shutdown(socket.SHUT_RDWR)
|
schenkd/webdev-project | data_import.py | Python | mit | 1,815 | 0.003309 | # ~*~ encoding: utf-8 ~*~
from pymongo import MongoClient
from pandas import read_csv
from datetime import date
mongodb = MongoClient('192.168.178.82', 9999)
db = mongodb['dev']
drug_collection = db['drug']
drugs = read_csv('~/Dokumente/bfarm_lieferenpass_meldung.csv', delimiter=';', encoding='iso8859_2').to_dict()
... | [x] == 'ja' else False
drug_collection.update_one({'enr': data['enr']}, {'$se | t': data}, upsert=True)
|
USGSDenverPychron/pychron | pychron/hardware/actuators/u3_actuator.py | Python | apache-2.0 | 1,297 | 0 | # ===============================================================================
# Copyright 2019 ross
#
# 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/LICE... | specific language governing permissions and
# limitations under the License.
# ===============================================================================
from pychron.hardware.actuators import get_switch_address
from pychron.hardware.actuators.gp_actuator import GPActuator
from pychron.hardware.labjack.base_u3_lv... | ator(BaseU3LV, GPActuator):
def _actuate(self, obj, action):
return BaseU3LV.set_channel_state(
self, get_switch_address(obj), action.lower() == "open"
)
def get_channel_state(self, obj, **kw):
return BaseU3LV.get_channel_state(self, get_switch_address(obj), **kw)
# ======... |
tpb261/hackerRank | warmup/diag_diff.py | Python | apache-2.0 | 198 | 0.025253 | import ast
n = int(input())
a=[]
s1=s2=0
for i | in range(0, n):
a = list(ast.literal_eval(','.join(i | nput().split())))
if(len(a) == n):
s1+=a[i]
s2+=a[n-1-i]
print(abs(s1-s2))
|
ckclark/leetcode | py/increasing-triplet-subsequence.py | Python | apache-2.0 | 409 | 0.002445 | class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
| :rtype: bool
"""
first, second = None, None
for n in nums:
if first is None or n <= first:
first = n
elif second is None or n <= second:
second = n
else:
return True
return | False
|
cogmission/nupic.research | projects/sequence_prediction/continuous_sequence/swarm_description/SWARM_CONFIG_sine.py | Python | agpl-3.0 | 1,556 | 0.000643 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013-2015, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This p... | he GNU Affero Public License for more details.
#
# You should have rece | ived a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
SWARM_CONFIG = {
"includedFields": [
{
"fieldName": "data",
"fieldType": "float"... |
mpetyx/pyrif | pyrif/FuXi/Rete/IteratorAlgebra.py | Python | mit | 4,077 | 0.001472 | """
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/492216
Iterator algebra implementations of join algorithms: hash join, merge
join, and nested loops join, as well as a variant I dub "bisect join".
Requires Python 2.4.
Author: Jim Baker, jbaker@zyasoft.com
"""
import operator
from rdflib import py3compat... | key=operator.itemgetter(0)):
yield k, list(g) |
R_grouped = advancer(sorted((predicate(r), r) for r in R))
S_grouped = advancer(sorted((predicate(s), s) for s in S))
# in the join we need to distinguish rp from rk in the unpack, so
# just use rk, sk
rk, R_matched = next(R_grouped) if py3compat.PY3 else R_grouped.next()
sk, S_matched = next... |
tnkteja/django-unchained | csc510project/urls.py | Python | mit | 110 | 0.018182 | from django.conf.urls import url
from . import views
urlpatterns | = [
u | rl(r'^$', views.index, name='index')
] |
konstantinoskostis/sqlalchemy-utils | tests/primitives/test_currency.py | Python | bsd-3-clause | 1,823 | 0 | # -*- coding: utf-8 -*-
import pytest
import six
from sqlalchemy_utils import Currency, i18n
@pytest.fixture
def set_get_locale():
i18n.get_locale = lambda: i18n.babel.Locale('en')
@pytest.mark.skipif('i18n.babel is None')
@pytest.mark.usefixtures('set_get_locale')
class TestCurrency(object):
def test_ini... | s(TypeError):
Currency(None)
@pytest.mark.parametrize(
('code', 'name'),
(
('USD', 'US Dollar'),
('EUR', 'Euro')
)
)
def test_name_property(self, code, name): |
assert Currency(code).name == name
@pytest.mark.parametrize(
('code', 'symbol'),
(
('USD', u'$'),
('EUR', u'€')
)
)
def test_symbol_property(self, code, symbol):
assert Currency(code).symbol == symbol
def test_equality_operator(self):
... |
aodn/compliance-checker | compliance_checker/cf/cf.py | Python | apache-2.0 | 220,804 | 0.001695 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import sqlite3
import sys
from collections import OrderedDict, defaultdict
from functools import wraps
from warnings import warn
imp | ort numpy as np
import pyproj
| import regex
from cf_units import Unit
from compliance_checker import cfutil
from compliance_checker.base import BaseCheck, BaseNCCheck, Result, TestCtx
from compliance_checker.cf import util
from compliance_checker.cf.appendix_d import (
dimless_vertical_coordinates_1_6,
dimless_vertical_coordinates_1_7,
... |
SciTools/iris | lib/iris/tests/unit/coords/test_Cell.py | Python | lgpl-3.0 | 7,147 | 0 | # Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""Unit tests for the :class:`iris.coords.Cell` class."""
# Import iris.tests first so that some things can be initialised bef... | ll = Cell(
datetime.datetime(2010, 1, 1),
bound=[
| datetime.datetime(2010, 1, 1),
datetime.datetime(2011, 1, 1),
],
)
self.assert_raises_on_comparison(
cell, dt, TypeError, "bounded region for datetime"
)
def test_PartialDateTime_unbounded_cell(self):
# Check that cell comparison works with... |
georgemarshall/django-rest-auth | rest_allauth/serializers.py | Python | mit | 830 | 0 | from allauth.account import app_settings
from rest_framework import serializers
from rest_framework.authtoken.models import Token
AuthenticationMethod = app_settings.AuthenticationMethod
EmailVerificationMethod = app_settings.EmailVerificationMethod
class UserSerializer(serializers.Serializer):
"""
A `Us | erSerializer` is just a regular `Serializer`, except that:
* A request is required as part of the context
* A user object is autom | atically populated from the request
"""
def __init__(self, *args, **kwargs):
super(UserSerializer, self).__init__(*args, **kwargs)
self.user = getattr(self.context['request'], 'user')
class TokenSerializer(serializers.ModelSerializer):
"""
Serializer for Token model.
"""
class... |
meteoswiss-mdr/monti-pytroll | scripts/plot_msg_minus_cosmo.py | Python | lgpl-3.0 | 20,832 | 0.021409 | from __future__ import division
from __future__ import print_function
#!/usr/bin/python
# program to plot SEVIRI observations
# usage from command line
# $ python plot_msg.py
#
# pass arguments to overwrite time, rgb, area given in the script
# $ python plot_msg.py year month day hour min rgb area
# year month... | # area -> string or string array, e.g. 'EuropeCanary' or 'ccs4' (default)
# for possible options have a look at the file area.def
# RSS -> logical (True or False) rapid scan service
# True -> 5min service for europe (default)
# | False -> 15min service for whole disk
# verbose-> logical (True or False) activates verbose output
# True -> more messages for debugging (default)
# False -> quiet
#
# Author Ulrich Hamann
# History 2014-10-01 U. Hamann, first version
# 2014-10-28 U. Hamann, area can also be used... |
sbc100/yapf | yapftests/reformatter_pep8_test.py | Python | apache-2.0 | 17,252 | 0.005738 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# 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 a... | ormatter.Reformat(uwlines))
def testHangingIndentCollision(self):
unformatted_code = textwrap.dedent("""\
if (aaaaaaaaaaaaaa + bbbbbbbbbbbbbbbb == ccccccccccccccccc and xxxxxxxxxxxxx or yyyyyyyyyyyyyyyyy):
pass
elif (xxxxxxxxxxxxxxx(aaaaaaaaaaa, bbbbbbbbbbbbbb, cccccccccccc, ddddddddd... | '):
pass
for connection in itertools.chain(branch.contact, branch.address, morestuff.andmore.andmore.andmore.andmore.andmore.andmore.andmore):
dosomething(connection)
""")
expected_formatted_code = textwrap.dedent("""\
if (aaaaaaaaaaaaaa + bbbbbbbbbbbbbbb... |
Cadair/ginga | ginga/qtw/Widgets.py | Python | bsd-3-clause | 54,587 | 0.001484 | #
# Widgets.py -- wrapped Qt widgets and convenience functions
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import os.path
from functools import reduce
from ginga.q... | if halign == 'left':
lbl.setAlignment(QtCore.Qt.AlignLef | t)
elif halign == 'center':
lbl.setAlignment(QtCore.Qt.AlignHCenter)
elif halign == 'center':
lbl.setAlignment(QtCore.Qt.AlignRight)
self.widget = lbl
lbl.mousePressEvent = self._cb_redirect
if style == 'clickable':
lbl.setSizePolicy(QtGui.QS... |
kikkomep/pydoop | test/mapreduce/test_utils.py | Python | apache-2.0 | 2,444 | 0 | # BEGIN_COPYRIGHT
#
# Copyright 2009-2015 CRS4.
#
# 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 agree... | 2\n \t dfasd \\',
'jdsfkj\\hsdjhfjh\\\t\n']:
self.assertEqual(x, unquote_string(quote_string(x)))
def test_digest(self):
with open(JOB_TOKEN) as f:
f.read(4) # magic
deserialize(int, f) # prot
deserialize(int, f) # n
deseriali... | ialize(str, f)
with open(MAP_JAVA_DOWNLINK_DATA) as istream:
cmd_stream = BinaryDownStreamFilter(istream)
cmd, args = cmd_stream.next()
self.assertEqual(cmd, 'authenticationReq')
xdigest = '5bMR7RdwmkLvK582eYWEK8X6jDA='
xchallenge = '159331782474988945206228551881... |
cole/tornforms | tornforms/utils.py | Python | mit | 1,334 | 0.005997 | # -*- coding: UTF-8 -*-
#
# Copyright 2014 Cole Maclean
"""Tornado forms: simple form validation.
Utility classes.
"""
import functools
def decapitalize(string):
"""Turn MinLength into minLength for JS"""
if not string:
return string
return "{0}{1}".format(string[:1].lower(), string[1:])
class E... | .format(**self.params)
else:
return self.message
def with_form(form=None, name='form'):
"""Decorator for `tornado.web.RequestHandler` methods.
Automatically sets up the form class given as `self._name_`
"""
def decorator(method):
assert form is not None, "Form instance requ... | gs, **kwargs)
return wrapper
return decorator |
Magnetic/cycy | cycy/parser/ast.py | Python | mit | 7,047 | 0.000426 | from characteristic import Attribute, attributes
from rply.token import BaseBox
from rpython.tool.pairtype import extendabletype
class Node(BaseBox):
# Allows using __extend__ to extend the type
__metaclass__ = extendabletype
@attributes(
[
Attribute(name="operator"),
Attribute(name="lef... | ith_init=False
)
class Call(Node):
def __init__(self, name, args):
self.name = name
self.args = args
class Null(Node):
# This isn't actually a type in C, but we don't support macros, or pointers
# yet which are required to #define NULL (void*)0
def __eq__(self, other):
if isins... | alse)
class Assembler(Node):
def __init__(self, instruction=None):
self.instruction = instruction
@attributes([Attribute(name="name")], apply_with_init=False)
class Include(Node):
def __init__(self, name=None):
self.name = name
@attributes(
[
Attribute(name="initial"),
At... |
chrisspen/homebot | src/ros/src/ros_homebot/nodes/system_node.py | Python | mit | 12,231 | 0.00417 | #!/usr/bin/env python
from commands import getoutput
import os
import multiprocessing
import rospy
from std_msgs.msg import Int16
from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue
from ros_homebot_msgs import msg as msgs
from ros_homebot_python import constants as c
OK = DiagnosticStatus.O... | msg.free_gbytes = memory_usage_free_gbytes
msg.total_gbytes = mem | ory_usage_total_gbytes
msg.percent_used = memory_usage_percent
self.memory_publisher.publish(msg)
# Find disk.
disk_usage_percent = to_percent(getoutput("df -H | grep -i "+self.drive_path+" | awk '{print $5}'"))
disk_usage_free_gbytes = to_gbytes(getoutput("d... |
w1ll1am23/home-assistant | homeassistant/components/starline/switch.py | Python | apache-2.0 | 2,715 | 0.000737 | """Support for StarLine switch."""
from homeassistant.components.switch import SwitchEntity
from .account import StarlineAccount, StarlineDevice
from .const import DOMAIN
from .entity import StarlineEntity
SWITCH_TYPES = {
"ign": ["Engine", "mdi:engine-outline", "mdi:engine-off-outline"],
"webasto": ["Webasto... | ities):
"""Set up the StarLine switch."""
account: StarlineAccount = hass.data[DOMAIN][entry.entry_id]
entities = []
for device in acco | unt.api.devices.values():
if device.support_state:
for key, value in SWITCH_TYPES.items():
switch = StarlineSwitch(account, device, key, *value)
if switch.is_on is not None:
entities.append(switch)
async_add_entities(entities)
class StarlineS... |
dbrandt/proc_events | proc_events/__init__.py | Python | mit | 146 | 0 | from .pec import pec_control as control
from .pec import pec_unpack as unpack
f | rom .pec import process_event | s
from .pec import process_events_rev
|
mbeloshitsky/syslog2eventlog | setup.py | Python | bsd-3-clause | 77 | 0 | from distutils.core import setup
import py2exe |
setup(con | sole=['server.py'])
|
timvandermeij/mobile-radio-tomography | zigbee/RF_Sensor.py | Python | gpl-3.0 | 15,115 | 0.00172 | # Core imports
import copy
import Queue
import thread
import time
# Package imports
from ..core.Threadable import Threadable
from ..reconstruction.Buffer import Buffer
from ..settings import Arguments
from Packet import Packet
from TDMA_Scheduler import TDMA_Scheduler
# pylint: disable=undefined-all-variable
__all__ ... | ead_manager)
# Make sure that the provided callbacks are callable.
for callback in [location_callback, receive_callback, valid_callback]:
if not hasattr(callback, "__call__"):
| raise TypeError("Provided RF sensor callback is not callable")
# Load settings for a specific RF sensor type.
if isinstance(arguments, Arguments):
self._settings = arguments.get_settings(self.type)
else:
raise ValueError("'arguments' must be an instance of ... |
AmandaMoen/AmandaMoen | students/JasonTyler/trigrams/trigrams.py | Python | gpl-2.0 | 4,256 | 0.00282 | #!/usr/bin/env python
"""Trigrams assignment"""
import re
import random
test_fragment = """
One night--it was on the twentieth of March, 1888--I was
returning from a journey to a patient (for I had now returned to
civil practice), when my way led me through Baker Street. As I
passed the well-remembered door, which mu... | key, item in dict2.iteritems():
if not dict1.has_key(key):
dict1.setdefault(key, []).extend(item)
else:
pass
if __name__ == "__main__":
# Using sherlock.txt and two methods of generating trigrams to translate test_fragment
trigrams = generate_trigram(read | _file_as_string('sherlock.txt'))
trigrams2 = generate_trigram_clean(read_file_as_string('sherlock.txt'))
update_dictlist(trigrams, trigrams2)
translated_test_fragment = translate_trigram(test_fragment, trigrams)
print translated_test_fragment
|
sankroh/satchmo | satchmo/payment/modules/purchaseorder/processor.py | Python | bsd-3-clause | 804 | 0.004975 | """
Handle a Purchase Order payments.
"""
from django.utils.translation import ugettext as _
from satchmo.payment.utils import record_payment
from satchmo.payment.modules.base import BasePaymentProcessor
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, se... | rchaseorder', settings)
def can_refund(self):
return True
def prepareData(self, | order):
super(PaymentProcessor, self).prepareData(order)
def process(self):
"""
Purchase Orders are always successful.
"""
reason_code = "0"
response_text = _("Success")
record_payment(self.order, self.settings, amount=self.order.balance)
... |
hackaugusto/raiden | raiden/tests/integration/transfer/test_refundtransfer.py | Python | mit | 24,174 | 0.001737 | import gevent
import pytest
from raiden.api.python import RaidenAPI
from raiden.tests.utils.detect_failure import raise_on_failure
from raiden.tests.utils.events import (
raiden_events_search_for_item,
search_for_item,
wait_for_raiden_event,
wait_for_state_change,
)
from raiden.tests.utils.network impo... | apacity, the transfer must fail"
assert payment_status.payment_done.wait() is False, msg
gevent.sleep(0.2)
# A lock structure with the correct amount
send_locked = raiden_events_search_for_ite | m(
app0.raiden, SendLockedTransfer, {"transfer": {"lock": {"amount": amount_refund}}}
)
assert send_locked
secrethash = send_locked.transfer.lock.secrethash
send_refund = raiden_events_search_for_item(app1.raiden, SendRefundTransfer, {})
assert send_refund
lock = send_locked.transfer.l... |
AABoyles/SlideGallery | index.py | Python | gpl-3.0 | 1,372 | 0.008746 | #!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from os import curdir, sep
import os
PORT_NUMBER = 8082
class myHandler(BaseHTTPRequestHandler):
def do_GET(self):
mimetype='text/html'
if self.path.endswith(".gif"):
mimetype='image/gif'
elif se... | f.close()
else:
f = open(curdir + sep + self.path)
self.wfile.write(f.read())
f.close()
return
try:
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , P | ORT_NUMBER
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
|
krishauser/pyOptimalMotionPlanning | pomp/example_problems/lqr.py | Python | apache-2.0 | 1,843 | 0.025502 | from OpenGL.GL import *
from .geometric import *
from ..spaces.objectives import *
from ..spaces.statespace import *
from ..spaces.configurationspace import *
from ..spaces.edgechecker import *
from ..spaces.metric import *
from ..spaces.biassets import InfiniteBiasSet
from ..planners.problem import PlanningProblem
imp... | B = np.zeros((n,m))
B[0,0] = 0.5*dt**2
B[1,0] = dt
Q = np.eye(n)*0.01
P = np.eye(m)*0.01
Qterm = np.eye(n)*1.0
objective = QuadraticObjectiveFunction(Q,np.zeros((n,m)),P,np.zeros(n),np.zeros(m),0,
Qterm,np.zeros(n))
controlSpace = LTIControlSpace(cspace,uspace,A,B)
return Pla | nningProblem(controlSpace,start,goal,
objective=objective,
visualizer=LQRVisualizer(cspace),
euclidean = True)
|
vsmolyakov/cv | manifold/manifold_learning.py | Python | mit | 2,762 | 0.025706 |
import numpy as np
import matplotlib.pyplot as plt
from time import time
from sklearn import manifold
from sklearn.datasets import load_digits
from sklearn.neighbors import KDTree
def plot_digits(X):
n_img_per_row = np.amin((20, np.int(np.sqrt(X.shape[0]))))
img = np.zeros((10 * n_img_per_row, 10 * n_img_p... | ))
plt.figure()
plt.imshow(img, cmap=plt.cm.binary)
plt.xticks([])
plt.yticks([])
plt.title('A selection from the 64-dimensional digits dataset')
def main():
digits = load_digits()
X = digits.data
y = digits.target
num_classes = np.unique(y).shape[0]
... | t0 = time()
tsne = manifold.TSNE(n_components = 2, init = 'pca', method = 'barnes_hut', verbose = 1)
X_tsne = tsne.fit_transform(X)
t1 = time()
print 't-SNE: %.2f sec' %(t1-t0)
tsne.get_params()
plt.figure(2)
for k in range(num_classes):
plt.plot(X_tsne[y==k,0], X_tsne[y=... |
UWCS/uwcs-website | uwcs_website/tournaments/admin.py | Python | agpl-3.0 | 197 | 0 | from uwcs_website.tournaments.models import *
from django.contrib import admin
admin.site.regi | ster(Tournament)
admin.site.register(Allocation)
admin.site.register(Match)
admin.site.registe | r(Game)
|
rajive/DDSChatApp | src/python/Chat_writer.py | Python | apache-2.0 | 1,610 | 0.004348 | ###############################################################################
# (c) 2005-2015 Copyright, Real-Time Innovations. All rights reserved. #
# No duplications, whole or partial, manual or electronic, may be made #
# without express written permission. Any such copies, or revisions thereof, #
... | t("Writing...")
for i in range(1, 100):
output.instance.set_string("id", "Rajive Python")
| output.instance.set_string("content", "Hello from Rajive Python" + str(i))
output.write()
sleep(0.5) # Write at a rate of one sample every 0.5 seconds, for ex.
print("Exiting...")
output.wait() # Wait for all subscriptions to receive the data before exiting |
Yadnyawalkya/integration_tests | cfme/utils/varmeth.py | Python | gpl-2.0 | 2,695 | 0.001485 | # -*- coding: utf-8 -*-
"""Method variant dec | orator. You specify the desired method variant by a kwarg.
.. code-block:: python
from cfme.utils.varmeth import variable
class SomeClass(object):
secret = 42
@variable
def mymethod(self):
print("I am defaul | t!")
@mymethod.variant("foo", "foo_too")
def i_foo(self):
print("I foo!")
@mymethod.variant("bar")
def in_bar(self):
print("In bar!")
@variable(alias="foo")
def myfoo(self):
print("foo!")
s = SomeClass()
s.mymethod() # => I... |
Clinical-Genomics/scout | tests/commands/update/test_update_institute_cmd.py | Python | bsd-3-clause | 2,917 | 0.0024 | # -*- coding: utf-8 -*-
from scout.commands import cli
from scout.server.extensions import store
def test_update_institute(mock_app):
"""Tests the CLI that updates an institute"""
runner = mock_app.test_cli_runner()
assert runner
# Test CLI base, no arguments provided
result = runner.invoke(cli... | ["update", "institute", "cust666"])
# it should return error message
assert "WARNING Institute cust666 does not exist in database" in result.output
# original institute in database
institute_obj = store.institute_collection.find_one()
updates = {
| "coverage_cutoff": 15,
"frequency_cutoff": 0.05,
"display_name": "updated_name",
"sanger_recipients": None,
}
# Test CLI to update coverage cutoff
result = runner.invoke(
cli, ["update", "institute", "cust000", "-c", updates["coverage_cutoff"]]
)
# it should r... |
stack-of-tasks/rbdlpy | tutorial/lib/python2.7/site-packages/OpenGL/WGL/EXT/create_context_es_profile.py | Python | lgpl-3.0 | 824 | 0.008495 | '''OpenGL extension EXT.create_context_es_profile
This module customises the behaviour of the
OpenGL.raw.WGL.EXT.create_context_es_profile to provide a more
Python-friendly API
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/EXT/create_conte | xt_es_profile.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.WGL import _types, _glgets
from OpenGL.raw.WGL.EXT.create_context_es_profile import *
from OpenGL.raw.WGL.EXT.create_context_es_profile import _EXTENSION_NAME
def glInitCreateContext... | ort extensions
return extensions.hasGLExtension( _EXTENSION_NAME )
### END AUTOGENERATED SECTION |
jcsp/manila | manila/tests/network/test_standalone_network_plugin.py | Python | apache-2.0 | 16,379 | 0 | # Copyright 2015 Mirantis, Inc.
# All Rights Reserved
#
# 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... | id='fake project', is_admin=False)
fake_share_server = dict(id='fake_share_server_id')
fake_share_network = dict(id='fake_share_network_id')
@ddt.ddt
class StandaloneNetworkPluginTest(test.TestCase):
@ddt.data('custom_config_group | _name', 'DEFAULT')
def test_init_only_with_required_data_v4(self, group_name):
data = {
group_name: {
'standalone_network_plugin_gateway': '10.0.0.1',
'standalone_network_plugin_mask': '24',
},
}
with test_utils.create_temp_config_with_... |
CroissanceCommune/autonomie | autonomie/alembic/versions/1_5_migrating_work_u_1212f113f03b.py | Python | gpl-3.0 | 2,158 | 0.00278 | """1.5 : Migrating work unity
Revision ID: 1212f113f03b
Revises: 1f07ae132ac8
Create Date: 2013-01-21 11:53:56.598914
"""
# revision identifiers, used by Alembic.
revision = '1212f113f03b'
down_revision = '1f07ae132ac8'
from alembic import op
import sqlalchemy as sa
UNITIES = dict(NONE="",
HOUR=u"h... |
for table in "estimation_line", "invoice_line", "cancelinvoice_line":
op.alter_column(table, "unity", type_=sa.String(100))
for value in UNITS:
unit = WorkUnit(label=value)
DBSESSION().add(unit)
for factory in (EstimationLine, InvoiceLine, | CancelInvoiceLine):
for line in factory.query():
line.unity = translate_unity(line.unity)
DBSESSION().merge(line)
def downgrade():
from autonomie.models.task import WorkUnit
from autonomie.models.task.estimation import EstimationLine
from autonomie.models.task.invoice import... |
ostree/plaso | plaso/parsers/bencode_plugins/__init__.py | Python | apache-2.0 | 131 | 0 | # -*- coding: utf-8 -*-
from plaso.parsers.ben | code_plugins import transmission
from p | laso.parsers.bencode_plugins import utorrent
|
micahflee/securedrop | securedrop/source_app/utils.py | Python | agpl-3.0 | 3,398 | 0.000589 | import subprocess
from datetime import datetime
from flask import session, current_app, abort, g
from threading import Thread
import crypto_util
import i18n
import store
from db import Source, db_session
def logged_in():
return 'logged_in' in session
def valid_codename(codename):
try:
filesystem_... | get_language())
# The maximum length of a word in the wordlist is 9 letters and the
# codename length is 7 | words, so it is currently impossible to
# generate a codename that is longer than the maximum codename length
# (currently 128 characters). This code is meant to be defense in depth
# to guard against potential future changes, such as modifications to
# the word list or the maximum coden... |
miguelgrinberg/heat | heat/common/grouputils.py | Python | apache-2.0 | 3,141 | 0 | #
# 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 writing, software
# ... | "Get a list of resource names of the resources in | the specified group.
Failed resources will be ignored.
"""
return [r.name for r in get_members(group)]
def get_resource(stack, resource_name, use_indices, key):
nested_stack = stack.nested()
if not nested_stack:
return None
try:
if use_indices:
return get_members(st... |
cbode/ssr | ssr_params.py | Python | gpl-2.0 | 7,659 | 0.009531 | #!/usr/bin/env python
############################################################################
#
# MODULE: ssr_params.py
# AUTHOR: Collin Bode, UC Berkeley
#
# PURPOSE: Consolidate parameters for all SSR scripts and to provide some
# common functions.
#
# DEPENDENCIES: requires fu... | ight
albedo = P + 'albedo' # albedo by vegtype
demhor = P + 'demhor' # horizon, bare-earth
canhor = P + 'demhor' # horizon, canopy
#--------------------------------------------------------------------------- | -
# SSR1: LIDAR IMPORT PARAMETERS
# LiDAR downloaded from http://opentopography.org.
# National Center for Airborne Laser Mapping (NCALM) distributes laser hits as 2 datasets: total and ground filtered.
# Version 1.0 only processes ASCII files with ground filtered exported to a separate directory. Future versions wil... |
chrisdickinson/nojs | build/android/apk_operations.py | Python | bsd-3-clause | 34,076 | 0.011944 | #!/usr/bin/env python
# Copyright 2017 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 argparse
import json
import logging
import os
import | pipes
import posixpath
import random
import re
import shlex
import sys
import devil_chromium
from devil import devil_env
from devil.android import apk_helper
from devil.android import device_errors
from devil.android import device_utils
from devil.android import flag_changer
from devil.android.sdk import adb_wrapper
f... | irname(__file__), '..', '..',
'third_party', 'colorama', 'src')):
import colorama
from incremental_install import installer
from pylib import constants
from pylib.symbols import deobfuscator
def _Colorize(color, text):
# |color| as a string to avoid pylint's no-member warning ... |
graebnerc/complexity-pluralism | src-python/reproduce_fig_2_3.py | Python | gpl-3.0 | 6,919 | 0.008239 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# figuers_2_3_complexity-and-pluralism.py
#
# Copyright 2017 Claudius Gräbner <claudius@claudius-graebner.com>
#
# 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 Fr... | _i[8+fixed_point[i]:-2][::2]:
add_arrow(y, j, direction="right", size=20)
else:
for j in shares_x_i[2+1:fixed_point[i]][::2]:
add_arrow(x, j,direction="left", size=20)
for j in shares_x_i[4+fixed_point[i]:-2][::2]:
add_arrow(y, j, direction="right", size=20)
... | er")
ax[locs[i]].set_xlabel("x_i")
ax[locs[i]].set_ylabel("p(x_i)")
ax[locs[i]].set_xticks(shares_x_i_print)
ax[locs[i]].spines["top"].set_visible(False)
ax[locs[i]].spines["right"].set_visible(False)
ax[locs[i]].get_xaxis().tick_bottom()
ax[locs[i]].get_yaxis().tick_left()
plt.tight... |
google/or-tools | ortools/linear_solver/linear_solver_natural_api.py | Python | apache-2.0 | 8,096 | 0.008646 | # Copyright 2010-2021 Google LLC
# 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 writing... | arg):
if isinstance(arg, | numbers.Number):
return LinearConstraint(self, arg, arg)
else:
return LinearConstraint(self - arg, 0.0, 0.0)
def __ge__(self, arg):
if isinstance(arg, numbers.Number):
return LinearConstraint(self, arg, inf)
else:
return LinearConstraint(self - arg, 0.0, inf)
def __le__(self, a... |
NicovincX2/Python-3.5 | Théorie des nombres/Arithmétique/Théorie algébrique des nombres/Arithmétique multiprécision/arbitrary-precision_integers_example.py | Python | gpl-3.0 | 152 | 0 | # -*- coding: utf-8 -*-
import os
y = s | tr(5**4**3**2)
print( | "5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y)))
os.system("pause")
|
talaniz/django-tdd | functional_tests/test_simple_list_creation.py | Python | mit | 3,306 | 0.005747 | from .base import FunctionalTest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class NewVisitorTest(FunctionalTest):
def test_can_start_a_list_and_retrieve_it_later(self):
# Edith has heard about a cool new online to-do app. She goes
# to check out its homepage
... | rtRegex(edith_list_url, '/lists/.+')
self.check_for_row_in_list_table('1: Buy peacock feathers')
# There is still a text box inviting her to add | another item. She
# enters "Use peacock feathers to make a fly" (Edith is very methodical)
inputbox = self.get_item_input_box()
inputbox.send_keys('Use peacock feathers to make a fly')
inputbox.send_keys(Keys.ENTER)
# The page updates again, and now shows both items on ... |
bmess/riak-python-client | riak/tests/test_datatypes.py | Python | apache-2.0 | 15,657 | 0 | # -*- coding: utf-8 -*-
"""
Copyright 2015 Basho Technologies, Inc.
This file is provided to you 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 require... | NotIn('a', mymap.counters)
self.assertIn('f', mymap.sets)
self.assertItemsEqual(['thing1', 'thing2'], mymap.sets['f'].value)
@unittest.skipIf(SKIP_DATATYPES, 'SKIP_DATATYPES is set')
def test_dt_set_remove_without_context(self):
bty | pe = self.client.bucket_type('pytest-sets')
bucket = btype.bucket(self.bucket_name)
set = datatypes.Set(bucket, self.key_name)
set.add("X")
set.add("Y")
set.add("Z")
with self.assertRaises(datatypes.ContextRequired):
set.discard("Y" |
projecthamster/hamster-lib | tests/helpers/test_config_helpers.py | Python | gpl-3.0 | 7,849 | 0.002166 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from configparser import ConfigParser
import pytest
from hamster_lib.helpers import config_helpers
from hamster_lib.helpers.config_helpers import HamsterAppDirs
class TestHamsterAppDirs(object):
"""Make sure that our cu... | instance, backend_config):
"""Make sure we try parsing a found config file."""
result = config_helpers.load_config_file()
assert isinstance(result, ConfigParser)
class TestConfigParserToBackendConfig(object):
"""Make sure that conversion works expected."""
de | f test_regular_usecase(self, configparser_instance):
"""Make sure basic mechanics work and int/time types are created."""
cp_instance, expectation = configparser_instance
result = config_helpers.configparser_to_backend_config(cp_instance)
assert result == expectation
|
FCP-INDI/nipype | nipype/workflows/smri/freesurfer/ba_maps.py | Python | bsd-3-clause | 8,682 | 0.00334 | import os
import nipype
from nipype.interfaces.utility import Function,IdentityInterface
import nipype.pipeline.engine as pe # pypeline engine
from nipype.interfaces.freesurfer import *
from nipype.interfaces.io import DataGrabber
from nipype.interfaces.utility import Merge
def create_ba_maps_wf(name="Brodmann_Area_M... | inputs.hemisphere = hemisphere
stats_node.inputs.mgz = True
stats_node.inputs.th3 = th3
stats_node.inputs.surface = 'white'
stats_node.inputs.tabular_output = True
stats_node. | inputs.copy_inputs = True
if threshold:
label2annot.inputs.out_annot = "BA_exvivo.thresh"
ba_WF.connect([(stats_node, outputspec, [('out_color',
'{0}_thresh_color'.format(hemisphere)),
... |
EndPointCorp/lg_ros_nodes | spacenav_remote/scripts/server.py | Python | apache-2.0 | 1,985 | 0 | #! /usr/bin/env python3
import json
import rospy
from sensor_msgs.msg import Joy
from geometry_msgs.msg import Twist
from spacenav_remote import SpacenavRemote
NODE_NAME = 'spacenav_remote'
def main():
rospy.init_node(NODE_NAME)
topic = rospy.get_param('~topic', '/spacenav')
port = rospy.get_param('~li... | '][1]
twist.angular.z = recived['rot'][2]
twist.li | near.x = recived['trans'][0]
twist.linear.y = recived['trans'][1]
twist.linear.z = recived['trans'][2]
twist_pub.publish(twist)
except AttributeError as e:
print(e)
server = SpacenavRemote(handler=handler, port=port)
server.fork_and_run()
... |
jolyonb/edx-platform | lms/djangoapps/courseware/access.py | Python | agpl-3.0 | 32,665 | 0.002878 | """
This file contains (or should), all access control logic for the courseware.
Ideally, it will be the only place that needs to know about any special settings
like DISABLE_START_DATES.
Note: The access control logic in this file does NOT check for enrollment in
a course. It is expected that higher layers check f... | uisite_courses_not_completed,
is_prerequisite_courses_enabled
)
from xmodule.course_module import CATALOG_VISIBILITY_ABOUT, CATALOG_VISIBILITY_CATALOG_AND_ABOUT, CourseDescriptor
from xmodule.error_module import ErrorDescriptor
from xmodule.partitions.partitions import NoSuchUserPartitionError, NoSuchUserPartitionG... |
"""
Check if user is a coach on this ccx.
Arguments:
user (User): the user whose descriptor access we are checking.
course_key (CCXLocator): Key to CCX.
Returns:
bool: whether user is a coach on this ccx or not.
"""
if hasattr(course_key, 'ccx'):
ccx_id = cours... |
lidaobing/itcc | itcc/ccs2/transformation.py | Python | gpl-3.0 | 1,262 | 0.025357 | import numpy
class RotationTranslation:
| """Combined translational and rotational transformation.
This is a subclass of Transformation.
Objects of this class are not created directly, but can be the
result of a composition of rotations and translations.
"""
def __init__(self, tensor, vector):
self.tensor = tensor.copy()
self.vector =... | tionTranslation(numpy.dot(self.tensor, other.tensor),
self.vector)
elif hasattr(other, 'is_translation'):
return RotationTranslation(self.tensor,
numpy.dot(self.tensor, other.vector)+self.vector)
elif hasattr(other, 'is_rotation_translation'):
return RotationTranslation(numpy.dot(self.... |
ferriman/SSandSP | pyxel-test/venv/lib/python3.8/site-packages/pyxel/examples/09_shooter.py | Python | gpl-3.0 | 8,375 | 0.000359 | from random import random
import pyxel
SCENE_TITLE = 0
SCENE_PLAY = 1
SCENE_GAMEOVER = 2
STAR_COUNT = 100
STAR_COLOR_HIGH = 12
STAR_COLOR_LOW = 5
PLAYER_WIDTH = 8
PLAYER_HEIGHT = 8
PLAYER_SPEED = 2
BULLET_WIDTH = 2
BULLET_HEIGHT = 8
BULLET_COLOR = 11
BULLET_SPEED = 4
ENEMY_WIDTH = 8
ENEMY_HEIGHT = 8
ENEMY_SPEED =... | aw(self):
pyxel.cls(0)
self.background.draw()
if self.scene == SCENE_TITLE:
self.draw_title_scene()
elif self.scene == SCENE_PLAY:
self.draw_play_scene()
elif self.scene == SCENE_GAMEOVER:
self.draw_gameover_scene()
| pyxel.text(39, 4, "SCORE {:5}".format(self.score), 7)
def draw_title_scene(self):
pyxel.text(35, 66, "Pyxel Shooter", pyxel.frame_count % 16)
pyxel.text(31, 126, "- PRESS ENTER -", 13)
def draw_play_scene(self):
self.player.draw()
draw_list(bullet_list)
draw_list(enemy_... |
scities-data/metro-atlas_2014 | bin/income/income_tract.py | Python | bsd-2-clause | 2,140 | 0.015421 | """income_tract.py
Extract the household income per tract for each cbsa, using the
crosswalk between CBSA and Tracts.
"""
import csv
import os
# Income file comprises estimates and margin of error
income_rows = [5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35]
#
# Import data
#
## CBSA to tract
tr_to_cbsa = {}
w... | bg]):
incomes_cbsa[cbsa][tr][i] += val
else:
out_cbsa += 1
print '%s tracts are | inside CBSAs'%in_cbsa
print '%s tracts are outside CBSAs'%out_cbsa
#
# Save the data
#
for cbsa in incomes_cbsa:
## Create dir if needed
if not os.path.isdir('data/income/cbsa/%s'%cbsa):
os.mkdir('data/income/cbsa/%s'%cbsa)
## Save
with open('data/income/cbsa/%s/%s_income_tract.txt'%(cb... |
ceph/swift | test/functional/tests.py | Python | apache-2.0 | 63,978 | 0.003642 | #!/usr/bin/python -u
# Copyright (c) 2010-2011 OpenStack, LLC.
#
# 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... |
self.assert_(self.env.conn.response.status == status_or_statuses or
(hasattr(status_or_statuses, '__iter__') and
self.env.conn.response.status in status_or_statuses),
'Status returned: %d Expected: %s' %
(self.env.conn.response.status, status_or_... | lf):
Utils.create_name = Utils.create_utf8_name
super(Base2, self).setUp()
def tearDown(self):
Utils.create_name = Utils.create_ascii_name
class TestAccountEnv:
@classmethod
def setUp(cls):
cls.conn = Connection(config)
cls.conn.authenticate()
cls.account = ... |
rebaltina/DAT210x | Module4/assignment2_true.py | Python | mit | 3,557 | 0.00506 | import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import assignment2_helper as helper
# Look pretty...
matplotlib.style.use('ggplot')
# Do * NOT * alter this line, until instructed!
scaleFeatures = True
# TODO: Load up the dataset and remove any and all
# Rows that have a nan. You should be a p... | e in the attribute info
# section: https://archive.ics.uci.edu/ml/datasets/Chronic_Kidney_Disease
# or you can actually peek through the dataframe by printing a few rows.
# What ki | nd of data type should these three columns be? If Pandas didn't
# properly detect and convert them to that data type for you, then use
# an appropriate command to coerce these features into the right type.
#
# .. your code here ..
df.wc=pd.to_numeric(df.iloc[:,1], errors='coerce')
df.rc=pd.to_numeric(df.iloc[:,2], erro... |
petrstehlik/weather-station | sensors/dht.py | Python | gpl-3.0 | 396 | 0.025253 | import sys
import os
sys.path.append(os.path.join(os.path.dirn | ame(__file__), '../modules'))
from DHT11_Python import dht11
import logging
from average import average
log = logging.getLogger(__name__)
# Set DHT11 to read data from pin 4
dht = dht11.DHT11(pin=4)
def read():
"""
For reading DHT11 sensor which is very unreliable
"""
log.debug("Reading DHT11 sensor")
return ... | ())
|
rustychris/stompy | stompy/model/data_comparison.py | Python | mit | 17,181 | 0.018509 | """
Tools related to comparing time series, typically model-obs or model-model.
"""
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
import logging as log
import matplotlib.gridspec as gridspec
from stompy import filters
from matplotlib import dates
from scipy.stats import spea... | model_labels)>=len(models),"Not enough model labels supplied"
# Collect inferred options for extracting model data, which
# can lat | er be overridden by extract_options
loc_extract_opts=dict()
# Convert BC instances into dataarrays
new_obs=[]
for oi,obs in enumerate(observations):
if isinstance(obs,hm.BC):
# Have to decide at this point what period of data to request
if period=='model': # the ... |
rohangoel96/IRCLogParser | IRCLogParser/lib/util.py | Python | mit | 6,615 | 0.006803 | import networkx as nx
import numpy as np
import igraph
import config
def correctLastCharCR(inText):#
""" if the last letter of the nick is '\\' replace it by 'CR'
for example rohan\ becomes rohanCR
to avoid complications in nx because of the special char '\\'
Args:
inText (str): input ... | st(list): list of connected nicks
nick_sen_rec(str): nick sender/receiver that we wish to find
"""
for i in range(iter_range):
if((i < len(conn_comp_list)) and (nick_to_search in conn_comp_list[i])):
nick_sen_rec = conn_comp_list[i][0]
brea | k
return nick_sen_rec
|
HewlettPackard/oneview-ansible | library/hpe_icsp_os_deployment.py | Python | apache-2.0 | 6,438 | 0.002019 | #!/usr/bin/python
# -*- coding: utf-8 -*-
###
# Copyright (2016-2017) Hewlett Packard Enterprise Development LP
#
# 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/licen... | ded network personalization, update the server to include it
if personality_data:
server_data['personalityData'] = personality_data
network_config = {"serverData": [server_data]}
# Monitor the execution of a nework personalization job.
hpICsp.common.monitor_execution(jb.add_job(netwo... | sg='OS Deployed Successfully.', ansible_facts={'icsp_server': server})
def main():
module = AnsibleModule(
argument_spec=dict(
api_version=dict(type='int', default=300),
icsp_host=dict(required=True, type='str'),
username=dict(required=True, type='str'),
pas... |
Yelp/kafka-python | kafka/coordinator/heartbeat.py | Python | apache-2.0 | 2,304 | 0.002604 | from __future__ import absolute_import, division
import copy
import time
class Heartbeat(object):
DEFAULT_CONFIG = {
'group_id': None,
'heartbeat_interval_ms': 3000,
'session_timeout_ms': 10000,
'max_poll_interval_ms': 300000,
'retry_backoff_ms': 100,
}
def __init... | alse
def fail_heartbeat(self):
self.heartbeat_failed = True
def received_heartbeat(self):
self.last_receive = time.tim | e()
def time_to_next_heartbeat(self):
"""Returns seconds (float) remaining before next heartbeat should be sent"""
time_since_last_heartbeat = time.time() - max(self.last_send, self.last_reset)
if self.heartbeat_failed:
delay_to_next_heartbeat = self.config['retry_backoff_ms'] /... |
tomspur/dnf-plugins-buildlocal | buildlocal.py | Python | gpl-2.0 | 8,142 | 0.000737 | # Copyright (C) 2013-2015 Red Hat, Inc.
# Copyright (C) 2015 Thomas Spura
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is di... | awkey.Goal(self.base.sack)
for pkg in pkgs:
goal.install(pkg)
rc = g | oal.run()
if rc:
pkgs = goal.list_installs()
return pkgs
else:
logger.debug(_('Error in resolve'))
return []
@staticmethod
def _get_source_packages(pkgs):
"""Get list of source rpm names for a list of packages."""
source_pkgs = set... |
kalaytan/findatapy | findatapy/market/datavendor.py | Python | apache-2.0 | 7,322 | 0.004644 | __author__ = 'saeedamen' # Saeed Amen
#
# Copyright 2016 Cuemacro
#
# 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 l... | return market_data_request.vendor_fields
source = market_data_request.data_source
fields_list = market_data_request.fields
| if isinstance(fields_list, str):
fields_list = [fields_list]
if self.config is None: return fields_list
fields_converted = []
for field in fields_list:
fields_converted.append(self.config.convert_library_to_vendor_field(source, field))
return fields_conv... |
alfredgamulo/cloud-custodian | c7n/filters/missing.py | Python | apache-2.0 | 2,027 | 0 | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from .core import Filter
from c7n.exceptions import PolicyValidationError
from c7n.loader import PolicyLoader
from c7n | .utils import type_schema
class Missing(Filter):
"""Assert the absence of a particular resource.
Intended for use at a logical account/subscr | iption/project level
This works as an effectively an embedded policy thats evaluated.
"""
schema = type_schema(
'missing',
policy={'type': 'object',
'required': ['resource'],
'properties': {'resource': {'type': 'string'}}},
required=['policy'])
d... |
paulcockram7/paulcockram7.github.io | 10python/l05/Exercise 3.py | Python | mit | 171 | 0.017544 | # Exercise 3
# creating a sim | ple loop
# print out 1 thru 10
#set the start | value
i = 0
upper_range=10
for i in range(upper_range):
print(str(i+1)+ " this is a loop")
|
WoLpH/pybagit | pybagit/multichecksum.py | Python | mit | 4,828 | 0.0029 | # !/usr/bin/env python
__author__ = "Andrew Hankinson (andrew.hankinson@mail.mcgill.ca)"
__version__ = "1.5"
__date__ = "2011"
__copyright__ = "Creative Commons Attribution"
__license__ = """The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of... | k(datadir):
datafiles = []
for dirpath, dirnames, filenames in os.walk(datadir):
for fn in filenames:
datafiles.append(os.path.join(dirpath, fn))
return datafiles
def csumfile(filename):
""" Based on
http://abstracthack.wor | dpress.com/2007/10/19/calculating-md5-checksum/
"""
hashalg = getattr(hashlib, HASHALG)() # == 'hashlib.md5' or 'hashlib.sha1'
blocksize = 0x10000
def __upd(m, data):
m.update(data)
return m
fd = open(filename, 'rb')
try:
contents = iter(lambda: fd.read(blocksize), ""... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.3/django/contrib/gis/tests/relatedapp/models.py | Python | bsd-3-clause | 1,686 | 0.005931 | from django.contrib.gis.db import models
from django.contrib.localflavor.us.models import USStateField
class Location(models.Model):
point = models.PointField()
objects = models.GeoManager()
def __unicode__(self): return self.point.wkt
class City(models.Model):
name = models.CharField(max_length=50)
... | toryEntry(models.Model):
listing_text = models.CharField(max_length=50)
location = models.ForeignKey(AugmentedLocation)
| objects = models.GeoManager()
class Parcel(models.Model):
name = models.CharField(max_length=30)
city = models.ForeignKey(City)
center1 = models.PointField()
# Throwing a curveball w/`db_column` here.
center2 = models.PointField(srid=2276, db_column='mycenter')
border1 = models.PolygonField(... |
parkus/arc | test_script_custom.py | Python | mit | 6,641 | 0.004969 | """
Some commands for testing out the ARC code.
"""
import numpy as np
import numpy.random as r
from math import pi, log10
import arc
import matplotlib.pyplot as plt
# for repeatability, seed the random number generator
r.seed(42)
N = 500 # number of data points
M = 200 # number of data series
t = np.arange(N)
#%%... | ARC can't handle.
noise_amps = np.sqrt(levels) * 0.05
data_err = np.outer(np.ones(N), noise_amps) # makes an NxM array of errors
noise = noise_amps[ | np.newaxis, :] * r.normal(size=[N, M])
data2 = data1 + noise
#%% ---------------------------------------------------------------------------
# IDENTIFY TRENDS WITH THE ARC
trends = arc.arc.arc(t, data2, rho_min=0.5)
# NOTE: A lower rho_min than that recommended by Roberts et al. is necessary
# to detect the trends in... |
craws/OpenAtlas | openatlas/api/csv_export.py | Python | gpl-2.0 | 5,849 | 0 | import zipfile
from collections import defaultdict
from io import BytesIO
from itertools import groupby
from typing import Any, Union
import pandas as pd
from flask import Response, g
from openatlas.api.v03.resources.util import get_linked_entities_api, \
link_parser_check, remove_duplicate_entities
from openatla... |
return {'type': None, 'coordinates': None}
def export_csv_for_network_analysis(
entities: list[Entity],
parser: dict[str, Any]) -> Response:
archive = BytesIO()
with zipfile.ZipFile(archive, 'w') as zipped_file:
for key, frame in get_entities_grouped_by_class(entities).items():
... | le:
file.write(bytes(
pd.DataFrame(data=frame).to_csv(), encoding='utf8'))
with zipped_file.open('links.csv', 'w') as file:
link_frame = [build_link_dataframe(link_) for link_ in
(link_parser_check(entities, parser) +
... |
ubuntunux/PyEngine3D | PyEngine3D/Render/Renderer.py | Python | bsd-2-clause | 60,697 | 0.004119 | from ctypes import c_void_p
import math
import numpy as np
from OpenGL.GL import *
from OpenGL.GLU import *
from PyEngine3D.Common import logger, COMMAND
from PyEngine3D.Common.Constants import *
from PyEngine3D.Utilities import *
from PyEngine3D.OpenGLContext import InstanceBuffer, FrameBufferManager, RenderBuffer,... | ('INV_VIEW_ORIGIN', np.float32, (4, 4)),
('PROJECTION', np.float32, (4, 4)),
('INV_PROJECTION', np.float32, (4, 4)),
('CAMERA_PO... | ('NEAR_FAR', np.float32, 2),
('JITTER_DELTA', np.float32, 2),
('JITTER_OFFSET', np.float32, 2),
('VIE |
arantes555/oblivious-movie-gharial | logger.py | Python | mit | 1,214 | 0 | import logging
import os
import utils
def initialize(output_dir, reset=True):
all_path = os.path.join(output_dir, 'all.log')
error_path = os.path.join(output_dir, 'error.log')
if reset:
utils.safe_remove(all_ | path)
utils.safe_remove(error_path)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# create console handler and set level to info
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s %(levelname)s - %(message)s")
h... | rror file handler and set level to error
handler = logging.FileHandler(error_path, "w", encoding=None, delay="true")
handler.setLevel(logging.ERROR)
formatter = logging.Formatter("%(asctime)s %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# create debug... |
mpharrigan/firstinbattle | firstinbattle/tests/test_json.py | Python | mit | 636 | 0 | from unittest import TestCase
from firstinbattle.deck import Card
from firstinbattle.json_util import js
class TestJson(TestCase):
def test_encode_loads(self):
cards = {
Card(5, 'diamond'),
Card(9, 'heart'),
}
encoded_str = js.encode({
'message': 'test_... | decoded_obj = js.loads(encoded_str)
self.assertEqual(decoded_obj['mes | sage'], 'test_msg')
for card in cards:
self.assertIn(
{'number': card.number, 'suit': card.suit},
decoded_obj['cards']
)
|
newsoft/dpapick | DPAPI/Probes/IE7.py | Python | gpl-3.0 | 4,651 | 0.00387 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#############################################################################
## ##
## This file is part of DPAPIck ##
## Windows DPAPI decryption & forensic ... | : %r" % self.dpapiblob)
return "\n".join(s)
def parse(self, data):
pass
def preprocess(self, **k):
self._dicurls = {}
self.entries = k.get("values", {})
self.urls = k.get("urls", [])
## Compute a dict of sha1 for faster looku | p
for i in self.urls:
u = (i + "\0").encode("UTF-16LE")
self._dicurls[hashlib.sha1(u).hexdigest().lower()] = u
## Strip the last 2 chars of hash & build the blob
arr = self.entries.keys()
for i in arr:
self.entries[i[:40].lower()] = IE7Autocomplete.IE7... |
antoinecarme/pyaf | tests/periodicities/Semi_Month/Cycle_Semi_Month_100_SM_120.py | Python | bsd-3-clause | 84 | 0.047619 | import tests.periodicities.pe | riod_test as per
per.bui | ldModel((120 , 'SM' , 100));
|
raycarnes/addons-yelizariev | reminder_phonecall/__openerp__.py | Python | lgpl-3.0 | 370 | 0 | {
'name': "Reminde | rs and Agenda for Phonecalls",
'version': '1.0.0',
'author': 'IT-Projects LLC, Ivan Yelizariev',
'category': 'Reminders and Agenda',
'website': 'https://yelizariev.github.io',
'price': 6.00,
'currency': 'EUR',
'depends': ['reminder_base', 'crm'],
| 'data': [
'views.xml',
],
'installable': True,
}
|
dschaefer/esp-idf | components/idf_test/integration_test/TestCaseScript/TCPStress/TCPMultiSTASendRecv.py | Python | apache-2.0 | 7,518 | 0.004789 | from TCAction import TCActionBase
from NativeLog import NativeLog
import time
import random
import string
TEST_COUNT_ONE_ROUND = 500
class TestCase(TCActionBase.CommonTCActionBase):
def __init__(self, test_case, test_env, timeout=45, log_path=TCActionBase.LOG_PATH):
TCActionBase.CommonTCActionBase.__init... | arent script, error is %s" % e)
raise StandardError("Error configuration")
# step0 reboot
for i in range(sta_number + 1):
checker_stings = ["P SSC%d C ready | !!!" % (i + 1)]
test_action_string = ["SSCC SSC%d restore" % (i + 1)]
fail_string = "Fail, Fail to restore"
if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:
return
# turn off recv print
for i in range(sta_number... |
jeroendierckx/Camelot | camelot/view/controls/editors/noteeditor.py | Python | gpl-2.0 | 2,297 | 0.016979 | # ============================================================================
#
# Copyright (C) 2007-2012 Conceptive Engineering bvba. All rights reserved.
# www.conceptive.be / project-camelot@conceptive.be
#
# This file is part of the Camelot Library.
#
# This file may be used under the terms of the GNU General... | g,
QtGui.QSizePolicy.Minimum )
style = """
QLabel {
margin: 0px;
padding: 3px;
border: 1px solid black;
color: black;
background-c | olor: %s;
}
"""%(ColorScheme.yellow_1.name())
self.setStyleSheet( style );
def set_value( self, value ):
value = super( NoteEditor, self ).set_value( value )
self.setVisible( value != None )
if value:
self.setText( unicode( value ) )
|
luisza/dfva_client | src/client_fva/ui/mysignaturesui.py | Python | gpl-3.0 | 2,400 | 0.003333 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'client_fva/ui/ui_elements/mysignatures.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MySignatures(object):
def setupUi(se... | es", "Mis Firmas"))
self.searchDocument.setPlaceholderText(_translate("MySignatures", "Buscar nombre del documento..."))
from . import resources_rc
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MySignatures = Q | tWidgets.QWidget()
ui = Ui_MySignatures()
ui.setupUi(MySignatures)
MySignatures.show()
sys.exit(app.exec_())
|
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_06_01/aio/operations/_virtual_network_gateways_operations.py | Python | mit | 110,053 | 0.005434 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | eader_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
| header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'VirtualNetworkGateway')
body_content_kwargs['content'] = body_content
request = self._client.put(url, quer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.