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 |
|---|---|---|---|---|---|---|---|---|
tudelft3d/geovalidation.server | setup.py | Python | gpl-3.0 | 590 | 0.064407 | from setuptools import setup
setup(
name='geovalidation.server',
version='0.5',
long_ | description="Flask-based server to validate GIS datasets (with prepair and val3dity).",
packages=['geovalidation'],
include_package_data=True,
| zip_safe=False,
install_requires=[ 'Flask>=1.1'
,'Jinja2>=2.7.2'
,'Werkzeug>=0.9.4'
,'celery>=3.1.11'
,'redis>=2.9.1'
,'lxml>=3.3.3'
,'subprocess32>=3.2.6'
,'cjio>=0.5'
]
author='Hugo Ledoux',
author_email='h... |
sserrot/champion_relationships | venv/Lib/site-packages/ipywidgets/__init__.py | Python | mit | 1,536 | 0.003906 | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Interactive widgets for the Jupyter notebook.
Provide simple interactive controls in the notebook.
Each Widget corresponds to an object in Python and Javascript,
with controls on the page.
To put a Widget on the p... | l is None:
kernel = get_ipython().kernel
kernel.comm_manager.register_target('jupyter.widget', Widget.handle_comm_opened)
# deprecated alias
handle_kernel = register_comm_target
def _handle_ipython():
"""Register with the comm target at import if running in IPython"""
ip = get_ipython()
if ip ... | n
load_ipython_extension(ip)
_handle_ipython()
|
takeflight/wagtailnews | wagtailnews/deprecation.py | Python | bsd-2-clause | 609 | 0 | import warnings
class DeprecatedCallableStr(str):
do_no_call_in_templates = True
def __new__(cls, value, *args, **kwargs):
return super(DeprecatedCallableStr, cls).__new__(cls, value)
def __init__(self, value, warning, warning_cls):
self.warning, self.warning_cls = warning, warning_cls
... | = super(DeprecatedCallableStr, self).__repr__()
| return '<DeprecatedCallableStr {}>'.format(super_repr)
|
anilveeramalli/cloudify-azure-plugin | blueprints/clustered-dns/dns/dns_remove_reverse_record.py | Python | apache-2.0 | 927 | 0.036677 | import subprocess, os, sys
from reverseZone_naming import reverseZone_name
from netaddr import *
zone_files_path="/etc/bind/ | zones"
def remove_reverse_record():
host_name_to_be_removed= sys.argv[1]
reverse_zone_file_name,reverse_zone_name=reverseZone_name()
os.chdir(zone_files_path)
readFiles = open(reverse_zone_file_name,'r')
reverse_zone_file_content = readFil | es.read()
readFiles.close()
readFiles = open(reverse_zone_file_name,'r')
lines = readFiles.readlines()
readFiles.close()
if host_name_to_be_removed in reverse_zone_file_content:
file_content = open(reverse_zone_file_name,'w')
for line in lines:
if not host_name_to_be_removed in line:
file_content.wri... |
Ecogenomics/GTDBNCBI | scripts_dev/ncbi_assembly_file_metadata.py | Python | gpl-3.0 | 7,410 | 0.001484 | #!/usr/bin/env python
###############################################################################
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License... | _rel_date',
'asm_name': 'ncbi_asm_name',
'gbrs_paired_asm': 'ncbi_gbrs_paired_asm',
'paired_asm_comp': 'ncbi_paired_asm_comp',
'relation_to_type_material': 'ncbi_type_material_designation'}
def run(self, refseq_bacteria_ass... | file,
genbank_archaea_assembly_summary_file, genome_id_file, output_file):
"""Create metadata by parsing NCBI assembly metadata file."""
# get identifier of genomes in GTDB
genome_ids = set()
for line in open(genome_id_file):
if line[0] == '#':
co... |
maleficarium/youtube-dl | youtube_dl/extractor/ruutu.py | Python | unlicense | 4,297 | 0.003495 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
determine_ext,
int_or_none,
xpath_attr,
xpath_text,
)
class RuutuIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ruutu\.fi/video/(... | .ruutu.fi/video/2057306',
'md5': '065a10ae4d5b8cfd9d0c3d332465e3d9',
'info_dict': {
'id': '2057306',
'ext': 'mp4',
'title': 'Superpesis: katso koko kausi Ruudussa',
'description': 'md5:da2736052fef3b2bd5e0005e63c25eac',
... | },
},
]
def _real_extract(self, url):
video_id = self._match_id(url)
video_xml = self._download_xml(
'http://gatling.ruutu.fi/media-xml-cache?id=%s' % video_id, video_id)
formats = []
processed_urls = []
def extract_formats(node):
fo... |
Kbman99/NetSecShare | app/logger_setup.py | Python | mit | 2,739 | 0.004381 | '''
logger_setup.py customizes the app's logging module. Each time an event is
logged the logger checks the level of the event (eg. debug, warning, info...).
If the event is above the approved threshold then it goes through. The handlers
do the same thing; they output to a file/shell if the event level is above their
t... | r', request.remote_addr)
#event_dict['ip_address'] = request.header.get('X-Real-IP')
except:
event_dict['ip_address'] = 'unknown'
return event_dict
# Add a handler to write log messages to a file
if app.config.get('LOG_FILE'):
file_handler = RotatingFileHandler(filena | me=app.config['LOG_FILENAME'],
maxBytes=app.config['LOG_MAXBYTES'],
backupCount=app.config['LOG_BACKUPS'],
mode='a',
encoding='utf-8')
file_handler.setLevel(log... |
firmlyjin/brython | www/tests/unittests/test/gdb_sample.py | Python | bsd-3-clause | 153 | 0.019608 | # Sample scri | pt for use by test_gdb.py
def foo(a, b, c):
bar(a, b, c)
def bar(a, b, c):
baz(a, b, c)
def baz( | *args):
id(42)
foo(1, 2, 3)
|
ddico/odoo | addons/website_blog/models/website_blog.py | Python | agpl-3.0 | 11,694 | 0.002993 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import datetime
import random
import json
from odoo import api, models, fields, _
from odoo.addons.http_routing.models.ir_http import slug
from odoo.tools.translate import html_translate
from odoo.tools im... | , readonly=True)
write_uid = fields.Many2one('res.users', 'Last Contributor', index=True, readonly=True)
visits = fields.Integer('No of Views', copy=False, default=0)
website_id = fields.Many2one(related='blog_id.website_id', readonly=True, store=True)
@api.depends('con | tent', 'teaser_manual')
def _compute_teaser(self):
for blog_post in self:
if blog_post.teaser_manual:
blog_post.teaser = blog_post.teaser_manual
else:
content = html2plaintext(blog_post.content).replace('\n', ' ')
blog_post.teaser = con... |
Drowrin/Weeabot | cogs/moderation.py | Python | mit | 5,452 | 0.002018 | import asyncio
import datetime
import discord
from discord.ext import commands
import utils
import checks
class Moderation:
"""Moderation commands."""
def __init__(self, bot: commands.Bot):
self.bot = bot
if 'jails' not in self.bot.status:
self.bot.status['jails'] = {}
... | return role, channel
server_perms = discord.Permissions()
server_perms.read_ | messages = False
server_perms.send_messages = False
role = await self.bot.create_role(server, name="prisoner", hoist=True, permissions=server_perms)
po = discord.PermissionOverwrite(read_messages=True)
prisoner = discord.ChannelPermissions(target=role, overwrite=po)
eo = discord... |
mylxiaoyi/caffe-with-spearmint | cwsm/cafferun.py | Python | mit | 3,964 | 0.00555 | import numpy as np
import cPickle
import math
import string
import re
import subprocess
from datetime import datetime
from cwsm.performance import Performance
def cafferun(params):
# load general and optimization parameters
with open('../tmp/optparams.pkl', 'rb') as f:
paramdescr = cPickle.load(f)
... | er, 'PLACEHOLDER_MODEL_STORE', '../caffeout/%s' % prefix, 1)
|
# store .prototxt for this run
with open('../tmp/%s_trainval.prototxt' % prefix, 'w') as f:
f.write(trainnet)
if optimize == 'kappa':
with open('../tmp/%s_val.prototxt' % prefix, 'w') as f:
f.write(valnet)
with open('../tmp/%s_solver.prototxt' % prefix, 'w') as f:
... |
zhangvs1988/zhangyl-Djangodemo | article/migrations/0003_auto_20160810_1219.py | Python | gpl-3.0 | 806 | 0.001253 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-10 04:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('article', '0002_auto_20160810_0134'),
]
operations = [
migrations.RemoveField... | preserve_default=False,
),
migrations.AlterField(
model_name='article',
name='ti | tle',
field=models.CharField(max_length=100, verbose_name='标题'),
),
]
|
KorayAgaya/ftpmap | tools/proftpd_versions.py | Python | gpl-3.0 | 1,228 | 0.012215 | #!/usr/bin/env python2.7
#
# ProFTPD versions - create proftpd versions and dump them into versions.h
#
# Copyright (c) 2015 by Hypsurus
#
#
import sys
# The proftpd versions cycle:
# proftpd-1.3.2rc1
# proftpd-1.3.2rc2
# proftpd-1.3.2rc3
# proftpd-1.3.2rc4
# proftpd-1.3.2
# proftpd-1.3.2a
# proftpd-1.3.2b
# p... | =1
for version_mi in xrange(1, 4):
# Just in case thay release 1.x.20
for version_mic in xrange(0, 21):
fixed = "ProFTPD%d.%d.%d" %(VERSION,version_mi,version_mi | c)
versions.append(fixed)
versions.append(fixed+"rc1")
versions.append(fixed+"rc2")
versions.append(fixed+"rc3")
versions.append(fixed+"rc4")
versions.append(fixed+"a")
versions.append(fixed+"b")
versions.append(fixed+"c")
versions.append(fixed+"d"... |
quaquel/EMAworkbench | ema_workbench/analysis/__init__.py | Python | bsd-3-clause | 682 | 0 | # importing anything from analysis segfaults java with netlogo on a mac
# for now no clue why
#
from . import pairs_plotting
from .b_and_w_plotting import set_fig_to_bw
from .ca | rt import setup_cart, CART
from .feature_scoring import (get_ex_feature_scores, get_feature_scores_all,
get_rf_feature_scores,
get_univariate_feature_scores)
from .logistic_regression import Logit
from .plotting import lines, envelopes, kde_o | ver_time, multiple_densities
from .plotting_util import Density, PlotType
from .prim import Prim, run_constrained_prim, pca_preprocess, setup_prim
from .scenario_discovery_util import RuleInductionType
|
thaim/ansible | lib/ansible/utils/path.py | Python | mit | 5,225 | 0.002679 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... |
def basedir(source):
""" returns directory for inventory or playbook """
source = to_bytes(source, errors='surrogate_or_strict | ')
dname = None
if os.path.isdir(source):
dname = source
elif source in [None, '', '.']:
dname = os.getcwd()
elif os.path.isfile(source):
dname = os.path.dirname(source)
if dname:
# don't follow symlinks for basedir, enables source re-use
dname = os.path.absp... |
NikolaYolov/invenio_backup | modules/bibformat/lib/elements/bfe_editors.py | Python | gpl-2.0 | 2,179 | 0.010555 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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
## ... |
##
## You should have received a copy of the GNU General Public License
## along with Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""BibFormat element - Prints editors
"""
__revision__ = "$Id$"
def format_element(bfo, limit, separator=' ; ',... | "yes"):
"""
Prints the list of editors of a record.
@param limit: the maximum number of editors to display
@param separator: the separator between editors.
@param extension: a text printed if more editors than 'limit' exist
@param print_links: if yes, print the editors as HTML link to their pub... |
rescale/django-money | djmoney/models/managers.py | Python | bsd-3-clause | 9,316 | 0.001073 | # -*- coding: utf-8 -*-
from django import VERSION
from django.db.models import F
from django.db.models.fields import FieldDoesNotExist
from django.db.models.query_utils import Q
from django.db.models.sql.constants import QUERY_TERMS
from django.db.models.sql.query import Query
from moneyed import Money
from .._compa... | elif hasattr(func, '__wrapped__'):
# Proxy model
model = func.__wrapped__.__self__.model
else:
# Custom method on user-defined model manager.
model = args[0].model
return model
def understands_money(func):
"""
Used to wrap a queryset method w | ith logic to expand
a query from something like:
mymodel.objects.filter(money=Money(100, "USD"))
To something equivalent to:
mymodel.objects.filter(money=Decimal("100.0"), money_currency="USD")
"""
@wraps(func)
def wrapper(*args, **kwargs):
model = _get_model(args, func)
... |
SUSE/azure-sdk-for-python | azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/shared_public_ip_address_configuration_fragment.py | Python | mit | 1,084 | 0.000923 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license infor | mation.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class SharedPublicIpAddressConfigurationFragme... | es of a virtual machine that determine how it is connected to a
load balancer.
:param inbound_nat_rules: The incoming NAT rules
:type inbound_nat_rules: list of :class:`InboundNatRuleFragment
<azure.mgmt.devtestlabs.models.InboundNatRuleFragment>`
"""
_attribute_map = {
'inbound_nat_r... |
clreinki/GalaxyHarvester | waypointMaps.py | Python | agpl-3.0 | 2,719 | 0.013608 | #!/usr/bin/python
"""
Copyright 2012 Paul Willworth <ioscode@gmail.com>
This file is part of Galaxy Harvester.
Galaxy Harvester is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of th... | 'gh_sid=' + sid
else:
disableStr = ' disabled="disabled"'
if (uiTheme == ''):
uiTheme = 'crafter'
pictureName = dbShared.getUserAttr(current | User, 'pictureName')
print 'Content-type: text/html\n'
env = Environment(loader=FileSystemLoader('templates'))
env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
template = env.get_template('waypointmaps.html')
print template.render(uiTheme=uiTheme, loggedin=logged_state, currentUser=currentUser, loginResult=log... |
suutari/shoop | shuup_tests/admin/test_home.py | Python | agpl-3.0 | 3,871 | 0.001033 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.core.urlresolvers import reverse
from s... | xt(text, rf, admin_user):
return any(text in b.text for b in get_blocks(rf, admin_user) if b.done)
@pytest.mark.django_db
def test_home_wizard_block(rf, admin_user, settings):
# wizard completion block should be present
get_default_shop()
assert has_block_with_text("wizard", rf, admin_user)
# no ... | ck_with_text("wizard", rf, admin_user)
@pytest.mark.django_db
def test_wizard_redirect(rf, admin_user, settings):
settings.SHUUP_SETUP_WIZARD_PANE_SPEC = []
shop = get_default_shop()
shop.maintenance_mode = True
shop.save()
request = apply_request_middleware(rf.get("/"), user=admin_user)
respo... |
thousandparsec/daneel-ai | daneel-ai.py | Python | gpl-2.0 | 9,338 | 0.019383 | #! /usr/bin/python
try:
import requirements
except ImportError:
pass
import time
import random
import logging
import sys
import os
import inspect
from optparse import OptionParser
import tp.client.threads
from tp.netlib.client import url2bits
from tp.netlib import Connection
from tp.netlib import failed, constant... | ir, os.F_OK)
dir_writeable = os.access(save_dir, os.W_OK)
dir_root_writeable = os.access(root_dir, os.W_OK)
if dir_exists and dir_writeable:
return True
if dir_exists and not dir_wr | iteable:
return False
if dir_root_writeable:
os.mkdir(save_dir)
return True
else:
return False
def init(cache,rulesystem,connection):
for m in mods:
#call init if it exists in m
if "init" in [x[0] for x in inspect.getmembers(m)]:
m.init(cache,rulesystem,connection)
#this is ... |
lexsos/heligate | dj-server/apps/accounts_web/auth_ldap.py | Python | gpl-3.0 | 2,203 | 0.00227 | import ldap
def extruct_group(fqdn):
return fqdn.split(',')[0].replace('CN=', '')
def extruct_group_list(data):
groups = []
for fqdn in data:
groups.append(extruct_group(fqdn).lower())
return groups
def get_user_info(
ldap_domain,
ldap_tree_scoupe,
user_name,
... | d (not self.ldap_bind_password is None):
bind_user_name = self.ldap_bind_user
bind_password = self.ldap_bind_password
return get_user_info(
self.ldap_domain,
self.ldap_tree_scoupe,
| user_name,
bind_user_name,
bind_password,
)
def auth(self, user_name, password):
info = self.get_user_info(user_name, password)
if info is None:
return False
if self.ldap_inet_group in info['groups']:
return True
return F... |
clinton-hall/nzbToMedia | core/utils/processes.py | Python | gpl-3.0 | 3,534 | 0.001132 | from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import os
import socket
import subprocess
import sys
import core
from core import logger, version_check, APP_FILENAME, SYS_ARGV
if os.name == 'nt':
from win32event import CreateMutex
fr | om win32api import CloseHandle, GetLastError
from winerror import ERROR_ALREADY_EXISTS
class WindowsProcess(object):
def __init__(self):
self.mutex = None
self.mutexname = 'nzbtomedia_{pi | d}'.format(pid=core.PID_FILE.replace('\\', '/')) # {D0E858DF-985E-4907-B7FB-8D732C3FC3B9}'
self.CreateMutex = CreateMutex
self.CloseHandle = CloseHandle
self.GetLastError = GetLastError
self.ERROR_ALREADY_EXISTS = ERROR_ALREADY_EXISTS
def alreadyrunning(self):
self.mutex = ... |
ziplokk1/python-amazon-mws | mws/parsers/fulfillment/listinboundshipmentitems.py | Python | unlicense | 2,481 | 0.006046 | from mws.parsers.base import first_element, BaseElementWrapper, BaseResponseMixin
from mws._mws import InboundShipments
namespaces = {
'a': 'http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/'
}
class Member(BaseElementWrapper):
def __init__(self, element):
BaseElementWrapper.__init__(... | [Member(x) for x in self.element.xpath('//a:member', namespaces=namespaces)]
@property
@first_element
def next_token(self):
return self.element.xpath('//a:NextToken/text()', namespaces=namespaces)
@classmethod
| def from_next_token(cls, mws_access_key, mws_secret_key, mws_account_id, next_token, mws_auth_token=None):
api = InboundShipments(mws_access_key, mws_secret_key, mws_account_id, auth_token=mws_auth_token)
response = api.list_inbound_shipment_items_by_next_token(next_token)
return cls.load(res... |
luci/luci-py | appengine/auth_service/realms/permissions_test.py | Python | apache-2.0 | 3,254 | 0.008297 | #!/usr/bin/env vpython
# Copyright 2020 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import logging
import sys
import unittest
import test_env
test_env.setup_test_env()
from proto import realms_config_pb2
f... | .p1', 'luci.dev.p2', 'luci.dev.p3'],
roles={
'role/dev.a': ('luci.dev.p1', 'luci.dev.p2'),
'role/dev.b': ('luci.dev.p1', 'luci.dev.p2', 'luci.dev.p3'),
})
def test_role_redeclaration(self):
self.role('role/dev.a', [])
with self.assertRaises(ValueError):
self.role... | ', [])
def test_bad_role_name(self):
with self.assertRaises(ValueError):
self.role('zzz/role', [])
def test_referencing_undeclared_role(self):
with self.assertRaises(ValueError):
self.include('role/zzz')
def test_non_idempotent_perm(self):
self.permission('luci.dev.p1')
self.permiss... |
kyubifire/softlayer-python | SoftLayer/CLI/user/permissions.py | Python | mit | 1,893 | 0.001585 | """List A users permissions."""
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
@click.command()
@click.argument('identifier')
@environment.pass_env
| def cli(env, identifier):
"""User Permissions. TODO change to list all permissions, and which users have them"""
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
object | _mask = "mask[id, permissions, isMasterUserFlag, roles]"
user = mgr.get_user(user_id, object_mask)
all_permissions = mgr.get_all_permissions()
user_permissions = perms_to_dict(user['permissions'])
if user['isMasterUserFlag']:
click.secho('This account is the Master User and has all permissions... |
factorlibre/l10n-spain | l10n_es_ticketbai_api_batuz/__init__.py | Python | agpl-3.0 | 40 | 0 | f | rom . import models
from . import lroe
| |
DataDog/sensei | clients/python/sensei/sensei_components.py | Python | apache-2.0 | 35,124 | 0.017082 | #!/usr/bin/env python
# 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
... | sedquery"
PARAM_RESULT_HIT_STORED_FIELDS = "stored"
PARAM_RESULT_HIT_STORED_FIELDS_NAME = "name"
PARAM_RES | ULT_HIT_STORED_FIELDS_VALUE = "val"
PARAM_RESULT_HIT_EXPLANATION = "explanation"
PARAM_RESULT_FACETS = "facets"
PARAM_RESULT_TID = "tid"
PARAM_RESULT_TOTALDOCS = "totaldocs"
PARAM_RESULT_NUMHITS = "numhits"
PARAM_RESULT_HITS = "hits"
PARAM_RESULT_HIT_UID = "uid"
PARAM_RESULT_HIT_DOCID = "docid"
PARAM_RESULT_HIT_SCORE ... |
access-missouri/am-django-project | am/legislative/migrations/0002_auto_20170705_2126.py | Python | bsd-2-clause | 1,234 | 0.003241 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-05 21:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('legislative', '0001_initial'),
]
operations = [
migrations.AlterField(
... | ull=True),
),
migrations.AlterField(
model_name='bill',
name='proposed_effective_date',
field=models.DateField(blank=True, help_text='Proposed date when the bill, if passed, would go into effect.', null=Tr | ue),
),
]
|
weddige/moneypenny | pywcl/scheduler/__init__.py | Python | mit | 3,088 | 0.003886 | # -*- coding: UTF-8 -*-
from datetime import datetime
from threading import Timer
from queue import Queue
import uuid
import logging
#Fallbacl for python < 3.3
try:
from time import perf_counter
except ImportError:
from time import clock as perf_counter
log = logging.getLogger(__name__)
class _Task:
_proc... | , interval=None, repeat=0):
self._function = function
if hasattr(due, '__iter__'):
self._due_iter = iter(due)
| self._due = self._due_iter.__next__()
else:
self._due_iter = None
self._due = due
self._interval = interval
self._repeat = repeat
if not (self._due or self._interval):
raise ValueError
def __call__(self, *args, job_uuid=None, **kwargs):
... |
leifurhauks/django-mailbox | django_mailbox/south_migrations/0005_rename_fields.py | Python | mit | 1,958 | 0.005618 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.rename_column('django_mailbox_message', 'from_address', 'address')
db.rename_column('django_mailbox_messa... | ,
'message_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'outgoing': ('django.db.models.fields.BooleanField', [], {'defau | lt': 'False'}),
'processed': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '255'})
}
}
complete_apps = ['django_mailbox']
|
mivade/qCamera | qcamera/thorlabs_dcx.py | Python | bsd-2-clause | 8,844 | 0.004636 | """Thorlabs DCx series cameras
Drivers for Windows and Linux can be downloaded from Thorlabs__.
__ http://www.thorlabs.de/software_pages/viewsoftwarepage.cfm?code=DCx
Python implementation of ueye interface: https://github.com/bernardokyotoku/pydcu
"""
from __future__ import print_function
import sys
import ctypes... | orlabs DCx series cameras."""
# Setup and shutdown
# -------------------------------------------------------------------------
# TODO: Change to use a logger!
def _chk(self, msg):
"""Check for errors from the C library."""
if msg:
if msg == 127:
print("Out o... | if msg == 125:
print(
"125: IS_INVALID_PARAMETER: One of the submitted " + \
"parameters is outside the valid range or is not " + \
"supported for this sensor or is not available in this mode.")
print("msg:", msg)
def _... |
sebrandon1/tempest | tempest/api/compute/admin/test_security_groups.py | Python | apache-2.0 | 3,588 | 0 | # Copyright 2013 NTT Data
# 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 appl... | ated Security Groups are present in fetched list
for sec_group in security_group_list:
self.assertIn(sec_group['id'], | sec_group_id_list)
# Fetch all security groups for non-admin user with 'all_tenants'
# search filter
fetched_list = (self.client.list_security_groups(all_tenants='true')
['security_groups'])
# Now check if all created Security Groups are present in fetched list
... |
GbalsaC/bitnamiP | venv/src/edx-milestones/milestones/models.py | Python | agpl-3.0 | 5,901 | 0.000508 | # pylint: disable=no-init
# pylint: disable=old-style-class
# pylint: disable=too-few-public-methods
"""
Database ORM models managed by this Django app
Please do not integrate directly with these models!!! This app currently
offers two APIs -- api.py for direct Python integration and receivers.py,
which leverages Djan... | ilestone relationship types (names) """
RELATIONSHIP_TYPE_CHOICES = {
'REQUIRES': 'requires',
'FULFILLS': 'fulfills',
}
return RELATIONSHIP_TYPE_CHOICES
class CourseMilestone(TimeStampedModel):
"""
A CourseMilestone represents the link between a Course and a
... | integrity will be limited to that
of specifying CourseKeyFields in this model, as well as related ones
below. In addition, a MilestoneRelationshipType specifies the
particular sort of relationship that exists between the Course and
the Milestone, such as "requires".
"""
course_id = models.CharFi... |
ak110/pytoolkit | pytoolkit/evaluations/classification_test.py | Python | mit | 808 | 0.001238 | import numpy as np
import pytoolkit as tk
def test_print_classification_multi():
y_true = np.array([0, 1, 1, 1, 2])
prob_pred = np.array(
[
[0.75, 0.00, 0.25],
[0.25, 0.75, 0.00],
[0.25, 0.75, 0.00],
[0.25, 0.00, 0.75],
[0.25, 0.75, 0.00],
... | tion_binary_multi():
y_true = np.array([0, 1, 1, 0])
prob_pred = np.array([[0.25, 0.75], [0.25, 0.75], [0.75, 0.25], [0.25, 0.75]])
tk.evaluat | ions.print_classification(y_true, prob_pred)
|
cghall/salesforce-reporting | test/common.py | Python | mit | 304 | 0.003289 | import json
import os
import unittest
class Par | serTest(unittest.TestCase):
def build_mock_report(self, report):
path = os.path.join(os.path.dirname(__file__), 'test_data', report) + '.json'
| path = os.path.abspath(path)
with open(path) as f:
return json.load(f)
|
justanr/py3traits | src/pytraits/core/singleton.py | Python | apache-2.0 | 2,036 | 0.000491 | #!/usr/bin/python -tt
# -*- coding: utf-8 -*-
'''
Copyright 2014-2015 Teppo Perä
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
Un... | tch
>>> import timeit
>>> class MySingleton(object, metaclass=Singleton):
... | def __init__(self):
... self._store = dict(one=1, two=2, three=3, four=4)
...
>>> class NonSingleton(object):
... def __init__(self):
... self._store = dict(one=1, two=2, three=3, four=4)
...
>>> #timeit.timeit(NonSingleton) > timeit.timeit(MySingleton)
True
>>>... |
JuBra/GEMEditor | GEMEditor/base/functions.py | Python | gpl-3.0 | 8,494 | 0.000706 | from collections import defaultdict
from six import iteritems
def invert_mapping(mapping):
""" Invert a mapping dictionary
Parameters
----------
mapping: dict
Returns
-------
"""
inverted_mapping = defaultdict(list)
for key, value in mapping.items():
if isinstance(value,... | s not None for x in metabolites.keys()):
return None
else:
return sum([metabolite.charge * coefficient for metabolite, coefficient in iteritems(metabolites)])
def check_element_balance(metabolites):
""" Check that the reaction is elementally balanced """
metabolite_elements = defaultdict(... | cient * count
return {k: v for k, v in iteritems(metabolite_elements) if v != 0}
def reaction_string(stoichiometry, use_metabolite_names=True):
"""Generate the reaction string """
attrib = "id"
if use_metabolite_names:
attrib = "name"
educts = [(str(abs(value)), getattr(key, attrib)) for... |
plotly/python-api | packages/python/plotly/plotly/validators/ohlc/_lowsrc.py | Python | mit | 432 | 0 | import _plotly_utils.basevalidators
class Lo | wsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="lowsrc", parent_name="ohlc", **kwargs):
super(LowsrcValidator, self).__init__(
| plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
rezoo/chainer | chainer/testing/serializer.py | Python | mit | 1,562 | 0 | import os
from chainer import serializers
from chainer import utils
def save_and_load(src, dst, filename, saver, loader):
"""Saves ``src`` and loads it to ``dst`` using a de/serializer.
This function simply runs a serialization and deserialization to check if
the serialization code is correctly implemen... | 5(src, dst):
"""Saves ``src`` to an HDF5 file and loads it to ``dst``.
This is a short cut of :func:`save_and_load` using HDF5 de/serializers.
Args:
src: An object to save.
dst: An object to load to.
"""
save_and_lo | ad(src, dst, 'tmp.h5',
serializers.save_hdf5, serializers.load_hdf5)
|
tedelhourani/ansible | test/units/plugins/inventory/test_script.py | Python | gpl-3.0 | 4,169 | 0.002883 | # -*- coding: utf-8 -*-
# Copyright 2017 Chris Meyers <cmeyers@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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
# (... | "dummyédata\n ")
def test_parse_utf8_fail(self):
self.popen_result.returncode = 0
self.popen_result.stderr = to_bytes("dummyédata")
self.loader.load.side_effect = TypeError('obj must be string')
inventory_module = InventoryModule()
with pytest.raises(... | ed to parse executable inventory script results from "
"/foo/bar/foobar.py: obj must be string\ndummyédata\n")
def test_parse_dict_fail(self):
self.popen_result.returncode = 0
self.popen_result.stderr = to_bytes("dummyédata")
self.loader.load.retu... |
paramite/blazar | climate/db/migration/alembic_migrations/versions/23d6240b51b2_add_status_to_leases.py | Python | apache-2.0 | 1,737 | 0.001151 | # Copyright 2014 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 applic | able law or agreed to in writing, software
# distributed und | er 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.
"""Add status to leases
Revision ID: 23d6240b51b2
Revises: 2bcfe76b0474
Create Date: 20... |
stuglaser/pychan | examples/ajmani-adv-patt.py | Python | bsd-3-clause | 4,939 | 0.00081 | #!/usr/bin/env python
#
# Examples from the talk:
# Sameer Ajmani - Advanced Go Concurrency Patterns - Google I/O 2013
# https://www.youtube.com/watch?v=QDDwwePbDtw
# https://code.google.com/p/go/source/browse/2013/advconc?repo=talks
import argparse
import collections
import random
import threading
import time
f... | .subscriptions]
while True:
c, value = chanselect(subchans + [self.quit], [])
if c == self.quit:
| value.put(self._close_subs_collect_errs())
self.updates_chan.close()
return
else:
item = value
c, _ = chanselect([self.quit], [(self.updates_chan, item)])
if c == self.quit:
value.put(self._close_subs_collect... |
fredo-editor/FreDo | setup.py | Python | bsd-3-clause | 684 | 0.001462 | # Parts of this file were derived from the setup.py file of scikit-image
# scikit-image license can be found at
# https://github.com/scikit-image/scikit-image/blob/master/LICENSE.txt |
from setuptools import setup, find_packages
with open('requirements.txt') as f:
INSTALL_REQUIRES = [l.strip() for l in f.readline | s() if l]
setup(name='FreDo-Editor',
version='0.1.0_dev',
description='Frequency Domain Image Editor',
author='Vighnesh Birodkar',
packages=find_packages(),
install_requires=INSTALL_REQUIRES,
author_email='vighneshbirodkar@nyu.edu',
entry_points={
'gui_scripts': ['fr... |
10clouds/edx-platform | lms/djangoapps/certificates/apis/v0/tests/test_views.py | Python | agpl-3.0 | 4,367 | 0.000687 | """
Tests for the Certificate REST APIs.
"""
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from certificates.models import CertificateStatuses
from certificates.tests.factories import GeneratedCertificateFactory
from course_modes.models impor... | te
"""
self.client.login(username=self.student.username, password='test')
resp = self.client.get(self.get_url(self.student.username))
self.assertEqual(resp.status_code, status.HT | TP_200_OK)
self.assertEqual(
resp.data, # pylint: disable=no-member
{
'username': self.student.username,
'status': CertificateStatuses.downloadable,
'grade': '0.88',
'download_url': 'www.google.com',
'certif... |
Tinkerforge/brickv | src/brickv/plugin_system/plugins/dual_relay/dual_relay.py | Python | gpl-2.0 | 5,730 | 0.001396 | # -*- coding: utf-8 -*-
"""
Dual Relay Plugin
Copyright (C) 2011-2012 Olaf Lüke <olaf@tinkerforge.com>
Copyright (C) 2014 Matthias Bolte <matthias@tinkerforge.com>
dual_relay.py: Dual Relay Plugin Implementation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General... | p)
if dr2:
self.dr2_button.setText('Switch Off')
self.dr2_image.setPixmap(self.a2_pixmap)
else:
self.dr2_button.setText('Switch On')
self.dr2_image.setPixmap(self.b2_pixmap)
def start(self):
async_call(self.dr.get_state, None, self.get_state_... |
self.monoflop.start()
def stop(self):
self.monoflop.stop()
def destroy(self):
pass
@staticmethod
def has_device_identifier(device_identifier):
return device_identifier == BrickletDualRelay.DEVICE_IDENTIFIER
def dr1_clicked(self):
width = self.dr1_button.w... |
electronicdaisy/WeissSchwarzTCGDatabase | card.py | Python | mit | 3,176 | 0.004094 | # img
# trigger = attributes[12]
# http://ws-tcg.com/en/cardlist
# edit
import os
import requests
import sqlite3
def get_card(browser):
attributes = browser.find_elements_by_xpath('//table[@class="status"]/tbody/tr/td')
image = attributes[0].find_element_by_xpath('./img').get_attribute('src')
if attri... | ds.sqlite3')
cursor | = connection.cursor()
cursor.execute('INSERT INTO cards (name, no, rarity, expansion, side, type, color, level, cost, power, soul,'
'special_attribute, text, flavor_text) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?)', card)
connection.commit()
connection.close()
|
tehpwny/insurrection_bot | insurrection_bot.py | Python | gpl-3.0 | 9,673 | 0.002791 | """
# TODO
"""
import os
import sys
from time import sleep
from subprocess import Popen
from random import choice, randrange
PRETTY = '--pretty' in sys.argv
class Tiqqun:
words = {
"things_we_like": [
"rupture", "insurrection", "crisis", "social war",
"zones of indistinction which ... | e", "alienated"
],
"fancy_words": [
"logic", "structure", "being", "temporality", "teleology"
],
"happiness": ["joy", "ecstasy"],
"sadness": ["misery", "catastrophe", "delusion"],
"really": [
"by | any means necessary", "with every weapon at our disposal",
"without looking back", "at all costs"
],
"making_things": [
"articulation", "construction", "elaboration", "setting forth",
"realization"
],
"plans": ["plan", "project", "concept"],
"a... |
akrherz/iem | scripts/dl/download_hrrr.py | Python | mit | 3,606 | 0 | """
Since the NOAAPort feed of HRRR data does not have radiation, we should
download this manually from NCEP
Run at 40 AFTER for the previous hour
"""
import subprocess
import sys
import datetime
import tempfile
import os
import requests
import pygrib
from pyiem.util import exponential_backoff, logger, utc
LOG = ... | "0-0 m below ground",
"0.1-0.1 m below ground",
"0.3-0.3 m below ground",
| "0.6-0.6 m below ground",
"1-1 m below ground",
]:
offsets.append([int(tokens[1])])
neednext = True
pqstr = valid.strftime(
"data u %Y%m%d%H00 bogus model/hrrr/%H/hrrr.t%Hz.3kmf00.grib2 grib2"
)
if len(offsets) != 13:
... |
CentralLabFacilities/m3meka | python/scripts/demo/m3_demo_behaviors.py | Python | mit | 2,341 | 0.026057 | #! /usr/bin/python
#Copyright 2010, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDI... | ED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
#FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
#Copyright OWNER OR CO | NTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
#LIA... |
Tinkerforge/brickv | src/brickv/mac_pasteboard_mime_fixed.py | Python | gpl-2.0 | 2,660 | 0.001128 | # -*- coding: utf-8 -*-
"""
brickv (Brick Viewer)
Copyright (C) 2019 Matthias Bolte <matthias@tinkerforge.com>
mac_pasteboard_mime_fixed.py: Don't add UTF BOM when copying text to the clipboard
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as... | = parts[1].split(';', 1)[0]
if charset == 'system':
return 'public.utf8-plain-text'
if charset in ['iso-106464-ucs-2', 'utf16']:
return 'public.utf16-plain-text'
| return None
def canConvert(self, mime, flavor):
return mime.startswith('text/plain') and flavor in ['public.utf8-plain-text', 'public.utf16-plain-text']
def mimeFor(self, flavor):
if flavor == 'public.utf8-plain-text':
return 'text/plain'
if flavor == 'public.utf16-... |
timothycrosley/WebBot | instant_templates/update_webbot_appengine/WebElements/StringUtils.py | Python | gpl-2.0 | 7,945 | 0.00365 | '''
StringUtils.py
Provides methods that ease complex python string operations
Copyright (C) 2013 Timothy Edmund Crosley
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; eit... | ttribute value):
value - the html value to interpret
"""
lowerCaseValue = value.lower()
if lowerCaseValue == "true":
return True
elif | lowerCaseValue == "false":
return False
elif lowerCaseValue == "none":
return None
return value
def listReplace(inString, listOfItems, replacement):
"""
Replaces instaces of items withing listOfItems with replacement:
inString - the string to do replacements on
... |
Critical-Impact/ffrpg-gen | django/settings/dev.py | Python | mit | 650 | 0.013846 | from settings.common import Common
class Dev(Common):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'po | stgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'ffrpg.sql', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # E | mpty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
} |
jrleeman/MetPy | metpy/io/_tools.py | Python | bsd-3-clause | 13,290 | 0.001204 | # Copyright (c) 2009,2016 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""A collection of general purpose tools for reading files."""
from __future__ import print_function
import bz2
from collections import namedtuple
import gzip
import logging
f... | re than 255 items and can't use
# NamedStruct. This is a CPython limit for arguments.
class DictStruct(Struct):
"""Parse bytes using :class:`Struct` but provide named fields using dictionary access."""
def __init__(self, info, prefmt=''):
"""Initialize the DictStruct."""
names, formats = zip(*i... | self._names = [n for n in names if n]
super(DictStruct, self).__init__(prefmt + ''.join(f for f in formats if f))
def _create(self, items):
return dict(zip(self._names, items))
def unpack(self, s):
"""Parse bytes and return a namedtuple."""
return self._create(super(DictStruc... |
antoinecarme/pyaf | tests/perf/test_long_cycles_nbrows_cycle_length_11000_440.py | Python | bsd-3-clause | 89 | 0.022472 | import tests.perf.test_cycles_full_long_long as gen
ge | n.test_nbrows_c | ycle(11000 , 440)
|
rongoro/clusto | src/clusto/drivers/devices/powerstrips/servertech.py | Python | bsd-3-clause | 4,454 | 0.021105 | """
Server Technology Power Strips
"""
from basicpowerstrip import BasicPowerStrip
from clusto.drivers.devices.common import IPMixin, SNMPMixin
from clusto.drivers.resourcemanagers import IPManager
from clusto.exceptions import DriverException
import re
class PowerTowerXM(BasicPowerStrip, IPMixin, SNMPMixin):
... | serial' : { 'numports':1, },
}
_portmap = {'aa1':1,'aa2':2,'aa3':3,'aa4':4,'aa5':5,'aa6':6,'aa7':7,'aa8':8,
'ab1':9,'ab2':10,'ab3':11,'ab4':12,'ab5':13,'ab6':14,'ab7':15,
'ab8':16,'ba1':17,'ba2':18,'ba3':19,'ba4':20,'ba5':21,'ba6':22,
'ba7':23,'ba... | b4':28,'bb5':29,
'bb6':30,'bb7':31,'bb8':32}
_outlet_states = ['idleOff', 'idleOn', 'wakeOff', 'wakeOn', 'off', 'on', 'lockedOff', 'reboot', 'shutdown', 'pendOn', 'pendOff', 'minimumOff', 'minimumOn', 'eventOff', 'eventOn', 'eventReboot', 'eventShutdown']
def _ensure_portnum(self, porttype, po... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/astroid/tests/unittest_inference.py | Python | agpl-3.0 | 59,256 | 0.002582 | # copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of astroid.
#
# astroid is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
#... | ", f
a, b= b, a # Gasp !
'''
ast = test_utils.build_module(CODE, __name__)
def test_module_inference(self):
infered = self.ast.infer()
obj = next(infered)
self.assertEqual(obj.name, __name__)
self.assertEqual(obj.root().name, __name__)
self.assertRaises... | ext(infered)
self.assertEqual(obj.name, 'C')
self.assertEqual(obj.root().name, __name__)
self.assertRaises(StopIteration, partial(next, infered))
def test_function_inference(self):
infered = self.ast['C']['meth1'].infer()
obj = next(infered)
self.assertEqual(obj.name... |
elastic7327/django-tdd-restful-api | src/posts/tests/base.py | Python | mit | 1,621 | 0 | """
File: base.py
Author: Me
Email: yourname@email.com
Github: https://github.com/yourname
Description:
"""
from datetime import timedelta
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from django.utils.crypto import get_... | est.mark.django_db
class PostsBaseTest(APITestCase):
def test_create_user_model(self):
User.objects.create(
username='Hello_World'
)
assert User.objects.count() == 1, "Should be equal"
def set_oauth2_app_by_admin(self | , user):
app = Application.objects.create(
name='SuperAPI OAUTH2 APP',
user=user,
client_type=Application.CLIENT_PUBLIC,
authorization_grant_type=Application.GRANT_PASSWORD,
)
return app
def get_token(self, access_user, app):
... |
bniemczyk/symbolic | symath/datastructures/onetimequeue.py | Python | bsd-2-clause | 333 | 0.021021 | from collec | tions import deque
class onetimequeue(object):
def __init__ (self):
self._q = deque()
self._seen = s | et()
def push(self, obj):
if obj in self._seen:
return
self._seen.add(obj)
self._q.append(obj)
def pop(self):
return self._q.popleft()
def __len__(self):
return len(self._q)
|
antoinecarme/pyaf | tests/artificial/transf_Logit/trend_MovingMedian/cycle_7/ar_12/test_artificial_1024_Logit_MovingMedian_7_12_100.py | Python | bsd-3-clause | 266 | 0.086466 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_ | artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, | trendtype = "MovingMedian", cycle_length = 7, transform = "Logit", sigma = 0.0, exog_count = 100, ar_order = 12); |
crs4/seal | tests/tseal/seqal/test_reducer.py | Python | gpl-3.0 | 23,258 | 0.008814 | # Copyright (C) 2011-2012 CRS4.
#
# This file is part of Seal.
#
# Seal is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Seal is dis... | proto.serialize_pair(p))
self.__reducer.reduce(self.__ctx)
self.assertEqual(1, len(self.__ctx.emitted.keys()))
self.assertEqual(1, len(self.__ctx.emitted.values()[0])) # only one SAM record | associated with the key
short_name = p0.get_name()[0:-2]
self.assertEqual(short_name, self.__ctx.emitted.keys()[0])
self.assertTrue( re.match("\d+\s+%s\s+%d\s+.*" % (p0.tid, p0.pos), self.__ctx.emitted[short_name][0]) )
# check counter
self.assertFalse(self.__ctx.counters.has_key... |
jminuscula/dixit-online | server/src/dixit/game/test/round.py | Python | mit | 13,429 | 0.003053 |
from django.test import TestCase
from django.contrib.auth.models import User
from dixit import settings
from dixit.game.models.game import Game
from dixit.game.models.player import Player
from dixit.game.models.round import Round, RoundStatus, Play
from dixit.game.models.card import Card
from dixit.game.exceptions im... | nly_storyteller_has_played(self):
story_card = self.game.storyteller._pick_card()
Play.play_for_round(self.current, self.game.storyteller, story_card, 'story')
self.assertEqual(self.current.status, RoundStatus.NEW)
def test_round_is_providing_until_all_players_have_provided(self):
s... | lf.game.storyteller.id)
for player in players[1:]:
Play.play_for_round(self.current, player, player._pick_card())
self.assertEqual(self.current.status, RoundStatus.PROVIDING)
def test_round_is_voting_when_all_players_have_provided_a_card(self):
Play.play_for_round(self.current,... |
kenwith/cs561 | cs561-as1-kenwith/.scratch/foo7.py | Python | gpl-3.0 | 929 | 0.018299 | #!/usr/bin/python
"""a simple test script"""
from mininet.util import ensureRoot, dumpNodeConnections
from mininet.topo import MinimalTopo, Topo
from mininet.net import Mininet
from time import sleep
#from subprocess import Popen
import subprocess
from time import sleep
class SingleSwitchTopo(Topo):
"Single sw... | 2):
switch = self.addSwitch('s1')
# Python's range(N) generates 0..N-1
for h in range(n):
host = self.addHost('h%s' % (h + 1))
self.addLink(host, switch)
def main():
# Ensure this script is being run as root.
ensureRoot()
topo = SingleSwitchTop | o(n=2)
net = Mininet(topo)
net.start()
h1 = net.get('h1')
h2 = net.get('h2')
print "Starting test..."
h1.sendCmd("ifconfig")
sleep(5)
output = h1.waitOutput()
print(output)
net.stop()
if __name__ == "__main__":
main()
|
bmazin/ARCONS-pipeline | examples/palomar-2011/palomar-2011.py | Python | gpl-2.0 | 1,501 | 0.009327 | #
# Look at a .h5 file from the Palomar 2011 run
#
# Set the environment variable MKID_RAW_PATH to point to the data location
#
# Example use:
#
# $ export MKID_RAW_PATH=/Volumes/data/Palomar2011/Pal20110728
# python palomar-2011.py obs_20110729-151443.h5
import sys, os
import tables
print sys.argv
if (len(sys.argv) ... | mImage = fid.getNode("/beammap/beamimage")
# count the total number of photons in the file
nPhoton = 0
iRow = -1
for rows in beamImage:
iRow += 1
print "Begin iRow = ",iRow
iCol = -1
for pixel in rows:
iCol += 1
print " iCol = ",iCol
print " pixel=",pixel
# ... | number.
packet = int(packet)
nPhoton += 1
print "nPhoton=",nPhoton
|
indonoso/small-Inventory | migrations/versions/f719fe7c700a_.py | Python | mit | 1,179 | 0.005937 | """empty message
Revision ID: f719fe7c700a
Revises: b8fa640ec739
Create Date: 2017-02-15 19:55:55.163798
"""
# revision identifiers, used by Alembic.
revision = 'f719fe7c700a'
down_revision = 'b8fa640ec739'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... | eds', sa.Column('product', sa.Integer(), nullable=False))
| op.drop_constraint('production_needs_product_out_fkey', 'production_needs', type_='foreignkey')
op.create_foreign_key(None, 'production_needs', 'product', ['product'], ['id_'])
op.drop_column('production_needs', 'product_out')
# ### end Alembic commands ###
def downgrade():
# ### commands auto genera... |
sjkingo/django-breadcrumbs3 | breadcrumbs3/tests/views.py | Python | bsd-2-clause | 660 | 0.004545 | from django.http import HttpResponse
from django.template import Template, RequestContext
breadcrumb_template_html = Template("""
{% load breadcrumbs %}
{% breadcrumbs %}
""")
def render(request):
"""
Renders a simple template that calls the breadcrumbs templatetag.
"""
context = RequestContext(reques... | return HttpResponse(breadcrumb_template_html.render(context=context))
def some_view_no_url(request):
request.breadcrumbs('Some title', None)
return render(request)
def some_view_with_url(request):
from .tests import Br | eadcrumbsTest as test
request.breadcrumbs('Some other title', test.s)
return render(request)
|
stormi/tsunami | src/primaires/interpreteur/masque/fonctions.py | Python | bsd-3-clause | 2,032 | 0.003457 | # -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# 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
# l... | /or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without speci | fic prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER ... |
vsoch/myconnectome | myconnectome/qa/run_qap_func.py | Python | mit | 2,129 | 0.053546 | """
run quality assurance measures on functional data
"""
import sys,glob
sys.path.append('/corral-repl/utexas/poldracklab/software_lonestar/quality-assessment-protocol')
import os
import numpy
from run_shell_cmd import run_shell_cmd
from compute_fd import compute_fd
from qap import load_func,load_image, load_mask, s... | it('/')[7]
print 'processing',subcode
funcdata['subcode'].append(subcode)
mask_file=func_file.replace('.nii.gz','_brain_mask.nii.gz')
if not os.path.exists(mask_file):
| cmd='bet %s %s -m -F'%(func_file,func_file.replace('.nii.gz','_brain'))
print cmd
run_shell_cmd(cmd)
func_data = load_func(func_file,mask_file)
mean_func_data = calc_mean_func(func_file)
func_mask = load_mask(mask_file)
func_efc = efc(func_data)
#func_fber = fber(func... |
tonioo/modoboa | modoboa/core/migrations/0010_auto_20161026_1011.py | Python | isc | 1,939 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-10-26 08:11
from __future__ import unicode_literals
from django.db import migrations
import jsonfield.fields
def set_parameter(store, parameter):
"""Add parameter to the specified store."""
app, name = parameter.name.split(".")
if app not in sto... | value = True
elif value == "no":
value = False
elif value.isdigit():
value = int(value)
store[app][name.lower()] = value
def move_parameters(apps, | schema_editor):
"""Move global and user parameters."""
Parameter = apps.get_model("lib", "Parameter")
LocalConfig = apps.get_model("core", "LocalConfig")
parameters = {}
for parameter in Parameter.objects.all():
set_parameter(parameters, parameter)
LocalConfig.objects.all().update(_param... |
spxiwh/pycbc-glue | glue/segmentdb/__init__.py | Python | gpl-3.0 | 1,209 | 0.000827 | #
# Copyright (C) 2006 Larne Pekowsky
#
# 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 later version.
#
# This program is distributed... | U 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.
#
# ================================================================== | ===========
#
# Preamble
#
# =============================================================================
#
"""
Utilities for working with segment databases
"""
from glue import git_version
__date__ = git_version.date
__version__ = git_version.id
__author__ = "Larne Pekowsky <lppekow... |
LettError/glyphBrowser | buildExtension.py | Python | bsd-3-clause | 2,493 | 0.003209 | # build RF extension
# run in RF
import os
from mojo.extensions import ExtensionBundle
from mojo.U | I import createModifier
print("did you update the names?")
#modifier = createModifier(command=True, shift=True)
#print(f"({modifier}, ']')")
# get current folder
basePath = os.path.dirname(__file__)
# folder with python files
libPath = os.path.join(basePath, 'lib')
# folder with html files
htmlPath = os.path.join(... | urcesPath = os.path.join(basePath, 'resources')
if not os.path.exists(resourcesPath):
resourcesPath = None
# load license text from file
# see http://choosealicense.com/ for more open-source licenses
licensePath = os.path.join(basePath, 'license.txt')
if not os.path.exists(licensePath):
licensePath = None
... |
mission-peace/interview | python/dynamic/knapsack_01.py | Python | apache-2.0 | 2,542 | 0.003541 | """
Problem Statement
=================
0/1 Knapsack Problem - Given items of certain weights/values and maximum allowed weight how to pick items to pick items
from this set to maximize sum of value of items such that sum | of weights is | less than or equal to maximum allowed
weight.
Runtime Analysis
----------------
Time complexity - O(W*total items)
Video
-----
* Topdown DP - https://youtu.be/149WSzQ4E1g
* Bottomup DP - https://youtu.be/8LusJS5-AGo
References
----------
* http://www.geeksforgeeks.org/dynamic-programming-set-10-0-1-knapsack-problem/... |
dreadrel/UWF_2014_spring_COP3990C-2507 | notebooks/scripts/book_code/code/timesqrt.py | Python | apache-2.0 | 621 | 0.011272 | # File timesqrt.py
import sys, timer2
reps = 10000
repslist = range(reps) # Pull out range list time for 2.6
from math import sqrt # Not math.sqrt: adds attr fetch time
def mathMod():
for i in repslist:
res | = sqrt(i)
return res
def powCall():
for i in repslist:
| res = pow(i, .5)
return res
def powExpr():
for i in repslist:
res = i ** .5
return res
print(sys.version)
for test in (mathMod, powCall, powExpr):
elapsed, result = timer2.bestoftotal(test, _reps1=3, _reps=1000)
print ('%s: %.5f => %s' % (test.__name__, elapsed, result))
|
patilsangram/erpnext | erpnext/selling/doctype/customer/customer_dashboard.py | Python | gpl-3.0 | 679 | 0.050074 | from frappe import _
def get_data():
return {
'heatmap': True,
'heatmap_message': _('This is based on transactions against this Customer. | See timeline below for details'),
'fieldname': 'customer',
'transactions': [
{
'label': _('Pre Sales'),
'items': ['Opportunity', 'Q | uotation']
},
{
'label': _('Orders'),
'items': ['Sales Order', 'Delivery Note', 'Sales Invoice']
},
{
'label': _('Support'),
'items': ['Issue']
},
{
'label': _('Projects'),
'items': ['Project']
},
{
'label': _('Pricing'),
'items': ['Pricing Rule']
},
{
'... |
rahulunair/nova | nova/tests/unit/privsep/test_fs.py | Python | apache-2.0 | 15,685 | 0.000191 | # Copyright 2013 OpenStack Foundation
# Copyright 2019 Aptira Pty Ltd
# 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/license... | nova.privsep.fs.mount('ext4', '/dev/nosuch', '/fake/path',
['-o', 'remount'])
mock_execute.assert_called_with('mount', '-t', 'ext4',
'-o', 'remount',
| '/dev/nosuch', '/fake/path')
@mock.patch('oslo_concurrency.processutils.execute')
def test_umount(self, mock_execute):
nova.privsep.fs.umount('/fake/path')
mock_execute.assert_called_with('umount', '/fake/path',
attempts=3,... |
smmribeiro/intellij-community | python/testData/refactoring/extractmethod/ElseBody.before.py | Python | apache-2.0 | 325 | 0.024615 | def foo():
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError | :
print('cannot open', arg)
else:
<selection>length = len(f.readlines()) #<---extract something from here
print("hi from else")</selection>
#anything els | e you need |
mksachs/UberCC | uber_API.py | Python | mit | 3,244 | 0.014797 | #!/usr/bin/env python
import json
import dateutil.parser
import datetime
import numpy as np
import calendar
import itertools
from flask import Flask, request, Response, render_template, redirect, url_for
import Uber
app = Flask(__name__)
'''
The index page has links to the from_file API and the from_stream API.
'''... | ''
The from_file API. Accepts a get parameter 'data_file' that points at a data file
containing the login data.
'''
@app.route('/from_file', methods=['GET'])
def from_file():
if request.method == 'GET':
data_file = request.args.get('data_file', '')
dp = Uber.DemandPredictor()
f = open(data_f... | .close()
logins_np = np.array([dateutil.parser.parse(x) for x in logins], dtype=datetime.datetime)
for login in logins_np:
dp.addLogin(login)
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
forecast = []
start_date = datetime.date... |
sbc100/yapf | yapf/yapflib/style.py | Python | apache-2.0 | 23,126 | 0.004886 | # Copyright 2015 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... | })"""),
COLUMN_LIMIT=textwrap.dedent("""\
The column limit."""),
CONTINUATION_ALIGN_STYLE=textwrap.dedent("""\
The style for continuation alignment. Possible values are:
- SPACE: Use spaces for continuation alignment. This is default behavior.
- FIXED: Use fixed number (CONTINUATION_IN... | CONTINUATION_INDENT_WIDTH/INDENT_WIDTH tabs) for continuation
alignment.
- LESS: Slightly left if cannot vertically align continuation lines with
indent characters.
- VALIGN-RIGHT: Vertically align continuation lines with indent
characters. Slightly right (one more indent character) ... |
samaitra/kafka | tests/kafkatest/tests/connect_test.py | Python | apache-2.0 | 4,906 | 0.005911 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | T_INPUT_LIST) + "\ | n"
SECOND_INPUT_LIST = ["razz", "ma", "tazz"]
SECOND_INPUT = "\n".join(SECOND_INPUT_LIST) + "\n"
SCHEMA = { "type": "string", "optional": False }
def __init__(self, test_context):
super(ConnectStandaloneFileTest, self).__init__(test_context, num_zk=1, num_brokers=1, topics={
'test'... |
dan-blanchard/conda-build | conda_build/main_metapackage.py | Python | bsd-3-clause | 4,053 | 0.001727 | # (c) Continuum Analytics, Inc. / http://continuum.io
# All Rights Reserved
#
# conda is distributed under the terms of the BSD 3-clause license.
# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.
from __future__ import absolute_import, division, print_function
import argparse
from collections impo... |
from conda_build.main_build import args_func
from conda_build.metadata import MetaData
from conda_build.build import build, bldpkg_path
from conda_build.main_build import handle_b | instar_upload
def main():
p = ArgumentParser(
description='''
Tool for building conda metapackages. A metapackage is a package with no
files, only metadata. They are typically used to collect several packages
together into a single package via dependencies.
NOTE: Metapackages can also be created by crea... |
nnugumanov/yandex-tank | yandextank/plugins/Android/plugin.py | Python | lgpl-2.1 | 7,170 | 0.001534 | import logging
import subprocess
import time
import urllib
import sys
import glob
import os
from multiprocessing import Process
from signal import SIGKILL
try:
from volta.analysis import grab, uploader
except Exception:
raise RuntimeError("Please install volta. https://github.com/yandex-load/volta")
from pkg_... | in, GeneratorPlugin):
SECTION = "android"
SECTION_META = "meta"
def __init__(self, core):
super(Plugin, self).__init__(core)
self.apk_path = None
self.test_path = None
self.package = None
self.package_test = None
self.clazz = None
self.device = None
... | .test_runner = None
self.process_test = None
self.process_stderr = None
self.process_grabber = None
self.apk = "./app.apk"
self.test = "./app-test.apk"
self.grab_log = "./output.bin"
self.event_log = "./events.log"
@staticmethod
def get_key():
ret... |
dimagi/commcare-hq | corehq/apps/commtrack/migrations/0006_remove_sqlcommtrackconfig_couch_id.py | Python | bsd-3-clause | 414 | 0 | # -*- coding: utf-8 -*-
# | Generated by Django 1.11.28 on 2020-05-03 02:00
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('commtrack', '0005_populate_config_models'),
]
operations = [
migrations.RemoveField(
model_name=... | ,
),
]
|
Ircam-Web/mezzanine-organization | organization/network/migrations/0099_organization_validation_status.py | Python | agpl-3.0 | 585 | 0.001709 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 | on 2017-04-07 09:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organization_network', '0098_producerdata'),
]
operations = [
migrations.AddField(
model_name='organization',
... | verbose_name='validation status'),
),
]
|
denverfoundation/storybase | apps/storybase_story/migrations/0030_auto__add_storyrelation__add_field_storytranslation_connected_prompt__.py | Python | mit | 29,792 | 0.007452 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'StoryRelation'
db.create_table('storybase_story_storyrelation', (
('id', self.... | 'asset_created': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'asset_id': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'blank': 'True'}),
'attribution': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
... | True', 'blank': 'True'}),
'datasets': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'assets'", 'blank': 'True', 'to': "orm['storybase_asset.DataSet']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'las... |
dr4g0nsr/phoenix-kodi-addon | plugin.video.phstreams/default.py | Python | gpl-2.0 | 5,936 | 0.003706 | # -*- coding: utf-8 -*-
'''
Phoenix Add-on
Copyright (C) 2015 Blazetamer
Copyright (C) 2015 lambda
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 Lic... | es.lib.libraries import downloader
downloader.downloader()
elif action == 'addDownload':
from resources.lib.libraries import downloader
downloader.addDownload(name,url,image)
elif action == 'removeDownload':
from resources.lib.libraries import downloader
downloade | r.removeDownload(url)
elif action == 'startDownload':
from resources.lib.libraries import downloader
downloader.startDownload()
elif action == 'startDownloadThread':
from resources.lib.libraries import downloader
downloader.startDownloadThread()
elif action == 'stopDownload':
from resources.lib.l... |
mozman/ezdxf | integration_tests/test_geo.py | Python | mit | 1,836 | 0 | # Copyright (c) 2020, Manfred Moitzi
# License: MIT License
import pytest
from ezdxf.entities import factory
from ezdxf.render.forms import square, translate
from ezdxf.lldxf import const
from ezdxf.addons import geo
shapely_geometry = pytest.importorskip("shapely.geometry")
def test_shapely_geo_interface():
p... | polygon = shapely_geometry.shape(p)
assert polygon.is_valid is True
p.filter(validate)
assert p.root["type"] == "Polygon"
assert len(p.root["coordinates"]) == 2
def test_valid_hatch():
hatch = factory.new("HATCH")
paths = hatch.paths
paths.add_polyline_path(square(10), flags=const.BOUN... | olyline_path(
translate(square(3), (1, 1)), flags=const.BOUNDARY_PATH_DEFAULT
)
paths.add_polyline_path(
translate(square(3), (5, 1)), flags=const.BOUNDARY_PATH_DEFAULT
)
p = geo.proxy(hatch)
polygon = shapely_geometry.shape(p)
assert polygon.is_valid is True
p.filter(valida... |
fw1121/ete | test/test_treeview.py | Python | gpl-3.0 | 5,124 | 0.003708 | import unittest
import random
import sys
import os
ETEPATH = os.path.abspath(os.path.split(os.path.realpath(__file__))[0]+'/../')
sys.path.insert(0, ETEPATH)
from ete2 import Tree, TreeStyle, NodeStyle, PhyloTree, faces, random_color
from ete2.treeview.faces import *
from ete2.treeview.main import _NODE_TYPE_CHECKER,... | e_grid, bubble_map, item_faces, node_style, node_background, face_positions, face_rotation, seq_motif | _faces, barchart_and_piechart_faces
sys.path.insert(0, os.path.join(ETEPATH, "examples/phylogenies"))
import phylotree_visualization
CONT = 0
class Test_Coretype_Treeview(unittest.TestCase):
""" Tests tree basics. """
def test_renderer(self):
main_tree = Tree()
main_tree.dist = 0
t,... |
poobalan-arumugam/stateproto | src/extensions/lang/python/reader/__init__.py | Python | bsd-2-clause | 65 | 0 | from . | parseStateProtoFile import *
from .StateTreeModel i | mport *
|
pombredanne/parakeet | test/core_language/test_div_bool.py | Python | bsd-3-clause | 679 | 0.013255 | import numpy as np
from parakeet import jit, testing_helpers
@jit
def true_divided(x):
return True / x
def test_true_divided_bool():
testing_ | helpers.expect(true_divid | ed, [True], True)
def test_true_divided_int():
testing_helpers.expect(true_divided, [1], 1)
testing_helpers.expect(true_divided, [2], 0)
def test_true_divided_float():
testing_helpers.expect(true_divided, [1.0], 1.0)
testing_helpers.expect(true_divided, [2.0], 0.5)
def test_true_divided_uint8():
... |
PanDAWMS/panda-bigmon-atlas | atlas/getdatasets/models.py | Python | apache-2.0 | 1,240 | 0.007258 | from django.db import models
class ProductionDatasetsExec(models.Model):
name = models.CharField(max_length=200, db_column='NAME', primary_key=True)
taskid = models.DecimalField(decimal_places=0, max_digits=10, db_colu | mn='TASK_ID', null=False, default=0)
status = models.CharField(max_length=12, db_column='STATUS', null=True)
phys_group = models.CharField(max_length=20, db_column='PHYS_GROUP', null=True)
events = models.DecimalField(decimal_places=0, max_digits=7, db_column='EVENTS', null=False, default=0)
class Met... | s=0, max_digits=10, db_column='REQID', primary_key=True)
total_events = models.DecimalField(decimal_places=0, max_digits=10, db_column='TOTAL_EVENTS')
task_name = models.CharField(max_length=130, db_column='TASKNAME')
status = models.CharField(max_length=12, db_column='STATUS')
class Meta:
app... |
dikujepsen/OpenTran | v3.0/test/C/run.py | Python | mit | 4,191 | 0.019327 | import os, os.path
import subprocess
import shutil
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--make", help="run make clean && make on all files",
action="store_true")
parser.add_argument("-c", "--check", help="run ./check.sh on all files",
... | if args.printresult:
command += " DEF=PRINT"
if args.check:
command = "./check.sh"
| for n in benchmark:
os.chdir(n)
p1 = subprocess.Popen(command, shell=True,\
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
erracc = ''
while True:
line = p1.stdout.readline()
if not line:
... |
memee/py-tons | pytons/files.py | Python | mit | 2,232 | 0.000896 | import six
#==============================================================================
# https://docs.python.org/2/library/csv.html
#==============================================================================
if six.PY2:
import csv
import codecs
| import cStringIO
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(sel... | which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [un... |
mozfreddyb/room-availability | ifb.py | Python | mpl-2.0 | 882 | 0.013605 | """ implement internet free/busy vcal extension
very basic just to get something like this running:
BEGIN:V | CALENDAR
PRODID:Zimbra-Calendar-Provider
VERSION:2.0
METHOD:PUBLISH
BEGIN:VFREEBUSY
ORGANIZER:mailto:ber201@mozilla.com
DTSTAMP:20140811T130952Z
DTSTART:20140811T130952Z
DTEND:20140812T130952Z
URL:http://zmmbox6.mail.corp.phx1.mozilla.com:8080/service/home/ber201@mozilla.com?view=day&date=20140811&fmt=ifb&start=0d&end=... | f get_busy_times(s):
lines = s.split("\r\n")
for line in lines:
if line == "":
continue
key,value = line.split(":", 1)
if key == "FREEBUSY;FBTYPE=BUSY":
start,end = value.split("/")
start = parser.parse(start)
end = parser.parse(end)
yield (start,end) |
adaptive-learning/proso-apps | proso_models/migrations/0001_initial.py | Python | mit | 11,335 | 0.003882 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-08-01 07:59
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import proso.django.models
class Migration(migrations.Migration):
initial = T... | model_name='item',
name='item_type',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.ItemType'),
),
migrations.AddField(
model_name='audit',
name='info',
field=model | s.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='proso_models.EnvironmentInfo'),
),
migrations.AddField(
model_name='audit',
name='item_primary',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=d... |
frossigneux/python-kwstandbyclient | kwstandbyclient/client.py | Python | apache-2.0 | 1,371 | 0 | # Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | wstandbyclient import exception
from kwstandbyclient.openstack.common.gettextutils import _ # noqa
from kwstandbyclient.openstack.common import importutils
def Client(version=1, *args, **kwargs):
version_map = {
'1': 'kwstandbyclient.v1.client.Client',
'1a0': 'kwstandbyclient.v1.client.Cli | ent',
}
try:
client_path = version_map[str(version)]
except (KeyError, ValueError):
msg = _("Invalid client version '%(version)s'. "
"Must be one of: %(available_version)s") % ({
'version': version,
'available_version': ', '.join(versio... |
spektom/incubator-airflow | tests/providers/qubole/operators/test_qubole_check.py | Python | apache-2.0 | 4,944 | 0.001416 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements | . See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License | , Version 2.0 (the
# "License"); you may not 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... |
garrettcap/Bulletproof-Backup | wx/lib/agw/ribbon/gallery.py | Python | gpl-2.0 | 32,914 | 0.007717 | """
A ribbon gallery is like a :class:`ListBox`, but for bitmaps rather than strings.
Description
===========
It displays a collection of bitmaps arranged in a grid and allows the user to
choose one. As there are typically more bitmaps in a gallery than can be displayed
in the space used for a ribbon, a gallery alwa... | nit__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, agwStyle=0,
name="RibbonGallery"):
"""
| Default class constructor.
:param `parent`: pointer to a parent window, typically a :class:`~lib.agw.ribbon.panel.RibbonPanel`;
:param `id`: window identifier. If ``wx.ID_ANY``, will automatically create an
identifier;
:param `pos`: window position. ``wx.DefaultPosition`` indic... |
Rediker-Software/litle-sdk-for-python | litleSdkPythonTest/certification/TestCert4.py | Python | mit | 11,409 | 0.007976 | #Copyright (c) 2011-2012 Litle & Co.
#
#Permission is hereby granted, free of charge, to any person
#obtaining a copy of this software and associated documentation
#files (the "Software"), to deal in the Software without
#restriction, including without limitation the rights to use,
#copy, modify, merge, publish, distri... | erId = "41"
sale.amount = 2008
sale.orderSource = 'telephone'
billtoaddress = litleXmlFields.contact()
billtoaddress.firstName = "Mike"
billtoaddress.middleInitial = "J"
billtoaddress.lastName = "Hammer"
sale.billToAddress = billtoaddress
... | 053100300"
sale.echeckOrEcheckToken = echeck
litleXml = litleOnlineRequest(config)
response = litleXml.sendRequest(sale)
self.assertEquals("301", response.response)
self.assertEquals("Invalid Account Number", response.message)
def test42(self):
sale... |
axonchisel/ax_metrics | py/axonchisel/metrics/foundation/query/mql.py | Python | mit | 11,429 | 0.002362 | """
Ax_Metrics - MQL Metrics Query Language Parser
------------------------------------------------------------------------------
Author: Dan Kamins <dos at axonchisel dot net>
Copyright (c) 2014 Dan Kamins, AxonChisel.net
"""
# ----------------------------------------------------------------------------
import co... | it: DAY
| smooth_val: 30
reframe_dt: 2014-11-01
format:
some_erout_plugin_id:
type: type1
title: "New Paid Accounts %"
subtitle: "(rolling 30d)"
ghosts:
- PREV_PERIOD1
- PREV_YEAR1
- PREV_YEAR2
"""
def __init__(self... |
T2DREAM/t2dream-portal | src/encoded/tests/test_auditor.py | Python | mit | 4,492 | 0.002004 | import pytest
def raising_checker(value, system):
from snovault.auditor import AuditFailure
if not value.get('checker1'):
raise AuditFailure('testchecker', 'Missing checker1')
def returning_checker(value, system):
from snovault.auditor import AuditFailure
if not value.get('checker1'):
... | or()
auditor.add_audit_checker(raising_checker, 'test', has_condition1)
return auditor
@pytest.fixture
def dummy_request(registry):
from pyramid.testing import DummyRequest
_embed = {}
request = DummyRequest(registry=registry, _embed=_embed, embed=lambda path: _embed[path])
return request
de... | checker1': True}
dummy_request._embed['/foo/@@embedded'] = value
errors = auditor.audit(request=dummy_request, path='/foo/', types='test')
assert errors == []
def test_audit_failure(auditor, dummy_request):
value = {}
dummy_request._embed['/foo/@@embedded'] = value
error, = auditor.audit(reque... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.