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 |
|---|---|---|---|---|---|---|---|---|
popazerty/openhdf-enigma2 | lib/python/Plugins/Extensions/ZapHistoryBrowser/plugin.py | Python | gpl-2.0 | 9,376 | 0.026024 | # -*- coding: UTF-8 -*-
## Zap-History Browser by AliAbdul
from Components.ActionMap import ActionMap
from Components.config import config, ConfigInteger, ConfigSelection, ConfigSubsection, getConfigListEntry
from Components.ConfigList import ConfigListScreen
from Components.Label import Label
from Components.Language ... | ontrol.getProtectionLevel(ref.toCompareString()) != -1:
return
if instance.servicePath is not None:
tmp = instance.servicePath[:]
tmp.append(ref)
try: del instance.history[instance.history_pos+1:]
except: pass
instance.history.append(tmp)
hlen = len(instance.history)
if hlen > config.plugins.ZapHistor... | instance.history_pos = hlen-1
ChannelSelection.addToHistory = addToHistory
################################################
class ZapHistoryConfigurator(ConfigListScreen, Screen):
skin = """
<screen position="center,center" size="420,70" title="%s" >
<widget name="config" position="0,0" size="420,70" scrollb... |
balazs-bamer/FreeCAD-Surface | src/Mod/Arch/ArchWall.py | Python | lgpl-2.1 | 22,906 | 0.013926 | #***************************************************************************
#* *
#* Copyright (c) 2011 *
#* Yorik van Havre <yorik@uncreated.net> *
#* ... | OOP("Arch_Wall","Wall"),
'Accel': "W, A",
'ToolTip': QtCore.QT_TRANSLATE_NOOP("Arch_Wall","Creates a wall object from scratch or from a selected object (wire, face or solid)")}
def IsActive(self):
return not FreeCAD.ActiveDocument is None
def Activated(self):
... | self.continueCmd = False
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
self.Width = p.GetFloat("WallWidth",200)
self.Height = p.GetFloat("WallHeight",3000)
self.JOIN_WALLS_SKETCHES = p.GetBool("joinWallSketches",False)
self.AUTOJOIN = p.GetBool("autoJoinWal... |
iceihehe/union-pay | basic.py | Python | mit | 4,174 | 0 | # -*- coding: utf-8 -*-
import OpenSSL.crypto
import base64
import urllib
import hashlib
class ChinaPay(object):
def __init__(self, MerId, pfx_path, pfx_pwd, cer_path):
"""
:param MerId: 商户号
:param pfx_path: 交易证书路径
:param pfx_pwd: 交易证书密码
:param cer_path: 验签证书路径
""... | rify(self, data):
"""验签
:param data: 银联返回的已签名的dictionary
"""
|
alg = 'sha1'
signature = base64.b64decode(data.pop('signature'))
sign_raw_str = self._get_sign_str(data)
sign_raw_str_sha1 = hashlib.sha1(sign_raw_str).hexdigest()
try:
OpenSSL.crypto.verify(self.cer, signature, sign_raw_str_sha1, alg)
return True
... |
molobrakos/home-assistant | homeassistant/components/google_assistant/__init__.py | Python | apache-2.0 | 3,249 | 0 | """Support for Actions on Google Assistant Smart Home Control."""
import asyncio
import logging
from typing import Dict, Any
import aiohttp
import async_timeout
import voluptuous as vol
# Typing imports
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.const import CONF_NAME
from homeassi... | al(CONF_ROOM_HINT): cv.string,
})
GOOGLE_ASSISTANT_SCHEMA = vol.Schema({
vol.Required(CONF_PROJECT_ID): cv.string,
vol.Optional(CONF_EXPOSE_BY_DEFAULT,
default=DEFAULT_EXPOSE_BY_DEFAULT): cv.boolean,
vol.Optional(CONF_EXPOSED_DOMAINS,
default=DEFAULT_EXPOSED_DOMAINS): cv.e... | Y): cv.string,
vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: ENTITY_SCHEMA},
vol.Optional(CONF_ALLOW_UNLOCK,
default=DEFAULT_ALLOW_UNLOCK): cv.boolean,
}, extra=vol.PREVENT_EXTRA)
CONFIG_SCHEMA = vol.Schema({
DOMAIN: GOOGLE_ASSISTANT_SCHEMA
}, extra=vol.ALLOW_EXTRA)
async def async_se... |
leocnj/dl_response_rater | archv/pd_load.py | Python | mit | 2,418 | 0.00579 | """
load score-level asroutput files into a pandas df
"""
import re
import pandas as pd
def mr_csvs():
"""
load data/mr.p and generate two csv files.
:return:
"""
x = pickle.load(open('data/mr.p', "rb"))
revs, W, W2, word_idx_map, vocab = x[0], x[1], x[2], x[3], x[4]
print("mr.p has been l... | "
txts = []
scores = []
for score in [0, 1, 2, 3]:
afile = data_folder[score]
print "score:" + str(score) + data_folder[score]
with open(afile, "rb") as f:
for line in f:
rev = []
rev.append(line.strip())
if clean_string:
... | orig_rev = " ".join(rev).lower()
scores.append(score)
txts.append(orig_rev)
df = pd.DataFrame({'text': txts, 'score': scores})
df.to_csv(open(csvFile, 'wb'))
def clean_str(string, TREC=False):
"""
Tokenization/string cleaning for all datasets except fo... |
Kami/libcloud | docs/examples/container/kubernetes/instantiate_driver_minikube_cert_auth.py | Python | apache-2.0 | 725 | 0 | from libcloud.container.types import Provider
from libcloud.container.providers import get_driver
import libcloud.security
# Disable cert vertification when running minikube locally using self signed
# cert
libcloud.security.VERIFY_SSL_CERT = False
cls = get_driver(Provider.KUBERNETES)
# You can retrieve cluster ip... | cert_file='/home/user/.minikube/client.crt',
ca_cert='/home/user/.minikube/ca.crt')
for container in conn.list_containers( | ):
print(container.name)
for cluster in conn.list_clusters():
print(cluster.name)
|
rstms/txtrader_client | txtrader_client/__init__.py | Python | mit | 356 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
txTrader Client Module
Copyright (c) 2017 Reliance Systems Inc. <mkrueger@rstms.net>
Li | censed under the MIT license. See LICENSE for details.
"""
fr | om .cli import cli
from .client import API
from .version import VERSION as __version__
from .version import DATE as __date__
from . import defaults
|
ducted/duct | duct/logs/follower.py | Python | mit | 2,971 | 0 | """
.. module:: follower
:synopsis: Log tailing classes
.. moduleauthor:: Colin Alston <colin@imcol.in>
"""
import os
class LogFollower(object):
"""Provides a class for following log files between runs
:param logfile: Full path to logfile
:type logfile: str
:param parser: Optional parser method f... | li)
else:
if self.history:
self.lastSize = 0
self.lastInode = 0
else:
# Don't re-read the entire file
| stat = os.stat(self.logfile)
self.lastSize = stat.st_size
self.lastInode = stat.st_ino
def get_fn(self, fn, max_lines=None):
"""Passes each parsed log line to `fn`
This is a better idea than storing a giant log file in memory
"""
stat = os.stat(self... |
zephyrproject-rtos/zephyr | scripts/tracing/parse_ctf.py | Python | apache-2.0 | 4,911 | 0.003462 | #!/usr/bin/env python3
#
# Copyright (c) 2020 Intel Corporation.
#
# SPDX-License-Identifier: Apache-2.0
"""
Script to parse CTF data and print to the screen in a custom and colorful
format.
Generate trace using samples/subsys/tracing for example:
west build -b qemu_x86 samples/subsys/tracing -t run \
-- -... | name in ['thread_switched_out', 'thread_switched_in'] and cpu is not None:
cpu_string = f"(cpu: {cpu})"
else:
| cpu_string = ""
if thread_name:
print(f"{dt} (+{diff_s:.6f} s): {event.name}: {thread_name} {cpu_string}")
elif thread_id:
print(f"{dt} (+{diff_s:.6f} s): {event.name}: {thread_id} {cpu_string}")
else:
print(f"{dt} (+{diff_s:.6f} s): {... |
nathanhilbert/FPA_Core | openspending/forum/forum/models.py | Python | agpl-3.0 | 34,388 | 0.000465 | # -*- coding: utf-8 -*-
"""
flaskbb.forum.models
~~~~~~~~~~~~~~~~~~~~
It provides the models for the forum
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
from datetime import datetime, timedelta
from flask import url_for, abort
from sqlalchemy.orm impor... | eck if there is a second last post, else it is the first post
if self.topic.second_last_post:
# Now the second last post will be the last post
self.topic.last_post_id = self.topic.second_last_post
| # there is no second last post, now the last post is also the
# first post
e |
dimagi/commcare-hq | corehq/apps/commtrack/migrations/0004_update_overstock_threshold.py | Python | bsd-3-clause | 449 | 0.002227 | # Generated by Django 2.2.16 on 2021-02-08 21:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('commtrack', '0003_create_config_models'),
]
operations = [
migrations.AlterField(
| model_name='sqlstocklevelsconfig',
name='overstock_threshold',
field=models.DecimalField(decimal_places=2, | default=3, max_digits=5),
),
]
|
Langhaarjoe/iRnWsLeo | search_backend/__init__.py | Python | mit | 1,949 | 0.00667 | from nltk.tokenize import word_tokenize
from nltk.stem.snowball import EnglishStemmer
from nltk.corpus import stopwords
from collections import defaultdict
from search_backend.search_index import searchIndex
import operator
#from iRnWsLeo.search_backend.search_index import searchIndex
#from search_backend.create_index ... | .format(query_string),
'href': 'http://www.google.com'
})
else:
for key in search_results:
resu | lt_list.append({
'title': '{}'.format(key[0]),
'snippet': '<b>Context</b>: ...{}...<br/><b>Summary</b>: '
'{}<br/>ranking: {}'.format(
context_list[key[0]]['snippet'],
context_list[key[0]]['summary'],
... |
ainur-fa/python_training_mantis | fixture/orm.py | Python | apache-2.0 | 3,010 | 0.00598 | from pony.orm import *
from datetime import datetime
from model.contact import Contact
from model.group import Group
from pymysql.converters import decoders
from pymysql.converters import encoders, decoders, convert_mysql_timestamp
class ORMFixture:
db = Database()
class ORMGroup(db.Entity):
_table_=... | , user, password):
#self.db.bind('mysql', host=host, database=name, user=user,password=password, conv=decoders)
# self.db.generate_mapping()
# sql_debug(True)
conv = encoders
conv.update(de | coders)
conv[datetime] = convert_mysql_timestamp
self.db.bind('mysql', host=host, database=name, user=user, password=password, conv=conv)
self.db.generate_mapping()
sql_debug(True)
def convert_groups_to_model(self, groups):
def convert(group):
return Group(id=str... |
kgronich/google-python-exercises | copyspecial/copyspecial.py | Python | apache-2.0 | 2,437 | 0.018055 | #!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
"""Copy Special exercise
"""
#... | f status: ## Error case, print the command's output to stderr and exit
sys.stderr.write(outpu | t)
sys.exit(1)
def main():
# This basic command line argument parsing code is provided.
# Add code to call your functions below.
# Make a list of command line arguments, omitting the [0] element
# which is the script itself.
args = sys.argv[1:]
if not args:
print "usage: [--todir dir][--tozip zip... |
armstrong/docs.armstrongcms.org | source/conf.py | Python | apache-2.0 | 8,620 | 0.006729 | # -*- coding: utf-8 -*-
#
# Armstrong Platform Documentation documentation build configuration file, created by
# sphinx-quickstart on Mon Sep 26 13:38:48 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# au... | al page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'armstrongplatformdocumentation', u'Armstrong Platform Documentation Documentation',
[u'Bay Citizen and Texas Tribu... | Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'Armstrong Platform Documentation'
epub_author = u'Bay Citizen and Texas Tribune'
epub_publisher = u'Bay Citizen and Texas Tribune'
epub_copyright = u'2011, Bay Citizen and Texas Tribune'
# The ... |
bswartz/manila | manila/tests/share/drivers/glusterfs/test_layout.py | Python | apache-2.0 | 12,949 | 0 | # Copyright (c) 2015 Red Hat, 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 require... | overy)
def test_update_access_via_manager(self):
self.assertRaises(NotImplementedError,
self._driver._update_access_via_manager,
mock.Mock(), self.fake_context, self.fake_share,
| [self.fake_access], [self.fake_access])
@ddt.data('NFS', 'PROTATO')
def test_check_proto_baseclass(self, proto):
self.assertRaises(exception.ShareBackendException,
layout.GlusterfsShareDriverBase._check_proto,
{'share_proto': ... |
nouiz/pydy | examples/Kane1985/Chapter5/Ex9.5.py | Python | bsd-3-clause | 2,089 | 0.00048 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Exercise 9.5 from Kane 1985."""
from __future__ import division
from sympy import sin, cos, pi, solve, symbols
from sympy.physics.mechanics import ReferenceFrame, Point
from sympy.physics.mechanics import dynamicsymbols
from util import msprint, subs, partial_velocities... | = dynamicsymbols('q1:4', level=1)
u1, u2, u3 = dynamicsymbols('u1:4')
g, m, L, t = symbols('g m L t')
# reference frame, points, velocities
| N = ReferenceFrame('N')
pO = Point('O')
pO.set_vel(N, 0)
pP1 = pO.locatenew('P1', L/2*(cos(q1)*N.x + sin(q1)*N.y))
pP2 = pP1.locatenew('P2', L/2*(cos(q1)*N.x + sin(q1)*N.y))
pP3 = pP2.locatenew('P3', L/2*(cos(q2)*N.x - sin(q2)*N.y))
pP4 = pP3.locatenew('P4', L/2*(cos(q2)*N.x - sin(q2)*N.y))
pP5 = pP4.locatenew('P5', ... |
ThomasMarcel/natural-selection-python | NaturalSelection/wsgi.py | Python | apache-2.0 | 409 | 0 | """
WSGI config for N | aturalSelection 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",... | |
varunarya10/rally | rally/benchmark/processing/plot.py | Python | apache-2.0 | 11,681 | 0 | # Copyright 2014: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi | th 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
# WARRANTIES OR CONDITIONS OF ANY KIND, either ... | License for the specific language governing permissions and limitations
# under the License.
import copy
import json
import six
from rally.benchmark.processing.charts import histogram as histo
from rally.benchmark.processing import utils
from rally.ui import utils as ui_utils
def _prepare_data(data):
durati... |
ryanss/holidays.py | holidays/countries/aruba.py | Python | mit | 3,023 | 0 | # -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: dr-prodigy <maurizio.... | self[queens_day] = "Aña di La Reina [Queen's D | ay]"
# Labour Day
self[date(year, MAY, 1)] = "Dia di Obrero [Labour Day]"
# Ascension Day
self[easter(year) + rd(days=39)] = "Dia di Asuncion [Ascension Day]"
# Christmas Day
self[date(year, DEC, 25)] = "Pasco di Nacemento [Christmas]"
# Second Christmas
... |
faturita/ShinkeyBot | NeoCortex/Fps.py | Python | mit | 1,316 | 0.009878 | import time
class Fps:
def __init__(self):
self.num_frames = 0
self.fps = 0
def tic(self):
self.start = time.time()
self.num_frames = 0
def toc(self):
self.end = time.time()
self.seconds = self.end - self.start
ffps = self.num_frames / self.second... | or i in range(1,1000):
ffps.step()
print ("Estimated frames per second: {0}".format(ffps.toc()))
for i in range(1,1000000):
ffps.steptoc()
print ("Estimated frames per second: {0}".format(ffps.fps))
# Start time
start = time.time()
num_frames = 0
while (True):
... | nt ("Time taken : {0} seconds".format(seconds))
num_frames = num_frames + 1
if (seconds>1):
break
# Calculate frames per second
fps = num_frames / seconds;
print ("Estimated frames per second : {0}".format(fps))
|
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/opus_gui/data_manager/run/tools/synthesizer_prepare_data.py | Python | gpl-2.0 | 5,044 | 0.012688 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
import MySQLdb
import numpy
import synthesizer.adjusting_pums_joint_distribution
import synthesizer.drawing_households
import synthesizer.psuedo_sparse_matrix
import time
import os, sys... | n=database_server_connection)
#opusDB = OpusDatabase(database_ | server_configuration=dbs_config, database_name=database_name)
db = MySQLdb.connect(host = dbs_config.host_name, user = dbs_config.user_name, passwd = dbs_config.password, db = database_name)
#begin inherited code...
# Processes/ methods to be called at the beginning of the pop_synthesis ... |
SUSE/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2016_12_01/models/express_route_circuit.py | Python | mit | 5,628 | 0.002132 | # 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 ... | .ExpressRouteCircuitSku>`
:param allow_classic_operations: Allow classic operations
:type allow_classic_operations: bool
:param circuit_provisioning_state: The CircuitProvisioningState state of
the resource.
:type circuit_provisioning_state: str
:param service_provider_provisioning_state: The
... | .
Possible values include: 'NotProvisioned', 'Provisioning', 'Provisioned',
'Deprovisioning'
:type service_provider_provisioning_state: str or
:class:`ServiceProviderProvisioningState
<azure.mgmt.network.v2016_12_01.models.ServiceProviderProvisioningState>`
:param authorizations: The list of... |
pchero/asterisk-outbound | test/test_queue.py | Python | bsd-2-clause | 2,084 | 0.006238 | # test_queue.py
# Created on: Dec 2, 2015
# Author: pchero
import os
import sys
import test_common
def main():
ast = test_common.Ami()
ast.username = sys.argv[1]
ast.password = sys.argv[2]
if ast.conn() == False:
print("Could not connect.")
return 1
# ... | e"
test_uuid = evt["Uuid"]
# get dlma
ret = ast.sendCmd("OutQueueShow", Uuid=test_uuid)
flg = False
for i in range(len(ret)):
msg = ret[i]
if "Uuid" not in msg:
| continue
if msg["Uuid"] == test_uuid:
flg = True
break
if flg == False:
print("Couldn not pass the test_queue. ret[%s]" % ret)
raise "test_queue"
# delete dlma
ret = ast.sendCmd("OutQueueDelete", Uuid=test_uuid)
if ret[0]["Response"] != "... |
HydrelioxGitHub/home-assistant | homeassistant/components/doorbird/__init__.py | Python | apache-2.0 | 14,277 | 0 | """Support for DoorBird devices."""
import logging
from urllib.error import HTTPError
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import (
CONF_DEVICES, CONF_HOST, CONF_MONITORED_CONDITIONS, CONF_NAME,
CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME)
... | ))
return False
# Subscribe to doorbell or motion e | vents
if events:
try:
doorstation.update_schedule(hass)
except HTTPError:
hass.components.persistent_notification.create(
'Doorbird configuration failed. Please verify that API '
'Operator permission is enabled for ... |
brunogabriel/mobile-rest-web | mrestweb/mrestweb/wsgi.py | Python | apache-2.0 | 393 | 0 | """
WSGI c | onfig for mrestweb project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/e | n/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mrestweb.settings")
application = get_wsgi_application()
|
MestreLion/pyrogue | pyrogue/player.py | Python | gpl-3.0 | 6,092 | 0.00394 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Rodrigo Silva (MestreLion) <linux@rodrigosilva.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 Free Software Foundation, either version 3 of the License, ... | d.rand(4, 11) # Harsh!
#@@ Disable running
#@@ Cancel multiple actions
# DOS 1.1: "%sYou faint", "You feel too weak from lack of food. "
self.screen.message("%sYou faint from the lack of food",
"You feel very weak. ")
return... | HUNGER.HUNGRY:
self.screen.message("You are starting to get hungry")
|
rnicoll/bitcoin | contrib/devtools/test-security-check.py | Python | mit | 5,500 | 0.020364 | #!/usr/bin/env python3
# Copyright (c) 2015-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Test script for security-check.py
'''
import os
import subprocess
import unittest
def write_testcode(... | stack-protector-all','-Wl,-zrelro','-Wl,-z,now','-pie','-fPIE', '-Wl,-z,noseparate-code']),
(1, executable+': failed separate_code'))
self.assertEqual(call_security_check(cc, source, executable, ['-Wl,-znoexecstack','-fstack-protector-all','-Wl,-zrelro','-Wl,-z,now' | ,'-pie','-fPIE', '-Wl,-z,separate-code']),
(0, ''))
clean_files(source, executable)
def test_PE(self):
source = 'test1.c'
executable = 'test1.exe'
cc = 'x86_64-w64-mingw32-gcc'
write_testcode(source)
self.assertEqual(call_security_check(cc, source, ... |
ktan2020/legacy-automation | win/Lib/email/charset.py | Python | mit | 16,440 | 0.000912 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Ben Gertzfield, Barry Warsaw
# Contact: email-sig@python.org
__all__ = [
'Charset',
'add_alias',
'add_charset',
'add_codec',
]
import codecs
import email.base64mime
import email.quoprimime
from email import errors
from... | -8859-14',
'latin_9': 'iso-8859-15',
'latin-9': 'iso-8859-15',
'latin_ | 10':'iso-8859-16',
'latin-10':'iso-8859-16',
'cp949': 'ks_c_5601-1987',
'euc_jp': 'euc-jp',
'euc_kr': 'euc-kr',
'ascii': 'us-ascii',
}
# Map charsets to their Unicode codec strings.
CODEC_MAP = {
'gb2312': 'eucgb2312_cn',
'big5': 'big5_tw',
# Hack: We... |
MilaPetrova/Mantis_testing | conftest.py | Python | apache-2.0 | 1,303 | 0.013814 | __author__ = 'Liudmila'
im | port pytest
import json
import os.path
from fixture.application import Application
fixture = None
target = None
def load_config(file):
global target
if target is None:
config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), file)
with open (config_file)as f:
target = ... | return target
@pytest.fixture(scope = "session")
def app(request):
global fixture
browser = request.config.getoption("--browser")
web_config = load_config(request.config.getoption("--target"))["web"]
web_config_login = load_config(request.config.getoption("--target"))["webadmin"]
if fixture is Non... |
sdoran35/hate-to-hugs | venv/lib/python3.6/site-packages/nltk/sem/cooper_storage.py | Python | mit | 4,067 | 0.002213 | # Natural Language Toolkit: Cooper storage for Quantifier Ambiguity
#
# Copyright (C) 2001-2017 NLTK Project
# Author: Ewan Klein <ewan@inf.ed.ac.uk>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from __future__ import print_function
from nltk.sem.logic import LambdaExpression, ApplicationExpres... | print() |
print("Core:")
print("-" * 15)
print(semrep.core)
print()
print("S-Retrieval:")
print("-" * 15)
semrep.s_retrieve(trace=True)
print("Readings:")
print("-" * 15)
for i, reading in enumerate(semrep.readings):
print("%s: %s" % (i... |
krafczyk/spack | var/spack/repos/builtin/packages/lumpy-sv/package.py | Python | lgpl-2.1 | 1,769 | 0.000565 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#########################... | pack import *
class LumpySv(MakefilePackage):
"""A probabilistic framework for structural variant discovery."""
homepage = "https://github.com/arq5x/lumpy-sv"
url = "https://github.com/arq5x/lumpy-sv/archive/0.2.13.tar.gz"
version('0.2.13', '36929d29fc3a171d3abbe1d93f9f3b50')
depends_on('h... |
Dronolab/antenna-tracking | pitch_servo.py | Python | mit | 713 | 0.008415 | from abstract_servo import AbstractServo
from PID import PID
class PitchServo(AbstractServo):
def __init__(self):
self.pid = PID()
self.pid.setSetPoint(0)
def refresh(self, WantedAngle, CurrentAngle):
AngleCorrection = (WantedAngle - CurrentAngle)
AngleCorrection = -AngleCorr... | angle to -1 , 1
command = self.pid.update(feed_back_value)
if abs(AngleCorrection) >= self.angle_tolerance:
ticks = self.get_y(self. | init, self.delta,command)
else:
ticks = self.adafruitpwmvalue(self.hold_pwm, self.servo_frequency)
return ticks
|
encukou/freeipa | ipapython/config.py | Python | gpl-3.0 | 9,257 | 0.001944 | # Authors: Karl MacMillan <kmacmill@redhat.com>
#
# Copyright (C) 2007 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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 ver... | self.default_realm
else:
raise IPAConfigError("no default realm")
def get_server(self):
if len(self.default_server):
return self.default_server
else:
raise IPAConfigError("no default server")
def get_domain(self):
if self.default_domain:
... | t_domain
else:
raise IPAConfigError("no default domain")
# Global library config
config = IPAConfig()
def __parse_config(discover_server = True):
p = SafeConfigParser()
p.read(paths.IPA_DEFAULT_CONF)
try:
if not config.default_realm:
config.default_realm = p.get("g... |
achoi007/CloudComputing | Concepts/SWIM.py | Python | mit | 2,292 | 0.003054 | import unittest
import random
from pygraph.classes.graph import graph
class SWIM(object):
def __init__(self, graph):
self.graph = graph
def edge_alive(self, nodeA, nodeB, alive):
'''
edge_alive(A, B, True|False)
'''
edge = (nodeA, nodeB)
if alive:
s... | setUp(self):
g = graph()
g.add_nodes(xrange(10))
g.complete()
| self.graph = g
self.swim = SWIM(g)
def test_good_ping(self):
swim = self.swim
self.assertTrue(swim.ping(0, 1, 0))
self.assertTrue(swim.ping(1, 3, 0))
def test_dead_edge_ping(self):
swim = self.swim
swim.edge_alive(0, 1, False)
self.assertFalse(swim.pi... |
ric2b/Vivaldi-browser | chromium/third_party/blink/tools/blinkpy/common/net/results_fetcher_mock.py | Python | bsd-3-clause | 3,794 | 0.000264 | # Copyright (C) 2011 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | e name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIM | ITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOO... |
lsaffre/timtools | tests/timtools/help/makethem.py | Python | bsd-2-clause | 1,292 | 0.013932 | ## Copyright 2004-2009 Luc Saffre
## This file is part of the Lino project.
## Lino 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) any later ... | out even the implied warranty of MERCHANTABILITY
## or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
## License fo | r more details.
## You should have received a copy of the GNU General Public License
## along with Lino; if not, write to the Free Software Foundation,
## Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from timtools.timtools import CONSOLE_TARGETS
from timtools.console.syscon import confirm
from ... |
davidea72/edir_1 | remote_command_2.py | Python | gpl-3.0 | 6,639 | 0.029071 | import serial
ser= serial.Serial('/dev/ttyUSB0', timeout=1)
print (ser.name)
version='\xFA\xF2'
start_learning='\xFA\xF5' #auto exit
start_learning2='\xFA\xFD' #non auto
stop_learning='\xFA\xF4'
sleep='\xFA\xF8'
wake='\xFA\xF7'
repeat='\xFA\xF3'
reset='\xFA\xF6'
start='\xFA'
stop='\xED'
#test
# FA 18 ... | ttempt < 30): #we make a 30 second loop (1 second timeout x 30 time)
answer=ser.read(200) #we read the serial with a 200 char buffer
attempt+=1
print("attempt number "+str(attempt))
if(len(answer)==0): #if we can't obtail an answer (lenght == 0) exit
print("no answer from the edir")
exit()
... | (len(answer)<5):
print ("lenght ",len(answer))
print (answer[0].encode("hex"))
print("exit with error , we have received some data")
exit()
char='a'
count=0
checksum=256
checksum_pos=0
checksum_is=0
end=0
for char in answer:
char=answer[count]
ascii_char=char.encode("hex") #convert the char into h... |
spennihana/h2o-3 | h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_ordinal_example.py | Python | apache-2.0 | 520 | 0.019231 | import h2o
from h2o.estimators.glm import H2OGeneralizedLinearEstimator
h2o.init()
h2o_df = h2o.import_file("http://h2o-public-test-data.s3.amazonaws.com/bigdata/laptop/glm_ordinal_logit/ordinal_multinomial_training_set.csv")
h2o_df['C11'] = h2o_df['C11'].asfactor()
ordinal_fit = H2OGeneralizedLinearEstimator(family =... | _epsilon=1e-8, ob | jective_epsilon=1e-10)
ordinal_fit.train(x=list(range(0,10)), y="C11", training_frame=h2o_df) |
carryLabs/carrydb | test/carrydb/connection.py | Python | bsd-3-clause | 23,711 | 0.002994 | #coding=utf-8
from __future__ import with_statement
from itertools import chain
from select import select
import os
import socket
import sys
import threading
from ssdb._compat import (b, xrange, imap, byte_to_chr, unicode, bytes, long,
BytesIO, nativestr, basestring,
... | buffer = None
self._sock = None
class PythonParser(BaseParser):
"""
Plain Python parsing class
"""
encoding = None
def __init__(self, socket_read_size):
self.socket_read_size = socket_read_size
self._sock = None
self._buffer = None
def __del__(self):
... | s
def on_connect(self, connection):
"""
Called when the socket connects
"""
self._sock = connection._sock
self._buffer = SocketBuffer(self._sock, self.socket_read_size)
if connection.decode_responses:
self.encoding = connection.encoding
... |
neavouli/yournextrepresentative | candidates/tests/test_upcoming_elections_api.py | Python | agpl-3.0 | 5,501 | 0.000364 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from mock import patch, Mock
from datetime import date, timedelta
from django.conf import settings
from django.utils.six.moves.urllib_parse import urljoin
from nose.plugins.attrib import attr
from django_webtest import WebTest
from candidates.tests.f... | aa'):
status_code = 200
json_result = sw1a1aa_result
elif url == urljoin(settings.MAPIT_BASE_URL, '/postcode/se240ag'):
status_code = 200
json_result = se240ag_result
elif url == urljoin(settings.MAPIT_BASE_URL, '/postcode/cb28rq'):
status_code = 404
json_result =... | "No Postcode matches the given query."
}
elif url == urljoin(settings.MAPIT_BASE_URL, '/postcode/foobar'):
status_code = 400
json_result = {
"code": 400,
"error": "Postcode 'FOOBAR' is not valid."
}
else:
raise Exception("URL that hasn't been mock... |
CristianCantoro/sbntoolkit | cron.py | Python | mit | 5,088 | 0.0057 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import argparse
from item import Item, INFO
import database
import update
# logging
LOGFORMAT_STDOUT = {logging.DEBUG: '%(module)s:%(funcName)s:%(lineno)s - %(levelname)-8s: %(message)s',
logging.INFO: '%(levelname)-8s: %(message)s',
... | logger.setLevel(logging.WARNING)
if args.quiet:
logger.setLevel(logging.CRITICAL)
if arg | s.drop:
database.drop()
if args.create:
database.create()
if not args.drop:
items_to_process = []
if args.update:
items_to_update = update.read_items_to_update(args.upfile)
# logger.debug(items_to_update)
items_to_process = get_items_with_inf... |
hyperdriveguy/mint-software-center | src/widgets/searchentry.py | Python | gpl-2.0 | 2,634 | 0.00038 | #!/usr/bin/python
# -*- coding:UTF-8 -*-
# Copyright (c) Stephen Smally <stephen.smally@gmail.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 Free Software Foundation; either version 2 of t... | .search_entry.set_width_chars(30)
self.search_entry.set_placeholder_text(_("Search a package..."))
self.search_entry.set_icon_from_stock(0, Gtk.STOCK_FIND)
self.search_entry.set_icon_activatable(0, True)
self.search_string = _("Search a package...")
self.add(self.search_entry)
... | self.timeout_id = 0
def clean_text(self):
'''Clean the text in the entry'''
self.search_entry.set_placeholder_text(self.search_string)
def emit_search(self):
self.search_function(self.search_entry.get_text(), 20)
return False
def set_searching_text(self, string):
... |
joelpx/plasma | plasma/lib/generate_ast.py | Python | gpl-3.0 | 25,145 | 0.000636 | #!/usr/bin/env python3
#
# PLASMA : Generate an indented asm code (pseudo-C) with colored syntax.
# Copyright (C) 2015 Joel
#
# 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 ... | tx, ast.branch)
def get_first_addr(ast):
# Assume that there are no Ast_Comment
if isinstance(ast, list):
return ast[0].address
if isinstance(ast, Ast_Branch):
if len(ast.nodes) > 0:
return get_first_addr(ast.nodes[0])
if isinstance(ast, Ast_Ifelse):
# Any instr... | ):
if len(ast.branch.nodes) > 0:
return get_first_addr(ast.branch.nodes[0])
if isinstance(ast, Ast_Goto):
return ast.addr_jump
if isinstance(ast, Ast_IfGoto):
return ast.orig_jump.address
if isinstance(ast, Ast_AndIf):
return ast.orig_jump.address
if isins... |
jakirkham/volumina | volumina/layerwidget_plugin.py | Python | lgpl-3.0 | 3,021 | 0.007282 | ###############################################################################
# volumina: volume slicing and editing library
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# modify it und... | yDesignerCustomWidgetPlugin):
def __init__(self, parent = None):
QPyDesignerCustomWidgetPlugin.__init__(self)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
retur... | model = LayerStackModel()
o1 = Layer()
o1.name = "Fancy Layer"
o1.opacity = 0.5
model.append(o1)
o2 = Layer()
o2.name = "Some other Layer"
o2.opacity = 0.25
model.append(o2)
o3 = Layer()
o3.name = "Invisible La... |
Yarrick13/hwasp | tests/asp/AllAnswerSets/tight/testcase.3.asp.test.py | Python | apache-2.0 | 2,531 | 0 | input = """
1 2 2 1 3 4
1 3 2 1 2 4
1 4 0 0
1 5 2 1 6 7
1 6 2 1 5 7
1 7 0 0
1 8 2 0 2 5
1 9 2 1 10 11
1 10 2 1 9 11
1 11 0 0
1 12 2 1 13 14
1 13 2 1 12 14
1 14 0 0
1 15 2 0 9 12
1 16 2 1 17 18
1 17 2 1 16 18
1 18 0 0
1 19 2 1 20 21
1 20 2 1 19 21
1 21 0 0
1 22 2 0 16 19
0
22 c
9 b1
3 n_a1
15 b
6 n_a2
8 a
10 n_b1
5 a2
1... | 2, c1, n_c2}
{a1, n_a2, n_b1, b2, n_c1, n_c2}
{a1, n_a2, n_b1, n_b2, n_c1, n_ | c2}
"""
|
deepchem/deepchem | deepchem/models/torch_models/pagtn.py | Python | mit | 10,872 | 0.003679 | """
DGL-based PAGTN for graph property prediction.
"""
import torch.nn as nn
import torch.nn.functional as F
from deepchem.models.losses import Loss, L2Loss, SparseSoftmaxCrossEntropy
from deepchem.models.torch_models.torch_model import TorchModel
class Pagtn(nn.Module):
"""Model for Graph Property Prediction
T... | ires DGL (https://github.com/dmlc/dgl) and DGL-LifeSci |
(https://github.com/awslabs/dgl-lifesci) to be installed.
"""
def __init__(self,
n_tasks: int,
number_atom_features: int = 94,
number_bond_features: int = 42,
mode: str = 'regression',
n_classes: int = 2,
output_node_featu... |
zengchunyun/s12 | day10/homework/rabbitmq_management/bin/controller.py | Python | gpl-2.0 | 337 | 0 | #!/usr/ | bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zengchunyun
"""
import os
import sys
base_dir = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.append(base_dir)
if __name__ == "__main__":
try:
from modules.rabbitmq_core import main
main()
except | KeyboardInterrupt:
pass
|
bradallred/gemrb | gemrb/GUIScripts/iwd2/Options.py | Python | gpl-2.0 | 2,412 | 0.016998 | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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) ... | 1 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# Options.py - scripts to control options windows mostly from GUIOPT winpack
import GemRB
import GUIOPT
from GUIDefines import *
OptionsWindow = 0
def OnLoad():
global OptionsWindow
MessageBarWindow = GemRB.LoadWindow(0, "GUIOPT")
CharactersBarWindo... | ionsWindow = GemRB.LoadWindow(13)
VersionLabel = OptionsWindow.GetControl(0x1000000B)
VersionLabel.SetText(GemRB.GEMRB_VERSION)
GraphicsButton = OptionsWindow.GetControl(7)
SoundButton = OptionsWindow.GetControl(8)
GamePlayButton = OptionsWindow.GetControl(9)
MoviesButton = OptionsWindow.GetControl(14)
Keyboar... |
andrewsmedina/django | tests/admin_scripts/tests.py | Python | bsd-3-clause | 79,511 | 0.002956 | # -*- coding: utf-8 -*-
"""
A series of tests to establish that the command-line managment tools work as
advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE
and default settings.py files.
"""
from __future__ import unicode_literals
import os
import re
import shutil
import socket
import s... | te-packages or similar.
django_dir = os.path.dirname(tests_dir)
ext_backend_base_dirs = self._ext_backend_paths()
# Remember the old environment
old_django_settin | gs_module = os.environ.get('DJANGO_SETTINGS_MODULE', None)
if sys.platform.startswith('java'):
python_path_var_name = 'JYTHONPATH'
else:
python_path_var_name = 'PYTHONPATH'
old_python_path = os.environ.get(python_path_var_name, None)
old_cwd = os.getcwd()
... |
bikash/h2o-dev | h2o-py/h2o/job.py | Python | apache-2.0 | 2,183 | 0.012826 | """
A job is an object with states: CREATED, RUNNING, DONE, FAILED, CANCELLED
A job can be polled for completion and reports the progress so far if it is still RUNNING.
"""
from connection import H2OConnection
import time
import sys
class H2OJob(object):
"""
A class representing an H2O Job.
"""
def __init__(... | ob = job
self.status = job["status"]
self.job_key = job['key']['name']
self.dest_key = job['dest']['name']
self.progress = 0
self._100_percent = False
self._progress_bar_width = 50
self._job_type = job_type
self.exception = job['exception'] if 'exception' in job else None
def poll(sel... | me.sleep(sleep)
if sleep < 1.0: sleep += 0.1
self._refresh_job_view()
running = self._is_running()
self._update_progress()
print
# check if failed... and politely print relevant message
if self.status == "CANCELLED":
raise EnvironmentError("Job with key {} was cancelled by the u... |
beav/katello | cli/src/katello/client/api/errata.py | Python | gpl-2.0 | 1,793 | 0.004464 | # -*- cod | ing: utf-8 -*-
#
# Copyright © 2011 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR | A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software ... |
Calchan/kernelconfig | setup.py | Python | gpl-3.0 | 3,439 | 0.001454 | # kernelconfig - Generate custom kernel configurations from curated sources
# Copyright (C) 2015 Denis Dupeyron <calchan@gentoo.org>
#
# 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 Foundat... | all them using your distribution's package",
"manager:")
for package in missing_packages:
print(package)
sys.exit(1)
# We can now import docutils
from docutils.core import publish_file
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, 'README.rst'), encod... | ('README.html', 'w') as \
readme_html:
publish_file(source=readme_rst, destination=readme_html, writer_name='html')
# If the user requested a --user install from pip or does not have read, write
# and execute access to /etc, then we install settings into
# ~/.config/kernelconfig instead instead of /etc/ker... |
anetasie/sherpa | sherpa/sim/tests/test_asymmetric.py | Python | gpl-3.0 | 8,923 | 0 | #
# Copyright (C) 2019, 2020, 2021 Smithsonian Astrophysical Observatory
#
#
# 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 License, or
# (at your option) any late... | th(filename)
ui.load_ascii_with_errors(1, infile, delta=delta)
data = ui.get_data(1)
| fit_asymmetric_err(RESULTS_BENCH_AVG, data)
@requires_data
@requires_fits
@pytest.mark.parametrize("filename, delta", [('gro.txt', False),
('gro_delta.txt', True)])
def test_load_ascii_defaultid(filename, delta, make_data_path):
"""Use the default id"""
infile =... |
drrk/micropython | tests/basics/tuple1.py | Python | mit | 266 | 0 | # | basic tuple functionality
x = (1, 2, 3 * 4)
print(x)
try:
x[0] = 4
except TypeError:
print("TypeError")
print(x)
try:
x.append(5)
except AttributeError:
print("AttributeError")
print(x[1:])
print(x[:-1])
print(x[2:3])
print(x + (10, 100, 10000 | ))
|
hurricanerix/swift | test/unit/proxy/controllers/test_container.py | Python | apache-2.0 | 15,514 | 0 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# 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... | rs)):
| resp = controller.HEAD(req)
self.assertEqual(2, resp.status_int // 100)
for key in owner_headers:
self.assertNotIn(key, resp.headers)
req = Request.blank('/v1/a/c', environ={'swift_owner': True})
with mock.patch('swift.proxy.controllers.base.http_connect',
... |
transientlunatic/pylightcurve | setup.py | Python | bsd-3-clause | 1,562 | 0.00128 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
requirements = [
# TODO: put package requireme... | requirements = [
# TODO: put package test requirements here
]
setup(
name='pyLightcurve',
version='0.1.0',
description='A python package for handling (potentially multispectral) time series observation data in astronomy.',
long_description=readme + '\n\n' + history,
author='Daniel Williams',
... | thub.com/transientlunatic/lightcurve',
packages=[
'pylightcurve',
],
package_dir={'pylightcurve':
'pylightcurve'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='pylightcurve',
classifiers=[
'Develop... |
wrenchell/MintAD | app/MintAD_pt2.py | Python | gpl-3.0 | 9,751 | 0.023382 | #!/usr/bin/python
###############################################################################
#
# MintAD_pt2
#
# Second part for the script that helps automate AD setup. This one should be
# run after the first one is run and then a restart. This one will mostly be
# editing config files, so bulletproofin... |
try:
profile = open('common-session', 'r+')
tempProfile = open('tempCommon', 'r+')
except IOError as err:
print "I/O error ({0}): {1}".format(err.errno, err.strerror)
sys.exit()
for line in profile:
line = line.strip()
if (line == '# and here are more per-package module... | tempProfile.write(line)
tempProfile.write("\n")
profile.close()
tempProfile.close()
os.system('mv common-session common-session.old')
os.system('mv tempCommon common-session')
else:
global skipNum
skipNum += 1
print "\nThe File located at /etc/pam.d/common-session has alrea... |
sveetch/Optimus | optimus/i18n/__init__.py | Python | mit | 86 | 0 | """
Inte | rnationalization and localization
=====================================
|
"""
|
rworkman/blueman | blueman/services/DialupNetwork.py | Python | gpl-3.0 | 260 | 0 | # coding=utf-8
| from blueman.services.meta import SerialService
from blueman.Sdp import DIALUP_NET_SVCLASS_ID
class DialupNetwork(SerialService):
__group__ = 'serial'
__svclass_id__ = DIALUP_NET_SVCLASS_ID
__icon__ = "modem"
| __priority__ = 50
|
uktrade/navigator | app/markets/migrations/0066_auto_20210428_0912.py | Python | mit | 1,397 | 0 | # Generated by Django 2.2.19 on 2021-04-28 09:12
from django.db import migrations, models
import image_cropping.fields
class Migration(migrations.Migration):
dependencies = [
('markets', '0065_auto_20190426_1255'),
]
operations = [
migrations.AlterField(
model_name="logo",
... | quality.", # noqa
hide_image_field=False,
size_warning=False,
verbose_name="cropping",
),
),
migrations.AlterField(
model_name="logo",
name="image",
field=models.ImageField(
help_text="After... | 'Cropping' tool and edit the image", # noqa
null=True,
upload_to="",
),
),
]
|
ScienceStacks/JViz | mysite/heatmap/helpers/test_table_view.py | Python | apache-2.0 | 2,324 | 0.003442 | '''Tests for helpers_views'''
from mysite import settings
from mysite.helpers.db_access import DBAccess
from mysite.helpers import testhelpers as th
from heatmap.helpers.table_view import (TableForm, QueryForm)
from heatmap.helpers import test_helpers_views as thv
from django.test import TestCase # Provides mocks for... | lf.assertEqual(response.status_code, 200)
def testDeletetable(self):
# Put in the file to delete
CLIENT_URL = '/heatmap/upload/'
post_dict = {'filename': thv.TEST_DATA_FILENAME}
response = self.client.post(CLIENT_URL, post_dict)
# Delete the file
CLIENT_URL = '/heatmap/deletetable/'
respo... | IENT_URL, post_dict)
self.assertEqual(response.status_code, 200)
def testQuery(self):
CLIENT_URL = '/heatmap/query/'
TABLE_LIST = ['data_rev', 'data']
TABLE_NAME = "testQuery"
response = self.client.get(CLIENT_URL)
self.assertEqual(response.status_code, 200)
# Test the post
th.CreateT... |
Statoil/libres | python/job_runner/reporting/__init__.py | Python | gpl-3.0 | 185 | 0 | """
The reporting package provide | s classes for reporting the results of forward
model jobs.
"""
from .file import File
from .interactive import Interactiv | e
from .network import Network
|
ellezv/django_imager | imagersite/imager_images/tests.py | Python | mit | 30,691 | 0.000554 |
from django.test import TestCase, Client, RequestFactory
from django.contrib.auth.models import User
from django.utils import timezone
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse_lazy
from imager_images.models import Image, Album
from imager_images.views import Librar... | um.objects.first()
image.albums.add(album1)
self.assertTrue(image.albums.count() == 1)
def test_album_has_no_image(self):
"""Test that an album has no image before assignemnt."""
album1 = Album.objects.first()
self.assertTrue(album1.images.count() == 0)
def test_album_h... | "
image = Image.objects.first()
album1 = Album.objects.first()
image.albums.add(album1)
self.assertTrue(image.albums.count() == 1)
def test_two_images_have_album(self):
"""Test that two images have same album."""
image1 = Image.objects.all()[0]
image2 = Image... |
wdv4758h/ZipPy | lib-python/3/test/test_mailbox.py | Python | bsd-3-clause | 89,486 | 0.001576 | import os
import sys
import time
import stat
import socket
import email
import email.message
import re
import io
import tempfile
from test import support
import unittest
import textwrap
import mailbox
import glob
try:
import fcntl
except ImportError:
pass
class TestBase(unittest.TestCase):
def _check_sam... | bin_msg.replace(b'\n',
os.linesep.encode()))
self.assertEqual(self._box[key].get_payload(), |
"Да, они летят.\n")
def test_add_binary_file(self):
with tempfile.TemporaryFile('wb+') as f:
f.write(_bytes_sample_message)
f.seek(0)
key = self._box.add(f)
# See issue 11062
if not isinstance(self._box, mailbox.Babyl):
... |
drjod/yWaves | yConnector.py | Python | gpl-3.0 | 3,005 | 0.000666 | class yConnector:
"""
Connector is node on grid 0 and link on grid 1
hosts primary / secondary variable, froude number, flux
source term / boundary condition
ghost connectors on 1D domain boundaries
"""
__primary_variable_slope = float()
__velocity_centered = float()
__froude_number... | def immediate_connectors_id(self, value):
self.__immediate_connectors_id = value
@ghost.setter
def ghost(self, value):
self.__ghost = value
@geometry.setter
def geometry(self, value):
self.__geometry = value
@source_term.setter
def source_term(self, value):
... | ef get_variable_value(self, variable):
"""
for output
:param variable:
:return:
"""
if variable == "waterDepth" or variable == "velocity":
return self.__primary_variable[1]
elif variable == "flux":
return self.__flux
elif variable =... |
andyneff/voxel-globe | voxel_globe/tools/__init__.py | Python | mit | 55 | 0.018182 | f | rom .voxel_dir import task_dir, storage_dir, image_di | r |
DockerNAS/yamlscript-formula | src/salt-call.py | Python | mit | 7,810 | 0.003073 | __author__ = 'Jason Mehring'
#
# This module is only used with WingIDE debugger for testing code within
# The debugging environment
#
# Stage 1: bind /srv/...modules to cache/extmods. No sync will take place
# since files are bound
# BIND
# True : bind custom modules
# False : do not bind custom module... | srv_dir.lstrip(os.sep) in path:
| index = BASE_DIR.index(srv_dir)
basepath = os.sep.join(path[:6+1])
cur_dirs = join_path(basepath, os.listdir(basepath))
srv_dirs = join_path(srv_dir, os.listdir(srv_dir))
for path in cur_dirs:
if path not in srv_dirs:
basename =... |
dims/oslo.utils | tests/test_utils.py | Python | apache-2.0 | 750 | 0 | # -*- coding: utf-8 -*-
# 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, softw... | implied. See the
# License for the spec | ific language governing permissions and limitations
# under the License.
"""
test_utils
----------------------------------
Tests for `utils` module.
"""
from . import base
class TestUtils(base.TestCase):
def test_something(self):
pass
|
acontry/GDAX-Python | gdax/authenticated_client.py | Python | mit | 11,447 | 0.002097 | #
# GDAX/AuthenticatedClient.py
# Daniel Paquin
#
# For authenticated requests to the GDAX exchange
import hmac
import hashlib
import time
import requests
import base64
import json
from requests.auth import AuthBase
from gdax.public_client import PublicClient
class AuthenticatedClient(PublicClient):
def __init__... | eturn r.json()
def get_order(self, | order_id):
r = requests.get(self.url + '/orders/' + order_id, auth=self.auth)
# r.raise_for_status()
return r.json()
def get_orders(self):
result = []
r = requests.get(self.url + '/orders/', auth=self.auth)
# r.raise_for_status()
result.append(r.json())
... |
Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/site-packages/numpy/lib/utils.py | Python | gpl-3.0 | 36,893 | 0.000705 | from __future__ import division, absolute_import, print_function
import os
import sys
import types
import re
from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype
from numpy.core import ndarray, ufunc, asarray
__all__ = [
'issubclass_', 'issubsctype', 'issubdtype', 'deprecate',
'deprecate_... | Bytes Type
===========================================================
y | 3 24 float64
x 2 16 float64
Upper bound on total bytes = 40
"""
if vardict is None:
frame = sys._getframe().f_back
vardict = frame.f_globals
sta = []
cache = {}
for name in vardict.keys():
... |
oudalab/phyllo | phyllo/extractors/bebelDB.py | Python | apache-2.0 | 3,089 | 0.009064 | import sqlite3
import urllib
import re
from urllib.request import urlopen
from bs4 import BeautifulSoup, NavigableString
from phyllo.phyllo_logger import logger
impor | t nltk
from itertools import cycle
nltk.download('punkt')
from nltk import sent_tokenize
def parseRes2(soup, title, url, cur, author, date, collectiontitle):
chapter = '-'
sen = ""
s=''
h=''
s1=[]
s2=[]
i=1
[e.extract() for e in soup.find_all('font')]
[e.extract() for e in soup.fi... | in soup.find_all('table')]
getp=soup.find_all('p')
for p in getp:
# make sure it's not a paragraph without the main text
try:
if p['class'][0].lower() in ['border', 'pagehead', 'shortborder', 'smallboarder', 'margin',
'internal_navigation']: ... |
juhasch/polymode | other/Nurbs/demos/LineCrv.py | Python | gpl-3.0 | 101 | 0.029703 | # Demonstration of a Line curve
from Nurbs import C | rv
crv = Crv.L | ine([0,0],[1,1])
crv.plot()
|
CodeForCary/django-dev-map | permit_map/urls.py | Python | mit | 1,506 | 0.017928 | from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
f | rom djgeojson.views import GeoJSONLayerView
from django.conf.urls import include, url
from django.contrib import admin
from permit_map import models
from permit_map import views
urlpatterns = [
# This URL maps to / and | is the main UI render. Note that we just spit out the contents of the permit_map/index.html template.
#url(r'^$', TemplateView.as_view(template_name="permit_map/index.html"), name='map'),
url(r'^$', views.index, name='map'),
# Lots of things going on here:
# - We're using a open source view to render our permits i... |
khosrow/metpx | pxStats/bin/webPages/graphicsRequestBroker.py | Python | gpl-2.0 | 8,456 | 0.032403 | #! /usr/bin/env python
"""
##############################################################################
##
##
## @Name : graphicsRequestBroker.py
##
##
## @author : Nicholas Lemay
##
## @since : 2007-06-28, last updated on 2008-04-23
##
##
## @license : MetPX Copyright (C) 2004-2006 Environment Canada
## ... | reply : Series of parameters to send as a reply to te querier.
"""
print """
HTTP/1.0 200 OK
Server: NCSA/1.0a6
Content-type: text/plain
"""
print """
%s
""" %( escape(reply) )
def getQuerierLocation( form ):
"""
... | programm was called.
@return : Returns the queriers location.
"""
try:
querier = form["querier"]
except:
querier = ""
return querier
def handlePlotRequest( form, language ):
"""
@param form: form wich contains
... |
sprax/python | romanize.py | Python | lgpl-3.0 | 570 | 0.007018 | #!/usr/bin/env python3
'''Convert decimal number to Roman numerals'''
@file: romanize.py
@auth: Sprax Lines
@date: 2017-07-29 15:32:03 Sat 29 Jul
NUMERAL = (
("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90),
("L", 50), ("XL", 40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1))
... | end(ltr * div)
return "".join(roman) |
YEAR = 1949
print(YEAR, romanize(YEAR))
|
clubcapra/Ibex | src/roboteq_motor/scripts/includes/config.py | Python | gpl-3.0 | 6,953 | 0.003452 | import rospy
class Config:
DEFAULT_RESOLUTION = 4000.0
DEFAULT_COUNTS_RPM = 542.29383
DEFAULT_COUNTS_REVS = 16.15444
DEFAULT_COUNTS_SEC = 4069.0
DEFAULT_GEAR_RATIO = 26.25
DEFAULT_WHEEL_DIAMETER = 0.305
DEFAULT_ROBOT_WIDTH = 0.53
DEFAULT_NB_MOTORS = 2
DEFAULT_MAX_SPEED = 3.0
D... | 96
DEFAULT_SWIVEL_GEAR_RATIO = 20
DEFAULT_SWIVEL_ENC_SERIAL_PORT = '/dev/ttyACM0'
DEFAULT_SWIVEL_ENC_BAUD_RATE = 9600
resolution = None
counts_ | rpm = None
counts_revs = None
counts_sec = None
gear_ratio = None
wheel_diameter = None
robot_width = None
nb_motors = None
max_speed = None
broadcast_address = None
serial_port = None
default_accel = None
baudrate = None
max_timeout_count = None
watchdog_timeout = No... |
Donkyhotay/MoonPy | zope/structuredtext/__init__.py | Python | gpl-3.0 | 2,116 | 0.00189 | ##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFT... | DocumentWithImages()(st)
return html.HTMLWithImages()(doc, header=header, level=level)
def stx2htmlWithReferences(text, level=1, header=1):
text = re.sub(
r'[\000\n]\.\. \[([0-9_%s-]+)\]' % letters,
r'\n <a name="\1">[\1]< | /a>',
text)
text = re.sub(
r'([\000- ,])\[(?P<ref>[0-9_%s-]+)\]([\000- ,.:])' % letters,
r'\1<a href="#\2">[\2]</a>\3',
text)
text = re.sub(
r'([\000- ,])\[([^]]+)\.html\]([\000- ,.:])',
r'\1<a href="\2.html">[\2]</a>\3',
text)
return stx2html(tex... |
mluo613/osf.io | admin/tasks.py | Python | apache-2.0 | 2,257 | 0.000443 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
from invoke import task
from website import settings
HERE = os.path.dirname(os.path.abspath(__file__))
WHEELHOUSE_PATH = os.environ.get('WHEELHOUSE')
@task()
def manage(ctx, cmd_str):
"""Take command string for manage commands
:param... | (command, echo=True)
| @task
def clean_assets(ctx):
"""Remove built JS files."""
public_path = os.path.join(HERE, 'static', 'public')
js_path = os.path.join(public_path, 'js')
ctx.run('rm -rf {0}'.format(js_path), echo=True)
@task(aliases=['bower'])
def bower_install(ctx):
if os.getcwd() != HERE:
os.chdir(HERE)
... |
sirex/databot | tests/test_export.py | Python | agpl-3.0 | 9,232 | 0.001192 | import io
import pytest
import databot
import pandas as pd
from databot.db.utils import Row
from databot.exporters.utils import flatten_nested_lists, flatten_nested_dicts, get_level_keys, flatten, sort_fields
from databot.exporters import jsonl
from databot.exporters import pandas
@pytest.fixture
def data():
re... | alue={'text': 'abcde'}),
]
update = {'size': databot.this.value.text.apply(len)}
assert list(flatten(rows, update=update)) == [
('key', 'size', 'text'),
(1, 3, 'abc'),
| (1, 5, 'abcde'),
]
def test_flatten_rows_callable_update(data):
rows = [
Row(key=1, value={'text': 'abc'}),
Row(key=1, value={'text': 'abcde'}),
]
def update(row):
return {'size': len(row.value['text'])}
assert list(flatten(rows, update=update)) == [
('size',),... |
patricklaw/pants | src/python/pants/backend/docker/util_rules/docker_build_context_test.py | Python | apache-2.0 | 7,173 | 0.001673 | # Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.docker.subsystems.dockerfile_parser import rules as parser_rules
from pants.backend.docke... | rc/b", ["Dockerfile"])
rule_runner.create_files("src/b/files", ["b01", "b02"])
# | We want files_B in build context for img_B
assert_build_context(
rule_runner,
Address("src/b", target_name="img_B"),
expected_files=["src/b/Dockerfile", "src/b/files/b01", "src/b/files/b02"],
)
# We want files_A in build context for img_A, but not files_B
assert_build_context(
... |
rhausch/System-Monitoring-Daemon | sensors/psutil_sensors/cpu.py | Python | gpl-3.0 | 1,700 | 0.013529 | #!/usr/bin/python
#
# CPU sensor ontop of psutil
#
# Copyright 2012 Dan Ballard and Robert Hausch
#
## License:
#
# This file is part of System-Monitoring-Daemon.
#
# System-Monitoring-Daemon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
#... | ails.
#
# You should have received a copy of the GNU General Public License
# along with System-Monitoring-Daemon. If not, see <http://www.gnu.org/licenses/>.
##
import psutil
class cpu_monitor:
def __init__(self):
self.num_cpus = len(psutil.cpu_percent(0,percpu=True))
def update(self):
self.cpu_usage = psu... | ','.join('{"value": %.1f}'%x for x in self.cpu_usage)+']}'
data += ',{"name": "Times", "values": [{"name": "user", "value": %.2f},{"name": "system", "value": %.2f},{"name": "idle", "value": %.2f},{"name":"nice", "value": %.2f},{"name": "iowait", "value": %.2f},{"name": "irq", "value": %.2f},{"name": "softirq", "value... |
czhouyi/xscredit | xscredit/urls.py | Python | mit | 966 | 0.001035 | """xscredit URL Configuration
The `urlpatterns` list routes URLs to views. For more inf | ormation please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to ur... | $', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from xscredit.views import *
urlpatterns = [
url(... |
beernarrd/gramps | gramps/gui/actiongroup.py | Python | gpl-2.0 | 1,674 | 0.000597 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2015 Nick Hall
#
# 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) a... | SS 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
A replacement ActionGroup that correctly loads named icons from an icon theme.
"""
from gi.repository import Gtk
class... |
Fantomas42/django-blog-zinnia | zinnia/templating.py | Python | bsd-3-clause | 1,264 | 0 | """Templates module for Zinnia"""
import os
from django.template.defaultfilters import slugify
def append_position(path, position, separator=''):
"""
Concatenate a path and | a position,
between the filename and the extension.
"""
filename, extension = os.path.splitext(path)
return ''.join([filename, separator, str(position), extension])
def loop_template_list(loop_positions, instance, instance_type,
default_template, registry):
"""
Build a ... | position within a loop
and a registry of templates.
"""
templates = []
local_loop_position = loop_positions[1]
global_loop_position = loop_positions[0]
instance_string = slugify(str(instance))
for key in ['%s-%s' % (instance_type, instance_string),
instance_string,
... |
Vagab0nd/SiCKRAGE | lib3/feedparser/sanitizer.py | Python | gpl-3.0 | 24,025 | 0.000291 | # Copyright 2010-2020 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistrib... | rt unicode_literals
import re
from .html import _BaseHTMLProcessor
from .sgml import _SGML_AVAILABLE
from .urls import make_safe_absolute_uri
class _HTMLSanitizer(_BaseHTMLProcessor):
acceptable_elements = {
'a',
'abbr',
'acronym',
'address',
'area',
'article',
... | aside',
'audio',
'b',
'big',
'blockquote',
'br',
'button',
'canvas',
'caption',
'center',
'cite',
'code',
'col',
'colgroup',
'command',
'datagrid',
'datalist',
'dd',
'del',
... |
prydom/MuseIC-EventServer | MuseEventServer/translators/facial_event_translator.py | Python | mit | 3,977 | 0.001509 | import time
import threading
from ..utils.abstract_pub_sub_trans import EventTranslator
class FacialEventTranslator(EventTranslator):
msg_keys_handled = ['OSC_jaw_clench', 'OSC_touching_forehead', 'OSC_blink']
# Facial event params
blink_event_time = 2
seek_multiplyer = 5
def __init__(self, msg... | ime )
print("EVENT: Clench for " + str(clench_time) + " seconds")
self.publish('clench_end', clench_time)
if clench_time > 1:
| rounded_int = int(round(clench_time * self.seek_multiplyer))
self.publish('long_clench_rounded_int', rounded_int)
if self.last_clench_time and self.last_clench_time < 1 and clench_time < 1:
self.publish('quick_clench_two_row', clench_time)
self.last_clench_time = ... |
burakince/ocl_web | ocl_web/config/orgs_urls.py | Python | mpl-2.0 | 24,166 | 0.004924 | # -*- coding: utf-8 -*-
"""
URL Configuration for "/orgs/..." and all its children.
Regex expression not split across lines -- pylint warnings for long lines supressed
with "# pylint: disable=C0301"
TODO:
- Org and source extras
- Source version for about, details, etc. -- only implemented now for concepts/mappings t... | sView.as_view(), name='org-sources'),
# /orgs/:org/collections/
url(r'^(?P<org>[a-zA-Z0-9\-\.]+)/collections/$',
OrganizationCo | llectionsView.as_view(), name='org-collections'),
## ORGANIZATION
# /orgs/new/ - create new org
url(r'^new/$', OrganizationNewView.as_view(), name='org-new'),
# /orgs/:org/ - points to /orgs/:org/details/
url(r'^(?P<org>[a-zA-Z0-9\-\.]+)/$',
OrganizationDetailsView.as_view(), name='org-h... |
GaugeAnomaly/Robotex-Grupp-9 | src/ROSPackage/src/tester.py | Python | gpl-3.0 | 3,204 | 0.019975 | # USAGE
# python ball_tracking.py --video ball_tracking_example.mp4
# python ball_tracking.py
# import the necessary packages
from collections import deque
import numpy as np
import argparse
import imutils
import cv2
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument... | he tracked points are None, ignore
# them
if pts[i - 1] is None o | r pts[i] is None:
continue
# otherwise, compute the thickness of the line and
# draw the connecting lines
thickness = int(np.sqrt(args["buffer"] / float(i + 1)) * 2.5)
cv2.line(frame, pts[i - 1], pts[i], (0, 0, 255), thickness)
# show the frame to our screen
cv2.imshow("Frame", frame)
key = cv2.waitKey(... |
kret0s/gnuhealth-live | tryton/server/trytond-3.8.3/trytond/modules/sale_stock_quantity/tests/test_sale_stock_quantity.py | Python | gpl-3.0 | 848 | 0.002358 | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import unittest
import doctest
import trytond.tests.test_tryton
from trytond.tests.test_tryton import ModuleTestCase
from trytond.tests.test_tryton import doctest_setup, docte... | .loadTestsFromTestCase(
SaleStockQuantityTestCase))
suite.addTests(doctest.DocFileSuite('scenario_sale_stock_quantity.rst',
setUp=doctest_setup, tearDown=doctest_teardown, encoding='utf-8 | ',
optionflags=doctest.REPORT_ONLY_FIRST_FAILURE))
return suite
|
cdemulde/wwdata | wwdata/Class_LabExperimBased.py | Python | agpl-3.0 | 7,474 | 0.011239 | # -*- coding: utf-8 -*-
"""
Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment.
Copyright (C) 2016 Chaim De Mulder
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General P... | umn : string
column containing the relative time values; default to index
| """
if time_column == 'index':
self.data['index']=self.time.values
self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1)
self.data['h'].fillna(0,inplace=True)
self.data.drop('index', axis=1, inplace=True)
else:
self.dat... |
inkmonk/flask-sqlalchemy-booster | tests/test_view_boosters/test_todo_list_api/test_api.py | Python | mit | 775 | 0.030968 | i | mport requests
import json
def test_api_endpoint_existence(todolist_app):
with todolist_app.test_client() as client:
resp = client.get('/tasks')
assert resp.status_code == 200
def test_task_creation(todolist_app):
with todolist_app.test_client() as client:
resp = client.jpost(
'/tasks', {
"title": "Fi... | sert resp['result']['id'] == 1
def test_task_updation(todolist_app):
with todolist_app.test_client() as client:
modified_title = "First task - modified"
resp = client.jput(
'/tasks/1', {
"title": "First task - modified"
}
)
assert resp['status'] == 'success'
assert 'id' in resp['result']
assert ... |
intel-analytics/BigDL | python/ppml/src/bigdl/ppml/algorithms/hfl_logistic_regression.py | Python | apache-2.0 | 942 | 0 | #
# Copyright 2016 The BigDL Authors.
#
# Licensed un | der 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 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from bigdl.dllib.utils.common import Ja... |
thatsIch/sublime-rainmeter | install/from_github.py | Python | mit | 75 | 0 | """This | module handles the business logic to install skins from GitHub."""
| |
ta2-1/pootle | tests/models/store.py | Python | gpl-3.0 | 64,439 | 0.000031 | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import io
import os
import six
import pyte... | assert last_unit.target == updated_target
assert last_unit.submission_set.count() == 0
# last_unit.target = "foo"
# last_unit.save()
# this should now have a submission with the old target
# but it fails
# assert last_unit.submission_set.count() == 1
# update_sub = last_unit.submission_set... | d_value == updated_target
# assert update_sub.new_value == "foo"
@pytest.mark.django_db
def test_update_unit_order(project0_nongnu, ordered_po, ordered_update_ttk):
"""Tests unit order after a specific update.
"""
# Set last sync revision
ordered_po.sync()
assert ordered_po.file.exists()
e... |
ollie314/kuma | kuma/wiki/tests/test_tasks.py | Python | mpl-2.0 | 4,327 | 0 | from __future__ import with_statement
from datetime import datetime
import os
from django.conf import settings
from kuma.core.cache import memcache
from kuma.core.tests import ok_
from kuma.users.models import User
from kuma.users.tests import UserTestCase, user
from . import document, revision
from ..models import... | ocumentSpamAttemptData(UserTestCase):
fixtures = UserTestCase.fixtures
def test_delete_old_data(self):
user = User.objects.get(username='testuser01')
admin = User.objects.get(username='admin')
new_dsa = DocumentSpamAttempt.objects.create(
user=user, title='new record', s | lug='users:me',
data='{"PII": "IP, email, etc."}')
old_reviewed_dsa = DocumentSpamAttempt.objects.create(
user=user, title='old ham', data='{"PII": "plenty"}',
review=DocumentSpamAttempt.HAM, reviewer=admin)
old_unreviewed_dsa = DocumentSpamAttempt.objects.create(
... |
bowlofstew/changes | migrations/versions/3f289637f530_remove_unused_models.py | Python | apache-2.0 | 442 | 0.002262 | """Remove unused models
Revision ID: 3f289637f530
Revise | s: 4ba1dd8c30 | 80
Create Date: 2014-04-17 11:08:50.963964
"""
# revision identifiers, used by Alembic.
revision = '3f289637f530'
down_revision = '4ba1dd8c3080'
from alembic import op
def upgrade():
op.drop_table('aggtestgroup')
op.drop_table('testgroup_test')
op.drop_table('testgroup')
op.drop_table('aggtestsuite... |
0todd0000/spm1d | spm1d/stats/normality/sw.py | Python | gpl-3.0 | 2,649 | 0.041525 |
'''
Normality testing using the Shapiro-Wilks statistic
'''
# Copyright (C) 2016 Todd Pataky
import numpy as np
from scipy import stats
from .. t import regress as _main_regress
from .. anova import anova1 as _main_anova1
from .. anova import anova1rm as _main_anova1rm
from .. anova import anova2 as _main_anova2
f... | siduals( spm[0].residuals )
def | regress(y, x):
spm = _main_regress(y, x)
return residuals( spm.residuals )
def ttest(y):
r = y - y.mean(axis=0)
return residuals(r)
def ttest_paired(yA, yB):
return ttest( yA - yB )
def ttest2(yA, yB):
rA = yA - yA.mean(axis=0)
rB = yB - yB.mean(axis=0)
r = _stack_data(rA, rB)
return residuals(r... |
nirmeshk/oh-mainline | mysite/base/tests.py | Python | agpl-3.0 | 25,144 | 0.001392 | # This file is part of OpenHatch.
# Copyright (C) 2010 Parker Phinney
# Copyright (C) 2010 Jack Grigg
# Copyright (C) 2011 Krzysztof Tarnowski (krzysztof.tarnowski@ymail.com)
# Copyright (C) 2009, 2010, 2011 OpenHatch, Inc.
# Copyright (C) 2011 Jairo E. Lopez
#
# This program is free software: you can redistribute it a... | (arg):
self.assertEqual(type(arg), unicode)
sample_thing(utf8_data)
class Fee | d(TwillTests):
fixtures = ['user-paulproteus', 'person-paulproteus']
def test_feed_shows_answers(self):
# Visit the homepage, notice that there are no answers in the context.
def get_answers_from_homepage():
homepage_ |
wevote/WeVoteServer | follow/urls.py | Python | mit | 369 | 0.00542 | # f | ollow/urls.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from django.conf.urls import re_path
from . import views_admin
# See also organization/urls.py for follow_organization-related urls
urlpatterns = [
re_path(r'^repair_follow_organization/$',
views_admin.repair_follow_organizatio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.