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 |
|---|---|---|---|---|---|---|---|---|
xeor/test_files | binary/noise/_script/utf-8_0-ffff.py | Python | unlicense | 119 | 0.033613 | #!/ | usr/bin/env python
open('utf-8_0-ffff', 'w').write(''.join([ unichr(i) for i in xrange(65535) ]).encode('utf-8'));
| |
ging/horizon | openstack_dashboard/api/nova.py | Python | apache-2.0 | 29,745 | 0 | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 OpenStack Foundation
# Copyright 2012 Nebula, Inc.
# Copyright (c) 2012 X.commerce, a business unit of eBay Inc.
#
# Licensed under the Apach... | er_usages', 'stop', 'tenant_id',
'total_local_gb_usage', 'total_memory_mb_usage',
'total_vcpus_usage', 'total_hours']
def get_summary(self):
return {'instances': self.total_active_instances,
'memory_mb': self.memory_mb,
'vcpus': getattr(self, "tot... | al_active_instances(self):
return sum(1 for s in self.server_usages if s['ended_at'] is None)
@property
def vcpus(self):
return sum(s['vcpus'] for s in self.server_usages
if s['ended_at'] is None)
@property
def vcpu_hours(self):
return getattr(self, "total_ho... |
RaD/django-tinymce | tinymce/widgets.py | Python | mit | 4,724 | 0.00127 | # Copyright (c) 2008 Joost Cassee
# Licensed under the terms of the MIT License (see LICENSE.txt)
"""
This TinyMCE widget was copied and extended from this code by John D'Agostino:
http://code.djangoproject.com/wiki/CustomWidgetsTinyMCE
"""
from django import forms
from django.conf import settings
from django.contrib... | onfig.get('theme', 'advanced'),
'languages': mce_config.get('language', ''),
'diskcache': True,
'debug': False,
}
compressor_json = simplejson.dumps(compressor_config)
html.append(u'<script type="text/javascript">tinyMCE_GZ.init(%s)</sc... | _json)
return mark_safe(u'\n'.join(html))
def _media(self):
if tinymce.settings.USE_COMPRESSOR:
js = [reverse('tinymce-compressor')]
else:
js = [tinymce.settings.JS_URL]
if tinymce.settings.USE_FILEBROWSER:
js.append(reverse('tinymce-filebrowser'... |
HuygensING/bioport-buildout | plone-buildout/bootstrap.py | Python | gpl-3.0 | 3,857 | 0.005445 | ##############################################################################
#
# Copyright (c) 2006 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... | VERSION = '==%s' % options.version
else:
VERSION = ''
USE_DISTRIBUTE = options.distribute
args = args + ['bootstrap']
to_reload = False
try:
import pkg_resources
if not hasattr(pkg_resources, '_distribute'):
to_reload = True
raise ImportError
except ImportError:
ez = {}
i | f USE_DISTRIBUTE:
exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py'
).read() in ez
ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True)
else:
exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
... |
Zlash65/erpnext | erpnext/selling/page/point_of_sale/point_of_sale.py | Python | gpl-3.0 | 4,834 | 0.03041 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.utils.nestedset import get_root_of
from frappe.utils import cint
from erpnext.accounts.doctype.pos_profile.pos_profile i... | ld, start, page_len, filters):
item_groups = []
cond = "1=1"
pos_profile= filters.get('pos_profile')
if pos_profile:
item_groups = get_item_groups(pos_profile)
if item_groups:
cond = "name in (%s)"%(', '.join(['%s']*len(item_groups)))
cond = cond % tuple(item_groups)
return frappe.db.sql(""" select di... | nd (name like %(txt)s) limit {start}, {page_len}"""
.format(condition = cond, start=start, page_len= page_len),
{'txt': '%%%s%%' % txt})
|
tbentropy/tilecutter | old/v.0.5/tc.py | Python | bsd-3-clause | 5,573 | 0.007177 | # TC Backend functions
# Hack to make PIL work with py2exe
import Image
import PngImagePlugin
import JpegImagePlugin
import GifImagePlugin
import BmpImagePlugin
Image._initialized=2
import wx
##import wx.lib.masked as masked
##import wx.lib.scrolledpanel as scrolled
##import wx.lib.hyperlink as hl
imp... | e.info.ydims)
yy = len(self.active. | info.xdims)
zz = self.active.info.zdims
w = (xx + yy) * (p/2)
h = ((xx + yy) * (p/4)) + (p/2) + ((zz - 1) * p)
offset_x = self.active.frame[f].direction[d].image[i].offset_x
offset_y = self.active.frame[f].direction[d].image[i].offset_... |
cbuntain/ncaa_football_predictor | Grabber/StatsClass.py | Python | bsd-2-clause | 7,312 | 0.00547 | #!/usr/bin/python
import StringIO
import urllib
import urllib2
from lxml import etree
class NcaaGrabber:
def __init__(self):
self.ncaaUrl = 'http://web1.ncaa.org'
self.ncaaStatsSite = self.ncaaUrl+'/football/exec/rankingSummary'
# self.ncaaTeamList2008 = self.ncaaUrl+'/mfb/%d/Interne... | lastScheduleRow = scheduleTableRows[-1]
isHome = False
if ( lastScheduleRow is not None ):
if ( lastScheduleRow.text is None ):
linkElement = lastScheduleRow.xpath('./a')[0]
gameLocation = linkElement.text
if ( gameLocation.isupper()... | isHome = 2
else:
isHome = 0
else:
gameLocation = lastScheduleRow.text
if ( gameLocation.isupper() and gameLocation.find("@") < 0 ):
if ( gameLocation.find("^") < 0 ):
isHome = 1
... |
khchine5/book | docs/dev/newbies/4.py | Python | bsd-2-clause | 280 | 0.017857 | # generator functions
def f1():
l = []
for i in range(1000):
l.append(i)
retur | n l
def f2():
for i in range(1000):
yield i # yield ulatama
# for i in f1():
# print i
# # to itera | te =
# for i in f2():
# print i
print f1()
print f2()
|
yajiedesign/mxnet | example/automatic-mixed-precision/amp_model_conversion.py | Python | apache-2.0 | 8,765 | 0.002738 | # 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 u... | 224, 224) '
'and run a dummy inference forward pass')
parser.add_argument('--cast-optional-params', action='store_true', default=False,
help='If enabled, will try to cast params to target dtype wherever possible')
args = parser.parse_args()
logging.basicC... | logger.setLevel(logging.INFO)
assert args.model in gluon_models, "Please choose one of the available gluon models: {}".format(gluon_models)
shape = None
if args.model in segmentation_models:
shape = (1, 3, 480, 480)
elif args.model in calib_ssd_models:
shape = (1, 3, 512, 544)
eli... |
Zlash65/erpnext | erpnext/patches/v11_0/move_item_defaults_to_child_table_for_multicompany.py | Python | gpl-3.0 | 3,389 | 0.027147 | # Copyright (c) 2018, Frappe and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
'''
Fields to move from the item to item defaults child table
[ default_warehouse, buying_cost_center, expense_account, selling_cost_center, ... | {}
default_data = company_wise_data[company]
default_data[d[0]] = item_data.get(d[0])
to_insert_data = []
# items_default_data data structure will be as follow
# {
# 'item_code 1': {'company 1': {'default_warehouse': 'Test Warehouse 1'} | },
# 'item_code 2': {
# 'company 1': {'default_warehouse': 'Test Warehouse 1'},
# 'company 2': {'default_warehouse': 'Test Warehouse 1'}
# }
# }
for item_code, companywise_item_data in items_default_data.items():
for company, item_default_data in companywise_item_data.items():
to_insert_data.a... |
loads/loads-broker | loadsbroker/tests/test_db.py | Python | apache-2.0 | 908 | 0 | import unittest
from loadsbroker.db import Project, Plan, Step, Database
class DatabaseTest(unittest.TestCase):
def setUp(self):
self.db = Database('sqlite:///:memory:')
def test_project(self):
session = self.db. | session()
| # a project is defined by a name, a repo and strategies
project = Project(
name='simplepush',
home_page='https://services.mozilla.com')
session.add(project)
plan = Plan(name='s1', enabled=True)
project.plans.append(plan)
# Attach a container set to th... |
gotlium/WebPlayer2LocalPlayer | setup.py | Python | gpl-2.0 | 929 | 0 | from setuptools import setup
from glob import glob
from WebPlayer2LocalPlayer import __version__
APP = ['WebPlayer2LocalPlayer.py']
DATA_FILES = [
('images', glob('images/*.png')),
]
OPTIONS = {
'argv_emulation': True,
'includes': [
'sip',
'PyQt5', 'PyQt5.QtGui', 'PyQt5.QtPrintSupport',
... | 'images/app_icon.icns',
"qt_plugins": ["imageformats", "platforms"],
"plist": dict(
LSMinimumSystemVersion='10.8.0',
LSEnvironment=dict(
PATH='./../Resources:/usr/local/bin:/usr/bin:/bin'
)
)
}
setup(
name="WP2LP",
version=__version__,
app=APP,
data_files... | },
setup_requires=['py2app'],
)
|
msimacek/koschei | koschei/locks.py | Python | gpl-2.0 | 3,496 | 0.000572 | # Copyright (C) 2018 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in... | try:
db.close_connection()
except Exception:
pass
if not ignore_exceptions:
raise e
def pg_unlock_all(db):
"""
Unlocks advisory session locks.
"""
db.query(func.pg_advisory_unlock_all()).one()
@contextmanager
def pg_session_lock(db, namespace... | Context manager for obtaining a session lock.
With block=True (default) blocks until the resource is locked.
"""
pg_lock(db, namespace, key, block=block, shared=shared)
try:
yield
pg_unlock(db, namespace, key, shared=shared, ignore_exceptions=False)
except Exception as e:
... |
t-mertz/slurmCompanion | django-web/sshcomm/migrations/0001_initial.py | Python | mit | 1,536 | 0.003255 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-06 12:34
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.for | ms.widgets
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='RemoteServer',
fields=[
('id', models.AutoField(auto_cr... | e, verbose_name='ID')),
('server_url', models.CharField(max_length=50)),
('server_name', models.CharField(max_length=20)),
('date_added', models.DateField()),
],
),
migrations.CreateModel(
name='UserData',
fields=[
... |
bostonlink/nwmaltego | nw_phrase_2_threat.py | Python | gpl-3.0 | 1,962 | 0.003568 | #!/usr/bin/env python
# Copyright (C) 2012 nwmaltego Developer.
# This file is part of nwmaltego - https://github.com/bostonlink/nwmaltego
# See the file 'LICENSE' for copying permission.
# Maltego Phrase to NW Threat
# Author: David Bressler (@bostonlink)
import sys
import urllib2, urllib, json
from datetime import ... | ect risk.warning where (time=%s) && risk.warning contains %s' % (diff, risk_phrase)
json_data = json.loads(nwmodule.nwQuery(0, 0, threat_ip_dst, 'application/json', 25))
ip_list = []
print trans_header
for d in json_data['results']['fields']:
value = d['value'].decode('ascii')
if value in ip_list:
cont... | nue
else:
# Kind of a hack but hey it works!
print """ <Entity Type="netwitness.NWThreatNOIP">
<Value>%s</Value>
<AdditionalFields>
<Field Name="phrase" DisplayName="Phrase">%s</Field>
<Field Name="metaid1" DisplayName="Me... |
garybake/microbake | fruity_notes.py | Python | mit | 547 | 0.001828 | from microbit im | port *
import music
# Plays a different note when pressing different fruits
# Put a buzzer between pin0 and Gnd
# Attach a fruit to Pin1 and Pin2
# Have a loose wire from Gnd
# Hold the Gnd wire
# Press your other hand on the fruits to hear notes
note_low = ["C4:4"]
note_high = ["C5:4"]
while True:
if pin1.is_... | ):
music.play(note_high)
display.show(Image.SURPRISED)
else:
display.show(Image.SAD) |
fsfrazao/Scarab-IBM | sim2.py | Python | gpl-2.0 | 9,111 | 0.035122 | '''
This program uses Scarab_IBM to implement Simulation 1.
Copyright (C) 2015 Fabio Soares Frazao
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 L... | keys(): Beetle_dots[bd].undraw()
for dd in Dung_dots.keys():
if dd not in Dung.Instances.keys(): Dung_dots[dd].undraw()
n=Beetle.PopulationSize()
N.append(n)
F1 | .append(world.r |
FOSSRIT/PyCut | game/objects/pizza.py | Python | mpl-2.0 | 13,934 | 0.007751 | import pygame
from pygame import gfxdraw
from .rangable import Rangable
import random
class Pizza(Rangable):
"""docstring for Pizza"""
def __init__(self, context):
Rangable.__init__(self)
self.context = context
self.pizza = self.context.plain_pizza
self.trashed = False
s... | f.drawing = None
self.draw()
"""
update the button drawing surface.
"""
def draw(self):
surf = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
pizza_img = pygame.transform.scale(self.context.plain_pizza, (self.width, self.height))
surf.blit(pizza_... | 0)
#gfxdraw.filled_ellipse(surf, self.width//2,self.height//2, self.width/2, self.height/2, (219,162,74))#pizza
#pygame.draw.arc(surf, (225,216,0), [0, 0, self.width, self.height], 0, 360, 2)#crust
#draw slices on here afterwards
self.drawing = surf
self.dirty = False
"""
... |
jamwt/diesel-pmxbot | pmxbot/karma.py | Python | bsd-3-clause | 9,256 | 0.029602 | # vim:ts=4:sw=4:noexpandtab
from __future__ import print_function, absolute_import
import itertools
import re
import random
import pmxbot
from . import storage
from .core import command
class SameName(ValueError): pass
class AlreadyLinked(ValueError): pass
class Karma(storage.SelectableStorage):
@classmethod
de... | ng):
thing = thing.strip().lower()
LOOKUP_SQL = 'SELECT karmavalue from karma_keys k join karma_values v on | k.karmaid = v.karmaid where k.karmakey = ?'
try:
karma = self.db.execute(LOOKUP_SQL, [thing]).fetchone()[0]
except:
karma = 0
if karma == None:
karma = 0
return karma
def set(self, thing, value):
thing = thing.strip().lower()
value = int(value)
UPDATE_SQL = 'UPDATE karma_values SET karmavalue ... |
mnjy/critters | CrittersProto/generator/hummingloop_algorithm.py | Python | mit | 3,992 | 0.007766 | #####################################################################
#
# hummingloop_algorithm.py
#
# Copyright (c) 2015, Nick Benson
# Modifications by benchan
#
# Released under the MIT License (http://opensource.org/licenses/MIT)
#
#####################################################################
import random... | ("C", 4)]
# Master pattern list
PATTERNS = [PATTERN_1,\
PATTERN_2, PATTERN_3,\
PATTERN_4, PATTERN_5,\
PATTERN_6, PATTERN_7]
# Interaction configuration
FOCUS_SPEED = 100 # velocity ints / second
MAX_VEL = 50
MIN_VEL = 50
NOTE_VELOCITY_MULT = 0.5
def choose_notes(key, chord):
notes_init = [key + chord[x]\
... | dict = {}
pattern = random.choice(PATTERNS)
silence_prob_list = random.choice(SILENCE_PROB_LISTS)
for subpat in pattern:
if subpat[0] not in subpat_dict:
# Generate new subpattern
new_subpat = []
for i in range(subpat[1]):
new_subpat += [random.cho... |
suutari-ai/shoop | shuup_tests/notify/notification_test_urls.py | Python | agpl-3.0 | 364 | 0 | # -*- coding: utf-8 -*-
# This file is part o | f Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.conf.urls import url
u | rlpatterns = [
url('test/(?P<arg>.+)/$', (lambda: 0), name="test"),
]
|
rsnakamura/oldape | tests/testunits/testtools/testnetwork/test_network.py | Python | apache-2.0 | 1,234 | 0.005673 | """
A set of tests that check different cases for the network tester
"""
#python
#third-party
from mock import MagicMock
import nose
#from apetools.tools import networkcheck
from apetools.tools import timetorecovery as ttr
from apetools.tools import networktester
from apetools.commons import errors
def test_case_1(... | test to the tpc (linux)
tpc_ttr = MagicMock()
tpc_ttr.run.return_value = ttr.TTRData(5, '0.98')
dut_ttr = MagicMock()
dut_ttr.run.return_value = ttr.TTRData(10, '9.2')
testers = [tpc_ttr, dut_ttr]
tester = networktester.NetworkTester(testers)
tester.run()
assert True
return
@nose.t... | ():
"""
:description: dut pings pc, ping fails to ping dut
:assert: Raises ConnectionError
"""
tpc_ttr = MagicMock()
tpc_ttr.run.return_value = None
dut_ttr = MagicMock()
dut_ttr.run.return_value = ttr.TTRData(2, '0.9')
tester = networktester.NetworkTester([dut_ttr, tpc_ttr])
t... |
kawamon/hue | desktop/core/ext-py/prometheus_client-0.7.1/prometheus_client/metrics.py | Python | apache-2.0 | 21,319 | 0.001782 | import sys
from threading import Lock
import time
import types
from . import values # retain this import style for testability
from .context_managers import ExceptionCounter, InprogressTracker, Timer
from .metrics_core import (
Metric, METRIC_LABEL_NAME_RE, METRIC_NAME_RE,
RESERVED_METRIC_LABEL_NAME_RE,
)
fro... | registry.register(self)
def labels(self, *labelvalues, **labelkwargs):
"""Return the child for the given labelset.
All metrics can have labels, allowing grouping of related time series.
Taking a counter as an example:
from prometheus_client import Counter
... | c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint'])
c.labels('get', '/').inc()
c.labels('post', '/submit').inc()
Labels can also be provided as keyword arguments:
from prometheus_client import Counter
c = Counter('my_requests_total', 'HTTP... |
typesupply/extractor | Lib/extractor/stream.py | Python | mit | 9,611 | 0 | # -*- coding: utf-8 -*-
fro | m fontTools.misc.textTools import num2binary
from fontTools.ttLib.t | ables.ttProgram import streamOpcodeDict, opcodeDict
from io import BytesIO
class InstructionStream(object):
"""
:param program_bytes: The program bytecode.
:type program_bytes: bytes
The instruction stream.
"""
def __init__(self, instruction_processor=None, program_bytes=b"") -> None:
... |
mattljc/LaminateTools | oldSauce/RevB/text_outputs.py | Python | apache-2.0 | 765 | 0.035294 | import numpy as np
def FullOut(outfi | le='results.txt',analysis={}, envelopes={}, index={}):
# Set global output options
np.set_printoptions(precision=5, linewidth=1000)
contents = outfile +'\n\n'
contents += '==LAMINATE CONSTANTS==\n'
for key in analysis:
contents += key+'\n'
contents += str(analysis[key])
contents += '\n'
contents += '==LA... | RE ENVELOPES==\n'
for key in envelopes:
contents += key + '\n'
for subkey in envelopes[key]:
contents += subkey + ' = '+str(envelopes[key][subkey])
contents += '\n'
contents += '\n'
file = open(outfile,'w')
file.write(contents)
file.close()
|
hashbrowncipher/pushmanager | pushmanager/servlets/delayrequest.py | Python | apache-2.0 | 2,656 | 0.00113 | import sqlalchemy as SA
import pushmanager.core.db as db
from pushmanager.core.mail import MailQueue
from pushmanager.core.requesthandler import RequestHandler
import pushmanager.core.util
class DelayRequestServlet(RequestHandler):
def post(self):
if not self.current_user:
return self.send_er... | tchers']:
user_string = '%s (%s)' % (req['user'], req['watchers'])
users = [req['user']] + req['watchers'].split(',')
else:
user_string = req['user']
users = [req['user']]
msg = (
"""
<p>
Request for %(user)s has bee... | hmaster)s, and will not be accepted into pushes until you
mark it as requested again:
</p>
<p>
<strong>%(user)s - %(title)s</strong><br />
<em>%(repo)s/%(branch)s</em>
</p>
<p>
Regards,<br />
... |
ganeshrn/ansible | lib/ansible/vars/clean.py | Python | gpl-3.0 | 6,161 | 0.001785 | # Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
from ansible import constants as C
from ansible.... | otherwise deemed unsafe '''
data = module_response_deepcopy(facts)
remove_keys = set()
fact_keys = set(dat | a.keys())
# first we add all of our magic variable names to the set of
# keys we want to remove from facts
# NOTE: these will eventually disappear in favor of others below
for magic_var in C.MAGIC_VARIABLE_MAPPING:
remove_keys.update(fact_keys.intersection(C.MAGIC_VARIABLE_MAPPING[magic_var]))
... |
ImageMarkup/isic-archive | isic_archive/models/annotation.py | Python | apache-2.0 | 10,692 | 0.000561 | from bson import ObjectId
import jsonschema
import numpy
from girder.exceptions import ValidationException
from girder.models.file import File
from girder.models.model_base import Model
from girder.models.upload import Upload
from girder.utility.acl_mixin import AccessControlMixin
from .image import Image
from .segme... | if doc.get('stopTime'):
schema = {
# '$schema': 'http://json-schema.org/draft-07/schema#',
'title': 'annotation',
'type': 'object',
'properties': {
'_id': {
# TODO
},
... | TODO
},
'imageId': {
|
Slack06/yadg | manage.py | Python | mit | 1,359 | 0.001472 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011-2015 Slack
#
# 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
... | PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING 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 ... | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os, sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.develop")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
sidnarayanan/BAdNet | train/pf/adv/plot.py | Python | mit | 8,432 | 0.025498 | #!/usr/local/bin/python2.7
from sys import exit
from os import environ, system
environ['KERAS_BACKEND'] = 'tensorflow'
environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
environ["CUDA_VISIBLE_DEVICES"] = ""
import numpy as np
import utils
import adversarial
import obj
import config
#config.DEBUG = True
#config.n_tru... | arange(0,1,0.01)),
# 'correlation_class' : (lambda x : (x['singletons'][:,obj.singletons['msd']], predict_conv(x, 0)),
# np.arange(40,400,10.),
# np.arange(0,1,0.01)),
# }
# unmasked first
hists = {}
for k,v in colls.iteritems():
hists[k | ] = v.draw(components=components,
f_vars=f_vars,
n_batches=n_batches, partition=partition)
#hists2d['q']['correlation_reg'].scale()
#hists2d['q']['correlation_class'].scale()
#hists2d['q']['correlation_reg'].plot(xlabel=r'$m_{SD}$', ylabel='Regularize... |
stephanie-wang/ray | rllib/optimizers/aso_minibatch_buffer.py | Python | apache-2.0 | 1,622 | 0 | """Helper class for AsyncSamplesOptimizer."""
class MinibatchBuffer:
"""Ring buffer of recent data batches for minibatch SGD.
This is for use with AsyncSamplesOptimizer.
"""
def __init__(self, inqueue, size, timeout, num_passes, init_num_passes=1):
"""Initialize a minibatch buffer.
... | released = self.ttl[self.idx] <= 0
if released:
self.buffers[self.idx] = None
self.idx = (self.idx + 1) % len(self.buffers)
return buf, re | leased
|
josephhardinee/PyDisdrometer | pydsd/tests/test_expfit.py | Python | lgpl-2.1 | 2,668 | 0.003373 | from ..utility import expfit
from unittest import TestCase
import numpy as np
class Test_expfit(TestCase):
""" Tests for the expfit module. """
def test_expfit_returns_correct_relationship(self):
"""
Test whether or not expfit can model a simple one variable exponential relationship.
... | = 2 * np.array([1, 3, 5, 7, 9])
y = a * np.power(x1, b) * np.power(x2, c)
fit = expfit.expfit2([x1, x2], y)[0]
self.assertAlmostEqual(fit[0], a, 7, "Fit of Scale Parameter Failed for expfit")
self.assertAlmostEqual(
fit[1], b, 7, "Fit of First Exponent Parameter Failed for ex... | fit[2], c, 7, "Fit of Second Exponent Parameter Failed for expfit2"
)
def test_expfit2_handles_nan(self):
"""
Test whether or not expfit2 can model a simple two variable exponential relationship in
the presence of nans.
"""
a = 1.5
b = 2.5
... |
tecnicatura-villa-el-libertador/CentroAsistencialH3 | CentroAsist/migrations/0007_profesional_user.py | Python | bsd-3-clause | 729 | 0.001372 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-10-29 23:47
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration( | migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('CentroAsist', '0006_auto_20161029_2341'),
]
operations = [
migrations.AddField(
model_name='profesional', |
name='user',
field=models.OneToOneField(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='profesional', to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]
|
Black-Cog/BCnukeTools | core/__init__.py | Python | bsd-3-clause | 23 | 0 |
imp | ort renderm | anScene
|
jonmuckell/Motion-Tracking-Data-Parser | XYZ.py | Python | gpl-3.0 | 2,996 | 0.013365 | '''
Created on May 26, 2016
@author: Jonathan Muckell, Ph.D.
@license: GNU General Public License v3.0
Users are encouraged to use, modify and extend this work under the GNU GPLv3 license.
Please cite the following paper to provide credit to this work:
Jonathan Muckell, Yuchi Young, and Mitch Leventhal.... | duct(a, b):
# Equation from # http://tutorial.math.lamar.edu/Classes/CalcII/CrossProduct.aspx#Vectors_CrossProd_Ex2
x = (a.y * b.z) - (a.z * b.y)
y = (a.z * b.x) - (a.x * b.z)
z = (a.x * b.y) - (a.y * b.x)
vector = XYZ([x, y, z])
# print("cross product = ", x, " | ",... | Q,R):
# http://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfPlanes.aspx
PQ = XYZ.getVector(P,Q)
PR = XYZ.getVector(P,R)
normal = XYZ.crossProduct(PQ, PR)
return normal
@staticmethod
def getMidpoint(pt1, pt2):
x = (pt1.x + pt2.x) / 2
y... |
rackerlabs/sloggingo | test_slogging/unit/test_compressing_file_reader.py | Python | apache-2.0 | 1,258 | 0 | # Copyright (c) 2010-2011 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co | mpliance with the License.
# You | may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the Licens... |
dbbhattacharya/kitsune | vendor/packages/translate-toolkit/translate/filters/helpers.py | Python | bsd-3-clause | 2,818 | 0.007097 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2004-2006 Zuza Software Foundation
#
# This | file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your optio | n) any later version.
#
# translate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General P... |
RNAcentral/rnacentral-webcode | rnacentral/portal/rfam_matches.py | Python | apache-2.0 | 14,300 | 0.00021 | """
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... | as_json(self):
"""
Create a JSON representation of the simplified data.
"""
return json.dumps(self.as_simple_data())
class DomainProblem(object):
"""
This detects if there is a mismatch between the domains of the matched
models and the sequence that has been run. For exampl... | here is some sort of problem, likely
contamination, with the sequence.
"""
name = 'possible_contamination'
def message(self, model, rna, taxid=None):
"""
Get a message that indicates a problem.
"""
names = ''
is_common_name = False
if taxid is None:
... |
alisaifee/flask-limiter | tests/test_flask_ext.py | Python | mit | 20,218 | 0.000692 | """
"""
import logging
import time
import hiro
import mock
from flask import Flask, request
from werkzeug.exceptions import BadRequest
from flask_limiter.extension import C, Limiter
from flask_limiter.util import get_remote_address
def test_reset(extension_factory):
app, limiter = extension_factory({C.DEFAULT_... | _client() as cli:
assert cli.get("/ping").status_code == 200
assert cli.get("/ping").status_code == 200
assert cli.get("/ping").status_code == 429
timeline.forward(1)
assert cli.get("/ping").sta | tus_code == 200
assert cli.get("/slowping").status_code == 200
timeline.forward(59)
assert cli.get("/slowping").status_code == 200
assert cli.get("/slowping").status_code == 429
timeline.forward(1)
assert cli.get("/slowping").status_code == 200
d... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_02_01/aio/operations/_express_route_gateways_operations.py | Python | mit | 22,493 | 0.005202 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | on/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'expressRouteGatewayName': self._s | erialize.url("express_route_gateway_name", express_route_gateway_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_argume |
Hasimir/pyjs | examples/jsobject/TestRect.py | Python | apache-2.0 | 1,626 | 0.005535 | from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.TextBox import TextBox
from pyjamas.ui.HTML import HTML
from pyjamas.ui.Button import Button
from __pyjamas__ import JS
class Rect:
def __init__(self, x, y):
JS("""@{{self}}.rect = new @{{!rectobj}}();""")
self.rect.init(x, y)
def add(... | ))
Roo | tPanel().add(HTML("New Area: %d" % self.r.area()))
if __name__ == '__main__':
app = TestRect()
app.onModuleLoad()
|
wuub/python_lcd | lcd/pyb_gpio_lcd_test8.py | Python | mit | 2,352 | 0.00085 | """Implements a character based lcd connected via PCF8574 on i2c."""
from pyb import Pin
from pyb import delay, millis
from pyb_gpio_lcd import GpioLcd
# Wiring used for this example:
#
# 1 - Vss (aka Ground) - Connect to one of the ground pins on you pyboard.
# 2 - VDD - I connected to VIN which is 5 volts when yo... | Lcd)
# 9 - D2 - connect to Y3 (as per call to GpioLcd)
# 10 - D3 - connect to Y4 (as per call to GpioLcd)
# 11 - D4 - connect to Y5 (as per call to GpioLcd)
# 12 - D5 - connect to Y6 (as per call to GpioLcd)
# 13 - D6 - connect to Y7 (as per call to GpioLcd)
# 14 - D7 - connect to Y8 (as per call to GpioLcd)
# 15 - A ... | pically connects to the center tap of a
# 10K potentiometer, and the other 2 legs of the 10K potentiometer are
# connected to pins 1 and 2 (Ground and VDD)
#
# The wiring diagram on the followig page shows a typical "base" wiring:
# http://www.instructables.com/id/How-to-drive-a-character-LCD-displays-using-DIP-sw/step... |
Alshak/clowdflows | workflows/cforange/interaction_views.py | Python | mit | 5,590 | 0.013775 | from django.shortcuts import render
import json
def cforange_filter_integers(request,input_dict,output_dict,widget):
return render(request, 'interactions/cforange_filter_integers.html',{'widget':widget,'intList':input_dict['intList']})
def cforange_hierarchical_clustering(request,input_dict,output_dict,widg... | ##try:
#iris = Orange.data.Table("vehicle")
##iris = Orange.data.Table("iris")
#print len(iris)
#m = Orange.misc.SymMatrix(len(iris))
#m = Orange.distance.distance_matrix(iris, Orange.distance.Euclidean)
#matrix = m
######################
matrix = input_dic | t['dm']
#print matrix
linkage = int(input_dict['linkage'])
root = Clustering.hierarchical_clustering(linkage, matrix)
dm_examples = True
######################
try:
#attributes = [x.name for x in matrix.items.domain]
attributes = [x.name for x in matrix.items.doma... |
pombredanne/anvil | anvil/ini_parser.py | Python | apache-2.0 | 9,960 | 0.000502 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2013 Yahoo! 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.or... | Mixin, ConfigParser.RawConfigParser, StringiferMixin):
def __init__(self, fns=None, templatize_values=False):
ConfigHelperMixin.__init__(self, templatize_values)
ConfigParser.RawConfigParser.__init__(self)
StringiferMixin.__init__(self)
# Make option names case sensitive
# Se... | r f in fns:
self.read(f)
class AnvilConfigParser(iniparse.RawConfigParser):
"""Extends RawConfigParser with the following functionality:
1. All commented options with related comments belong to
their own section, but not to the global scope. This is
needed to insert new options into pr... |
logpai/logparser | logparser/LKE/LKE.py | Python | mit | 21,195 | 0.016183 | """
Description : This file implements the log key extraction algorithm for log parsing
Author : LogPAI team
License : MIT
"""
import math
from datetime import datetime
from ..logmatch import regexmatch
import re
import os
import sys
import pandas as pd
import hashlib
import numpy as np
SAVED... | Threshold(distArray)
print('the threshold1 is: %s'%(threshold1))
# connect two loglines with distance < threshold, logDict is a dictionary
# where the key is line num while
logDict={}
for i in range(logNum):
logLineSet=set()
for j in rang... | Set
#use DFS to get the initial group.
flag=np.zeros((logNum,1)) # used to label whether line has been visited, 0 represents not visited
for key in logDict:
if flag[key]==1:
continue
groupLoglist=[]
groupLoglist.append(key) # ... |
vitorio/pygrow | grow/pods/preprocessors/preprocessors.py | Python | mit | 1,086 | 0.007366 | from grow.pods.preprocessors import clo | sure_compiler
from g | row.pods.preprocessors import google_sheets
from grow.pods.preprocessors import sass_preprocessor
from protorpc import protojson
import json
_preprocessor_kinds_to_classes = {}
_builtins = (
sass_preprocessor.SassPreprocessor,
google_sheets.GoogleSheetsPreprocessor,
closure_compiler.ClosureCompilerPreproc... |
munhyunsu/Hobby | 2019S_TCPIP/t07-tls-socket/c02-tcp-client.py | Python | gpl-3.0 | 716 | 0.001397 | import socket
FLAGS = None
def main(_):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.sett | imeout(5)
sock.connect((FLAGS.ip, FLAGS.port))
print('Connected with server')
msg = input('Type the message: ')
msg = msg.encode('utf-8')
sock.sendall(msg)
data = sock.recv(1500)
print('Echoed {0}'.format(data.decode('utf-8')))
soc | k.close()
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--ip', type=str,
default='localhost')
parser.add_argument('-p', '--port', type=int,
default=8000)
FLAGS, _ = parser.parse_known_args()... |
frlen/simian | src/tests/simian/auth/x509_test.py | Python | apache-2.0 | 37,278 | 0.003246 | #!/usr/bin/env python
#
# 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 require... | nary').AndReturn(None)
self.mox.ReplayAll()
self.assertEqual(
mock_x509,
x509.LoadCertificateFromBase64('b64str'))
self.mox.VerifyAll()
def testLoadCertificateFromBase64WhenBase64CharacterCheckFail(self):
"""Test LoadCertificateFromBase64()."""
self.mox.StubOutWithMock(x509.base6... |
self.mox.ReplayAll()
self.assertRaises(
x509.PEMFormatError,
x509.LoadCertificateFromBase64, 'b64str')
self.mox.VerifyAll()
def testLoadCertificateFromBase64WhenBase64DecodeFail(self):
"""Test LoadCertificateFromBase64()."""
self.mox.StubOutWithMock(x509.base64, 'b64decode')
... |
shoopio/shoop | shuup_tests/core/test_foreignkeys.py | Python | agpl-3.0 | 4,853 | 0.00103 | # This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from django.db.models import ProtectedError
from shuup.core.models import (... | sm.delete()
assert PersonContact.objects.filter(pk=contact.pk).exists()
@pytest.mark.django_db
def test_payment_method_removal():
tax_class = TaxClass.objects.create(name="test")
shop = get_default_shop()
pm = PaymentMethod.objects.create(name="sm", shop=shop, tax_class=tax_class)
contact = Person... | pm.delete()
assert PersonContact.objects.filter(pk=contact.pk).exists()
@pytest.mark.django_db
def test_customer_tax_group_removal():
ctg = CustomerTaxGroup.objects.create(name="test")
contact = PersonContact.objects.create(name="test", tax_group=ctg)
with pytest.raises(ProtectedError):
ctg.d... |
the-it/WS_THEbotIT | service/ws_re/register/register_types/public_domain.py | Python | mit | 3,225 | 0.002171 | from typing import Dict, List
from service.ws_re.register._base import Register
from service.ws_re.register.author import Author
from service.ws_re.register.authors import Authors
from service.ws_re.register.lemma import Lemma
from service.ws_re.register.register_types.volume import VolumeRegister
class PublicDomain... | header = """{|class="wikitable sortable"
!Artikel
!Band
!Status
!Wikilinks
!Seite
!Autor
!Sterbejahr"""
table = [header]
for lemmas in self.squash_lemmas(self._lemmas):
chapter_sum = 0
| table_rows = []
lemma = None
for lemma in lemmas:
# if there are no chapters ... one line must be added no madder what
chapter_sum += max(len(lemma.chapters), 1)
table_rows.append(lemma.get_table_row(print_volume=True))
# strip |-/n for... |
NicovincX2/Python-3.5 | Physique/Onde/Mécanique ondulatoire/Acoustique/battements_interactif.py | Python | gpl-3.0 | 2,089 | 0.00144 | # -*- coding: utf-8 -*-
import os
"""
Ce programme est proposé par Vincent Grenard (PCSI, Lycée Poincaré, Nancy).
Il produit une boîte de dialogue qui permet un tracé interactif des battements
en permettant de modifier les divers paramètres pour illustrer la notion de
battements.
"""
import numpy as np
import pyl... | l2.set_ydata(np.abs(a2-a1)+np.abs(s(t,(f2-1)/2.0,2*a1,phi/2.0)))
ax.axes.axis([0, 100, 1.1 * min(y), 1.1 * max(y)])
py.draw()
sld_amplitude1 = py.axes([0.2, 0.1, 0.7, 0.03], axisbg='grey')
sld_amplitud | e2 = py.axes([0.2, 0.15, 0.7, 0.03], axisbg='grey')
sld_frequence2 = py.axes([0.2, 0.2, 0.7, 0.03], axisbg='grey')
sld_phase2 = py.axes([0.2, 0.25, 0.7, 0.03], axisbg='grey')
amplitude1 = Slider(sld_amplitude1, 'amplitude 1', 0.0, 2.0, valinit=1)
amplitude2 = Slider(sld_amplitude2, 'amplitude 2', 0, 2.0, valinit=1)
fr... |
cloudbase/maas | src/metadataserver/tests/test_nodeinituser.py | Python | agpl-3.0 | 1,151 | 0.003475 | # Copyright 2012, 2013 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Model tests f | or metadata server."""
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
str = None
__metaclass__ = type
__all__ = []
from django.contrib.auth.models import User
from maasserver.models import UserProfile
from maastesting.testcase import MAASTestCase
from metadataserver. | nodeinituser import (
get_node_init_user,
user_name,
)
class TestNodeInitUser(MAASTestCase):
"""Test the special "user" that makes metadata requests from nodes."""
def test_always_returns_same_user(self):
node_init_user = get_node_init_user()
self.assertEqual(node_init_user.id, ge... |
aspiringguru/sentexTuts | PracMachLrng/sentex_ML_demo7.py | Python | mit | 1,403 | 0.027085 | '''
working exercise from sentex tutorials. with mods for clarification + api doc references.
How to program the Best Fit Line - Practical Machine Learning Tutorial with Python p.9
https://youtu.be/KLGfMGsgP34?list=PLQVvvaa0QuDfKTOs3Keq_kaG2P55YRn5v
linear regression model y=mx+b
m = mean(x).mean(y) - mean (x.y)
... | e = [m*x+b for x in xs]
print ( "m={}".format(m), ", b={}".format(b) )
predict_x = 8
predict_y = (m*predict_x) + b
plt.scatter(xs, ys)
plt.scatter(predict_x, predict_y, color = 'g', marker='s', s=50)
#plt.plot(xs, xs*m+b)
plt.plot(xs, regression_line)
plt.xlabel('xs')
plt.ylabel('ys')
plt.title("plot mx+b usi | ng linear regression fit")
plt.show()
'''
http://matplotlib.org/examples/style_sheets/plot_fivethirtyeight.html
''' |
ppolewicz/ant-colony | antcolony/simulation.py | Python | bsd-3-clause | 2,667 | 0.005249 | import heapq
class AbstractSimulation(object):
def __init__(self, reality, antmoves, stats):
self.reality = reality
self.antmoves = antmoves
heapq.heapify(antmoves)
self.stats = stats
self.ticks = 0
def tick(self):
ant_move = heapq.heappop(self.antmoves)
... | mulation):
def advance(self):
if self.reality.is_resol | ved():
return [], True, None
tick_changed_items, stats = self.tick()
print 'ticks: %d, food_discovered: %d' % (self.ticks, stats.food_discovered)
return tick_changed_items, False, stats.last_route
class MultiSpawnStepSimulation(AbstractSimulation):
def __init__(self, reality, *a... |
sunzhongyuan/MxOnline | apps/courses/views.py | Python | mit | 2,367 | 0.000892 | # _*_ coding:utf-8 _*_
from django.shortcuts import render
from django.views.generic.base im | port View
from django.http import HttpResponse
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from .models import Course, Lesson
from operation.models import UserFavorite
# Create your views here.
class CourseView(View):
def get | (self, request):
course_all = Course.objects.all()
# 热门课程
course_hot = course_all.order_by('-fav_nums')[:3]
# 排序 最热门
sort = request.GET.get('sort', '')
if sort == 'students':
course_all = course_all.order_by('-students')
elif sort == 'hot':
... |
mad-lab/transit | src/pytpp/tpp_gui.py | Python | gpl-3.0 | 25,744 | 0.017557 | #!/usr/bin/env python
# Copyright 2017.
# Michael A. DeJesus, Chaitra Ambadipudi, and Thomas R. Ioerger.
#
#
# This file is part of TRANSIT.
#
# TRANSIT 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 Foun... | anel,choices=['Sassetti','Mme1', 'Tn5'],size=(400,30))
self.protocol.SetStringSelection(vars.protocol)
sizer_protocol.Add(self.protocol, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
protocol_tooltip_text = """Select which protocol used to prepare the sequencing samples. Default val... | .
The Sassetti protocol generally assumes the reads include the primer prefix and part of the transposon sequence, followed by genomic sequence. It also assumes reads are sequenced in the forward direction. Barcodes are in read 2, along with genomic DNA from the other end of the fragment.
The Mme1 protocol generally... |
PetrDlouhy/django-fluent-comments | example/article/tests.py | Python | apache-2.0 | 2,825 | 0.002479 | # -*- coding: utf-8 -*-
# Author: Petr Dlouhý <petr.dlouhy@auto-mat.cz>
#
# Copyright (C) 2015 o.s. Auto*Mat
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, o... | object_pk,
"name": "Testing name",
"email": "test@email.com",
"comment": "Testing comment",
"timestamp": timestamp,
"security_hash": security_hash,
}
response = self.client.post(reverse("comments-post-comment-ajax"), post_data, HTTP_X_REQUESTED... | sponse.content.decode("utf-8"))
|
fmichea/lpbm | setup.py | Python | bsd-3-clause | 2,729 | 0.000733 | import os
import shlex
import sys
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
_ROOT = os.path.abspath(os.path.dirname(__file__))
class PyTest(TestCommand):
user_options = [
('args=', 'a', 'Additional arguments to pass to py.test'),
('debug=... | ROOT, 'tests'))
print('execute: py.test', ' '.join(shlex.quote(arg) for arg in args))
try:
errno = pytest.main(args)
finally:
cov_file = os.path.join(_ROOT, '.coverage')
if self.coverage != 'keep-result' and os.path.exists(cov_file):
os.unlink(... | ',
url='http://github.com/fmichea/lpbm',
# Version information.
license='BSD',
version='3.0.0',
# Author.
author='Franck Michea',
author_email='franck.michea@gmail.com',
# File information.
install_requires=open('requirements/command.txt').readlines(),
packages=find_packages(e... |
PhasesResearchLab/ESPEI | tests/testing_data.py | Python | mit | 49,302 | 0.001765 | """Databases and datasets used in common tests"""
import yaml
YAML_LOADER = yaml.FullLoader
A_B_REGULAR_SOLUTION_TDB = """
ELEMENT A ALPHA 0.0 0.0 0.0 !
ELEMENT B ALPHA 0.0 0.0 0.0 !
TYPE_DEFINITION % SEQ *!
PHASE ALPHA % 1 1 !
CONSTITUENT ALPHA : A B : !
$ Default the lattice stability and regular solution para... | D DEFINE_SYSTEM_ELEMENT VA !
PHASE FCC_A1 % 2 1 1 !
CONSTITUENT FCC_A1 :CU,MG:VA: !
PARAMETER G(FCC_A1,CU:VA;0) 1 GFCCCU#; 10000 N !
PARAMETER G(FCC_A1,MG:VA;0) 1 GFCCMG#; 10000 N !
PARAMETER L(FCC_A1,CU,MG:VA;0) 1 VV0003#; 10000 N !
PARAMETER L(FCC_A1,CU, | MG:VA;1) 1 VV0002#; 10000 N !
PARAMETER L(FCC_A1,CU,MG:VA;2) 1 VV0001#; 10000 N !
"""
CU_MG_TDB_ASSOC = """$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$ ASSOC TDB FROM CU_MG
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
ELEMENT CU BLANK 0 0 0 !
ELEM... |
cbertinato/pandas | pandas/tests/io/conftest.py | Python | bsd-3-clause | 2,699 | 0 | from distutils.version import LooseVersion
import os
import pytest
import pandas.util.testing as tm
from pandas.io.parsers import read_csv
@pytest.fixture
def tips_file(datapath):
"""Path to the tips dataset"""
return datapath('io', 'parser', 'data', 'tips.csv')
@pytest.fixture
def jsonl_file(datapath):
... | pytest.fixture
def salaries_table(datapath):
"""DataFrame with the salaries dataset"""
return read_csv(datapath('io', 'parser', 'data', 'salaries.csv'), sep='\t')
@pytest.fixture
def s3_resource(tips_file, jsonl_file):
"""Fixture for mocking S3 interaction.
The primary bucket name is "pandas-test". T... | ing datasets
are loaded.
- tips.csv
- tips.csv.gz
- tips.csv.bz2
- items.jsonl
A private bucket "cant_get_it" is also created. The boto3 s3 resource
is yielded by the fixture.
"""
pytest.importorskip('s3fs')
boto3 = pytest.importorskip('boto3')
botocore = pytest.importorski... |
Donkyhotay/MoonPy | zope/testing/testrunner-ex/sample1/sampletests/test112.py | Python | gpl-3.0 | 3,574 | 0.005596 | ##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SO... | x)
def setUp(test):
test.globs['z'] = 1
test.globs['layer'] = layer.layer
test.globs['layerx'] = layer.layerx
def test_y0(self):
"""
>>> y
0
>>> (layer == samplelayers.layer), (layerx | == samplelayers.layerx)
(True, True)
"""
def test_x0(self):
"""
>>> x
0
>>> (layer == samplelayers.layer), (layerx == samplelayers.layerx)
(True, True)
"""
def test_z1(self):
"""
>>> z
1
>>> (layer == samplelayers.layer), (layerx == samplelayers.layerx)
(True, Tr... |
plotly/plotly.py | packages/python/plotly/plotly/validators/layout/xaxis/_ticktextsrc.py | Python | mit | 410 | 0.002439 | import _p | lotly_utils.basevalidators
class TicktextsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="ticktextsrc", parent_name="layout.xaxis", **kwargs):
super(TicktextsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | edit_type=kwargs.pop("edit_type", "none"),
**kwargs
)
|
ryanofsky/bitcoin | test/functional/feature_fee_estimation.py | Python | mit | 11,247 | 0.003201 | #!/usr/bin/env python3
# Copyright (c) 2014-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 fee estimation code."""
from decimal import Decimal
import random
from test_framework.mininode im... | pend({"txid": txid, "vout": 0, "amount": half_change})
txouts.append({"txid": txid, "vout": 1, "amount": rem_change})
def check_estimates(node, fees_seen, max_invalid):
"""Call estimatesmartfee and verify that the estimates meet certain invariants."""
de | lta = 1.0e-6 # account for rounding error
last_feerate = float(max(fees_seen))
all_smart_estimates = [node.estimatesmartfee(i) for i in range(1, 26)]
for i, e in enumerate(all_smart_estimates): # estimate is for i+1
feerate = float(e["feerate"])
assert_greater_than(feerate, 0)
if ... |
devilry/devilry-django | devilry/devilry_import_v2database/migrations/0002_auto_20190624_1238.py | Python | bsd-3-clause | 463 | 0 | # Generated by Django 2.2.1 on 2019-06-24 10:38
import django.contrib.postgres.fields.jsonb
from django.db import | migrations
class Migration(migrations.Migration):
dependencies = [
('devilry_import_v2database', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='imp | ortedmodel',
name='data',
field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
),
]
|
jhole89/convet-image-classifier | test/test_dataset.py | Python | gpl-3.0 | 1,572 | 0.000636 | from main.dataset import DataSet
import numpy as np
def test_dataset(load_image_data, image_size):
images, labels, ids, cls, _ = load_image_data
dataset = DataSet(images, labels, ids, cls)
assert sorted(list(dataset.cls)) == sorted(['cat', 'dog'] * 10)
assert dataset.cls.shape == (20,)
assert ... | size, 3)
assert dataset.images.dtype == np.float32
assert dataset.images.min() == float(0)
assert dataset.images.max() == float(1)
assert np.array_equal(dataset.labels, [[1., 0.]] * 10 + [[0., 1.]] * 10)
assert dataset.labels.shape == (20, 2)
assert dataset.labels.dtype == np.float64
assert... | == 20
def test_next_batch(load_image_data, image_size):
images, labels, ids, cls, _ = load_image_data
dataset = DataSet(images, labels, ids, cls)
image_batch, label_batch, id_batch, cls_batch = dataset.next_batch(batch_size=2)
assert list(cls_batch) == ['cat', 'cat']
assert cls_batch.shape == ... |
hzj123/56th | pombola/core/admin.py | Python | agpl-3.0 | 8,525 | 0.001525 | from django import forms
from django.contrib import admin
from django.contrib.gis import db
from django.contrib.contenttypes.generic import GenericTabularInline
from django.core.exceptions import ValidationError
from ajax_select import make_ajax_form
from ajax_select.admin import AjaxSelectAdmin
from pombola.core imp... | extra = 0
can_delete = False
fields = ['source', 'note', 'entered']
formfield_overrides = {
db.models.TextField: {
'widget': forms.Textarea(attrs={'rows':2, 'cols':40}),
},
}
class ContactAdmin(ContentTypeModelAdmin):
list_display = ['kind', 'value', 'show_foreign'... | search_fields = ['value']
inlines = [InformationSourceInlineAdmin]
class ContactInlineAdmin(GenericTabularInline):
model = models.Contact
extra = 0
can_delete = True
fields = ['kind', 'value', 'source', 'note']
formfield_overrides = {
db.models.TextField: {
'widget': forms.... |
nickstenning/honcho | tests/integration/test_main.py | Python | mit | 382 | 0 | import pytest
i | mport textwrap
@pytest.mark.parametrize('testenv', [{
'Procfile': textwrap.dedent("""
foo: python web.py
bar: ruby worker.rb
""")
}], indirect=True)
def test_main(testenv):
result = testenv.run(['python', '-m', 'honcho', 'check'], check=True)
assert 'Valid procfile detected' in resul | t.stderr
assert 'foo, bar' in result.stderr
|
apsmi/PyTanks | server_dispatcher.py | Python | gpl-2.0 | 4,595 | 0.007973 | # -*- coding: utf-8 -*-
import asyncore
import socket
import struct
import pickle
from server_tank import Tank, Tank_config
from server_player import Game_Client
# сокет, принимающий соединение от клиентов
class Game_Server_UDP(asyncore.dispatcher):
# инициализация
def __init__(self, host, port, BLOCK_SIZE, ... | rs_green, players_yellow
self.total_level_width, self.total_level_height, self.level_width, self.level_height, self.BLOCK_DEMAGE, self.FRAME_RATE, self.blocks = \
total_level_width, total_level_height, level_width, level_height, BLOCK_DEMAGE, FRAME_RATE, blocks
self.create_socket(socket.AF_... | (host, port))
self.player_count = 0 # количество подключенных клиентов
self.players = [] # список пдключенных клиентов
# подготовка пакета к передаче
def pack_data(self, data):
tmp = pickle.dumps(data)
l = len(tmp)
return struct.pack('L', l) + tmp
# входящее сое... |
aperigault/ansible | test/units/module_utils/basic/test_tmpdir.py | Python | gpl-3.0 | 4,159 | 0.001443 | # -*- coding: utf-8 -*-
# Copyright (c) 2018 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division)
__metaclass__ = type
import json
import os
import shutil
import tempfile
import p... | = {'called': False} |
def mock_mkdtemp(prefix, dir):
return os.path.join(dir, prefix)
def mock_makedirs(path, mode):
makedirs['called'] = True
makedirs['path'] = path
makedirs['mode'] = mode
return
monkeypatch.setattr(tempfile, 'mkdtemp', mock_mkdtemp)
... |
sander76/home-assistant | homeassistant/components/demo/sensor.py | Python | apache-2.0 | 3,738 | 0.000268 | """Demo platform that has a couple of fake sensors."""
from __future__ import annotations
from typing import Any
from homeassistant.components.sensor import STATE_CLASS_MEASUREMENT, SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
CONCENTR... | DemoSensor(
"sensor_5",
"Power consumption",
100,
DEVICE_CLASS_POWER,
STATE_CLASS_MEASUREMENT,
POWER_WATT,
None,
),
DemoSensor(
"sensor_6",
| "Today energy",
15,
DEVICE_CLASS_ENERGY,
STATE_CLASS_MEASUREMENT,
ENERGY_KILO_WATT_HOUR,
None,
),
]
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities... |
ocket8888/slackbot | slackbot/modules/patch/patch.py | Python | gpl-3.0 | 1,502 | 0.023302 | """
This module checks for the name of a supported game in the arguments to the api command, and
if found it reads the latest patch, printing it to the channel in which it was requested.
"""
import os.path
import typing
#I should probably find a way to utilize these
dota_synonymns=["dota", "Dota", "dota2", "Dota2"]
o... |
# If there isn't a game name, print and log an error
if len(args) == 0:
slackAPI.chat.post_message(channel['name'], "Not eno | ugh arguments to `!patch`. Usage: `!patch <game>`")
return "WW: patch: not enough arguments"
# Read in the patch notes from the file if it exists
datfile = "/etc/slackbot/modules/patch/" + args[0]
if os.path.isfile(datfile):
patchnotes = open('/etc/slackbot/modules/patch/'+args[0]).read()
slackAPI.chat.post_m... |
prometheanfire/openstack-guest-agents-unix | commands/kms.py | Python | apache-2.0 | 1,790 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (c) 2011 Openstack, LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); yo | u may
# not use this file exce | pt in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITI... |
uclouvain/OSIS-Louvain | base/migrations/0017_person_language.py | Python | agpl-3.0 | 520 | 0.001927 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-25 11:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bas | e', '0016_auto_20160224_1039'),
]
operations = [
migrations.AddField(
model_name='person',
name='language',
field=models.CharField(choices=[('FR', 'Français'), ('EN', 'English')], default=' | FR', max_length=30, null=True),
),
]
|
Tapo4ek/django-banzai | banzai/migrations/0001_initial.py | Python | mit | 4,368 | 0.008013 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Package'
db.create_table('banzai_package', (
('id', self.gf('django.db.models.fi... | lds.CharField', [], {'max_length': '4', 'blank': 'True'})
},
'banzai.report': {
'Meta': {'object_name': 'Report'},
'email': ('django.db.models.fields.EmailField', [], {'ma | x_length': '75'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'package': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['banzai.Package']"}),
'reject_code': ('django.db.models.fields.CharField', [], {'max_length': '250'}),
'r... |
lucasa/landell_gst-gengui | sltv/gstmanager/sbins/source.py | Python | gpl-2.0 | 601 | 0.009983 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class AVSource(object):
def __init__(self, sbin_conten | t):
self.tags = ["a_src", "v_src"]
#self.sbin = "%s ! queue ! tee name=%s_tee" %(sbin_content, self.tags[0])
self.sbin = sbin_content
class AudioSource(object):
def __init__(self, sbin_content):
self.tags = ["a_src"]
self.sbin = "%s ! tee name=%s_tee" %(sbin_content, self.ta... | self.sbin = "%s ! tee name=%s_tee" %(sbin_content, self.tags[0])
|
wordsforthewise/shinyei-ppd42ns-arduino | plotdustlive.py | Python | mit | 995 | 0.047236 | import pylab as plt
import pickle, csv, matplotlib, time
import numpy as np
import matplotlib.dates as mdates
import pandas as pd
import matplotlib.animation as animation
| def get_data(file):
with open(file,'rb') as f:
data=pickle.load(f)
f.close()
counter=0
dates=[]
dustdata=[]
for each in data:
if counter%2==0:
dates.append(each)
else:
dustdata.append(str(each).split(',')[2])
counter+=1
return dates, dustdata
def animate(i):
da | tes,dustdata=get_data('dustdata')
dates = matplotlib.dates.date2num(dates)
dustdata=np.array(dustdata)
ax.plot_date(dates, dustdata,c='grey')
ax.plot_date(dates, pd.rolling_mean(dustdata,20),'w-',linewidth=4)
return
fig = plt.figure(facecolor='k')
ax = fig.add_subplot(111,axisbg='k')
ax.xaxis.set_maj... |
nish10z/CONCUSS | lib/coloring/basic/trans_frater_augmentation.py | Python | bsd-3-clause | 1,365 | 0.000733 | #!/usr/bin/python
#
# This file is part of CONCUSS, https://github.com/theoryinpractice/concuss/,
# | and is Copyright (C) North Carolina State University, 2015. It is licensed
# under the three-clause BSD license; see LICENSE.
#
from lib.util.memori | zed import memorized
from lib.graph.graph import Graph
# Calculate one transitive-fraternal-augmentation-step and
# result a tuple (newgraph, transedges, fratedges)
@memorized(['orig', 'step'])
def trans_frater_augmentation(orig, g, trans, frat, col,
nodes, step, td, ldoFunc):
fratGr... |
shoopio/shoop | shuup/admin/modules/products/views/edit_parent.py | Python | agpl-3.0 | 3,373 | 0.001779 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from django.http import HttpResponseRedir... | rgs={"pk": parent.id}))
return super(ProductParentBaseView, self).dispatch(request, *args, **kwargs)
def get_breadcrumb_parents(self):
return [MenuEntry(text=self.object, url=get_model_url(self.object, shop=self.request.shop))]
def post(self, reque | st, *args, **kwargs):
command = request.POST.get("command")
if command:
return self.dispatch_command(request, command)
return super(ProductParentBaseView, self).post(request, *args, **kwargs)
def get_form_part_classes(self):
for form_part_class in self.form_part_classes:... |
ivanamihalek/blender | texture_shadow_no_bg/cube_to_png.py | Python | gpl-2.0 | 10,222 | 0.007826 | #!bpy
"""
to run:
(aAtually I have not been able to run this from command line - the thing
exits without rendering. If I add bpy.ops.render, it alwys renders layers, rather
then compositing output)
blender -b --python this_fnm.py
"""
import bpy
from math import radians
import fnmatch
import os
####################... | "main"
render_layers.new("shadow")
render_layers["main"].layers = [l==0 for l in range(20)]
render_layers["shadow"].layers = [l==1 for l in range(20)]
render_layers["shadow"].use_pass_s | hadow = True
scene.layers[0] = True
scene.layers[1] = True
# and now ... compositing!
# I'll want transaprent background
scene.cycles.film_transparent = True
# switch on nodes and get reference
scene.use_nodes = True
tree = scene.node_tree
# the default nodes are Composite an... |
michaupl/materialsapp | finishes/admin.py | Python | apache-2.0 | 1,110 | 0.003604 | # coding: utf-8
from __future__ import unicode_literals
from django.contrib import admin
from core.admin import SubcategoryAdmin, DetailAdmin
from .models import FinishDetail, FinishSubcategory
class FinishSubcategoryAdmin(SubcategoryAdmin):
def get_form(self, request, obj=None, **kwargs):
from | . import DETAIL_TYPE
form = super(Fi | nishSubcategoryAdmin, self).get_form(request, obj, **kwargs)
if 'category' in form.base_fields:
field = form.base_fields['category']
field.queryset = field.queryset.filter(type=DETAIL_TYPE)
return form
admin.site.register(FinishSubcategory, FinishSubcategoryAdmin)
class Finish... |
apy2017/Anaconda | technobot/__init__.py | Python | mit | 6,849 | 0.001752 | from technobot import api
from technobot import utils
from threading import Timer
from functools import wraps
import re
import copy
import logging
logging.basicConfig(level = logging.DEBUG)
class TechnoBot:
def __init__(self, token, exit_button=None, ignore_old=False, timeout=3):
self.token = ... |
if message is None: return
self._process_conversation(message)
self._process_handlers(message)
def _process_updat | es(self):
self._receive_updates()
self._thread.cancel()
for update_id, update in self._updates.items():
message = update.message
if message is None: break
self._process_conversation(message)
self._process_handlers(message)
self._t... |
paninetworks/neutron | neutron/extensions/quotasv2.py | Python | apache-2.0 | 5,149 | 0 | # Copyright 2011 OpenStack Foundation.
# 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 req... | check_admin(context)
return {self._resource_name + "s":
self._driver.get_all_quotas(context, QUOTAS.resources)}
def tenant(self, request):
"""Retrieve the tenant info in context."""
context = request.context
if not context.tenant_id:
raise n_e | xc.QuotaMissingTenant()
return {'tenant': {'tenant_id': context.tenant_id}}
def show(self, request, id):
if id != request.context.tenant_id:
self._check_admin(request.context,
reason=_("Only admin is authorized "
"to a... |
dnacreative/jam-py | tests/server.py | Python | bsd-3-clause | 232 | 0 | #!/usr/bin/env python
# - | *- coding: utf-8 -*-
if __name__ == '__main__':
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
im | port jam.webserver
from jam.server import server
jam.webserver.run(server)
|
gratefulfrog/ArduGuitar | Ardu2/design/POC-3_MAX395/pyboard/DraftDevt/dbh.py | Python | gpl-2.0 | 761 | 0.027595 | #!/usr/local/bin/python3.4
# dbh.ph debounce hardware
"""
Pyboard:
Switch pins: Y1 or X19
usage:
>>> init()
>>> loop()
"""
from pyb import ExtInt,Pin
# declare the pin id
pinId = 'X19' # interrupt 0 'Y1' # interrupt 6
# itnerrupt mechanics and debounce globals
flag= False
interCount=0
eObj = None
# define ISR
d... | try:
while True:
if flag>0:
doFlag()
except KeyboardInterrupt:
print('Test ended!\nBye . | ..')
|
sbobovyc/GameTools | TSW/src/rdbdata.py | Python | gpl-3.0 | 1,836 | 0.006536 | """
Copyright (C) 2013 Stanislav Bobovych
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 h... | _pointer.tell()
file_pointer.seek(offset)
self.data_type, = struct.unpack("<I", file_pointer.read(4) | )
self.RDB_id, = = struct.unpack("<I", file_pointer.read(4))
self.data_length, = struct.unpack("<I", file_pointer.read(4))
self.unknown, = struct.unpack("<I", file_pointer.read(4))
self.data = file_pointer.read(self.data_length)
file_pointer.seek(old_offset)
class RDBDAT... |
teamfx/openjfx-8u-dev-rt | modules/web/src/main/native/Source/JavaScriptCore/Scripts/builtins/builtins_generate_wrapper_implementation.py | Python | gpl-2.0 | 2,485 | 0.000402 | #!/usr/bin/env python
#
# Copyright (c) 2016 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain | the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWA... | SS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
# 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
# INTE... |
sharoonthomas/clearstate | clearstate/public/views.py | Python | bsd-3-clause | 2,490 | 0 | # -*- coding: utf-8 -*-
'''Public section, including homepage and signup.'''
from flask import (
Blueprint, request, render_template, flash, url_for,
redirect, session
)
from flask.ext.login import login_user, login_required, logout_user
from clearstate.extensions import login_manager
from clearstate.user.mode... | ame
# If there are no matches, are there any pages or users at all ?
if not users_exist():
return redirect(url_for('user.initial_setup'))
else:
return redirect(url_for('pages.pages'))
@blueprint.route("/login", methods=["GET", "POST" | ])
def login():
form = LoginForm(request.form)
# Handle logging in
if request.method == 'POST':
if form.validate_on_submit():
login_user(form.user)
flash("You are logged in.", 'success')
redirect_url = request.args.get("next") or \
url_for("pages.p... |
DominikDitoIvosevic/Uni | AI/lab2/ghostAgents.py | Python | mit | 3,390 | 0.019174 | # ghostAgents.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.e... | tate( self.index )
legalActions = state.getLegalActions( self.index )
pos = state.getGhostPosition( self.index )
isScared = ghostState.scaredTimer > 0
speed = 1
if isScared: speed = 0.5
actionVectors = [Actions.directionToVector( a, speed ) for a in legalActions]
... | nPosition = state.getPacmanPosition()
# Select best actions given the state
distancesToPacman = [manhattanDistance( pos, pacmanPosition ) for pos in newPositions]
if isScared:
bestScore = max( distancesToPacman )
bestProb = self.prob_scaredFlee
else:
... |
vitay/ANNarchy | ANNarchy/parser/report/LatexParser.py | Python | gpl-2.0 | 16,861 | 0.007532 | from sympy import *
from sympy.parsing.sympy_parser import parse_expr, standard_transformations, convert_xor, auto_number
from sympy.printing.latex import LatexPrinter
import re
import ANNarchy.core.Global as Global
from ANNarchy.core.Random import RandomDistribution
from ..Extraction import *
from ANNarchy.parser.Ana... | rget',
'fourthtarget',
'fifthtarget',
'si | xthtarget',
'seventhtarget',
'eighthtarget',
'ninthtarget',
'tenthtarget',
]
def _process_neuron_equations(neuron):
code = ""
# Extract parameters and variables
parameters = extract_parameters(neuron.parameters, neuron.extra_values)
variables = extract_variables(neuron.equations)
v... |
TylerTemp/tomorrow | lib/ui/error.py | Python | gpl-3.0 | 4,288 | 0.000233 | import logging
import os
import base64
try:
from io import BytesIO
except ImportError:
try:
from cStringIO import StringIO as BytesIO
except ImportError:
from StringIO import StringIO as BytesIO
import tornado.web
import cairocffi as cairo
from lib.config.tomorrow import Config
from lib.too... |
bg_context.set_source_surface(num_surface, x, y)
bg_context.paint()
result = BytesIO()
source.write_to_png(result)
| return result.getvalue()
def find_position(self, s_width, s_height, b_width, b_height):
left = (b_width - s_width) / 2.0
top = (b_height - s_height) / 2.0
return (left, top)
def get_num_file(self, num):
with open(os.path.join(self.base, '%s.png' % num), 'rb') as f:
... |
simbs/edx-platform | lms/djangoapps/instructor_task/tests/test_api.py | Python | agpl-3.0 | 13,801 | 0.003623 | """
Test for LMS instructor background task queue management
"""
from mock import patch, Mock
from bulk_email.models import CourseEmail, SEND_TO_ALL
from courseware.tests.factories import UserFactory
from xmodule.modulestore.exceptions import ItemNotFoundError
from instructor_task.api import (
get_running_instruct... | rTaskModuleTestCase.problem_location(problem_url_name)
if student is not None:
instructor_task = task_function(self.create_task_request(self.instructor), location, student)
else:
instructor_task | = task_function(self.create_task_request(self.instructor), location)
# test resubmitting, by updating the existing record:
instructor_task = InstructorTask.objects.get(id=instructor_task.id)
instructor_task.task_state = PROGRESS
instructor_task.save()
with self.assertRaises(Al... |
ljx0305/ice | scripts/tests/Ice/properties.py | Python | gpl-2.0 | 1,004 | 0.005976 | # -*- coding: utf-8 -*-
# **********************************************************************
#
# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# ***********************************... | ,
["# Automatically generated by Ice test driver.",
"Ice.Trace.Protocol=1",
"Ice.Trace.Network=1",
"Ice.ProgramName=PropertiesClient",
| "Config.Path=./config/" + name],
"utf-8")
PropertiesTestSuite(__name__, [ ClientTestCase(client=Client(args=["{testdir}"])) ])
|
memsharded/conan | conans/test/integration/install_outdated_test.py | Python | mit | 8,169 | 0.002938 | import time
import unittest
from collections import OrderedDict
from conans.model.ref import ConanFileReference
from conans.test.utils.cpp_test_files import cpp_hello_conan_files
from conans.test.utils.tools import TestClient, TestServer, TurboTestClient, GenConanfile
from conans.util.env_reader import get_env
from co... | p to date", self.client.user_io.out)
# Then we can export a modified recipe and try to install without --build outdated
files = | cpp_hello_conan_files("Hello0", "0.1", build=False)
files["conanfile.py"] += "\n#Otherline"
self.client.save(files)
self.client.run("export . lasote/stable")
self.client.run("install Hello0/0.1@lasote/stable")
self.assertIn("Hello0/0.1@lasote/stable: Already installed!", self.cli... |
IPMITMO/statan | coala-bears/bears/css/StyleLintBear.py | Python | mit | 7,474 | 0 | import json
from coalib.bearlib.abstractions.Linter import linter
from dependency_management.requirements.NpmRequirement import NpmRequirement
@linter(executable='stylelint',
output_format='regex',
output_regex=r'\s*(?P<filename>.+)\s*(?P<line>\d+):(?P<column>\d+)\s*'
r'\D\s*(?P<m... | alues']}
]
rules['declaration-empty-line-before'] = [
'always',
{'except': | ['after-declaration', 'first-nested'],
'ignore': ['after-comment', 'inside-single-line-block']}
]
rules['rule-nested-empty-line-before'] = [
'always-multi-line',
{'except': ['first-nested'], 'ignore': ['after-comment']}
]
rules['rule-non-nested-empty-li... |
griffy/sikwidgets | sikwidgets/window.py | Python | mit | 3,281 | 0.003048 | import types
from sikwidgets.region_group import RegionGroup
from sikwidgets.util import to_snakecase
from sikwidgets.widgets import *
def gen_widget_method(widget_class):
def widget(self, *args, **kwargs):
return self.create_widget(widget_class, *args, **kwargs)
return widget
class Window(RegionGroup... | = region
self.widgets = []
self.windows = []
self.add_widget_methods()
self.contains()
# FIXME: str() shouldn't return a URI.. use image_folder() method for this
def __str__(self):
uri = to_snakecase(self.__class__.__name__)
if self.parent:
uri = os.... | )
for window in self.windows:
window.create_image_folders()
def capture_screenshots(self):
for widget in self.widgets:
widget.capture_screenshots()
for window in self.windows:
window.capture_screenshots()
def contains(self):
pass
... |
shedskin/shedskin | shedskin/graph.py | Python | gpl-3.0 | 71,909 | 0.002336 | '''
*** SHED SKIN Python-to-C++ Compiler ***
Copyright 2005-2013 Mark Dufour; License GNU GPL version 3 (See LICENSE)
graph.py: build constraint graph used in dataflow analysis
constraint graph: graph along which possible types 'flow' during an 'abstract execution' of a program (a dataflow analysis). consider the ass... | s[newnode] = set()
fakefunc = CallFunc(Getattr(objexpr, attrname), args)
fakefunc.lineno = objexpr.lineno
self.visit(fakefunc, func)
self.add_constraint((inode(self.gx, fakefunc), newnode), func)
inode(self.gx, objexpr).fakefunc = fakefun | c
return fakefunc
# simple heuristic for initial list split: count nesting depth, first constant child type
def list_type(self, node):
count = 0
child = node
while isinstance(child, (List, ListComp)):
if not child.getChildNodes():
return None
... |
google-research/data-driven-advection | datadrivenpdes/core/readers_test.py | Python | apache-2.0 | 6,924 | 0.001155 | # python3
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | .get_output_grid(dataset_metadata)
high_res_grid = readers.get_simulation_grid(dataset_metadata)
equation = readers.get_equation(dataset_metadata)
self.assertEqual(low_re | s_grid.size_x, low_resolution)
self.assertEqual(low_res_grid.size_y, low_resolution)
self.assertEqual(high_res_grid.size_x, high_resolution)
self.assertEqual(high_res_grid.size_y, high_resolution)
self.assertAlmostEqual(high_res_grid.step, 2 * np.pi / high_resolution)
self.assertAlmostEqual(
... |
dan-cristian/haiot | main/persistence/__init__.py | Python | gpl-2.0 | 5,411 | 0.005729 | from common import Constant
from common import utils
from main.logger_helper import L
__author__ = 'Dan Cristian <dan.cristian@gmail.com>'
# saves record to cloud database
def save_to_history_cloud(obj):
try:
L.l.debug('Trying to save historical record to cloud {}'.format(obj))
if Constant.JSON_P... | ppend history to source table name
dest_table = str(table) + 'History'
# L.l.debug('Saving to local db table {} obj={}'.format(dest_table, obj))
from storage.sqalc import models
# http://stackoverflow.com/questions/4030982/initialise-class-object-by-name
try:
class_ta... | field) and field != "id":
setattr(new_record, field, obj[field])
if new_record.add_commit_record_to_db():
# L.l.debug('Saved OK to local db table {} obj={}'.format(dest_table, new_record))
pass
else:
L.l.critical("Cannot save hi... |
Affirm/cabot | cabot/cabotapp/utils.py | Python | mit | 2,425 | 0.006186 | from django.conf import settings
from mock import Mock
from cabot.cabotapp import defs
from datetime import datetime
def build_absolute_url(relative_url):
"""Prepend https?://host to a url, useful for links going into emails"""
return '{}://{}{}'.format(settings.WWW_SCHEME, settings.WWW_HTTP_HOST, relative_ur... | ck = Mock()
service_mock.configure_mock(id=0, pk=0, name='Alert Testing Service', alerts_enabled=True,
# plugins use service.CRITICAL_STATUS etc, so we mock these constants too
CRITICAL_STATUS=defs.CRITICAL_STATUS, PASSING_STATUS=defs.PASSING_STATUS,
... | defs.ERROR_STATUS,
status_checks=[check_mock], recent_snapshots=[],
overall_status=defs.CRITICAL_STATUS,
active_status_checks=lambda: [check_mock],
all_passing_checks=lambda: [], all_failing_c... |
bhpayne/domino_tile_floor | transitions/domino_tiles_transition_graph_breadth_first_multiprocessing.py | Python | apache-2.0 | 5,268 | 0.019172 | #!/usr/bin/env python3
# http://sebastianraschka.com/Articles/2014_multiprocessing.html
import multiprocessing as mp
import yaml
# Define an output queue
output = mp.Queue()
def create_transition_dic(width,height):
transition_dic={}
num_tiles=width*height
# print("width= "+str(width))
# print("height=... | )+"\n")
# print("list of transitions:")
# print_list_of_transitions(list_of_transitions)
# return list_of_transitions
f.close()
output.put(list_of_transitions)
# these values get over-written by the config.yaml values
width=4
height=4
#starting_value=1
number_of_p | rocesses=4
try:
config = yaml.load(file('config.yaml', 'r'))
except yaml.YAMLError, exc:
print "Error in configuration file:", exc
config=yaml.load(file('config.yaml','r'))
width=config['width']
height=config['height']
number_of_processes=config['num_proc']
number_of_tiles_to_fill=width*height
transition_di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.