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 |
|---|---|---|---|---|---|---|---|---|
jkandasa/integration_tests | scripts/azure_cleanup.py | Python | gpl-2.0 | 3,453 | 0.003186 | import argparse
import sys
import traceback as tb
from datetime import datetime
from cfme.utils.path import log_path
from cfme.utils.providers import list_provider_keys, get_mgmt
def parse_cmd_line():
parser = argparse.ArgumentParser(argument_default=None)
parser.add_argument('--nic-template',
... | ="target file name, default "
"'cleanup_azure.log' in "
| "utils.path.log_path",
default=log_path.join('cleanup_azure.log').strpath)
args = parser.parse_args()
return args
def azure_cleanup(nic_template, pip_template, days_old, output):
with open(output, 'w') as report:
report.write(... |
fiduswriter/fiduswriter | fiduswriter/bibliography/migrations/0003_alter_entry_options.py | Python | agpl-3.0 | 357 | 0 | # Generated by Django 3.2.4 on 2021-07-05 13:56
from django.db import migrations
class Migration | (migrations.Migration):
dependencies = [
("bibliography", "0002_move_json_data"),
]
operations = [
migrations.AlterModelOptions(
| name="entry",
options={"verbose_name_plural": "Entries"},
),
]
|
secondfoundation/Second-Foundation-Src | src/haruspex/python/echelon/investopedia_generator.py | Python | lgpl-2.1 | 2,630 | 0.031179 | #Parsing program to sort through Investopedia
import urllib2
import re
#This is the code to par | se the List of Terms
def get_glossary(res_num):
html_lowered = res_num.lower();
begin = html_lowered.find('<!-- .alphabet -->')
end = html_lowered.find('<!-- .idx-1 -->')
if begin == -1 or end == -1:
return None
else:
return res_num[begin+len('<!-- .alphabet -->'):end].strip()
#This is the code to parse the | Title
def get_title(res_num):
html_lowered = res_num.lower();
begin = html_lowered.find('<title>')
end = html_lowered.find('</title>')
if begin == -1 or end == -1:
return None
else:
return res_num[begin+len('<title>'):end].strip()
#We start with the numbers section of Investopedia
url = "http://www.investoped... |
nimbis/django-cms | menus/base.py | Python | bsd-3-clause | 1,763 | 0.001134 | # -*- coding: utf-8 -*-
from django.utils.encoding import smart_str
class Menu(object):
namespace = | None
def __init__(self, renderer):
self.renderer = renderer
if not self.namespace:
self.name | space = self.__class__.__name__
def get_nodes(self, request):
"""
should return a list of NavigationNode instances
"""
raise NotImplementedError
class Modifier(object):
def __init__(self, renderer):
self.renderer = renderer
def modify(self, request, nodes, namesp... |
dlenwell/refstack-client | tests/unit/tests.py | Python | apache-2.0 | 909 | 0.0011 | #
# Copyright (c) 2014 Piston Cloud Computing, 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 o | btain
# 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 t... | ttest.TestCase):
def setUp(self):
pass
def test_nothing(self):
# make sure the shuffled sequence does not lose any elements
pass
if __name__ == '__main__':
unittest.main()
|
DIVERSIFY-project/SMART-GH | sensor_processing/constants.py | Python | apache-2.0 | 359 | 0.013928 | """
This contains all the constants needed for the daemons to run
"""
LOGGING_CONSTANTS = {
'LOGFILE' : 'summer.log',
| 'MAX_LOG_SIZE' : 1048576, # 1 MEG
'BACKUP_COUNT' : 5
}
def getLoggingConstants(constant):
"""
| Returns various constants needing by the logging module
"""
return LOGGING_CONSTANTS.get(constant, False)
|
tmerrick1/spack | var/spack/repos/builtin/packages/py-psyclone/package.py | Python | lgpl-2.1 | 2,637 | 0.000758 | ##############################################################################
# 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... | even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Pub | lic
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
#
from spack import *
class PyPsyclone(PythonPackage):
"""Code generation for the PSyKA... |
rhots/automation | heroes-sidebar-master/reddit.py | Python | isc | 1,603 | 0.029944 | import praw
import requests
from env import env
from twitch import twitch
class reddit:
def __init__(self):
self.r = praw.Reddit(user_agent='Heroes of the Storm Sidebar by /u/Hermes13')
self.env = env()
self.access_information = None
def setup(self):
# self.r.set_oauth_app_info( client_id=self.env.redditC... | n(self.env.redditRefreshToken)
authenticated_user=self.r.ge | t_me()
def updateSidebar(self, matches, streams, freeRotation):
sidebar = self.r.get_wiki_page('heroesofthestorm', 'sidebar')
sidebarWiki = sidebar.content_md
if matches:
sidebarWiki = sidebarWiki.replace("%%EVENTS%%", matches)
if streams:
sidebarWiki = sidebarWiki.replace("%%STREAMS%%", streams)
if f... |
hansbrenna/NetCDF_postprocessor | plotter3.py | Python | gpl-3.0 | 4,021 | 0.034071 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 15:32:58 2015
@author: hanbre
"""
from __future__ import print_function
import sys
import numpy as np
import pandas as pd
import xray
import datetime
import netCDF4
from mpl_toolkits.basemap import Basemap
import matplotlib
from matplotlib.pylab import *
import matplo... | y=getattr(ds,yvar)
if typ == 'm':
print('here')
mvar1 | = l[5]; mvar2 = l[6]
if size(v.dims)==4:
mvars = [mvar1,mvar2]
else:
mvars = [mvar1]
vm=meaner(v,mvars)
savestring = '{0}{1}{2}{3}{4}{5}{6}.png'.format(id_in,typ,var,xvar,yvar,mvar1,mvar2)
print(save... |
naturali/tensorflow | tensorflow/models/rnn/ptb/ptb_word_lm.py | Python | apache-2.0 | 10,545 | 0.010906 | # Copyright 2015 The TensorFlow Authors. 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 applica... | n_size - the number of LSTM units
- max_epoch - the number of epochs trained with the initial learning rate
- max_max_epoch - the total number of epochs for training
- keep_prob - the probability of keeping weights in the dropout layer
- lr_decay - the decay of the learning rate for each epoch after "max_epoch"
- batch... | $ wget http://www.fit.vutbr.cz/~imikolov/rnnlm/simple-examples.tgz
$ tar xvf simple-examples.tgz
To run:
$ python ptb_word_lm.py --data_path=simple-examples/data/
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
import t... |
showmen15/testEEE | src/amberdriver/drive_to_point/drive_to_point_controller.py | Python | mit | 7,564 | 0.003173 | import logging
import logging.config
import sys
import threading
import os
from amberclient.collision_avoidance.collision_avoidance_proxy import CollisionAvoidanceProxy
from amberclient.common.amber_client import AmberClient
from amberclient.location.location import LocationProxy
from amberclient.roboclaw.roboclaw imp... | == '__main__':
client_for_location = AmberClient('127.0.0.1', name="location")
client_for_driver = AmberClient('127.0.0.1', name="driver")
location_proxy = LocationProxy(client_for_location, 0)
if USE_COLLISION_AVOIDANCE:
driver_proxy = CollisionAvoidanceProxy(client_for_driver, 0)
else:
... | d = threading.Thread(target=drive_to_point.driving_loop, name="driving-thread")
driving_thread.start()
location_thread = threading.Thread(target=drive_to_point.location_loop, name="location-thread")
location_thread.start()
controller = DriveToPointController(sys.stdin, sys.stdout, drive_to_point)
... |
kennedyshead/home-assistant | homeassistant/components/zeroconf/models.py | Python | apache-2.0 | 1,697 | 0.001179 | """Models for Zeroconf."""
import asyncio
from typin | g import Any
from zeroconf import DNSPointer, DNSRecord, ServiceBrowser, Zeroconf
from zeroconf.asyncio import AsyncZeroconf
class HaZeroconf(Zeroconf):
"""Zeroconf t | hat cannot be closed."""
def close(self) -> None:
"""Fake method to avoid integrations closing it."""
ha_close = Zeroconf.close
class HaAsyncZeroconf(AsyncZeroconf):
"""Home Assistant version of AsyncZeroconf."""
def __init__( # pylint: disable=super-init-not-called
self, *args: An... |
adamgreenhall/openreviewquarterly | builder/config.py | Python | mit | 879 | 0.025028 | issues=[
dict(name='Habit',number=5,season='Winter 2012',
description='commit to a change, experience it, and record'),
dict(name='Interview', number=4, season='Autumn 2011',
description="this is your opportunity to inhabit another's mind"),
dict(name= 'Digital Presence', number= 3, season= ... | te about it.'),
dict(name= 'Unplugging', number=1, season= 'Winter 2011',
description='what are you looking forward to leaving?')
]
siteroot='/Users/adam/open review quarterly/ | source/'
infodir='/Users/adam/open review quarterly/info'
skip_issues_before=5
illustration_tag='=== Illustration ==='
illustration_tag_sized="=== Illustration width: 50% ===" |
davidko/evolspyse | core/behaviours/ooda.py | Python | lgpl-2.1 | 1,291 | 0.000775 | """Spyse OODA behaviour module"""
import time
# http://www.mindsim.com/MindSim/Corporate/OODA.html
# http://www.d-n-i.net/second_level/boyd_military.htm
# http://www.belisarius.com/modern_business_strategy/boyd/essence/eowl_frameset.htm
# http://www.valuebasedmanagement.net/methods_boyd_ooda_loop.html
# http:... | tegy. Boyd developed the theory based on his earlier
# experience as a fighter pilot and work on energy maneuverability.
# He initially used it to explain victory in air-to-air combat,
# but in the last years of his career he expanded his OODA loop
# theory into a grand strategy that would defeat an enemy
# strate... | ological paralysis.
from spyse.core.behaviours.fsm import FSMBehaviour
class Observation(object):
pass
class Orientation(object):
pass
class Decision(object):
pass
class Action(object):
pass
class OODABehaviour(FSMBehaviour):
pass
|
hgsoft/hgsoft-addons | custom_survey_multi_emails_and_portal/models/custom_survey.py | Python | gpl-3.0 | 454 | 0.015419 | # -*- coding: utf-8 -*-
from odoo import fields, models
class Cu | stomSurvey(models.Model):
_inherit = 'survey.survey'
auth_required = fields.Boolean('Login required', help="Users with a public link will be requested to login before taking part to the survey",
oldname="authenticate", default=True)
users_can_go_back = fields.Boolean('Users can go b | ack', help="If checked, users can go back to previous pages.", default=True) |
CAIDA/bgpstream | pybgpstream/docs/conf.py | Python | gpl-2.0 | 8,420 | 0.005819 | # -*- coding: utf-8 -*-
#
# pybgpstream documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 19 11:07:23 2015.
#
# 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
# autogenerated file.
#... | this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# direct... | _updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page nam... |
bonattt/name-masher | tests/masher_test.py | Python | mit | 289 | 0.00346 | import unittest
class ATest(unittest.TestCase):
def setUp(self):
| print("setup")
pass
def test_a(self):
| self.assertTrue(True)
def tearDown(self):
print("tear down")
if __name__ == "__main__":
print("masher_test.py")
unittest.main() |
tflovorn/scSuperSolver | src/RunInterface.py | Python | mit | 4,820 | 0.002905 | # Copyright (c) 2010, 2011 Timothy Lovorn
#
# 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... | Data.
runData is a list of tuples which contain a label and a dict.
Labels are used to name generated configs and their specified output
files. The dicts are key-value pairs for data to modify in the
base config. Return a list of the names of config files generated.
"""
| configNames = []
baseConfigFullPath = os.path.join(self.path, baseConfig)
for label, labelData in runData:
newConfig = FileDict(baseConfigFullPath)
newConfigFullPath = os.path.join(self.path, label + "_config")
labelData.update({"outputLogName" : label + "_out.fd... |
hsoft/moneyguru | core/gui/import_window.py | Python | gpl-3.0 | 15,326 | 0.002088 | # Copyright 2019 Virgil Dupras
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
import datetime
from collections import defaultdict
from core.util import ... | .name:
self.loader.accounts.rename_account(account, new_name)
accounts.append(account)
parsing_date_format = DateFormat.from_sysformat(self.loader.parsi | ng_date_format)
for account in accounts:
target = target_account
if target is None and account.reference:
target = getfirst(
t for t in self.target_accounts if t.reference == account.reference
)
self.panes.append(
... |
axant/tgapp-mailtemplates | tests/test_controller_auth.py | Python | mit | 626 | 0.007987 | from .base import configure_app, create_app
impo | rt re
find_urls = re.compile('http[s]?://(?:[a-zA-Z]|[0-9 | ]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')
class MailTemplatesAuthControllerTests(object):
def setup(self):
self.app = create_app(self.app_config, True)
class TestMailTemplatesAuthControllerSQLA(MailTemplatesAuthControllerTests):
@classmethod
def setupClass(cls):
cls.app_config... |
strets123/rdkit | rdkit/ML/Data/Quantize.py | Python | bsd-3-clause | 10,583 | 0.02882 | # $Id$
#
# Copyright (C) 2001-2008 Greg Landrum and Rational Discovery LLC
# All Rights Reserved
#
""" Automatic search for quantization bounds
This uses the expected informational gain to determine where quantization bounds should
lie.
**Notes**:
- bounds are less than, so if the bounds are [1.,2.],
[0.9... | """ floating point equality with a tolerance factor
**Arguments**
- v1: a flo | at
- v2: a float
- tol: the tolerance for comparison
**Returns**
0 or 1
"""
return abs(v1-v2) < tol
def FindVarQuantBound(vals,results,nPossibleRes):
""" Uses FindVarMultQuantBounds, only here for historic reasons
"""
bounds,gain = FindVarMultQuantBounds(vals,1,results,nPossibleRe... |
zenanhu/pluto | hydra/server1.py | Python | apache-2.0 | 1,675 | 0.001194 | import errno
import signal
import os
import socket
import time
SERVER_ADDRESS = (HOST, PORT) = '', 8888
REQUEST_QUEUE_SIZE = 1024
def grim_reaper(signum, frame):
while True:
try:
pid, status = os.waitpid(
-1,
os.WNOHANG,
)
except OSError:
... | inue
else:
raise
pid = os.fork()
if pid == 0:
listen_socket.close()
handle_request(client_connection)
client_connection.close()
os._exit(0)
else:
client_connection.close()
if __na | me__ == '__main__':
serve_forever()
|
beardbig/bandsharing | tests/bandsharing_tests.py | Python | gpl-2.0 | 1,065 | 0.030047 | #!/usr/bin/env python
#:::::::::::::::::::::::::::::::::::::::::::::::::::::
#Author: Damiano Barboni <damianobarboni@gmail.com>
#Version: 0.1
#Description: Script used to test bandsharing.py
#Changelog: Wed Jun 11 12:07:33 CEST 2014
# First test version
#
#::::::::... | s
def test_bs( self ):
pass
def test_csv( self ):
pass
def makeSuite():
suite = unittest.TestSuite()
suite.addTest( TestBandSharing( 'test_bs' ) )
suite.addTest( TestBandSharing( 'test_cs | v' ) )
return suite
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=3).run(makeSuite())
|
doge-search/webdoge | liqian/WISC/research/research/spiders/WISCSpider.py | Python | unlicense | 678 | 0.022124 | import scrapy
import re
from research.items import ResearchItem
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class CaltechSpider(scrapy.Spider):
name = "WISC"
allowed_domains = ["cs.wisc.edu"]
start_urls = ["https://www.cs.wisc.edu/research/groups"]
def parse(self, response):
item = ResearchItem()
f... | in response.xpath('//table[@class="views-table cols-2"]'):
item[' | groupname'] = sel.xpath('caption/text()').extract()[0]
item['proflist'] = []
for selp in sel.xpath('.//div[@class="views-field views-field-name-1"]/span/a'):
tmpname = selp.xpath('text()').extract()
print str(tmpname)
item['proflist'].append(tmpname)
yield item
|
AlexYang1949/FuturesMeasure | restful/restfulApi.py | Python | mit | 837 | 0.012063 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from flask import Flask, jsonify, request
app = Flask(__name__)
from charge.chargeManager import Char | geManager
from data.dataProvider import DataProvider
@ap | p.route('/')
def hello_world():
return jsonify(testPreMa(['棉花'],20))
@app.route('/result')
def get_result():
name = request.args.get('name').encode('utf-8')
print name
return jsonify(testPreMa([name], 20))
def testPreMa(nameArray,period):
for name in nameArray:
print 'preMa----------------... |
zurfyx/simple | simple/projects/views.py | Python | mit | 17,984 | 0.001335 | from annoying.functions import get_object_or_None
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.db import transaction
from django.db.models import Q
from django.http.response import JsonResponse
from django.http import HttpResponseRedirect
from django.shortcuts import get_... | for each in form.cleaned_data['attachments']:
ProjectAttachment.objects.create(project=project, object=each)
# create owner role
self._create_owner_role(project, project.user)
| messages.success(self.request, project.title)
return HttpResponseRedirect(reverse(self.success_url))
class ProjectPendingApproval(TemplateView):
"""
Basic view to display that a project is "now pending to be approved".
"""
template_name = 'projects/pending-approval.html'
class ProjectAp... |
almossawi/firefox-code-quality | scripts/codequality.py | Python | mpl-2.0 | 4,809 | 0.02121 | import numpy as np
from scipy import sparse
import statistics
def metrics(data_file):
output_str = ''
dsms = []
# the first thing we do is load the csv file (file #,from,to)
# into a DSM; we do this by converting the triples to a sparse matrix
# dsm is the first-order DSM of dependencies
dsm_initial = loa... | )
initial_matrix.data.fill(1)
done = 0
current_path_length = 0
matrices = []
if max_paths == -1:
max_paths = 1000
matrices.append(initial_matrix)
while done == 0 and current_path_length < max_paths:
print(' | Calculating DSM for path length = ', current_path_length + 1)
# square the current matrix
matrix_squared = matrices[current_path_length] * matrices[current_path_length]
# sum the matrix with the previous one
matrix_squared = matrix_squared + matrices[current_path_length]
# sponify the matrix, so ... |
kitsunde/jack-bower | bower/tests/test_settings.py | Python | mit | 783 | 0 | import os
DEBUG = True
SITE_ID = 1
APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ''))
DATABASES = {
'default': {
| 'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
STATIC_URL = '/static/'
# STATIC_ROOT = os.path.join(APP_ROOT, '../app_static')
STATICFILES_DIRS = (
os.path.join(APP_ROOT, 'static'),
)
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.admindocs',
'django.co... | go.contrib.sitemaps',
'django.contrib.sites',
'bower',
'bower.tests.test_app',
]
SECRET_KEY = 'foobar'
TEST_RUNNER = 'discover_runner.DiscoverRunner'
|
aerofs/zendesk-help-center-backer | zendesk/create_new_post_shell.py | Python | bsd-3-clause | 2,438 | 0.006563 | """
Python script to create a new article in a given section id.
"""
import os
import sys
from zdesk import Zendesk
from scripts import file_constants
from colorama import init
from colorama import Fore
init()
def _create_shell(section_id):
# Get subdomain.
try:
subdomain = os.environ["ZENDESK_SU... | sys.exit(1)
# Get password.
try:
password = os.environ["ZENDESK_PWD"]
except KeyError:
print(Fore.RED + | "Please set the environment variable ZENDESK_PWD" + Fore.RESET)
sys.exit(1)
zendesk = Zendesk(url, username, password)
# Add a temporary title and leave it in draft mode.
new_article = {"article": {"title": "Temporary Title", "draft": True}}
response = zendesk.help_center_section_article_crea... |
alasdairtran/mclearn | projects/jakub/test_appx_gp.py | Python | bsd-3-clause | 3,431 | 0.002332 | import sys
import matplotlib.pyplot as plt
import numpy as np
import sklearn.gaussian_process
import sklearn.kernel_approximation
import splitter
from appx_gaussian_processes import appx_gp
TRAINING_NUM = 1500
TESTING_NUM = 50000
ALPHA = .003
LENGTH_SCALE = 1
GAMMA = .5 / (LENGTH_SCALE ** 2)
COMPONENTS = 100
def... | plt.title(r'$\gamma = {:.4},$ #components$= {}$'.format(GAMMA,
COMPONENTS))
plt.xlabel('GP uncertainty')
plt.ylabel('Approximate GP uncertainty')
| plt.text(.975, .1, '$y = {:.4}x {:+.4}$'.format(*best_fit),
horizontalalignment='right',
verticalalignment='bottom',
transform = ax.transAxes)
colorbar = plt.colorbar(sc)
colorbar.set_label('Redshift')
plt.legend(loc='lower right')
plt.show()
if __name__ == '__main__':
... |
WillisXChen/django-oscar | oscar/lib/python2.7/site-packages/IPython/html/widgets/tests/test_interaction.py | Python | bsd-3-clause | 13,235 | 0.013827 | """Test interact and interactive."""
#-----------------------------------------------------------------------------
# Copyright (C) 2014 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#---------------... | (0.5,-0.5))
for min, max in [ (0.5, 1.5), (1.1,10.2), (1,2.2), (-5.,5), (-20,-19.) ]:
c = interactive(f, tup=(min, max), lis=[min, max])
nt.assert_equal(len(c.children), 2)
d = dict(
cls=widgets.FloatSliderWidget,
min=min,
max=max,
step=.1,
... | ve(f, tup=(1,2,0.0))
with nt.assert_raises(ValueError):
c = interactive(f, tup=(-1,-2,1.))
with nt.assert_raises(ValueError):
c = interactive(f, tup=(1,2.,-1.))
for min, max, step in [ (0.,2,1), (1,10.,2), (1,100,2.), (-5.,5.,4), (-100,-20.,4.) ]:
c = interactive(f, tup=(min, max, st... |
mlperf/training_results_v0.5 | v0.5.0/google/cloud_v3.8/resnet-tpuv3-8/code/resnet/model/staging/models/rough/nmt_gpu/nmt.py | Python | apache-2.0 | 46,513 | 0.007095 | # Copyright 2017 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... | t=True,
help="Whether to use time-major mode for dynamic RNN.")
parser.add_argument("-- | num_embeddings_partitions", type=int, default=0,
help="Number of partitions for embedding vars.")
# attention mechanisms
parser.add_argument(
"--attention",
type=str,
default="normed_bahdanau",
help="""\
luong | scaled_luong | bahdanau | normed_bahdanau or set to... |
jocelynj/weboob | weboob/applications/webcontentedit/webcontentedit.py | Python | gpl-3.0 | 3,817 | 0.00131 | # -*- coding: utf-8 -*-
# Copyright(C) 2010 Romain Bignon
#
# 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, version 3 of the License.
#
# This program is d | istributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; ... | _future__ import with_statement
import os
import sys
import tempfile
from weboob.core.bcall import CallErrors
from weboob.capabilities.content import ICapContent
from weboob.tools.application.repl import ReplApplication
__all__ = ['WebContentEdit']
class WebContentEdit(ReplApplication):
APPNAME = 'webcontente... |
thejeshgn/quest | quest/migrations/0001_initial.py | Python | gpl-3.0 | 349 | 0.005731 | # -*- coding: utf- | 8 -*-
f | rom south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
}
complete_apps = ['que... |
jmoreman/eTrack | etrack/urls.py | Python | mit | 355 | 0 | import os
from django.conf.urls import url, include
urlp | atterns = [
url(r'^misc/', include('misc.urls')),
url(r'^qualification/', include('qualification.urls')),
]
if os.environ.get('DJANGO_SETTINGS_MODULE') | == 'etrack.settings.dev':
import debug_toolbar
urlpatterns += [
url(r'^__debug__/', include(debug_toolbar.urls)),
]
|
sjdv1982/seamless | tests/lowlevel/codepen-seamless-client.py | Python | mit | 643 | 0.001555 | # run with https://codepen.io/sjdv1982/pen/MzNvJv
# copy-paste seamless-client.js
from seamless.highlevel import Context
ctx = Context()
ctx.cell1 = "test!"
ctx.cell1.share()
ctx.translate()
ctx.compute()
from seamless import shareserver
print(sha | reserver.namespaces["ctx"].shares)
print(shareserver.namespaces["ctx"].shares["cell1"].bound)
print(shareserver.namespaces["ctx"].shares["cell1"].bound.cell)
ctx.cell1.celltype = "plain"
ctx.translate(force=True)
ctx.compute()
print(shareserver.namespaces["ct | x"].shares)
print(shareserver.namespaces["ctx"].shares["cell1"].bound)
print(shareserver.namespaces["ctx"].shares["cell1"].bound.cell)
|
mcjug2015/mfserver2 | django_app/forms.py | Python | gpl-3.0 | 444 | 0 | ''' forms, mostly used for simple tastypie valida | tion '''
from django.contrib.gis import forms
class MeetingForm(forms.Form):
''' form for meetings '''
day_of_week = forms.IntegerField(min_value=1, max_value=7)
start_time = forms.TimeField()
end_time = forms.TimeField()
name = forms.CharField(max_length=100)
description = forms.CharField(max... | )
|
blink1073/imageio | imageio/core/format.py | Python | bsd-2-clause | 21,404 | 0.006634 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, imageio contributors
# imageio is distributed under the terms of the (new) BSD License.
"""
.. note::
imageio is under construction, some details with regard to the
Reader and Writer classes may change.
These are the main classes of imageio. They expose an int... | return self.Reader(self, request)
def get_writer(self, request):
""" get_writer(request)
Return a writer object that can be used to write data and info
to the given file. Users are encouraged to use
imageio.get_writer() instead.
"""
select_mode =... | elf.modes:
raise RuntimeError('Format %s cannot write in mode %r' %
(self.name, select_mode))
return self.Writer(self, request)
def can_read(self, request):
""" can_read(request)
Get whether this format can read data from the specifie... |
akrherz/pyIEM | util/make_ramps.py | Python | mit | 848 | 0 | """Serialization of geometries for use in pyIEM.plot mapping
We use a pickled protocol=2, which is compat binary.
"""
from pandas import read_sql
from pyiem.util import get_dbconnstr
PATH = "../src/pyiem/data/ramps/"
# Be annoying
print("Be sure to run this against Mesonet dat | abase and not laptop!")
def do(ramp):
"""states."""
df = read_sql(
"SELECT l.coloridx, l.value, l.r, l.g, l.b from iemrasters_lookup l "
"JOIN iemrasters r ON (l.iemraster_id = r.id) WHERE r.name = %s and "
"value is not null "
"ORDER by coloridx ASC",
get_dbconnstr("me... | site_n0r", "composite_n0q"]:
do(table)
if __name__ == "__main__":
main()
|
SalesforceFoundation/CumulusCI | cumulusci/cli/tests/test_run_task.py | Python | bsd-3-clause | 4,367 | 0.000458 | """Tests for the RunTaskCommand class"""
from cumulusci.cli.runtime import CliRuntime
from cumulusci.cli.cci import RunTaskCommand
import click
import pytest
from unittest.mock import Mock, patch
from cumulusci.cli import cci
from cumulusci.core.exceptions import CumulusCIUsageError
from cumulusci.cli.tests.utils imp... | ts.utils.DummyTask"},
| "dummy-derived-task": {
"class_path": "cumulusci.cli.tests.test_run_task.DummyDerivedTask"
},
}
@pytest.fixture
def runtime():
runtime = CliRuntime(load_keychain=False)
runtime.project_config.config["tasks"] = {**test_tasks}
runtime.keychain = Mock()
runtime.keychain.get_default_org.ret... |
ashmastaflash/cloudpassage_slim | cloudpassage_slim/halo_session.py | Python | bsd-2-clause | 3,951 | 0 | import base64
import httplib
import json
import os
import re
import ssl
import urllib
from urlparse import | urlunsplit
from exceptions import CloudPassageAuthentication
class HaloSession(object):
"""All Halo API session management happens in this object.
Args:
key(str): Halo API key |
secret(str): Halo API secret
Kwargs:
api_host(str): Hostname for Halo API. Defaults to
``api.cloudpassage.com``
cert_file(str): Full path to CA file.
integration_string(str): This identifies a specific integration to the
Halo API.
"""
def __init__(s... |
beiko-lab/gengis | bin/Lib/site-packages/numpy/oldnumeric/mlab.py | Python | gpl-3.0 | 3,566 | 0.009534 | # This module is for compatibility only. All functions are defined elsewhere.
__all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle',
'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort',
'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud',
... | y = m
else:
y = y
if rowvar:
m = transpose(m)
y = transpose(y)
if (m.shape[0] == 1):
m = transpose(m)
if (y.shape[0] == 1):
y = transpose(y)
N = m.shape[0]
if (y.shape[0] != N):
raise ValueError("x | and y must have the same number of observations")
m = m - _Nmean(m,axis=0)
y = y - _Nmean(y,axis=0)
if bias:
fact = N*1.0
else:
fact = N-1.0
return squeeze(dot(transpose(m), conjugate(y)) / fact)
from numpy import sqrt, multiply
def corrcoef(x, y=None):
c = cov(x, y)
... |
gpersistence/tstop | python/persistence/PAMAPSegments.py | Python | gpl-3.0 | 4,400 | 0.009091 | #TSTOP
#
#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 in the hope that it will be useful,
... | or window_start in range(segment_start, segment_end - self.config.window_size + 1, self.config.window_stride):
window_end = window_start + self.config.window_size
windows.append(list(itertools.chain(*itertools.izip(*[[float(d[i]) for d in full_data[window_start:window_end]] \
... | t_start:segment_end]]
label_dict = dict([(str(l), len([d for d in labels if d == l])) for l in list(set(labels))])
segment = Segment(windows=windows,
segment_start=segment_start,
segment_size=self.config.segment_size,
... |
siimeon/Kipa | web/urls.py | Python | gpl-3.0 | 485 | 0.010309 | from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf impor | t settings
admin.autodiscover()
urlpatterns = patterns('',
(r'^kipa/', include('tupa.urls')),
(r'^admin/', include(admin.site.urls)),
)
if se | ttings.DEBUG :
urlpatterns += patterns('',
(r'^kipamedia/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT}),)
handler500 = 'tupa.views.raportti_500'
|
johnson1228/pymatgen | pymatgen/io/feff/__init__.py | Python | mit | 311 | 0 | # coding: utf-8
# Copyright (c) Pymatgen Dev | elopment Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
"""
This package provides the modules to perform FEFF IO.
FEFF: http://feffproject.org/feffproject-feff.html
"""
from .inputs import *
fro | m .outputs import *
|
texastribune/wjordpress | wjordpress/admin.py | Python | apache-2.0 | 1,830 | 0.003825 | from django.contrib import admin
from django.core.urlresolvers import NoReverseMatch
from . import models
class WPSiteAdmin(admin.ModelAdmin):
list_display = ('name', 'url', 'hook')
readonly_fields = ('name', 'description')
def save_model(self, request, obj, form, change):
# TODO do this sync as... | in(admin.ModelAdmin):
readonly_fields = ('synced_at', )
a | dmin.site.register(models.WPTag, WPTagAdmin)
class WPPostAdmin(admin.ModelAdmin):
list_display = ('title', 'date', 'type', 'status', )
list_filter = ('type', 'status', )
readonly_fields = ('synced_at', )
admin.site.register(models.WPPost, WPPostAdmin)
class WPLogAdmin(admin.ModelAdmin):
list_display... |
sitexa/foobnix | foobnix/util/agent.py | Python | gpl-3.0 | 1,349 | 0.007429 | #-*- coding: utf-8 -*-
'''
Created on 24 дек. 20%0
@author: ivan
'''
import ra | ndom
all_agents = """
Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3
Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)
Mozilla/5.0 (Windows; U; Windows NT 5.2; | en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)
Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.1) Gecko/20090718 Firefox/3.5.1
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.1 (KHTML, like Gecko) Chrome/4.0.219.6 Safari/532.1
Mozilla/4.0 (compatible; MSIE 8.0; Windows NT ... |
ryanmiao/libvirt-test-API | repos/network/start.py | Python | gpl-2.0 | 1,786 | 0.003919 | #!/usr/bin/evn python
# Start a network
import time
import os
import re
import sys
import commands
import libvirt
from libvirt import libvirtError
from src import sharedmod
required_params = ('networkname',)
optional_params = {}
def start(params):
"""activate a defined network"""
global logger
logger ... |
try:
logger.info("begin to activate virtual network %s" % networkname)
netobj.create()
except libvirtError, e:
logger.error("API error message: %s, error code is %s" \
% (e.message, e.get_error_code()))
logger.error("fail to destroy domain")
return ... | tNetworks()
if networkname not in net_activated_list:
logger.error("virtual network %s failed to be activated." % networkname)
return 1
else:
shell_cmd = "virsh net-list --all"
(status, text) = commands.getstatusoutput(shell_cmd)
logger.debug("the output of 'virsh net-li... |
remiotore/Python-Tools | DirBuster.py | Python | mit | 1,875 | 0.011733 | #!/usr/bin/python
import os, sys
from termcolor import colored
try:
import requests
except:
print "[!]Requests module not found. Try to (re)install it.\n[!]pip install requests"
oks = []
print("EASY DIRBUSTER!")
def parser():
#URL
flag = False
while ( flag == False ):
url = raw_input("Ins... | return 0
else:
with open(fpath) as f:
for path in f:
temp1 = url + "/" + str(path).replace("\n","")
temp2 = url + "/" + str(path).replace("\n","") + "/"
for temp in temp1,temp2:
r = requests.get(temp)
if (r.... | + temp), 'green')
oks.append(str(temp))
elif (r.status_code == 403):
print colored(("[!] " + str(r.status_code) + " Forb -> " + temp), 'yellow')
else:
print colored(("[!] " + str(r.status_code) + " NotF -> " ... |
Roma2Lug-Projects/BEST_App | src/config.py | Python | apache-2.0 | 8,273 | 0.003747 | '''
Created on 10/mar/2014
@author: sectumsempra
'''
import sys
'''
from variab_conc import errbox
from PyQt4 import QtGui, QtCore, Qt
from PyQt4.QtCore import pyqtSignal, SLOT
from PyQt4.QtCore import pyqtSlot, SIGNAL
from PyQt4.QtGui import QPushButton, QTextEdit, QTableWidgetItem
'''
from PyQt4 import QtGui, QtCor... | VBoxLayout()
vlay.addWidget(tab_pesi)
vlay.addWidget(ok)
sWidget.setLayout(vlay)
self.setCentralWidget(sWidget)
self.resize(400, 400)
ok.clicked.connect(self.switchwind1)
self.setStyleSheet("font: 16pt \"DejaVu Serif\";\n ")
self.setWindowTitle("BESTAPP Co... | tchwind1(self):
global mainwind
self.saveconstants()
self.hide()
mainwind = maingui()
mainwind.showMaximized()
print("connected")
def saveconstants(self):
global var_lis, pes_lis, tab_pesi
top = len(var_lis)
for i in range(0, top):
... |
paultag/moxie | migrations/env.py | Python | mit | 2,125 | 0.002353 | from __future__ import with_statement
import os
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file ... | target_metadata=target_metadata
| )
try:
with context.begin_transaction():
context.run_migrations()
finally:
connection.close()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
|
milasudril/anja | versioninfo.py | Python | gpl-3.0 | 2,158 | 0.056534 | #@ {
#@ "targets":
#@ [{
#@ "name":"versioninfo.txt"
#@ ,"status_check":"dynamic"
#@ ,"dependencies":[{"ref":"maike","rel":"tool"}]
#@ }]
#@ }
import sys
import subprocess
import shutil
import os
def modified_time(filename):
try:
return (os.path.getmtime(filename),True)
except (KeyboardInterrupt, Sys... | None of the files %s, and %s are accessible.'%(file_a,file_b))
if not mod_a[1]:
return False
if not mod_b[1]:
return True
return mod_a[0] > mod_b[0]
def newer_than_all(file_a, files):
for file in files:
if newer(file,file_a):
return False
return True
def git_changes():
with subprocess.Popen(('git', ... | .split('\n')):
result.append( k[3:].split(' ')[0] )
return result
def get_revision():
if shutil.which('git')==None:
with open('versioninfo-in.txt') as versionfile:
return versionfile.read().strip()
else:
with subprocess.Popen(('git', 'describe','--tags','--dirty','--always') \
,stdout=subprocess.PIPE)... |
ManoSeimas/manoseimas.lt | manoseimas/lobbyists/json_urls.py | Python | agpl-3.0 | 304 | 0 | from django.conf.urls import patterns | , url
from manoseimas.lobbyists import views
urlpatterns = patterns(
'',
url(r'^lobbyists/?$', views.lobbyists_json, name='lobbyists_json'),
url(r'^law_projects/(?P<lobbyist_slug>[^/]+)/?$',
views.law_projects_json, name='law_projects_json'), |
)
|
skitzycat/beedraw | beenetwork.py | Python | gpl-2.0 | 14,234 | 0.039834 | # Beedraw/Hive network capable client and server allowing collaboration on a single image
# Copyright (C) 2009 Thomas Becker
#
# 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; eith... | here isn't data already available
if not self.socket.bytesAvailabl | e():
status=self.socket.waitForReadyRead(-1)
data=self.socket.read(size)
if data:
retstring="%s" % qtcore.QString(data)
elif self.type==BeeSocketTypes.python:
try:
retstring=self.socket.recv(size)
except socket.error, errmsg:
print_debug("exception while trying to read data: %s" % errmsg)... |
owenwater/alfred-cal | src/open.py | Python | mit | 1,042 | 0.003839 | #!/usr/bin/python
# encoding: utf-8
import subprocess
from config import Config
applescript_name_tem = "osascript/open_%s.scpt"
arg_tem = {
"calendar": "%s %s %s",
"fantastical": "%s-%s-%s",
"busycal": "%s-%s-%s",
"google": "%s%s%s"
}
SOFTWARE = 'software'
def open_cal(arg):
arg = arg.strip()
... | f open_file(file):
subprocess.call(['open', file])
if __name__ == "__main__":
import sys
open_cal(' '.join(sys.argv[1:]))
| |
purepitch/trove | features/steps/file_command_line_option.py | Python | gpl-3.0 | 1,396 | 0.003582 | # -*- coding: utf-8 -*-
from behave import given, then
from nose.tools import assert_true, assert_regexp_matches
import pexpect
import re
@then(u'I should see how many entries were found')
def see_number | _of_entries_found(context):
expected_text = 'Found total number of \d+ entries.'
context.trove.expect(expected_text)
output = context.trove.match.string.strip()
regexp = re.compile(expected_text)
assert_regexp_matches(output, regexp)
@then(u'the trove prompt should be shown')
@given(u'the trove pro... | rove)'
context.trove.expect(expected_text)
output = context.trove.match.string.strip()
regexp = re.compile(expected_text)
assert_regexp_matches(output, regexp)
@given(u'trove is started with an empty --file option')
def trove_starts_with_empty_file_option(context):
trove = pexpect.spawn("python tro... |
archatas/imageuploads | imageuploads/settings.py | Python | gpl-2.0 | 4,670 | 0.001285 | # Django settings for imageuploads project.
import os
PROJECT_DIR = os.path.dirname(__file__)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql... | jango.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers' | : ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
CRISPY_TEMPLATE_PACK = 'bootstrap3'
try:
execfile(os.path.join(os.path.dirname(__file__), "local_settings.py"))
except IOError:
pass
|
Azure/azure-sdk-for-python | sdk/storage/azure-storage-file-datalake/azure/storage/filedatalake/aio/_upload_helper.py | Python | mit | 4,443 | 0.001576 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: ... | settings=None,
**kwargs):
try:
if length == 0:
return {}
properties = kwargs.pop('properties', None)
umask = kwargs.pop('umask', None)
permissions = kwargs.pop('permissions', None)
path_http_headers = kwargs.pop('path_http | _headers', None)
modified_access_conditions = kwargs.pop('modified_access_conditions', None)
chunk_size = kwargs.pop('chunk_size', 100 * 1024 * 1024)
if not overwrite:
# if customers didn't specify access conditions, they cannot flush data to existing file
if not _any_co... |
lhirschfeld/JargonBot | jargonbot.py | Python | mit | 5,805 | 0.002756 | # Lior Hirschfeld
# JargonBot
# -- Imports --
import re
import pickle
import random
import praw
from custombot import RedditBot
from time import sleep
from define import getDefinition
from collections import Counter
from nltk.stem import *
from sklearn import linear_model
# -- Setup Variables --
jargonBot = RedditBo... | break
if ml:
if sub not in jargonBot.models:
jargonBot.createModel(sub, [[[1000000, 10, 10]], [10]])
# If ML, after basic checks, predict using the model
# to decide whether to reply.
... | popularity = 1000000
info = {"popularity": popularity, "wLength": len(word),
"cLength": len(com.body), "cID": com.id,
"sID": submission.id, "sub": sub}
if popularity > 10000:
... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/tensorflow/contrib/keras/python/keras/layers/merge.py | Python | bsd-2-clause | 18,999 | 0.007158 | # Copyright 2015 The TensorFlow Authors. 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 applica... | output_shape.append(i)
return t | uple(output_shape)
def build(self, input_shape):
# Used purely for shape validation.
if not isinstance(input_shape, list):
raise ValueError('A merge layer should be called ' 'on a list of inputs.')
if len(input_shape) < 2:
raise ValueError('A merge layer should be called '
... |
gmontamat/pyaw-reporting | awreporting/awreporting.py | Python | apache-2.0 | 4,023 | 0.000249 | #!/usr/bin/env python
# Copyright 2021 - Gustavo Montamat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | nloader threads pool
logging.info("Starting ReportDownloader threads.")
max_threads = min(queue_ids.qsize(), threads)
for i in range(max_threads):
if queue_ids.qsize() == 0:
break
report_downloader = ReportDownloader(
token, queue_ids, queu... | report_downloader.start()
sleep(0.1)
logging.info("Used {thread_num} threads.".format(thread_num=i + 1))
# Wait until all the account ids have been processed
queue_ids.join()
queue_ids.put(END_SIGNAL)
# Wait until all gzipped reports have been extracted
q... |
nils-werner/SimpleCV | SimpleCV/examples/detection/facetrack.py | Python | bsd-3-clause | 849 | 0.002356 | #!/usr/bin/env python
#
# Released under the BSD license. See LICENSE file for details.
"""
This program basically does face detection an blurs the face out.
"""
print __doc__
from SimpleCV import Camera, Display, HaarCascade
# Initialize the camera
cam = Camera()
# Create the display to show the image
display = Di... | isNotDone():
# Get image, flip it so it looks mirrored, scale to speed things up
img = cam.getImage().flipHorizontal().scale(0.5)
# Load in trained face file
faces = img.findHaarFeatures(haarcascade)
# Pixelize the detected face
if faces:
bb = faces[-1].boundingBox()
img | = img.pixelize(10, region=(bb[0], bb[1], bb[2], bb[3]))
# Display the image
img.save(display)
|
mapycz/mapnik | scons/scons-local-3.0.1/SCons/Tool/gcc.py | Python | lgpl-2.1 | 3,530 | 0.003966 | """SCons.Tool.gcc
Tool-specific initialization for gcc.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2017 The SCons Foundation
#
# Permission is hereby granted, free of charge, to... | ge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# T... | LUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# ... |
jordanemedlock/psychtruths | temboo/core/Library/Bitly/OAuth/InitializeOAuth.py | Python | apache-2.0 | 5,111 | 0.005087 | # -*- coding: utf-8 -*-
###############################################################################
#
# InitializeOAuth
# Generates an authorization URL that an application can use to complete the first step in the OAuth process.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under ... | r(InitializeOAuthInputSet, self)._set_input('CustomCallbackID', value)
def set_ForwardingURL(self, value):
"""
Set the value of the ForwardingURL input for this Choreo. ((optional, string) The URL that Temboo will redirect your users to after they grant access to your application. Th | is should include the "https://" or "http://" prefix and be a fully qualified URL.)
"""
super(InitializeOAuthInputSet, self)._set_input('ForwardingURL', value)
class InitializeOAuthResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the InitializeOAuth Choreo.
... |
Exgibichi/statusquo | test/functional/net.py | Python | mit | 4,228 | 0.001419 | #!/usr/bin/env python3
# Copyright (c) 2017 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 RPC calls related to net.
Tests correspond to code in rpc/net.cpp.
"""
import time
from test_framewo... | (self.nodes[0].getconnectioncount(), 2)
def _test_getnettotals(self):
# check that getnettotals totalbytesrecv and totalbytessent
# are consistent with getpeerinfo
peer_info = self.nodes[0].getpeerinfo()
assert_equal(len(peer_info), 2)
net_totals = self.nodes[0].getnettotals... | assert_equal(sum([peer['bytessent'] for peer in peer_info]),
net_totals['totalbytessent'])
# test getnettotals and getpeerinfo by doing a ping
# the bytes sent/received should change
# note ping and pong are 32 bytes each
self.nodes[0].ping()
time.slee... |
cherylyli/stress-aid | env/lib/python3.5/site-packages/helowrld/__init__.py | Python | mit | 45 | 0.022222 | d | ef tryprint():
return ('it will | be oke') |
ytsarev/rally | rally/exceptions.py | Python | apache-2.0 | 6,154 | 0 | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | rl)s")
class InvalidAdminException(InvalidArgumentsException):
msg_fmt = _("user %(username)s doesn't have 'admin' role")
class InvalidEndpointsException(InvalidArgumentsException):
msg_fmt = _("wrong keystone credentials specified in your endpoint"
" properties. (HTTP 401)")
class HostUnr... | ioArgument(RallyException):
msg_fmt = _("Invalid scenario argument: '%(message)s'")
|
manhhomienbienthuy/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | Python | bsd-3-clause | 20,619 | 0.001261 | import pytest
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal, assert_allclose
from sklearn.datasets import load_linnerud
from sklearn.cross_decomposition._pls import (
_center_scale_xy,
_get_first_singular_vectors_power_method,
_get_first_singular_vectors_svd,
... | expected_x_rotations)
x_weights_sign_flip = np.sign(pls.x_weights_ / expected_x_weights)
y_rotations_sign_flip = np.sign(pls.y_rotations_ / expected_y_rotations)
y_weights_sign_flip = np.sign(pls.y_weights_ / expected_y_weights)
assert_array_almost_equal(x_rotations_sign_flip, x_weights_sign_flip)
... | ert_matrix_orthogonal(pls.y_weights_)
assert_matrix_orthogonal(pls._x_scores)
assert_matrix_orthogonal(pls._y_scores)
def test_sanity_check_pls_canonical_random():
# |
mammique/django | django/contrib/auth/tests/auth_backends.py | Python | bsd-3-clause | 15,671 | 0.002106 | from __future__ import unicode_literals
from datetime import date
from django.conf import settings
from django.contrib.auth.models import User, Group, Permission, AnonymousUser
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.contrib.auth.tests.custom_user import ExtensionUser, CustomPermission... | ,
email='test@example.com',
| password='test',
date_of_birth=date(2006, 4, 25)
)
self.superuser = ExtensionUser._default_manager.create_superuser(
username='test2',
email='test2@example.com',
password='test',
date_of_birth=date(1976, 11, 8)
)
@override... |
teoreteetik/api-snippets | lookups/lookup-get-cname-example-1/lookup-get-cname-example-1.6.x.py | Python | mit | 417 | 0 | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Clien | t
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACCOUNT_SID"
auth_token = "your_auth_token"
client = Client(account_si | d, auth_token)
number = client.lookups.phone_numbers("+16502530000").fetch(
type="caller-name",
)
print(number.carrier['type'])
print(number.carrier['name'])
|
kikusu/chainer | chainer/iterators/__init__.py | Python | mit | 214 | 0 | from ch | ainer.iterators import multiprocess_iterator
from chainer.iterators import serial_iterator
MultiprocessIterator = multiprocess_iterator.MultiprocessIterator
SerialIterator = serial_iterator | .SerialIterator
|
bomjacob/htxaarhuslan | main/migrations/0027_auto_20170103_1130.py | Python | mit | 977 | 0.001028 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-03 10:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migr | ation(migrations.Migration):
dependencies = [
| ('main', '0026_auto_20161215_2204'),
]
operations = [
migrations.AddField(
model_name='lan',
name='show_calendar',
field=models.BooleanField(default=False, help_text='Hvorvidt en kalender skal vises på forsiden. Slå kun dette til hvis turneringer og andre events efte... |
codexgigassys/codex-backend | src/PlugIns/PE/CypherPlug.py | Python | mit | 513 | 0 | # Copyright (C) 2016 Deloitte Argentina.
# This file is part of CodexGigas - https://github.com/codexgigassys/
# See the file 'LICENSE' for copying permission.
from PlugIns.PlugIn import PlugIn
cl | ass CypherPlug(PlugIn):
def __init__(self, sample=None):
PlugIn.__init__(self, sample)
def getPath(self):
return "particular_header.cypher"
def getName(self):
return "cypher"
def getVersion(self):
return 1
def process(self):
re | turn "Not_implemented"
|
hlzz/dotfiles | graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/internet/iocpreactor/const.py | Python | bsd-3-clause | 550 | 0.001818 | # Copyright | (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Windows constants for IOCP
"""
# this stuff should really be gotten from Windows headers via pyrex, but it
# probably is not going to change
ERROR_PORT_UNREACHABLE = 1234
ERROR_NETWORK_UNREACHABLE = 1231
ERROR_CONNECTION_REFUSED = 1225
... | E_CONNECT_CONTEXT = 0x7010
SO_UPDATE_ACCEPT_CONTEXT = 0x700B
|
antoinecarme/sklearn2sql_heroku | tests/regression/boston/ws_boston_LGBMRegressor_postgresql_code_gen.py | Python | bsd-3-clause | 131 | 0.015267 | fro | m sklearn2sql_heroku.tests.regression import generic as reg_gen
reg_gen.test_mo | del("LGBMRegressor" , "boston" , "postgresql")
|
sjdv1982/seamless | tests/lowlevel/simple-remote.py | Python | mit | 1,438 | 0.002086 | # run scripts/jobslave-nodatabase.py
import os
os.environ["SEAMLESS_COMMUNION_ID"] = "simple-remote"
os.environ["SEAMLESS_COMMUNION_INCOMING"] = "localhost:8602"
import seamless
seamless.set_ncores(0)
from seamless import communion_server
communion_server.configure_master(
buffer=True,
transformation_job=Tru... | text, cell, transformer, unilink
ctx = context(toplevel=True)
ctx.cell1 = cell().set(1)
ctx.cell2 = cell().set(2)
ctx.result = cell()
ctx.tf = transformer({
"a": | "input",
"b": "input",
"c": "output"
})
ctx.cell1_unilink = unilink(ctx.cell1)
ctx.cell1_unilink.connect(ctx.tf.a)
ctx.cell2.connect(ctx.tf.b)
ctx.code = cell("transformer").set("c = a + b")
ctx.code.connect(ctx.tf.code)
ctx.result_unilink = unilink(ctx.result)
ctx.tf.c.connect(ctx.result_unilink)
ctx.result_c... |
cms-externals/sherpa | MODEL/UFO/templates.py | Python | gpl-3.0 | 427 | 0.009368 | import pkg_resources
from string import Template
model | _template = Template(pkg_resources.resource_string(__name__, "model_template.C"))
lorentz_calc_template = Template(pkg_resources.resource_string(__name__, "lorentz_calc_template.C"))
sconstruct_ | template = Template(pkg_resources.resource_string(__name__, "sconstruct_template"))
run_card_template = Template(pkg_resources.resource_string(__name__, "run_card_template"))
|
a113n/bcbio-nextgen | bcbio/pipeline/cleanbam.py | Python | mit | 8,337 | 0.003958 | """Clean an input BAM file to work with downstream pipelines.
GATK and Picard based pipelines have specific requirements for
chromosome order, run group information and other BAM formatting.
This provides a pipeline to prepare and resort an input.
"""
import os
import sys
import pysam
from bcbio import bam, broad, u... | cmd = ("samtools reheader {new_header} {in_bam} | "
"samtools addreplacerg -@ {cores} -r '{rg_info}' -m overwrite_all -O bam -o {tx_out_file} -")
do.run(cmd.format(**locals()), "Fix read groups: %s" % dd.get_sample_nam | e(data))
return out_file
def remove_extracontigs(in_bam, data):
"""Remove extra contigs (non chr1-22,X,Y) from an input BAM.
These extra contigs can often be arranged in different ways, causing
incompatibility issues with GATK and other tools. This also fixes the
read group header as in fixrg.
... |
brain0/archweb | devel/management/commands/pgp_import.py | Python | gpl-2.0 | 8,172 | 0.000734 | # -*- coding: utf-8 -*-
"""
pgp_import command
Import keys and signatures from a given GPG keyring.
Usage: ./manage.py pgp_import <keyring_path>
"""
from collections import namedtuple, OrderedDict
from datetime import datetime
import logging
from pytz import utc
import subprocess
import sys
from django.core.managem... | in keydata.values():
parent_id = None
if data.parent:
parent_data = keydata.get(data.parent, None)
if parent_data:
parent_id = parent_data.db_id
other = {
'expires': data.expires,
'revoked': data.rev... | created, defaults=other)
data.db_id = dkey.id
# set or update any additional data we might need to
needs_save = False
if created:
created_ct += 1
else:
for k, v in other.items():
if getattr(dkey, k) != v:
... |
qxf2/qxf2-page-object-model | utils/Base_Logging.py | Python | mit | 4,369 | 0.013733 | """
Qxf2 Services: A plug-n-play class for logging.
This class wraps around Python's loguru module.
"""
import os, inspect
import pytest,logging
from loguru import logger
from pytest_reportportal import RPLogger, RPLogHandler
class Base_Logging():
"A plug-n-play class for logging"
def __init__(self,log_file_na... | at,test_module_name=None):
"Add an handler sending log messages to a sink"
if test_module_name is None:
test_module_name = self.get_calling_module()
if not os.path.exists | (self.log_file_dir):
os.makedirs(self.log_file_dir)
if log_file_name is None:
log_file_name = self.log_file_dir + os.sep + test_module_name + '.log'
else:
log_file_name = self.log_file_dir + os.sep + log_file_name
logger.add(log_file_name,level=level,format=f... |
rvmoura96/projeto-almoxarifado | mysite/urls.py | Python | mit | 838 | 0 | """mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/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')
C... | 1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^adm | in/', admin.site.urls),
url(r'', include('almoxarifado.urls')),
]
|
LCOGT/valhalla | valhalla/proposals/migrations/0017_auto_20181109_1828.py | Python | gpl-3.0 | 1,094 | 0.001828 | # Generated by Django 2.1.3 on 2018-11-09 18:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('proposals', '0016_auto_20180405_2116'),
]
operations = [
migrations.AlterField(
model_name='timeallocation',
name='i... | , '0M8-SCICAM-SBIG'), ('1M0-NRES-SCICAM', '1M0-NRES-SCICAM'), ('1M0-SCICAM-SINISTRO', '1M0-SCICAM-SINISTRO'), ('1M0-SCICAM-SBIG', '1M0-SCICAM-SBIG'), ('1M0-NRES-COMMISSIONING', '1M0-NRES-COMMISSIONING'), ('2M0-FLOYDS-SCICAM', '2M0-FLOYDS-SCICAM'), ('2M0-SCICAM-SPECTRAL', '2M0-SCICAM-SPECTRAL'), ('2M0-SCICAM-SBIG', '2M0... | meallocation',
name='telescope_class',
field=models.CharField(choices=[('0m4', '0m4'), ('0m8', '0m8'), ('1m0', '1m0'), ('2m0', '2m0')], max_length=20),
),
]
|
lukas-hetzenecker/home-assistant | homeassistant/components/transport_nsw/sensor.py | Python | apache-2.0 | 4,474 | 0 | """Support for Transport NSW (AU) to query next leave event."""
from datetime import timedelta
from TransportNSW import TransportNSW
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_MODE,
CONF_API_KE... | SCAN_INTE | RVAL = timedelta(seconds=60)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_STOP_ID): cv.string,
vol.Required(CONF_API_KEY): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_ROUTE, default=""): cv.string,
vol.Optional(CONF... |
qtile/qtile | test/layouts/test_treetab.py | Python | mit | 6,060 | 0.001155 | # Copyright (c) 2019 Guangwang Huang
#
# 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, dis... | ocus
assert_focused(manager, "three")
manager.c.layout.up()
assert_focused(manager, "two")
manager.c.layout.down()
assert_focused(manager, "three")
# test command move_up/down
manager.c.layout.move_up()
assert manager.c. | layout.info()["clients"] == ["one", "three", "two"]
assert manager.c.layout.info()["client_trees"] == {
"Foo": [["one"], ["three"], ["two"]],
"Bar": [],
}
manager.c.layout.move_down()
assert manager.c.layout.info()["client_trees"] == {
"Foo": [["one"], ["two"], ["three"]],
... |
TouK/vumi | vumi/middleware/tests/test_tagger.py | Python | bsd-3-clause | 5,053 | 0 | """Tests for vumi.middleware.tagger."""
import re
from vumi.middleware.tagger import TaggingMiddleware
from vumi.message import TransportUserMessage
from vumi.tests.helpers import VumiTestCase
class TestTaggingMiddleware(VumiTestCase):
DEFAULT_CONFIG = {
'incoming': {
'addr_pattern': r'^\d+... | self.assertEqual(TaggingMiddleware.map_msg_to_tag(msg), None)
msg['helper_metadata']['tag'] = {'tag': ['pool', 'mytag']}
self.assertEqual(TaggingMiddleware.map_ms | g_to_tag(msg),
("pool", "mytag"))
def test_add_tag_to_msg(self):
msg = self.mk_msg("123456")
TaggingMiddleware.add_tag_to_msg(msg, ('pool', 'mytag'))
self.assertEqual(msg['helper_metadata']['tag'], {
'tag': ['pool', 'mytag'],
})
def test... |
tarballs-are-good/sympy | sympy/polys/tests/test_monomialtools.py | Python | bsd-3-clause | 3,561 | 0.048301 | """Tests for tools and arithmetics for monomials of distributed polynomials. """
from sympy.polys.monomialtools import (
monomials, monomial_count,
monomial_lex_cmp, monomial_grlex_cmp, monomial_grevlex_cmp, mo | nomial_cmp,
monomial_mul, monomial_div, monomial_gcd, monomial_lcm, monomial_max, mono | mial_min,
)
from sympy.abc import x, y
from sympy.utilities.pytest import raises
def test_monomials():
assert sorted(monomials([], 0)) == [1]
assert sorted(monomials([], 1)) == [1]
assert sorted(monomials([], 2)) == [1]
assert sorted(monomials([], 3)) == [1]
assert sorted(monomials([x], 0)) == [1... |
ChinaMassClouds/copenstack-server | openstack/src/nova-2014.2/nova/api/openstack/compute/contrib/extended_status.py | Python | gpl-2.0 | 3,926 | 0 | # Copyright 2011 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 a... | esp_obj):
context = req.environ['nova.context']
| if authorize(context):
# Attach our slave template to the response object
resp_obj.attach(xml=ExtendedStatusesTemplate())
servers = list(resp_obj.obj['servers'])
for server in servers:
db_instance = req.get_db_instance(server['id'])
#... |
jdburton/gimp-osx | src/gimp-2.6.12/plug-ins/pygimp/plug-ins/pyconsole.py | Python | gpl-2.0 | 20,993 | 0.00181 | #
# pyconsole.py
#
# Copyright (C) 2004-2006 by Yevgen Muntyan <muntyan@math.tamu.edu>
# Portions of code by Geoffrey French.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public version 2.1 as
# published by the Free Software Foundat... | t
import pango
import gtk.keysyms as _keys
import code
import sys
import keyword
import re
# commonprefix() from posixpath
def _commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
prefix | = m[0]
for item in m:
for i in range(len(prefix)):
if prefix[:i+1] != item[:i+1]:
prefix = prefix[:i]
if i == 0:
return ''
break
return prefix
class _ReadLine(object):
class Output(object):
def __init__(self, ... |
sachinpro/sachinpro.github.io | tensorflow/python/framework/docs.py | Python | apache-2.0 | 21,127 | 0.008425 | # 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... | :
if ((inspect.isfunction(member) or inspect.isclass(member)) and
not _always_drop_symbol_re.match(name) and
(all_names is None or name in all_names)):
fullname = "%s.%s" % (module_name, name)
if fullname in exclude:
continue
if name in members:
othe... | raise RuntimeError("Short name collision between %s and %s" %
(fullname, other_fullname))
if len(fullname) == len(other_fullname):
raise RuntimeError("Can't decide whether to use %s or %s for %s: "
"both full names have length %d"... |
muet/Espruino | boards/OLIMEXINO_STM32_RE.py | Python | mpl-2.0 | 4,169 | 0.015112 | #!/bin/false
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at h... | ',
'build' : {
'defines' : [
'USE_NET',
'USE_GRAPHICS',
'USE_FILESYSTEM',
'USE_TV',
'USE_HASHLIB'
]
}
}
chip = {
'part': 'STM32F103RET6',
'family': 'STM32F1',
'package': 'LQFP64',
'ram': 64,
'flash': 512,
'speed': 72,
'usart': 5,
'spi': 3,
'i2c': 2,
'adc': 3,
'dac': 2
}
devi... | 'pin': 'D38'},
'USB': {'pin_disc': 'D39',
'pin_dm': 'D40',
'pin_dp': 'D41'},
'SD': {'pin_cs': 'D25',
'pin_di': 'D34',
'pin_do': 'D33',
'pin_clk': 'D32'}}
# left-right, or top-bottom order
board = {
'top': ['D14', 'GND', 'D13', 'D12', 'D11', 'D10', 'D9', 'D8', '', 'D7', 'D6'... |
liqd/adhocracy4 | tests/comments/test_model.py | Python | agpl-3.0 | 2,973 | 0 | from urllib.parse import urljoin
import pytest
from adhocracy4.comments import models as comments_models
from adhocracy4.ratings import models as rating_models
@pytest.mark.django_db
def test_delete_comment(comment_factory, rating_factory):
comment = comment_factory()
for i in range(5):
comment_fac... | ment.content_object.get_absolute_url(),
"?comment={}".format(str(child_comment.id)))
@pytest.mark.django_db
de | f test_notification_content(comment):
assert comment.notification_content == comment.comment
@pytest.mark.django_db
def test_project(comment):
assert comment.project == comment.module.project
@pytest.mark.django_db
def test_module(comment, child_comment):
assert comment.module == comment.content_object.... |
ihmpdcc/cutlass | tests/test_sample_attr.py | Python | mit | 10,454 | 0.001148 | #!/usr/bin/env python
""" A unittest script for the SampleAttribute module. """
import unittest
import json
from cutlass import SampleAttribute
from CutlassTestConfig import CutlassTestConfig
from CutlassTestUtil import CutlassTestUtil
# pylint: disable=W0703, C1801
class SampleAttributeTest(unittest.TestCase):
... | ed value."
)
def testDataInJson(self):
""" Test if the correct data is in the generated JSON. """
attrib = self.session.create_sample_attr()
| success = False
fecalcal = "test fecalcal"
sample_desc = "DNA: mom-vaginal"
sample_type = "BC1D"
subproject = "earlyPregStudy"
attrib.fecalcal = fecalcal
attrib.sample_desc = sample_desc
attrib.sample_type = sample_type
attrib.subproject = subproject... |
rocketDuck/folivora | folivora/migrations/0007_normalize_names.py | Python | isc | 9,029 | 0.007864 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from ..utils.pypi import normalize_name
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
for package in orm['folivora.Package'... | models.fields.URLField', [], {'max_length': '200'})
},
'folivora.packageversion': {
'Meta': {'unique_together': "(('package', 'version'),)", 'object_name': 'PackageVersio | n'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'package': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'versions'", 'to': "orm['folivora.Package']"}),
'release_date': ('django.db.models.fields.DateTimeField', [], {}),
... |
NeoBelerophon/transwhat | buddy.py | Python | gpl-3.0 | 5,903 | 0.027444 | __author__ = "Steffen Vogel"
__copyright__ = "Copyright 2015, Steffen Vogel"
__license__ = "GPLv3"
__maintainer__ = "Steffen Vogel"
__email__ = "post@steffenvogel.de"
"""
This file is part of transWhat
transWhat is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public Li... | elf.presence = 0
def update(self, nick, groups, image_hash):
self.nick = nick
self.groups = groups
if image_hash is not None:
self.image_hash = image_hash
def __str__(self):
return "%s (nick=%s)" % (self.number, self.nick)
class BuddyList(dict):
def __init__(self, owner, backend, user, session):
sel... | logging.getLogger(self.__class__.__name__)
self.synced = False
def _load(self, buddies):
for buddy in buddies:
number = buddy.buddyName
nick = buddy.alias
statusMsg = buddy.statusMessage.decode('utf-8')
groups = [g for g in buddy.group]
image_hash = buddy.iconHash
self[number] = Buddy(self.owner... |
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram2dcontour/textfont/_color.py | Python | mit | 424 | 0.002358 | import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="col | or", parent_name="histogram2dcontour.textfont", **kwargs
):
super(ColorValidato | r, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
**kwargs
)
|
arypbatista/gobspy | gobspy.py | Python | gpl-3.0 | 75 | 0 | #!/usr/bin/python
# -*- coding: | utf-8 -*-
from gob | spy import main
main()
|
pantuza/art-gallery | src/timer.py | Python | gpl-2.0 | 1,202 | 0.003328 | # -*- coding: utf-8 -*-
import time
|
class Timer(object):
'''
Simple timer control
'''
def __init__(self, delay):
self.current_time = 0
self.set_delay(delay)
def pause(self, pause):
if pause >= self.delay:
self.current_time = time.clock()
self.next_time = self. | current_time + pause
def set_delay(self, delay):
assert delay >= 0
self.delay = delay
if self.delay == 0:
self.next_time = self.current_time
else:
self.current_time = time.clock()
self.next_time = self.current_time + self.delay
... |
foolwealth/django_multi_deployable_template | lib/lib_a/helper.py | Python | mit | 115 | 0.008696 | import ra | ndom
def | say_thing():
return random.choice([
"dude",
"sup",
"yo mama"
]) |
cuppa-joe/dsame | defs.py | Python | isc | 274,490 | 0.029815 | VERSION = '0.1.3.0'
PROGRAM = 'dsame'
DESCRIPTION = 'dsame is a program to decode EAS/SAME alert messages'
COPYRIGHT = 'Copyright (C) 2016 Joseph W. Metcalf'
TEST_STRING = 'EAS: ZCZC-WXR-RWT-055027-055039-055047-055117-055131-055137-055139-055015-055071+0030-0771800-KMKX/NWS-'
MSG__TEXT={
'EN' :
{'MSG1' ... | '60' : 'American Samoa',
'61' : 'American Samoa Waters',
'64' : 'Federated States of Micronesia',
'65' : 'Mariana Islands Waters (including Guam)',
'66' : 'Guam',
'68' : 'Marshall Islands',
'69' : 'Northern Mariana Islands',
'70' : 'Palau',
'72' : 'Puerto Rico',
'73' : 'Atlantic Co... | nor Outlying Islands',
'75' : 'Atlantic Coast from North Carolina to Florida, and the Coasts of Puerto Rico and Virgin Islands',
'77' : 'Gulf of Mexico',
'78' : 'Virgin Islands',
'91' : 'Lake Superior',
'92' : 'Lake Michigan',
'93' : 'Lake Huron',
'94' : 'Saint Clair River, Detroit River, an... |
pyfa-org/eos | eos/restriction/restriction/resource.py | Python | lgpl-3.0 | 4,071 | 0 | # ==============================================================================
# Copyright (C) 2011 Diego Duclos
# Copyright (C) 2011-2018 Anton Vorobyov
#
# This file is part of Eos.
#
# Eos is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as publi... | ion.calibration
_stat_name = 'calibration'
_use_attr_id = AttrId.upgrade_cost
class DroneBayVolumeRestriction(ResourceRestriction):
"""Drone bay volume use by items should not exceed ship drone bay v | olume.
Details:
For validation, stats module data is used.
"""
type = Restriction.dronebay_volume
_stat_name = 'dronebay'
_use_attr_id = AttrId.volume
class DroneBandwidthRestriction(ResourceRestriction):
"""Drone bandwidth use by items should not exceed ship drone bandwidth.
De... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.