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 |
|---|---|---|---|---|---|---|---|---|
tovmeod/anaf | anaf/core/middleware/domain.py | Python | bsd-3-clause | 1,463 | 0.000684 | """
Domain middleware: enables multi-tenancy in a single process
"""
from anaf.core.domains import setup_domain, setup_domain_database
from anaf.core.db import DatabaseNotFound
from anaf.core.conf import settings
from django.http import HttpResponseRedirect
from django.db.utils import DatabaseError
from django.core.url... | if isinstance(exception, DatabaseNotFound):
evergreen_url = getattr(
settings, 'EV | ERGREEN_BASE_URL', 'http://tree.io/')
return HttpResponseRedirect(evergreen_url)
|
alephobjects/Cura2 | plugins/LegacyProfileReader/LegacyProfileReader.py | Python | lgpl-3.0 | 10,008 | 0.006695 | # Copyright (c) 2017 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import configparser # For reading the legacy profile INI files.
import io
import json # For reading the Dictionary of Doom.
import math # For mathematical operations included in the Dictionary of Doom.
import os.path # ... | he old ones.
#
# This fills a dictionary with all settings from the legacy Cura version
# and their values, so that they can be used in evaluating the new setting
# values as Python code.
#
# \param config_parser The ConfigParser that finds t | he settings in the
# legacy profile.
# \param config_section The section in the profile where the settings
# should be found.
# \param defaults The default values for all settings in the legacy Cura.
# \return A set of local variables, one for each setting in the legacy
# profile.
... |
krux/adspygoogle | examples/adspygoogle/dfp/v201204/get_user.py | Python | apache-2.0 | 1,504 | 0.001995 | #!/usr/bin/python
#
# Copyright 2012 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 b... | m)'
# Locate the client library. If module was installed via "setup.py" script, then
# the following two lines are not needed.
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
# Import appropriate classes from the client library.
from adspygoogle import DfpClient
# Initialize client obj... | ent = DfpClient(path=os.path.join('..', '..', '..', '..'))
# Initialize appropriate service.
user_service = client.GetService('UserService', version='v201204')
# Set the id of the user to get.
user_id = 'INSERT_USER_ID_HERE'
# Get user.
user = user_service.GetUser(user_id)[0]
# Display results.
print ('User with id... |
menzenski/django-year-end-site | yearendsite/wsgi.py | Python | mit | 399 | 0 | """
W | SGI config for yearendsite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTIN... | lication = get_wsgi_application()
|
jdemel/gnuradio | grc/gui/Dialogs.py | Python | gpl-3.0 | 15,494 | 0.002259 | # Copyright 2008, 2009, 2016 Free Software Foundation, Inc.
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
from __future__ import absolute_import
import sys
import textwrap
from distutils.spawn import find_executable
from gi.repository import Gtk, GLib
from . import Utils, Actions... | efault_response:
self.set_default_response(default_response)
def run_and_destroy(self):
response = self.run()
self.hide()
return response
class ErrorsDialog(Gtk.Dialog):
""" Display flowgraph errors. """
def __init__(self, parent, flowgraph):
"""Create a listv... | e,
destroy_with_parent=True,
)
self.add_buttons(Gtk.STOCK_OK, Gtk.ResponseType.ACCEPT)
self.set_size_request(750, Constants.MIN_DIALOG_HEIGHT)
self.set_border_width(10)
self.store = Gtk.ListStore(str, str, str)
self.update(flowgraph)
self.treeview = ... |
dongguangming/python-github3 | pygithub3/requests/git_data/tags.py | Python | isc | 412 | 0 | # -*- encoding: utf-8 -*-
from pygithub3.requests.base import Re | quest
from pygithub3.resources.git_data import Tag
class Get(Request):
uri = 'repos/{user}/{repo}/git/tags/{sha}'
resource = Tag
class Create(Request):
uri = 'repos/{user}/{repo}/git/tags'
resource = Tag
body_schema = {
'schema': ('tag', 'message', 'object', 'type', 'tagger' | ),
'required': ('type',),
}
|
jbrinley/HocrConverter | HocrConverter.py | Python | mit | 5,986 | 0.019044 | from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.units import inch
from xml.etree.ElementTree import ElementTree
import Image, re, sys
class HocrConverter():
"""
A class for converting documents to/from the hOCR format.
For details of the hOCR format, see:
http://docs.google.com/View?docid... | a warning
print "Warning: DPI unavailable for image %s. Assuming 96 DPI."%(imageFileName)
width = float(im.size[0])/96
height = float(im.size[1])/96
# create the PDF file
pdf = Canvas(outFileName, pagesize=(width*inch, height*inch), pageCompression=1) # page size in points (1/72 in.)
... | for line in self.hocr.findall(".//%sspan"%(self.xmlns)):
if line.attrib['class'] == 'ocr_line':
coords = self.element_coordinates(line)
text = pdf.beginText()
text.setFont(fontname, fontsize)
text.setTextRenderMode(3) # invisible
# set cursor to botto... |
fausthuang/faust-s-test-repo | hello world.py | Python | gpl-2.0 | 76 | 0.013158 | print "hello"
print "world | "
print | "hello world"
print hello world
end
haha
|
INRA-LPGP/bio_tools | bio_tools/parameters/type_checks.py | Python | mit | 1,406 | 0 | import os
from distutils.util import strtobool
def is_int(value):
"""
Verifies that 'value' is an integer.
"""
try:
int(value)
except ValueError:
return False
else:
return True
def is_float(value):
"""
Verifies that 'value' is a float.
"""
try:
... | ""
Verifies that 'value' is a path to an existing file.
"""
if not (type(value) is str and os.path.isfile(value)):
return False
else:
return True
def is_file_o(value):
"""
Verifies that 'value' is a path to a valid directory to create an output
file.
"""
if not (typ... | ) is str and os.path.split(value)[0]):
return False
else:
return True
|
jkonecny12/anaconda | docs/conf.py | Python | gpl-2.0 | 11,653 | 0.006522 | # -*- coding: utf-8 -*-
#
# Anaconda documentation build configuration file, created by
# sphinx-quickstart on Wed Sep 18 14:37:01 2013.
#
# 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.
#
# Al... | for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Def | ault is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or... |
AlexandreDecan/Dashbird | widgets/schoolwidget/migrations/0001_initial.py | Python | gpl-3.0 | 2,474 | 0.005255 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='MissingTeacherEntry',
fields=[
('id', models.Au... | ty', models.BooleanField(default=True, help_text="Masque les heures de cours pour lesquelles aucuneinformation n'a \xe9t\xe9 entr\xe9e.", verbose_name='Cacher les \xe9l\xe9ments vides')),
| ],
options={
'verbose_name': 'enseignant absent',
'verbose_name_plural': 'enseignants absents',
},
bases=(models.Model,),
),
migrations.AddField(
model_name='missingteacherentry',
name='widget',
field... |
google/CFU-Playground | proj/hps_accel/gateware/gen1/set.py | Python | apache-2.0 | 4,133 | 0 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | o gateware.
Attributes
----------
output: Endpoint(unsigned(32))
An output stream of values. A new value onto the stream whenever
the register is set.
value: unsigned(32), out
The value held by the register.
new_en: Signal(1), in
Indicates to register that a new value is ... | super().__init__()
self.output = Endpoint(unsigned(32))
self.value = self.output.payload
self.new_en = Signal()
self.new_value = Signal(32)
def elab(self, m):
with m.If(self.output.is_transferring()):
m.d.sync += self.output.valid.eq(0)
with m.If(self.n... |
morelab/weblabdeusto | server/src/weblab/core/coordinator/checker.py | Python | bsd-2-clause | 5,307 | 0.006785 | #!/usr/bin/env python
#-*-*- encoding: utf-8 -*-*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individual... | laboratory_resource in broken_resources:
notifications = self.coordinator.mark_resource_as_broken(laboratory_resource, broken_resources[laboratory_resource])
else:
notifications = self.coordinator.mark_resource_as_fixed(laboratory_resource)
... | all_notifications[recipients].extend(notifications[recipients])
else:
all_notifications[recipients] = list(notifications[recipients])
if all_notifications:
self.coordinator.notify_status(all_notifications)
except... |
cactusbin/nyt | matplotlib/examples/event_handling/data_browser.py | Python | unlicense | 2,233 | 0.011196 | import numpy as np
class PointBrowser:
"""
Click on a point to select and highlight it -- the data that
generated the point will be shown in the lower axes. Use the 'n'
and 'p' keys to browse through the next and previous points
"""
def __init__(self):
self.lastind = 0
self.t... | browser = PointBrowser()
fig.canvas.mpl_connect('pick_event', browser.onpick)
fig.canv | as.mpl_connect('key_press_event', browser.onpress)
plt.show()
|
facelessuser/sublime-markdown-popups | st3/mdpopups/pygments/lexers/pascal.py | Python | mit | 32,536 | 0.001014 | # -*- coding: utf-8 -*-
"""
pygments.lexers.pascal
~~~~~~~~~~~~~~~~~~~~~~
Lexers for Pascal family languages.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from ..lexer import Lexer, RegexLexer, include, bygroups, words, ... | ir', 'move', 'new', 'odd',
'olestrtostring', 'olestrtostrvar', 'ord', 'paramcount',
'paramstr', 'pi', 'pos', 'pred', 'ptr', 'pucs4chars', 'random',
'randomize', 'read', 'readln', 'reallocmem',
'releaseexceptionobject', 'rename', 'reset', | 'rewrite', 'rmdir',
'round', 'runerror', 'seek', 'seekeof', 'seekeoln',
'set8087cw', 'setlength', 'setlinebreakstyle',
'setmemorymanager', 'setstring', 'settextbuf',
'setvariantmanager', 'sin', 'sizeof', 'slice', 'sqr', 'sqrt',
'str', 'stringofchar', 'stringto... |
vileopratama/vitech | docs/tutorials/ebook/Odoo Development Cookbook/OdooDevelopmentCookbook_Code/Chapter06_code/Ch06_R05/some_model_ch06r05/models.py | Python | mit | 913 | 0 | # coding: utf-8
from openerp import models, ap | i, fields
class LibraryReturnsWizard(models.TransientModel):
_name = 'library.returns.wizard'
member_id = fields.Many2one('library.member', 'Member')
book_ids = fields.Many2many('library.boo | k', 'Books')
@api.multi
def record_returns(self):
loan = self.env['library.book.loan']
for rec in self:
loans = loan.search(
[('state', '=', 'ongoing'),
('book_id', 'in', self.book_ids.ids),
('member_id', '=', self.member_id.id)]
... |
RexChenjq/AWS-Image-Backup | purge latest.py | Python | mit | 2,667 | 0.009374 | import boto3
import collections
import datetime
import time
import sys
import botocore
ec2_client = boto3.client('ec2',region_name='ap-southeast-2')
ec2_resource = boto3.resource('ec2',region_name='ap-southeast-2')
sns = boto3.client('sns')
images_all = ec2_resource.images.filter(Owners=["self"])
today_fmt = (datetime... | lambda_handler(event, context):
try:
images_to_remove=[]
toremoveimagecount = 0
snapshotcount = 0
totalimagecount=0
for image in images_all:
if (image.name.startswith('Lambda-')):
totalimagecount+=1
try:
if imag... | f t['Key'] == 'DeleteOn'][0]
delete_date = time.strptime(deletion_date, "%Y-%m-%d")
except IndexError:
deletion_date = False
delete_date = False
if delete_date <= today_date:
images_to_remove.append(image... |
e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/module_utils/facts/network/dragonfly.py | Python | bsd-3-clause | 1,202 | 0.000832 | # This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eithe | r version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 shou... | have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.facts.network.base import NetworkCollector
from ansible.module_utils.facts.network... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/nbconvert/preprocessors/convertfigures.py | Python | bsd-2-clause | 1,450 | 0.002759 | """Module containing a preprocessor | that converts outputs in the notebook from
one format to another.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD Li | cense.
from .base import Preprocessor
from traitlets import Unicode
class ConvertFiguresPreprocessor(Preprocessor):
"""
Converts all of the outputs in a notebook from one format to another.
"""
from_format = Unicode(help='Format the converter accepts').tag(config=True)
to_format = Unicode(help=... |
dianvaltodorov/happy-commas | db_create.py | Python | mit | 566 | 0 | #!env/bin/python
"""Create the database"""
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
from app import db
import os.path
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIGRATE_REPO, 'database reposit... | l(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
else:
api.version_control(SQLALCHEMY_DATABASE_URI,
| SQLALCHEMY_MIGRATE_REPO,
api.version(SQLALCHEMY_MIGRATE_REPO))
|
jittat/adm2 | application/views/update.py | Python | agpl-3.0 | 12,858 | 0.003085 | # -*- coding: utf-8 -*-
import datetime
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.conf import settings
from django import forms
from commons.decorators import submitted_applicant_required
from commons.decorator... | ionality = forms.CharField(label="สัญชาติ")
ethnicity = forms.CharField(label="เชื้อชาติ")
def clean_phone_number(self):
if not validate_phone_number(self.cleaned_data['phone_number']):
raise forms.ValidationError("หมายเลขโทรศัพท์ไม่ถูกต้อง")
return self.cleaned_data['phone_... | ine
@submitted_applicant_required
def update_personal_info(request):
applicant = reques |
jokkebk/euler | p144.py | Python | mit | 538 | 0.013011 | inside = lambda | x, y: 4*x*x+y*y <= 100
def coll(sx, sy, dx, dy):
m = 0
for p in range(32):
m2 = m + 2**(-p)
if inside(sx + dx * m2, sy + dy * m2): m = m2
return (sx + dx*m, sy + dy*m)
def norm(x, y):
l = (x*x + y*y)**0.5
return (x/l, y/l)
sx, sy = 0, 10.1
dx, dy = 1.4, -19.7
for I in range(999)... | + 2 * my * d
|
lukas/ml-class | examples/keras-transfer/resnet50-inspect.py | Python | gpl-2.0 | 517 | 0.001934 | from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image |
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
model = ResNet50(weights='imagenet')
img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
model.summ... | :', decode_predictions(preds, top=3)[0])
|
abutcher/openshift-ansible | roles/lib_openshift/src/lib/base.py | Python | apache-2.0 | 21,696 | 0.001244 | # pylint: skip-file
# flake8: noqa
# pylint: disable=too-many-lines
# noqa: E301,E302,E303,T001
class OpenShiftCLIError(Exception):
'''Exception class for openshiftcli'''
pass
ADDITIONAL_PATH_LOOKUPS = ['/usr/local/bin', os.path.expanduser('~/bin')]
def locate_oc_binary():
''' Find and return oc binar... | We are removing the 'resourceVersion' to handle
# a race condition when modifying oc objects
yed = Yedit(fname)
results = yed.delete('metadata.resourceVersion')
if results[0]:
| yed.write()
cmd = ['replace', '-f', fname]
if force:
cmd.append('--force')
return self.openshift_cmd(cmd)
def _create_from_content(self, rname, content):
'''create a temporary file and then call oc create on it'''
fname = Utils.create_tmpfile(rname + ... |
abhishekgahlot/unirest-python | setup.py | Python | mit | 431 | 0 | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='Unirest',
version='1.1.7',
| author='Mashape',
author_email='opensource@mashape.com',
packages=['unirest'],
url='https://github.com/Mashape/unirest-python',
license='LICENSE',
description='Simplified, lightweight HTTP client library',
install_requires=[
"poster >= 0.8.1"
]
) | |
birdland/dlkit-doc | dlkit/mongo/osid/summary_doc.py | Python | mit | 17,271 | 0 | # -*- coding: utf-8 -*-
"""Core Service Interface Definitions
osid version 3.0.0
The Open Service Interface Definitions (OSIDs) is a service-based
architecture to promote software interoperability. The OSIDs are a large
suite of interface contract specifications that describe the integration
points among services and ... | es are generally defined along lines of |
interoperability separating issues of data access from data management
and searching. These interfaces may also implement any of the abstract
behavioral interfaces listed above. The OSIDs do not adhere to a DAO/DTO
model in its service definitions in that there are service methods
defined on the objects (although they... |
jmorenobl/django-template-project-1.8 | project_name_project/config/settings/base.py | Python | mit | 9,481 | 0.004324 | """
Django settings for {{ project_name }} project.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_D... | },
},
]
# See: http://django-crispy-forms.readthedocs.org/en/latest/install.html#template-packs
CRISPY_TEMPLATE_PACK = 'bootstrap3'
########## END TEMPLATE CONFIGURATION
########## WSGI CONFIGURATION
# See: https://docs.djangoproject. | com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = 'config.wsgi.application'
########## END WSGI CONFIGURATION
########## INTERNATIONAL CONFIGURATION
# https://docs.djangoproject.com/en/1.8/topics/i18n/
# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone
TIME_ZONE = 'Europe/Madrid'
# See: ... |
google/tmppy | _py2tmp/utils/__init__.py | Python | apache-2.0 | 784 | 0 | # 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... | nder the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._ast_to_string import ast_to_s | tring
from ._clang_format import clang_format
from ._graphs import compute_condensation_in_topological_order
from ._ir_to_string import ir_to_string
|
paulcon/active_subspaces | tutorials/test_functions/borehole/borehole_functions.py | Python | mit | 2,595 | 0.035067 | import numpy as np
import active_subspaces as ac
def borehole(xx):
#each row of xx should be [rw, r, Tu, Hu, Tl, Hl, L, Kw] in the normalized space
#returns column vector of borehole function at each row of inputs
x = xx.copy()
x = np.atleast_2d(x)
M = x.shape[0]
#unnormalize inpus
... | x[:,2]; Hu = x[:,3]
Tl = x[:,4]; Hl = x[:,5]; L = x[:,6]; Kw = x[:,7]
pi = np.pi
return (2*pi*Tu*(Hu - Hl) | /(np.log(r/rw)*(1 + 2*L*Tu/(np.log(r/rw)*rw**2*Kw) + Tu/Tl))).reshape(M, 1)
def borehole_grad(xx):
#each row of xx should be [rw, r, Tu, Hu, Tl, Hl, L, Kw] in the normalized space
#returns matrix whose ith row is gradient of borehole function at ith row of inputs
x = xx.copy()
x = np.atleast_2... |
jyi/ITSP | prophet-gpl/tools/return_counter.py | Python | mit | 423 | 0.018913 | #!/usr/bin/env python
f = open("repair.log", "r");
lines = f.readl | ines();
cnt = 0;
for line in lines:
| tokens = line.strip().split();
if (len(tokens) > 3):
if (tokens[0] == "Total") and (tokens[1] == "return"):
cnt += int(tokens[3]);
if (tokens[0] == "Total") and (tokens[2] == "different") and (tokens[3] == "repair"):
cnt += int(tokens[1]);
print "Total size: " + str(cnt);
|
ploggingdev/djangochat | djangochat/urls.py | Python | gpl-3.0 | 817 | 0 | """djangochat 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')
Class... | RL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
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
url... | (r'^admin/', admin.site.urls),
]
|
natetrue/ReplicatorG | skein_engines/skeinforge-40/fabmetheus_utilities/geometry/manipulation_paths/_outset.py | Python | gpl-2.0 | 1,041 | 0.009606 | """
Create inset.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
i | mport __init__
from fabmetheus_utilities.geometry.creation import lineation
from fabmetheus_utilities.geometry.geometry_utilities import evaluate
from fabmetheus_utilities import intercircle
__author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
__credits | __ = 'Art of Illusion <http://www.artofillusion.org/>'
__date__ = '$Date: 2008/02/05 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
globalExecutionOrder = 80
def getManipulatedPaths(close, loop, prefix, sideLength, xmlElement):
"Get outset path."
radius = lineation.getS... |
GabMus/simpelblog | blog/models.py | Python | gpl-3.0 | 969 | 0.034056 | from django.db import models
class Article(models.Model):
posttitle = models.TextField(default="Post")
post = models.TextField()
piclink = models.TextField(blank=True)
pub_date = models.DateTimeField(auto_now_add=True)
class BlogPost(Article):
def __str__(self):
return self.posttitle
class PagePost(Article):
... | , null=True)
def __str__(self):
return self.tag+" "+self.posttitle
class Page(models.Model):
page_index = models.IntegerField(default=0)
name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.name
class Comment(models.Model):
name=models.CharField(max_length=20, blank=False)... | blank=False)
parent_article=models.ForeignKey('BlogPost', null=False)
pub_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.email+" "+self.parent_article.__str__()
|
duyuan11/glumpy | examples/interpolations.py | Python | bsd-3-clause | 4,303 | 0.008599 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014, Nicolas P. Rougier. All Rights Reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
""" Thi... | on_mouse_motion(x,y,0,0)
zoom = 0.25
program = gloo | .Program(vertex, fragment)
vertices = np.zeros((16+1,4),
[("position", np.float32, 2),
("texcoord", np.float32, 2),
("interpol", np.float32, 1)]).view(gloo.VertexBuffer)
vertices["position"][0] = (-1,+1), (-1,-1), (0,+1), (0,-1)
dx, dy = 1/4.0, 1/2.0
for j i... |
wrenchzc/photomanager | photomanager/db/imagehandler.py | Python | mit | 2,547 | 0.000785 | import os
from sqlalchemy import and_
from photomanager.lib.pmconst import TODO_INX_NAME
from photomanager.utils.imageutils import ImageInfo
from photomanager.db.helper import exif_to_model
from photomanager.db.models import ImageMeta
from photomanager.lib.helper import get_file_md5
from photomanager.db.config import C... |
"""
self.session = session
self.config = Config(self.session)
self.folder = folder
self.skip_exis | ted = skip_existed
self._on_index_image = None
@property
def on_index_image(self):
return self._on_index_image
@on_index_image.setter
def on_index_image(self, func_on_index_image):
assert callable(func_on_index_image)
self._on_index_image = func_on_index_image
def ... |
denverfoundation/storybase | apps/storybase_story/feeds.py | Python | mit | 4,815 | 0.003323 | from mimetypes import guess_type
from django.conf import settings
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.utils.text import Truncator
from django.utils.translation import ugettext as _
from storybase_asse... | ):
category_objs = list(item.projects.all()) + list(item.organizations.all()) + list(item.tags.all()) + list(item.topics.all())
return [obj.name for obj in category_objs | ]
def item_copyright(self, item):
return item.license_name()
def item_enclosure_url(self, item):
return item.featured_asset_thumbnail_url()
def item_enclosure_length(self, item):
asset = item.get_featured_asset()
thumbnail_options = {
'size': (FEATURED_ASSET_THUMB... |
brutasse/graphite-api | graphite_api/render/datalib.py | Python | apache-2.0 | 7,097 | 0 | """Copyright 2008 Orbitz WorldWide
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwa... | series.pathExpression = path_expr
series_list.append(series)
return series_list
def fetchData(requestContext, pathExprs):
from ..app import app
startTime = int(epoch(requestContext['startTime']))
endTime = int(epoch(requestContext['endTime']))
if 'now' i | n requestContext:
now = int(epoch(requestContext['now']))
else:
now = None
# Convert to list if given single path
if not isinstance(pathExprs, list):
pathExprs = [pathExprs]
data_store = DataStore()
multi_nodes = defaultdict(list)
single_nodes = []
path_to_exprs = ... |
rewiko/chat_django | chat/urls.py | Python | gpl-2.0 | 881 | 0.013652 | # -*- coding: utf-8 -*-
from chat.models import Message
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.auth.models import User
from django.views | .generic.list import ListView
# Uncomment the next two lines to enable the admin:
admin.autodiscover()
urlpatterns = patterns('chat.views',
# Nous allons réécrire l'URL de l'accueil
url(r'^check_messages_ajax', 'check_messages_ajax', name='check_messages_ajax'),
url(r'^connexion/$', 'connexion', name='co... | ),
url(r'^$', 'connexion', name='connexion'),
url(r'^add_message', 'add_message', name='add_message'),
url(r'^$', ListView.as_view(model=Message, context_object_name="derniers_messages",
template_name="message_list.html")),
)
|
alexandr-fonari/raman-sc | VASP/vasp_raman.py | Python | mit | 11,443 | 0.008914 | #!/usr/bin/env python
#
# Raman off-resonant activity calculator
# using VASP as a back-end.
#
# Contributors: Alexandr Fonari (Georgia Tech)
# Shannon Stauffer (UT Austin)
#
# MIT license, 2013
#
def parse_poscar_header(inp_fh):
import sys
from math import sqrt
#
inp_fh.seek(0) # just in... | [[0.0 for x in range(3)] for y in range(3)]
for j in range(len(disps)):
disp_filename = 'OUTCAR.%04d.%+d.out' % (i+1, disps[j])
#
| try:
|
mikehulluk/morphforge | doc/srcs_generated_examples/python_srcs/poster1.py | Python | bsd-2-clause | 4,063 | 0.007138 |
import matplotlib as mpl
mpl.rcParams['font.size'] = 14
from morphforge.stdimports import *
from morphforgecontrib.stdimports import *
eqnset_txt_na = """
define_component hh_na {
i = g * (v-erev) * m**3*h
m_inf = m_alpha_rate / (m_alpha_rate + m_beta_rate)
m_tau = 1.0 / (m_alpha_rate + m_beta... | , what='n', cell_location=cell.soma, user_tags=[StandardTags.StateVariable])
# Create t | he stimulus and record the injected current:
cc = sim.create_currentclamp(name="CC1", amp=qty("100:pA"), dur=qty("100:ms"), delay=qty("100:ms"), cell_location=cell.soma)
sim.record(cc, what=StandardTags.Current)
# run the simulation
results = sim.run()
TagViewer(results, timerange=(50, 250)*units.ms, show=True)
|
google/wasserstein-dist | compute_all.py | Python | apache-2.0 | 2,165 | 0.006467 | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | epattern,
label=i) for i in range(10)]
print('Computing Wasserstein distance(s)...')
for i in range(10):
for j in range(10):
with tf.Graph().as_default():
# compute Wasserstein distance between sets of labels i and j
wasserstein | = Wasserstein(dataset[i], dataset[j])
loss = wasserstein.dist(C=.1, nsteps=FLAGS.loss_steps)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
res = sess.run(loss)
print_flush('%f ' % res)
print_flush('\n')
if __name__ == '__main__':
tf.app.run(... |
tarzenda/gasp | tests/mockbackends.py | Python | gpl-3.0 | 772 | 0 | # -*- coding: utf-8 -*-
#
| # This program is part of GASP, a toolkit for newbie Python Programmers.
# Copyright (C) 2009, the GASP Development Team
#
# 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... | Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class MockBackEnd(object):
def __init__(self):
self.screen = None
self.rate = None
def create_screen(self, screen):
self.screen = screen
def set_frame_rate(self, rate):
self.rate = rate... |
skolsuper/imagedicer | imagedicer.py | Python | mit | 3,913 | 0.004856 | import Image
import os
import math
import argparse
# Set the root directory
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
HTML_DIR = os.path.join( | BASE_DIR, 'diced_images')
def dice(image_path, out_name, out_ext, outdir, slices):
img = Image.open(image_path) # Load image
imgdir = os.path.join(outdir, out_name)
if not os.path.exists(imgdir):
os.makedirs(imgdir)
imageWidth, imageHeight = img.size # Get image dimensions
# Make sure the... | s are bigger than the floats to avoid
# making 1px wide slices at the edges
sliceWidth = int(math.ceil(float(imageWidth) / slices))
sliceHeight = int(math.ceil(float(imageHeight) / slices))
percent = 100.0 / slices
html_file = open(os.path.join(HTML_DIR, out_name + '.html'), 'w+')
html_fi... |
sernst/cauldron | cauldron/test/cli/commands/test_alias.py | Python | mit | 2,067 | 0 | import os
from cauldron.test import support
from cauldron.test.support import scaffolds
class TestAlias(scaffolds.ResultsTest):
"""..."""
def test_unknown_command(self):
"""Should fail if the command is not recognized."""
r = support.run_command('alias fake')
self.assertTrue(r.faile... | te('This is a test')
support.run_command('alias add test "{}" --temporary'.format(path))
r = support.run_command('alias remove test --temporary')
self.assertFalse(r.failed, 'should not have failed')
self.assertFalse(r.failed, 'should not have failed')
def test_empty(self):
... | _ARG')
def test_autocomplete_command(self):
"""..."""
result = support.autocomplete('alias ad')
self.assertEqual(len(result), 1)
self.assertEqual(result[0], 'add')
def test_autocomplete_alias(self):
"""..."""
result = support.autocomplete('alias add fake-alias... |
watchdogpolska/feder | feder/alerts/filters.py | Python | mit | 466 | 0 | import django_filters
from dal import autocomplete
fr | om .models import Alert
class AlertFilter(django_filters.FilterSet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.filters["reason"].look | up_expr = "icontains"
self.filters["author"].widget = autocomplete.ModelSelect2(
url="users:autocomplete"
)
class Meta:
model = Alert
fields = ["reason", "author", "status"]
|
9929105/KEEP | keep_backend/repos/migrations/0002_auto__add_field_repository_study.py | Python | mit | 8,118 | 0.007761 | # -*- 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 field 'Repository.study'
db.add_column(u'repos_repository', 'study',
self.gf(... | rm['repos.Repository']"}),
'repo_parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'parent_relations'", 'to': u"orm['repos.Repository']"})
},
u'repos.repository': {
'Meta': {'ordering': "['org', 'name']", 'object_name': 'Repository'},
'date... | eTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'date_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}),
u'id': ('django.db... |
jminardi/syncnet | syncnet/main.py | Python | mit | 8,094 | 0.001483 | import os
import sys
import threading
import SimpleHTTPServer
import SocketServer
import shutil
import enaml
from enaml.qt.qt_application import QtApplication
from PyQt4.QtCore import QFileSystemWatcher
from atom.api import Atom, Unicode, observe, Typed, Property, Int
from btsync import BTSync
import logging
logger ... | cret) != 33:
return False
if not secret.isupper():
return False
# ensure only legal chars as defined by RFC 4648
for char in ('1', '8', '9', '='):
if char in secret:
return False
return True
### Observers #########################... | address_changed(self, change):
""" Check the text entered into the address field to see if it contains
a valid secret. If so, attempt to load that secret.
"""
address = self.address.upper()
if self.is_valid_secret(address):
self.load_secret(address)
def on_direc... |
baidu/broc | dependency/BrocConfig.py | Python | apache-2.0 | 5,186 | 0.003471 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
Description : manage config file $HOME/.b... | stfix_branch = conf.get('repo', 'svn_postfix_branch')
self._sv | n_postfix_tag = conf.get('repo', 'svn_postfix_tag')
except ConfigParser.Error as e:
raise BrocConfigError(str(e))
def RepoDomain(self, repo_type):
"""
return repository domain
Args:
repo_type : BrocMode_pb2.Module.EnumR... |
dedupeio/dedupe-examples | patent_example/patent_evaluation.py | Python | mit | 1,311 | 0.006102 | import csv
import collections
import itertools
def evaluateDuplicates(found_dupes, true_dupes):
true_positives = found_dupes.intersection(true_dupes)
false_positives = found_dupes.difference(true_dupes)
uncovered_dupes = true_dupes.difference(found_dupes)
print('found duplicate')
print(len(found_d... | lename) as f:
reader = csv.DictReader(f, delimiter=',', quotechar='"')
for row in reader:
dupe_d[row[colname]].append(row['person_id'])
if 'x' in dupe_d :
del dupe_d['x']
dupe_s = set([])
for (unique_id, cluster) in dupe_d.items():
if len(cluster) > 1:
... | s = 'patstat_output.csv'
manual_clusters = 'patstat_reference.csv'
test_dupes = dupePairs(dedupe_clusters, 'Cluster ID')
true_dupes = dupePairs(manual_clusters, 'leuven_id')
evaluateDuplicates(test_dupes, true_dupes)
|
pipermerriam/flex | flex/loading/schema/paths/path_item/__init__.py | Python | mit | 1,084 | 0 | from flex.datastructures import (
ValidationDict,
)
from flex.constants import (
OBJECT,
)
from flex.validation.common import (
generate_object_validator,
)
from | .operation import (
operation_validator,
)
from .parameters import (
parameters_validator,
)
path_item_schema = {
'type': OBJECT,
}
non_field_validators = ValidationDict()
non_field_validators.add_property_validator('get', o | peration_validator)
non_field_validators.add_property_validator('put', operation_validator)
non_field_validators.add_property_validator('post', operation_validator)
non_field_validators.add_property_validator('delete', operation_validator)
non_field_validators.add_property_validator('options', operation_validator)
non_... |
thydeyx/LeetCode-Python | Palindrome Number.py | Python | mit | 302 | 0.023179 | class Solution(object):
def isPalindrome(self, x):
"""
: | type x: int
:rtype: bool
"""
s=str(x)
l=list(s)
l.reverse()
sq=''
s1=sq.join(l)
| if s==s1:
return True
else:
return False
|
aronparsons/spacewalk | client/rhel/rhn-client-tools/src/firstboot-legacy-rhel5/rhn_provide_certificate_gui.py | Python | gpl-2.0 | 2,411 | 0.004977 | # Copyright 2006 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; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY W... | nreg.registered():
self.skipme = True
def _getVbox(self):
return self.provideCertificatePageVbox()
def apply(self, *args):
"""Returns True to change the page or None to stay on the same page."""
status = self.provideCertificatePageApply()
if status == 0: # cert was ... | message to disk like the other cases? need to decide
# how we want to do error handling in general.
self.parent.setPage("rhn_finish_gui")
return True
else: # an error occurred and the user was notified
assert status == 2
return None
childWindow = Rh... |
tsl143/zamboni | mkt/constants/base.py | Python | bsd-3-clause | 10,226 | 0 | from tower import ugettext_lazy as _
# Add-on and File statuses.
STATUS_NULL = 0
STATUS_PENDING = 2
STATUS_PUBLIC = 4
STATUS_DISABLED = 5
STATUS_DELETED = 11
STATUS_REJECTED = 12
STATUS_APPROVED = 13
STATUS_BLOCKED = 15
STATUS_UNLISTED = 16
# AMO-only statuses. Kept here only for memory and to not re-use the IDs.
_S... | _DISABLED: _(u'Banned from Marketplace'),
STATUS_DELETED: _(u'Deleted'),
STATUS_REJECTED: _(u'Rejected'),
# Approved, but the developer would like to put it public when they want.
# The need to go to the marketplace and actualy make it public.
STATUS_APPROVED: _(u'Approved but private'),
STATUS_... | US_FILE_CHOICES[STATUS_DISABLED] = _(u'Obsolete')
MKT_STATUS_FILE_CHOICES[STATUS_APPROVED] = _(u'Approved')
MKT_STATUS_FILE_CHOICES[STATUS_PUBLIC] = _(u'Published')
# We need to expose nice values that aren't localisable.
STATUS_CHOICES_API = {
STATUS_NULL: 'incomplete',
STATUS_PENDING: 'pending',
STATUS_P... |
Widdershin/community-review-poster | autoposter/__init__.py | Python | mit | 91 | 0.010989 | fr | om .app import App
from .reviews import Reviews
from .r_longb | oarding import RLongboarding |
MacHu-GWU/single_file_module-project | sfm/obj_file_io.py | Python | mit | 6,059 | 0.000332 | # -*- coding: utf-8 -*-
"""
object file io is a Python object to single file I/O framework. The word
'framework' means you can use any serialization/deserialization algorithm here.
- dump: dump python object to a file.
- safe_dump: add atomic writing guarantee for ``dump``.
- load: load python object from a file.
Fe... | r.encode("utf-8")
else:
b = b_or_str
if compress:
b = zlib.compress(b)
with atomic | _write(abspath, overwrite=overwrite, mode="wb") as f:
f.write(b)
elapsed = time.clock() - st
prt_console(" Complete! Elapse %.6f sec." % elapsed, verbose)
if serializer_type is "str":
return b_or_str
else:
return b
def _load(abspath, serializer_type,
loader_func=... |
grigorisg9gr/menpo | menpo/image/test/image_copy_test.py | Python | bsd-3-clause | 1,372 | 0 | import numpy as np
from menpo.image import Image, BooleanImage, MaskedImage
from menpo.shape import PointCloud
from menpo.testing import is_same_array
def test_image_copy():
pixels = np.ones([1, 10, 10])
landmarks = PointCloud(np.ones([3, 2]), copy=False)
im = Image(pixels, copy=False)
im.landmarks['... | ks['test'] = landmarks
| im_copy = im.copy()
assert (not is_same_array(im.pixels, im_copy.pixels))
assert (not is_same_array(im_copy.landmarks['test'].points,
im.landmarks['test'].points))
def test_maskedimage_copy():
pixels = np.ones([1, 10, 10])
landmarks = PointCloud(np.ones([3, 2]), copy... |
siddhantgoel/tornado-sqlalchemy | examples/multiple_databases.py | Python | mit | 2,508 | 0 | from sqlalchemy import BigInteger, Column, String
from tornado.gen import coroutine
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
from tornado_sqlalchemy import (
SessionMixin,
as_future,
set_max_workers,
SQLAlchemy,
)
db = SQLAlchemy()
set_max_workers(10)
c... | n.add(User(username='c'))
session.add(Foo(foo='d'))
session.add(Bar(bar='e'))
session.commit()
count = await as_future(session.query(User).count)
self.write('{} users so far!'.format(count))
if __name__ | == '__main__':
db.configure(
url='sqlite://',
binds={'foo': 'sqlite:///foo.db', 'bar': 'sqlite:///bar.db'},
)
app = Application(
[
(r'/sync', SynchronousRequestHandler),
(r'/gen-coroutines', GenCoroutinesRequestHandler),
(r'/native-coroutines', Na... |
rschnapka/bank-payment | account_banking_uk_hsbc/account_banking_uk_hsbc.py | Python | agpl-3.0 | 5,362 | 0 | ##############################################################################
#
# Copyright (C) 2009 EduSense BV (<http://www.edusense.nl>).
# Copyright (C) 2011 credativ Ltd (<http://www.credativ.co.uk>).
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# i... | info_owner,
string="Owner Account",
type="text",
help='Address of the Main Partner',
),
'info_partner': fields.function(
info_partner,
string="Destination Account",
type="t | ext",
help='Address of the Ordering Customer.'
),
}
|
jeff-allen-mongo/mut | mut/tuft/config.py | Python | apache-2.0 | 911 | 0 | import importlib.util
class Config:
def __init__(self, path: str) -> None:
spec = importlib.util.spec_from_file_location('conf', path)
self.module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(self.module)
@property
def rst_epilog(self) -> str:
| """A string that is appended to the end of every rst file. Useful for
replacements. Defaults to an empty string."""
return str(self.get('rst_epilog', ''))
@property
def source_suffix(self) -> str:
"""The file extension used for source files. Defaults to ".txt"."""
retur... | object) -> object:
try:
return self[key]
except AttributeError:
return default
def __getitem__(self, key: str) -> object:
return getattr(self.module, key)
|
dhirajt/dtc | wsgi/dtcbusroutes/dtcbusroutes/wsgi.py | Python | gpl-3.0 | 1,146 | 0.000873 | """
WSGI config for dtcbusroutes project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... | is used by any WSGI server configured to use this
# file. This | includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
brakhane/panda3d | direct/src/interval/ProjectileIntervalTest.py | Python | bsd-3-clause | 437 | 0.009153 | """Undocumented Module"""
__all__ = ['doTest']
from panda3d.core import *
from panda3d.dir | ect import *
from .IntervalGlobal import *
def doTest():
smiley = loader.loadModel('models/misc/smiley')
smiley.reparentTo(render)
pi = ProjectileInterval(smiley, startPos=Point3(0, 0, 0),
endZ = -10, wayPoint=Point3(10, 0, 0),
timeToWayPoint=3)
... | urn pi
|
thatcr/cffi-xll | src/xlcall/templates/__init__.py | Python | mit | 47 | 0.021277 | fro | m .co | nstants import *
from ._xlcall import * |
collinjackson/mojo | mojo/devtools/common/devtoolslib/linux_shell.py | Python | bsd-3-clause | 2,385 | 0.002935 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import subprocess
from devtoolslib.shell import Shell
from devtoolslib import http_server
class LinuxShell(Shell):
"""Wrapper around Mojo shell running ... | refix=None):
self.executable_path = executable_path
self.command_prefix = command_prefix if command_prefix else []
def ServeLocalDirectory(self, local_dir_path, port=0):
"""Serves the content of the local (host) directory, making it available to
the shell under the url returned by the function.
... | : port at which the server will be available to the shell
Returns:
The url that the shell can use to access the content of |local_dir_path|.
"""
return 'http://%s:%d/' % http_server.StartHttpServer(local_dir_path, port)
def Run(self, arguments):
"""Runs the shell with given arguments until she... |
slogan621/tscharts | tschartslib/clinicstation/clinicstation.py | Python | apache-2.0 | 30,523 | 0.003407 | #(C) Copyright Syd Logan 2017-2020
#(C) Copyright Thousand Smiles Foundation 2017-2020
#
#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... | tPatient(self, patient):
self._payload["nextpatient"] = patient
self.setPayload(self._payload)
def setAwayTime(self, minutes):
self._payload["awaytime"] = minutes
self.setP | ayload(self._payload)
class DeleteClinicStation(ServiceAPI):
def __init__(self, host, port, token, id):
super(DeleteClinicStation, self).__init__()
self.setHttpMethod("DELETE")
self.setHost(host)
self.setPort(port)
self.setToken(token)
self.setURL("tscharts/... |
prikevs/PasteSite | paste/database.py | Python | mit | 173 | 0.00578 | #coding:utf8
from flask.ext.sqlalchemy import SQLAlchemy
from . import app
app.config['SQLALC | HEMY_DATABASE_URI'] = 'sqlite:///relative/../../test.db'
db = SQLAl | chemy(app)
|
DMPwerkzeug/DMPwerkzeug | rdmo/questions/migrations/0001_initial_after_reset.py | Python | apache-2.0 | 5,793 | 0.003798 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
import rdmo.core.models
class Migration(migrations.Migration):
dependencies = [
('domain', '0001_initial_after_reset'),
]
operations = [
migrations.C... | _length=256)),
('title_de', models.CharField(max_length=256)),
('section', models.ForeignKey(related_name='subsections', to='questions.Section', on_delete=models.CASCADE)),
],
options={
'ordering': ('section__catalog__order', 'section__order', 'ord... | 'verbose_name_plural': 'Subsections',
},
bases=(models.Model, rdmo.core.models.TranslationMixin),
),
migrations.CreateModel(
name='Question',
fields=[
('questionentity_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary... |
iammrdollar/ProjectEulerSolutions | Problem 1 - Multiples of 3 and 5/mul_3_5.py | Python | mit | 296 | 0.016892 | # Sum of num divisble by 3 and 5 upto 1000
def sumN(n):
return ((n * (n+1)) // 2)
def sumDivisibleBy(num, upto):
linearUpto = (upto-1)//num
return num * sumN(linearUpto)
upto = int(inpu | t())
ans = sumDivisibleBy(3,upto) + sumDi | visibleBy(5,upto) - sumDivisibleBy(15,upto)
print(ans)
|
CanalTP/flask-restful | examples/todo.py | Python | bsd-3-clause | 1,446 | 0.003458 | from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
TODOS = {
'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'ta | sk': 'profit!'},
}
def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id))
parser = reqparse.RequestParser()
parser.add_argument('task', type=str)
# Todo
# show a single todo item and lets you delete them
class Todo(Resource):
de... | odo_id)
del TODOS[todo_id]
return '', 204
def put(self, todo_id):
args = parser.parse_args()
task = {'task': args['task']}
TODOS[todo_id] = task
return task, 201
# TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
... |
openstack/senlin | senlin/tests/unit/cmd/test_conductor.py | Python | apache-2.0 | 1,992 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | from senlin.common imp | ort messaging
from senlin.common import profiler
from senlin.conductor import service
from senlin.tests.unit.common import base
CONF = cfg.CONF
class TestConductor(base.SenlinTestCase):
def setUp(self):
super(TestConductor, self).setUp()
@mock.patch('oslo_log.log.setup')
@mock.patch('oslo_log.lo... |
skosukhin/spack | var/spack/repos/builtin/packages/htop/package.py | Python | lgpl-2.1 | 1,706 | 0.000586 | ##############################################################################
# Copyright (c) 2013-2017, 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... | , February 1999.
#
# This program 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 terms and
# conditions of the GNU Lesser General Public License fo | r more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack i... |
sbarakat/graph-partitioning | graph_partitioning/partitioners/patoh/patoh.py | Python | mit | 5,305 | 0.005844 | import ctypes
import graph_partitioning.partitioners.utils as putils
from graph_partitioning.partitioners.patoh.parameters import PATOHParameters
'''
Usage:
# Load the library
libPath = 'path/to/libpatoh.dylib' # .so for linux
lib = LibPatoh(libraryPath = libPath)
lib.load()
# Check library is Loaded
if lib.libIsLo... | ath = None):
super().__init__(libraryPath=librar | yPath)
def _getDefaultLibPath(self):
return putils.defaultPATOHLibraryPath()
def _loadLibraryFunctions(self):
self.PATOH_Version = self.clib.Patoh_VersionStr
self.PATOH_Version.restype = (ctypes.c_char_p)
self.PATOH_InitializeParameters = self.clib.Patoh_Initialize_Parameters
... |
krischer/prov | prov/tests/attributes.py | Python | mit | 5,400 | 0.000926 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from prov.model import *
EX_NS = Namespace('ex', 'http://example.org/')
EX_OTHER_NS = Namespace('other', 'http://example.org/')
class TestAttributesBase(object):
"""This is the base class for testing su... | ous datatypes.
It is not runnable and needs to be included in a subclass of RoundTripTestCase.
"""
attribute_values = [
"un lieu",
Literal("un lieu", langtag='fr'),
Literal("a place", langtag='en'),
Literal(1, XSD_INT),
Literal(1, XSD_LONG),
Literal(1, XSD_SH... | False,
Literal(10, XSD_BYTE),
Literal(10, XSD_UNSIGNEDINT),
Literal(10, XSD_UNSIGNEDLONG),
Literal(10, XSD_INTEGER),
Literal(10, XSD_UNSIGNEDSHORT),
Literal(10, XSD_NONNEGATIVEINTEGER),
Literal(-10, XSD_NONPOSITIVEINTEGER),
Literal(10, XSD_POSITIVEINTEGER)... |
portnov/sverchok | utils/sv_IO_monad_helpers.py | Python | gpl-3.0 | 3,948 | 0.002786 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 distrib... | npack_monad(nodes, node_ref):
params = node_ref.get('params')
if params:
socket_prop_data = params.get('all_props')
monad_name = params.get('monad')
monad = bpy.data.node_groups[monad_name]
if socket_prop_data:
# including this to keep bw comp for trees that don't in... | pdate_cls()
node = nodes.new(cls_ref.bl_idname)
# -- addition 1 --------- setting correct properties on sockets.
cls_dict = params.get('cls_dict')
input_template = cls_dict['input_template']
for idx, (sock_name, sock_type, sock_props) in enumerate(input_template):
so... |
kumar303/zamboni | mkt/developers/tests/test_tasks.py | Python | bsd-3-clause | 24,331 | 0 | import codecs
import json
import os
import shutil
import socket
import subprocess
import tempfile
from contextlib import contextmanager
from cStringIO import StringIO
from django.conf import settings
from django.core import mail
from django.core.files.storage import default_storage as storage
from django.core.urlresol... | pload.objects.get(pk=self.upload.pk)
@mock.patch('mkt.developers.tasks.run_validator')
def test_pass_validation(self, _mock):
_mock.return_value = '{"errors": 0}'
tasks.validator(self.upload.pk)
assert self.get_upload().valid
@mock.patch('mkt.developers.tasks.run_validator')
de... | ation(self, _mock):
_mock.return_value = '{"errors": 2}'
tasks.validator(self.upload.pk)
assert not self.get_upload().valid
@mock.patch('mkt.developers.tasks.run_validator')
def test_validation_error(self, _mock):
_mock.side_effect = Exception
eq_(self.upload.task_error,... |
54lihaoxin/GoogleFooBar | src/guard_game/test_suite.py | Python | apache-2.0 | 938 | 0.007463 | import sys
import solution
# from classes import ?
class TestSuite:
def run(self):
self.test000()
self.test001()
self.tes | t002()
# self.test003()
# self.test004()
def test000(self):
print 'test 000\n'
n = 13
r = solution.answer(n)
print ' input:\t', n
print ' expect:\t', 4
print ' output:\t', r
print
def test001(self):
print 'test 002\n'
... | print ' expect:\t', 2
print ' output:\t', r
print
def test002(self):
print 'test 002\n'
n = 6471289
r = solution.answer(n)
print ' input:\t', n
print ' expect:\t', 1
print ' output:\t', r
print
def main(argv):
Tes... |
stregatto/fabric_lib | apt.py | Python | gpl-2.0 | 651 | 0.003072 |
from fabric.api import *
from fabric.utils import *
from fabric.contrib import *
class Apt( | object):
def __init__(self):
return
def update(self):
cmd = 'sudo apt update'
run(cmd)
print(cmd)
def purge(self, package):
cmd = 'sudo apt purge -y %(package)s' % {'package': package}
# print(cmd)
run(cmd)
def upgrade(s | elf):
cmd = 'sudo apt upgrade -y'
run(cmd)
# print(cmd)
def install(self, package):
if package != None:
cmd = 'sudo apt -y install %(package)s' % {'package': package}
run(cmd)
# print(cmd)
|
mclumd/pelawak | pelawak/wsgi.py | Python | mit | 482 | 0 | """
WSGI config for pelawak project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, s | ee
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pelawak.settings")
application = get_wsgi_applicat | ion()
application = DjangoWhiteNoise(application)
|
bkabrda/anymarkup-core | test/test_serialize.py | Python | bsd-3-clause | 3,156 | 0.000951 | # -*- coding: utf-8 -*-
import io
import os
import pytest
import six
from anymarkup_core import *
from test import *
class TestSerialize(object):
"""Note: testing serialization is a bit tricky, since serializing dicts can result
in different order of values in serialized string in different runs.
That ... | parsed_back == struct
assert type(parsed_back) == type(struct)
def test_serialize_works_with_wb_opened_file(self, tmpdir):
f = os.path.join(str(tmpdir), 'foo.xml')
fhandle = open(f, 'wb+')
serialize(exampl | e_as_ordered_dict, 'xml', fhandle)
assert self._read_decode(fhandle) == example_xml
def test_serialize_raises_with_unicode_opened_file(self, tmpdir):
# on Python 2, this can only be simulated with io.open
f = os.path.join(str(tmpdir), 'foo.json')
fhandle = io.open(f, 'w+', encoding=... |
CellProfiling/cam_acq | camacq/plugins/automations/__init__.py | Python | apache-2.0 | 10,741 | 0.000745 | """Handle automations."""
# Copyright 2013-2017 The Home Assistant Authors
# https://github.com/home-assistant/home-assistant/blob/master/LICENSE.md
# This file was modified by The Camacq Authors.
import logging
from collections import deque
from functools import partial
import voluptuous as vol
from camacq.exception... | d = False
self._action_sequence = action_sequence
self._attach_triggers = attach_triggers
self._detach_triggers = None
self._cond_func = cond_func
if enabled:
self.enable()
def __repr__(self):
"""Return the representation."""
return (
... | nce}, enabled={self.enabled})"
)
def enable(self):
"""Enable automation."""
if self.enabled:
return
self._detach_triggers = self._attach_triggers(self.trigger)
self.enabled = True
def disable(self):
"""Disable automation."""
if not self.enabl... |
teamtachyon/Quillpad-Server | QuillTrainer.py | Python | bsd-3-clause | 4,979 | 0.022896 | # -*- coding: utf-8 -*-
# @Date : Jul 13, 2016
# @Author : Ram Prakash, Sharath Puranik
# @Version : 1
import CART
from QuillLanguage import QuillLanguage
import pickle
class QuillTrainer(object):
def __init__(self,quillLang):
if isinstance(quillLang,QuillLanguage):
self.langua... | language+'.data'
f = file(fname,'w')
f.write('<QuillTrainData lang="%s" script="%s" deffont="%s" epsilon="%s" context-len="%s">\n'%(self.language.language,self.language.script,self.language.default_font,self.language.epsilon.encode('utf-8'),scope))
f.write('\t<SpecialRul... | f.write(repr(eachRule))
f.write('</SpecialRule>')
f.write('\n')
f.write('\t\t</SpecialRules>\n')
keyToCARTMap = {}
data={}
for uWord in uWords:
try:
trainPairs = self.language.getTrainingPairs(uWord)
... |
jtriley/s3site | s3site/static.py | Python | gpl-3.0 | 2,179 | 0 | """
Module for storing static data structures
"""
import os
import sys
VERSION = 0.9999
PID = os.getpid()
S3SITE_CFG_DIR = os.path.join(os.path.expanduser('~'), '.s3site')
S3SITE_CFG_FILE = os.path.join(S3SITE_CFG_DIR, 'config')
S3SITE_LOG_DIR = os.path.join(S3SITE_CFG_DIR, 'logs')
S3SITE_META_FILE = '__s3site.cfg'
... | t_on_fa | ilure:
sys.stderr.write("!!! ERROR - %s *must* be a directory\n" %
path)
elif not os.path.isdir(path) and exit_on_failure:
sys.stderr.write("!!! ERROR - %s *must* be a directory\n" % path)
sys.exit(1)
def create_config_dirs():
__makedirs(S3SITE_... |
jchiang87/TimeBombs | display.py | Python | gpl-3.0 | 548 | 0.021898 | from pylab import *
data = loadtxt('Data/dummy_data.dat')
posterior_sample = atleast_2d(loadtxt('posterior_sample.txt'))
ion()
for i in xrange(0, posterior_sample.shape[0]):
hold(False)
plot(data[:,0], data[:,1], 'bo')
hold(True)
plot(d | ata[:,0], posterior_sample[i, -data.shape[0]:], 'r-')
ylim([0, 1.1*data[:,1].max()])
draw()
ioff()
show()
hist(posterior_sample[:,9], 20)
xlabel('Number of Bursts')
show()
pos = posterior_sample[:, 10:110]
pos = pos[pos != 0.]
hist(pos, 1000)
xlabel('Time')
title('Positions of Bursts | ')
show()
|
karlnapf/kameleon-mcmc | kameleon_mcmc/tools/Visualise.py | Python | bsd-2-clause | 5,656 | 0.006895 | """
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.
Written (W) 2013 Heiko Strathmann
Written (W) 2013 Dino Sejdinovic
"""
fro... | ensity
for i in range(len(Xs)):
for j in range(len(Ys)):
x = array([[Xs[i], Ys[j]]])
D[j, i] = distribution.log_pdf(x)
if log_domain == False:
D = exp(D)
im = imshow(D, origin='lower')
im.set_extent([Xs.min(), Xs.m... | s.min(), Ys.max()])
xlim([Xs.min(), Xs.max()])
@staticmethod
def contour_plot_density(distribution, Xs=None, Ys=None, log_domain=False):
"""
Contour-plots a 2D density. If Gaussian, plots 1.96 interval contour only
density - distribution instance to plot
... |
Seraf/LISA | lisa/server/tests/test_plugins.py | Python | mit | 2,790 | 0.002867 | import os
from twisted.trial import unittest
from lisa.server.plugins.PluginManager import PluginManagerSingleton
class LisaPluginTestCase(unittest.TestCase):
def setUp(self):
self.pluginManager = PluginManagerSingleton.g | et()
def test_a_install_plugin_ok(self):
answer = self.pluginManager.installPlugin(plugin_name="UnitTest", test_mode=True, version='0.1.6')
self.assertEqual(answer['status'], "success")
def test_aa_install_plugin_fail(self):
answer = self.pluginManager.installPlugin(plugin_name="UnitTe... | ssertEqual(answer['status'], "fail")
def test_b_disable_plugin_ok(self):
answer = self.pluginManager.disablePlugin(plugin_name="UnitTest")
self.assertEqual(answer['status'], "success")
def test_bb_disable_plugin_fail(self):
answer = self.pluginManager.disablePlugin(plugin_name="UnitTes... |
lo-windigo/fragdev | wiblog/migrations/0004_auto_20170703_1156.py | Python | agpl-3.0 | 1,015 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-03 18:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('wiblog', '0003_auto_20160325_1441'),
]
operations =... | odels.manager.Manager()),
],
),
migrations.AlterModelManagers(
name='post',
managers=[
('published', django.db.models.manager.Manager()),
],
),
migrations.AlterF | ield(
model_name='comment',
name='url',
field=models.URLField(blank=True, null=True),
),
migrations.AlterField(
model_name='tag',
name='desc',
field=models.SlugField(unique=True, verbose_name='Tag'),
),
]
|
h-mayorquin/time_series_basic | examples/auto_correlations_compare.py | Python | bsd-3-clause | 1,897 | 0 | """
This scripts compares the autocorrelation in statsmodels with
the one that you can build using only correlate.
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal
import statsmodels.api as sm
from signals.time_series_class import MixAr, AR
from signals.aux_functions import sidekick... | lt.plot(time, mix_series)
plt.show()
# Let's calculate the auto correlation
nlags = 40
normal_series -= normal_series.mean()
var = np.var(normal_series)
n = len(normal_series)
nlags1 = nlags
normalizing = np.arange(n, n - nlags1, -1)
auto_correlation1 = np.correlate(normal_series, normal_series, mode='full')
aux... | orrelation1.size/2
auto_correlation1 = auto_correlation1[aux:aux + nlags1] / (normalizing * var)
auto_correlation2 = sm.tsa.stattools.acf(normal_series, nlags=nlags)
print 'result', np.sum(auto_correlation1 - auto_correlation2)
if plot2:
plt.subplot(2, 1, 1)
plt.plot(auto_correlation1)
plt.subplot(2, 1,... |
Answeror/torabot | torabot/tasks/delete.py | Python | mit | 1,277 | 0.003132 | from logbook import Logger
from ..core.local import get_current_conf
from ..core.connection import autoccontext
from .. import db
from datetime import timedelta, datetime
log = Logger(__name__)
def del_inactive_queries():
conf = get_current_conf()
with autoccontext(commit=True) as conn:
before = db.... | db.get_change_count(conn)
db.del_old_changes(
conn,
before=datetime.utcnow() - timedelta(days=conf['TORABOT_DELETE_OLD_CHANGES_BEFORE_DAYS']),
limit=conf['TORABOT_DELETE_OLD_CHANGES_LIMIT']
)
after = db.get_change_count(conn)
log.info('delete old chan... | ed {}', before, after, before - after)
return before - after
|
nacc/autotest | client/tests/aio_dio_bugs/aio_dio_bugs.py | Python | gpl-2.0 | 1,337 | 0.005236 | import os
from autotest.client import test, utils
# tests is a simple array of "cmd" "arguments"
tests = [["aio-dio-invalidate-failure", "poo"],
["aio-dio-subblock-eof-read", "eoftest"],
["aio-free-ring-with-bogus-nr-pages", ""],
["aio-io-setup-with-nonwritable-context-pointer", ""],
... | utodir + '/deps/libaio/lib'
cflags = '-I ' + self.autodir + '/deps/libaio/include'
self.gcc_flags = ldflags + ' ' + cflags
def setup(self):
os.chdir(s | elf.srcdir)
utils.make('"CFLAGS=' + self.gcc_flags + '"')
def execute(self, args = ''):
os.chdir(self.tmpdir)
libs = self.autodir + '/deps/libaio/lib/'
ld_path = utils.prepend_path(libs,
utils.environ('LD_LIBRARY_PATH'))
var_ld_path = 'LD_LIBRA... |
alexforencich/xfcp | lib/eth/lib/axis/tb/axis_frame_length_adjust_fifo/test_axis_frame_length_adjust_fifo.py | Python | mit | 9,383 | 0.001172 | #!/usr/bin/env python
"""
Copyright (c) 2021 Alex Forencich
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, merg... | riginal_length == len_test
assert tb.sink.empty()
await RisingEdge(dut.clk)
await RisingEdge(dut.clk)
async def run_test_tuser_assert(dut):
tb = TB(dut)
await tb.reset()
test_data = bytearray(itertools.islice(itertools.cycle(range(256)), 32))
test_frame = AxiStreamFrame(test | _data, tuser=1)
await tb.source.send(test_frame)
rx_frame = await tb.sink.recv()
assert rx_frame.tdata == test_data
assert rx_frame.tuser
assert tb.sink.empty()
await RisingEdge(dut.clk)
await RisingEdge(dut.clk)
async def run_test_init_sink_pause(dut):
tb = TB(dut)
await tb.... |
miguelpedroso/neuralmind | examples/cifar10_mlp2.py | Python | mit | 1,690 | 0.049112 | import sys
sys.path.append("../")
sys.path.append("../neuralmind")
import gzip
import cPickle
import numpy as np
import theano
import theano. | tensor as T
from neuralmind import NeuralNetwork
from layers import HiddenLayer
from layers import DropoutLayer
import activations
from trainers import SGDTrainer
from trainers import ExponentialDecay
import datasets
# Load MNIST
#datasets = datasets.load_cifar10("/home/miguel/deeplearning/datasets")
datasets = dat... | tify
}),
(HiddenLayer,
{
'n_units': 512,
'non_linearity': activations.rectify
}),
(HiddenLayer,
{
'n_units': 10,
'non_linearity': activations.softmax
})
],
trainer=(SGDTrainer,
{
'batch_size': 20,
'learning_rate': 0.1,
'n_epochs': 400,
'global_L2_regularization': 0.0001,
'... |
atizo/djangojames | djangojames/forms/fields.py | Python | gpl-2.0 | 2,436 | 0.006568 | # -*- coding: utf-8 -*-
#
# Atizo - The Open Innovation Platform
# http://www.atizo.com/
#
# Copyright (c) 2008-2010 Atizo AG. All rights reserved.
#
# 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 Foundati... | django.for | ms.widgets import Select
from django.utils.safestring import mark_safe
from django import forms
from widgets import Html5DateTimeInput
class InputLabelWidget(Select):
def render(self, name, value, attrs=None, choices=()):
if value is None: value = ''
final_attrs = self.build_attr... |
woju/qubes-core-admin | tests/hardware.py | Python | lgpl-2.1 | 2,564 | 0.00078 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2016 Marek Marczykowski-Górecki
# <marmarek@invisiblethingslab.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the ... | e implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# | Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, see <https://www.gnu.org/licenses/>.
#
#
import os
import qubes.tests
import time
import subprocess
from unittest import expectedFailure
class TC_00_HVM(qube... |
adam111316/SickGear | lib/chardet/eucjpprober.py | Python | gpl-3.0 | 3,754 | 0.001332 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
... | port MultiByteCharSetProber
from .codingstatemachine import CodingStateMachine
from .chardistri | bution import EUCJPDistributionAnalysis
from .jpcntx import EUCJPContextAnalysis
from .mbcssm import EUCJP_SM_MODEL
class EUCJPProber(MultiByteCharSetProber):
def __init__(self):
super(EUCJPProber, self).__init__()
self.coding_sm = CodingStateMachine(EUCJP_SM_MODEL)
self.distribut... |
mattseymour/django | tests/serializers/models/base.py | Python | bsd-3-clause | 3,903 | 0.000769 | """
Serialization
``django.core.serializers`` provides interfaces to converting Django
``QuerySet`` objects to and from "flat" data (i.e. strings).
"""
from decimal import Decimal
from django.db import models
class CategoryMetaDataManager(models.Manager):
def get_by_natural_key(self, kind, name):
retur... | CharField(max_length=20, primary_ke | y=True)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class Movie(models.Model):
actor = models.ForeignKey(Actor, models.CASCADE)
title = models.CharField(max_length=50)
price = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
... |
okuta/chainer | chainer/datasets/text_dataset.py | Python | mit | 6,272 | 0 | import io
import sys
import threading
import six
from chainer.dataset import dataset_mixin
class TextDataset(dataset_mixin.DatasetMixin):
"""Dataset of a line-oriented text file.
This dataset reads each line of text file(s) on every call of the
:meth:`__getitem__` operator.
Positions of line bound... | he number of '
'text files to read')
self._paths = paths
self._encoding = encoding
self._errors = errors
self._newline = newline
self._fps = None
self._open()
# Line number is 0-origin.
# `lines` is a list of line numbers not filtered; i... | ven, it is range(linenum)).
# `bounds` is a list of cursor positions of line boundaries for each
# file, i.e. i-th line of k-th file starts at `bounds[k][i]`.
linenum = 0
lines = []
bounds = tuple([[0] for _ in self._fps])
while True:
data = [fp.readline() for... |
fbradyirl/home-assistant | homeassistant/components/http/auth.py | Python | apache-2.0 | 7,407 | 0.001215 | """Authentication for HTTP component."""
import base64
import logging
from aiohttp import hdrs
from aiohttp.web import middleware
import jwt
from h | omeassistant.auth.providers import legacy_api_password
from homeassistant.auth.util import generate_secret
from homeassistant.const import HTTP_HEADER_HA_AUTH
from homeassistant.core import callback
from homeassistant.util import dt as dt_util
from .const import KEY_AUTHENTICATED, KEY_HASS_USER, KEY_REAL_IP
_LOGGER =... | DATA_API_PASSWORD = "api_password"
DATA_SIGN_SECRET = "http.auth.sign_secret"
SIGN_QUERY_PARAM = "authSig"
@callback
def async_sign_path(hass, refresh_token_id, path, expiration):
"""Sign a path for temporary access without auth header."""
secret = hass.data.get(DATA_SIGN_SECRET)
if secret is None:
... |
timwaizenegger/swift-bluebox | _runApp_Development_nodebug.py | Python | mit | 442 | 0.011312 | # -*- coding: utf-8 -*-
"""
Project Bluebox
Copyright (C) <2015> < | University of Stuttgart>
This software may be modified and distributed under the terms
of the MIT license. See the LICENSE file for details.
"""
from mcm.Bluebox import app
from mcm.Bluebox import configuration
# socketio.run(
# app,
app.run(
host=configuration.my_bind_host,
port=int(configuration.my_e... | |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/model_utils/models.py | Python | agpl-3.0 | 3,021 | 0 | from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models.fields import FieldDoesNotExist
from django.core.exceptions import ImproperlyConfigured
from django.utils.timezone import now
from model_utils.managers import QueryManager... | lly-added manager for each
status that returns objects with that status only.
"""
status = StatusField(_('status'))
status_changed = MonitorField(_('status changed'), monitor='st | atus')
class Meta:
abstract = True
def add_status_query_managers(sender, **kwargs):
"""
Add a Querymanager for each status item dynamically.
"""
if not issubclass(sender, StatusModel):
return
for value, display in getattr(sender, 'STATUS', ()):
if _field_exists(sender... |
nuxgu/magic_db | sqldb/card_dao.py | Python | gpl-3.0 | 1,343 | 0.001489 | import logging
from dao import DAO, TableDesc, FieldDesc
log = logging.getLogger(__name__)
card_td = TableDesc("Cards", "multiverseid",
[FieldDesc("multiverseid", "int"),
FieldDesc("set_code", "text"),
FieldDesc("number", "int"),
Fiel... | nn):
card_td.create_table(conn)
def __init__(self, card, conn):
super(CardDAO, self).__init__(card_td, conn)
self.card = card
| def get_pkey(self):
return self.card.multiverseid
def get_values(self):
return [self.card.multiverseid,
self.card.set_code,
self.card.number,
self.card.name.decode('utf-8'),
self.card.language,
self.card.translation... |
patrickm/chromium.src | tools/telemetry/telemetry/core/timeline/model_unittest.py | Python | bsd-3-clause | 529 | 0.003781 | # Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from telemetry.core.timeline i | mport model
from telemetry.core.backends.chrome import tracing_timeline_data
class TimelineModelUnittest(unittest.TestCase):
def testEmptyImport(self):
| model.TimelineModel(
tracing_timeline_data.TracingTimelineData([]))
model.TimelineModel(
tracing_timeline_data.TracingTimelineData(''))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.