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 |
|---|---|---|---|---|---|---|---|---|
mph-/lcapy | doc/examples/networks/ladderRC3.py | Python | lgpl-2.1 | 163 | 0.01227 | from lcapy import R, C
n = C('C1') | (R('R1') + (C('C2') | (R('R2') + (C('C3') | (R('R3') + C('C4'))))))
n.d | raw(__file__.replace('.py', '.png'), lay | out='ladder')
|
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/network_interface_association_py3.py | Python | mit | 1,345 | 0 | # 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 ... | m security rules.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Network interface ID.
:vartype id: str
:param security_rules: Collection of custom security rules.
:type security_rules:
list[~azure.mgmt.network.v2018_01_01.models.Security... | yRules', 'type': '[SecurityRule]'},
}
def __init__(self, *, security_rules=None, **kwargs) -> None:
super(NetworkInterfaceAssociation, self).__init__(**kwargs)
self.id = None
self.security_rules = security_rules
|
ayys/collegesearch | main/models.py | Python | gpl-3.0 | 507 | 0 | from django.db import models
# Create your models here.
class Collage(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(unique=True)
no_of_students = models.IntegerField()
y | ear_estd = models.IntegerField()
def __str | __(self):
return self.name
class Faculty(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField()
year_started = models.IntegerField()
collage = models.ForeignKey(Collage, default=None)
|
BYVoid/OpenCC | data/scripts/find_target.py | Python | apache-2.0 | 282 | 0 | #!/usr/bin/env python
# - | *- coding: utf-8 -*-
import sys
from common import find_target_items
if len(sys.argv) != 3:
print("Find the value keyword in all pairs")
print(("Usage: ", sys.argv[0], "[input] [keyword]"))
exit(1)
find_target_it | ems(sys.argv[1], sys.argv[2])
|
unnikrishnankgs/va | venv/lib/python3.5/site-packages/jupyter_core/migrate.py | Python | bsd-2-clause | 8,222 | 0.004014 | from __future__ import unicode_literals
"""Migrating IPython < 4.0 to Jupyter
This *copies* configuration and resources to their new locations in Jupyter
Migrations:
- .ipython/
- nbextensions -> JUPYTER_DATA_DIR/nbextensions
- kernels -> JUPYTER_DATA_DIR/kernels
- .ipython/profile_default/
- static/custom -... | log.debug("Not migrating empty config file: %s" % src)
return migrated
def migrate():
"""Migrate IPython configuration to Jupyter"""
env = {
'jupyter_data': jupyter_data_dir(),
'jupyter_config': jupyter_config_dir(),
'ipython_dir': get_ipython_dir(),
'profile': os.path.joi... | _ipython_dir(), 'profile_default'),
}
migrated = False
for src_t, dst_t in migrations.items():
src = src_t.format(**env)
dst = dst_t.format(**env)
if os.path.exists(src):
if migrate_one(src, dst):
migrated = True
for name in config_migrations:
... |
AMairesse/hc-client | src/hc_component.py | Python | gpl-2.0 | 1,780 | 0.002809 | import pytz
import datetime
# statics
UNKNOWN_TYPE = 'Unknown'
DEFAULT_FREQ = 0 # No automatic update by default
DEFAULT_TIMEZONE = 'UTC'
DEFAULT_STATUS = False
class Component(dict):
# Private attributes
client_hostname = None
server_host = None
server_user = None
server_password = None
# P... | new_value_dt = self.last_value_dt + da | tetime.timedelta(seconds=self.freq)
return max(new_value_dt, datetime.datetime.now(self.timezone))
# Add a server hosting config
def add_config_server(self, client_hostname, server_host, server_user, server_password):
self.client_hostname = client_hostname
self.server_host = server_... |
SunDwarf/curious | curious/exc.py | Python | mit | 4,130 | 0.000484 | # This file is part of curious.
#
# curious is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# curious is distributed in the ho... | self) -> str:
if self.error_code == ErrorCode.UNKNOWN:
return repr(self.error)
return "{} ({}): {}".format(self.error_code, self.error_code.name, self.error_message)
__repr__ = __str__
class Unauthorized(HTTPException):
"""
Raised when your bot token is invalid.
"""
cla... | ing could not be found.
"""
class PermissionsError(CuriousError, PermissionError):
"""
Raised when you do not have sufficient permission to perform an action.
:ivar permission_required: The string of the permission required to perform this action.
"""
def __init__(self, permission_required: ... |
jonnyniv/boost_converter | host/gui/GTK+/share/glib-2.0/gdb/glib.py | Python | apache-2.0 | 7,426 | 0.010908 | import gdb
# This is not quite right, as local vars may override symname
def read_global_var (symname):
return gdb.selected_frame().read_var(symname)
def g_quark_to_string (quark):
if quark == None:
return None
quark = long(quark)
if quark == 0:
return None
try:
val = read_... | )
# Queue value for next result
self.value = ('[%dv]'% (self.pos), val)
# Return key
return ('[%dk]'% (self.pos), key)
raise StopIteration
def __init__ (self, val):
self.val = val
self.keys_are_strings = F... | ead_global_var ("g_str_hash")
except:
string_hash = None
if self.val != 0 and string_hash != None and self.val["hash_func"] == string_hash:
self.keys_are_strings = True
def children(self):
return self._iterator(self.val, self.keys_are_strings)
def to_string (sel... |
cdemers/networktools | UDPNetTests/test_server.py | Python | mit | 3,592 | 0.003898 | import socket
UDP_IP = "0.0.0.0"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
packet_stack = {}
sequence_pointer = 1
peak_stack_size = 0
print "Listening on IP %s, Port: %s" % (UDP_IP, UDP_PORT)
def decode_packet(packet):
seq = int(packet[0:16])
siz... | e: %i" % stack_size
if stack_size > peak_stack_size:
peak_stack_size = s | tack_size
print "\n"
except KeyboardInterrupt:
dump_state(peak_stack_size, packet_stack)
except:
print "ERROR!"
print "Data: '%s'" % data
print addr
print "Sequence Index: %i" % sequence_pointer
print "Peak Stack Size: %i" % peak_stack_size
stack_size = len(packet_stack)
print ... |
ericholscher/pinax | pinax/apps/groups/templatetags/group_tags.py | Python | mit | 3,311 | 0.003926 | from django import template
from django.utils.encoding import smart_str
from django.core.urlresolvers import reverse, NoReverseMatch
from django.db.models import get_model
from django.db.models.query import QuerySet
register = template.Library()
class GroupURLNode(template.Node):
def __init__(self, view_name, g... | y:
url = reverse(self.view_name, kwargs=kwargs)
except NoReverseMatch:
if self.asvar is None:
raise
if self.asvar:
| context[self.asvar] = url
return ""
else:
return url
class ContentObjectsNode(template.Node):
def __init__(self, group_var, model_name_var, context_var):
self.group_var = template.Variable(group_var)
self.model_name_var = template.Variable(model_name_var)
... |
tri2sing/PyOO | patterns/composite/entities.py | Python | gpl-2.0 | 1,989 | 0.012569 | '''
Created on Dec 2, 2015
@author: Sameer Adhikari
'''
# Class that represents the common operations between
# composite and leaf/primitive nod | es in the hierarchy
# This is a simulation which lacks a lot of operations
class Component(object):
def __init__(self, name):
self.name = name
def move(self, destination_path):
destination_folder = get_folder(destination_path)
del self.parent.children[self.name] # Remove folder... | destination_folder.children[self.name] = self # Move to new folder location
self.parent = destination_folder # Set up traversal path to root
def delete(self):
del self.parent.children[self.name] # Remove folder from current location
def add_child(self, child):
ch... |
veselosky/webquills | webquills/sites/middleware.py | Python | apache-2.0 | 275 | 0 | from .models import Site
class Si | tesMiddleware(object):
def __init__(self, get_re | sponse):
self.get_response = get_response
def __call__(self, request):
request.site = Site.objects._get_for_request(request)
return self.get_response(request)
|
hoangt/gem5v | tests/configs/o3-timing-mp.py | Python | bsd-3-clause | 2,805 | 0.010339 | # Copyright (c) 2006-2007 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this ... | from m5.objects import *
m5.util.addToPath('../configs/common')
from Caches import *
nb_cores = 4
cpus = [ DerivO3CPU(cpu_id=i) for i in xrange(nb_cores) ]
# system simulated
system = System(cpu = cpus, physmem = SimpleMemor | y(), membus = CoherentBus())
# l2cache & bus
system.toL2Bus = CoherentBus(clock = '2GHz')
system.l2c = L2(clock = '2GHz', size='4MB', assoc=8)
system.l2c.cpu_side = system.toL2Bus.master
# connect l2c to membus
system.l2c.mem_side = system.membus.slave
# add L1 caches
for cpu in cpus:
cpu.addPrivateSplitL1Caches... |
gen2brain/comic-utils | setup.py | Python | gpl-3.0 | 576 | 0.0625 | #!/usr/bin/env python
from distutils.core import setup
setup(name = "comic-utils",
| version = "0.4",
description = "Comic Utils",
author = "Milan Nikolic",
author_email = "gen2brain@gmail.com",
license = "GNU GPLv3",
url = "https://github.com/gen2brain/comic-utils",
packages = ["comicutils", "comicutils.ui"],
package_dir = {"comicutils": "comicut... | ,
scripts = ["comic-convert", "comic-thumbnails"],
requires = ["Image", "PngImagePlugin"],
platforms = ["Linux", "Windows"]
)
|
noironetworks/neutron | neutron/db/migration/alembic_migrations/versions/queens/expand/594422d373ee_fip_qos.py | Python | apache-2.0 | 1,485 | 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
# ... | 16:10.323756
"""
# revision identifiers, used by Alembic.
revision = '594422d373ee'
down_revision = '7d32f979895f'
# milestone identifier, used by neutron-db-manage
neutron_milestone = [migration.QUEENS]
def upgrade():
op.create_table(
'qos_fip_policy_bindings',
sa.Column('policy_id',
... | const.UUID_FIELD_SIZE),
sa.ForeignKey('qos_policies.id', ondelete='CASCADE'),
nullable=False),
sa.Column('fip_id',
sa.String(length=db_const.UUID_FIELD_SIZE),
sa.ForeignKey('floatingips.id', ondelete='CASCADE'),
nullable=F... |
browning/shows | shows/shows/settings/local.py | Python | mit | 1,629 | 0.00798 | """Development settings and globals."""
from os.path import join, normpath
from base import *
########## DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLATE_DEBUG = DEBUG
########## END... | oolbar/django-debug-toolbar#installation
INSTALLED_APPS += (
'debug_toolbar',
)
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
INTERNAL_IPS = ('127.0.0.1',)
# See: https://github.com/django-debug-toolbar/django-debug-toolbar#installation
MIDDLEWARE_CLASSES += (
'debug_toolbar... | are',
)
########## END TOOLBAR CONFIGURATION
|
eightHundreds/irides | tests/mocks/pictures.py | Python | gpl-3.0 | 743 | 0.002692 | import pytest
from app import models
from app.extensions import db
@pytest.fixture(scope='function')
def mock_picture():
def make_mock_picture(user=None, tags=None, despriction=None, address=None):
_picture = models.Picture(
userId=str(user.id),
despriction=despriction or 'testdes',... | )
| _picture.tags = [
models.Tag(tag=tags or 'testtags')
]
db.session.add(_picture)
db.session.commit()
# _tags = models.Tags(
# picId=_picture.id,
# tag='testtag'
# )
# db.session.add(_tags)
# db.session.commit()
... |
eysho/BestKnownGame-Coins---Source | share/qt/clean_mac_info_plist.py | Python | mit | 922 | 0.016269 | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make s | ure the Nichts-Qt.app contains t | he right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "Nichts-Qt.app/Conte... |
KevinGrahamFoster/django-cities-light | test_project/tests.py | Python | mit | 1,189 | 0.004205 | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from django.utils import unittest
from django.test.client import RequestFactory
from django.db.models import query
from django.contrib.admin.sites import AdminSite
from cities_light import admin as cl_admin
from cities_light import models as cl_models
... | = cl_admin.CityAdmin(cl_models.City, self.admin_site)
changelist = cl_admin.CityChangeList(
request, cl_models.City, cl_admin.CityAdmin.list_display,
cl_admin.CityAdmin.list_display_links, cl_admin.CityAdmin.list_filter,
cl_admin.CityAdmin.date_hierarchy, cl_admin.CityAdmin.... | min.list_editable, city_admin)
self.assertIsInstance(changelist.get_query_set(request), query.QuerySet)
|
GoogleChromeLabs/chromium-bidi | tests/_helpers.py | Python | apache-2.0 | 4,890 | 0.000613 | # Copyright 2021 Google LLC.
# Copyright (c) Microsoft Corporation.
#
# 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 a... | butes)
return
assert expected == actual
# Returns an id of an open context.
async def get_open_context_id(websocket):
result = await execute_command(websocket, {
"method": "browsingContext.getTree",
"params": {}})
return result['contexts'][0]['context']
async def send_JSON_comma... | json.dumps(command))
async def read_JSON_message(websocket):
return json.loads(await websocket.recv())
# Open given URL in the given context.
async def goto_url(websocket, context_id, url):
await execute_command(websocket, {
"method": "browsingContext.navigate",
"params": {
"url"... |
RecursiveGreen/spradio-django | savepointradio/radio/managers.py | Python | mit | 278 | 0 | from django.db import models
from .querysets import | SongQuerySet
class SongManager(models.Manager):
def get_queryset(self):
return SongQuerySet(self.model, using=self._db)
def available(self):
return self.get_queryset().song | s().enabled().published()
|
hstau/manifold-cryo | setup.py | Python | gpl-2.0 | 792 | 0.002525 | from setuptools import setup
def rea | dme():
with open('README.rst.example') as f:
return f.read()
setup(name='manifold_gui',
version='0.1',
description='GUI for a manifold technique',
long_description=readme(),
classifiers=[
'Development Status :: 1 - Alpha',
'Environment :: Console',
'Environme... | :: GNU General Public License (GPL)',
'Programming Language :: Python :: 2.7 :: chimera',
'Intended Audience :: End Users/Desktop',
],
keywords='manifold chimera',
author='Hstau Y Liao',
platform='linux chimera',
author_email='hstau.y.liao@gmail.com',
packages=['gui'... |
atimothee/django-playground | django_playground/movie_library/migrations/0006_auto__chg_field_movie_studio.py | Python | bsd-3-clause | 4,380 | 0.007763 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Movie.studio'
db.alter_column(u'movie_library_movie', ... | 'max_length': '100'}),
'director': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['movie_library.Director']", 'symmetrical': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_featured': ('django.db.models.fields.BooleanFie... | 'blank': 'True'}),
'studio': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['movie_library.Studio']", 'null': 'True', 'blank': 'True'}),
'synopsis': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max... |
moreati/numpy | runtests.py | Python | bsd-3-clause | 15,724 | 0.001717 | #!/usr/bin/env python
"""
runtests.py [OPTIONS] [-- ARGS]
Run tests, building the project first.
Examples::
$ python runtests.py
$ python runtests.py -s {SAMPLE_SUBMODULE}
$ python runtests.py -t {SAMPLE_TEST}
$ python runtests.py --ipython
$ python runtests.py --python somescript.py
$ python... | cmd)
sys.exit(1)
else:
| commits = [x.strip() for x in args.bench_compare.split(',')]
if len(commits) == 1:
commit_a = commits[0]
commit_b = 'HEAD'
elif len(commits) == 2:
commit_a, commit_b = commits
else:
p.error("Too many commits to compare ... |
fredex42/gnmvidispine | gnmvidispine/vs_metadata.py | Python | gpl-2.0 | 5,748 | 0.008525 | __author__ = 'Andy Gallagher <andy.gallagher@theguardian.com>'
import xml.etree.ElementTree as ET
import dateutil.parser
from .vidispine_api import always_string
class VSMetadata:
def __init__(self, initial_data={}):
self.contentDict=initial_data
self.primaryGroup = None
def addValue(self,key... | _xmlns = "{http://xml.vidispine.com/schema/vidispine}"
@staticmethod
def _safe_get_attrib(xmlnode, attribute, default):
try:
return xmlnode.attrib[attribute]
except AttributeError:
return default
@staticmethod
def _safe_get_subvalue(xmlnode, subnode_name, def... | if node is not None:
return node.text
else:
return default
except AttributeError:
return default
class VSMetadataValue(VSMetadataMixin):
def __init__(self, valuenode=None, uuid=None):
self.user = None
self.uuid = None
self... |
gelbander/blues | blues/python.py | Python | mit | 997 | 0.002006 | """
Python Blueprint
================
Does not install python itself, only develop and setup tools.
Contains pip helper for other blueprints to use.
**Fabric environment:**
.. code-block:: yaml
blueprints:
- blues.python
"""
from fabric.decorators import task
from refabric.api import run, info
from refa... | sudo
from . import debian
__ | all__ = ['setup']
pip_log_file = '/tmp/pip.log'
@task
def setup():
"""
Install python develop tools
"""
install()
def install():
with sudo():
info('Install python dependencies')
debian.apt_get('install', 'python-dev', 'python-setuptools')
run('easy_install pip')
... |
mezz64/home-assistant | homeassistant/helpers/reload.py | Python | apache-2.0 | 5,950 | 0.00084 | """Class to reload platforms."""
from __future__ import annotations
import asyncio
from collections.abc import Iterable
import logging
from typing import Any
from homeassistant import config as conf_util
from homeassistant.const import SERVICE_RELOAD
from homeassistant.core import Event, HomeAssistant, callback
from ... | latform, platform_configs: list[dict[str, Any]]
) -> None:
"""Reconfigure an already loaded platform."""
await platform.async_reset()
tasks = [platform.async_setup(p_config) for p_config in platform_configs]
await asyncio.gather(*tasks)
asyn | c def async_integration_yaml_config(
hass: HomeAssistant, integration_name: str
) -> ConfigType | None:
"""Fetch the latest yaml configuration for an integration."""
integration = await async_get_integration(hass, integration_name)
return await conf_util.async_process_component_config(
hass, aw... |
jsoref/django | django/contrib/gis/utils/layermapping.py | Python | bsd-3-clause | 27,310 | 0.00216 | # LayerMapping -- A Django Model/OGR Layer Mapping Utility
"""
The LayerMapping class provides a way to map the contents of OGR
vector files (e.g. SHP files) to Geographic-enabled Django models.
For more information, please consult the GeoDjango documentation:
https://docs.djangoproject.com/en/dev/ref/contrib/gi... | e = model_field.__class__.__name__
if isinstance(model_field, GeometryField):
if self.geom_field:
raise LayerMapError('LayerMapping does | not support more than one GeometryField per model.')
# Getting the coordinate dimension of the geometry field.
coord_dim = model_field.dim
try:
if coord_dim == 3:
gtype = OGRGeomType(ogr_name + '25D')
else:... |
bennylope/django-site-broadcasts | test.py | Python | mit | 1,601 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import organizations
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
os.system('python setup.py bdist_wheel upload')
sy... | . :changelog:', '')
|
setup(
author="Ben Lopatin",
author_email="ben@wellfire.co",
name='django-organizations',
version=organizations.__version__,
description='Group accounts for Django',
long_description=readme + '\n\n' + history,
url='https://github.com/bennylope/django-organizations/',
license='BSD Licen... |
tyler274/Recruitment-App | tests/test_functional.py | Python | bsd-3-clause | 3,980 | 0.000251 | # -*- coding: utf-8 -*-
"""Functional tests using WebTest.
See: http://webtest.readthedocs.org/
"""
from flask import url_for
from recruit_app.user.models import User
from .factories import UserFactory
class TestLoggingIn:
"""Login."""
def test_can_log_in_returns_200(self, user, testapp):
"""Login ... | get(url_for('security.register'))
# Fills out form, but email is already registered
form = res.forms['registerForm']
form['email'] = user.email
form['password'] = 'secret'
form['password_confirm'] = 'secret'
# Submits
res = form.submit()
# sees error
... | 'is already associated with an account' in res
|
m5w/matxin-lineariser | matxin_lineariser/statistical_linearisation/Linearisation/NeuralNet.py | Python | gpl-3.0 | 431 | 0.006961 | imp | ort sklearn.neural_network
class NeuralNet:
def __init__(self):
self.regression = sklearn.neural_network.MLPRegressor(hidden_layer_sizes=100)
def train(self, X, Y):
self.regression.fit(X, Y)
def score(self, X):
return self.regression.predict(X)
def set_param(self, param):
... | s() |
IndonesiaX/edx-platform | common/test/acceptance/tests/studio/test_studio_home.py | Python | agpl-3.0 | 5,862 | 0.001365 | """
Acceptance tests for Home Page (My Courses / My Libraries).
"""
from bok_choy.web_app_test import WebAppTest
from opaque_keys.edx.locator import LibraryLocator
from ...fixtures import PROGRAMS_STUB_URL
from ...fixtures.config import ConfigModelFixture
from ...fixtures.programs import ProgramsFixture
from ...pages.... | "
def setUp(self):
"""
| Load the helper for the home page (dashboard page)
"""
super(CreateLibraryTest, self).setUp()
self.auth_page = AutoAuthPage(self.browser, staff=True)
self.dashboard_page = DashboardPage(self.browser)
def test_create_library(self):
"""
From the home page:
... |
vladimir-ipatov/ganeti | lib/tools/burnin.py | Python | gpl-2.0 | 42,651 | 0.00823 | #!/usr/bin/python
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Google 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)... | ="Max Memory size",
default=256, type="unit", metavar="<size> | ",
completion_suggest=("128M 256M 512M 1G 4G 8G"
" 12G 16G").split()),
cli.cli_option("--minmem-size", dest="minmem_size", help="Min Memory size",
default=128, type="unit", metavar="<size>",
completion_suggest=("128M 256M 512M 1G ... |
rudikovrf/django_blog | generic/pagination.py | Python | mit | 1,556 | 0.003213 | from django.views.generic.base import ContextMixin
class PaginationPages(ContextMixin):
"""
Class is for extending the context with pages_list and url_without_page for pagination.
"""
def get_context_data(self, **kwargs):
"""
Function extends the context with pages_list and url_withou... | start = current_page - self.page_dif
if start < 1:
start = 1
finish = current_page + self.page_dif
pages_list = []
if start > 1:
pages_list.append(1)
if start > 2:
pages_list.append('...')
pages_list.extend(pages[start - 1:finish]) #... | # we get pages with numbers
# from start to finish.
if finish + 1 < count:
pages_list.append('...')
if finish < count:
pages_list.append(count)
context['pages_list'] = pages_list
get ... |
tchellomello/home-assistant | tests/components/zoneminder/test_init.py | Python | apache-2.0 | 4,539 | 0.001763 | """Tests for init functions."""
from datetime import timedelta
from zoneminder.zm import ZoneMinder
from homeassistant import config_entries
from homeassistant.components.zoneminder import const
from homeassistant.components.zoneminder.common import is_client_in_data
from homeassistant.config_entries import (
ENT... | TTR_ID,
ATTR_NAME,
CONF_HOS | T,
CONF_PASSWORD,
CONF_PATH,
CONF_SOURCE,
CONF_SSL,
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
from tests.async_mock import MagicMock, patch
from tests.common import... |
RealDolos/volaparrot | volaparrot/commands/info.py | Python | mit | 10,159 | 0.001084 | """
The MIT License (MIT)
Copyright © 2015 RealDolos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publi... | me)
def __init | __(self, *args, **kw):
super().__init__(*args, **kw)
self.conn.execute("CREATE TABLE IF NOT EXISTS seen ("
"user TEXT PRIMARY KEY, "
"time INT"
")")
try:
cur = self.conn.cursor()
cur.execute("SE... |
we-inc/mms-snow-white-and-the-seven-pandas | webserver/apps/booths/migrations/0003_auto_20171116_0220.py | Python | mit | 501 | 0.001996 | # -*- c | oding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-15 19:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('booths', '0002_auto_20171116_0045'),
]
operations = [
migrations.AlterField(
... | ),
]
|
gsarma/PyOpenWorm | tests/ContextTest.py | Python | mit | 12,077 | 0.000414 | import rdflib
from rdflib.term import URIRef, Variable
from PyOpenWorm.dataObject import DataObject, InverseProperty
from PyOpenWorm.context import Context
from PyOpenWorm.context_store import ContextStore
from .DataTestTemplate import _DataTest
try:
from unittest.mock import MagicMock, Mock
except ImportError:
... | nt_uri2_1 = 'http://example.com/context_2_1'
ident_uri3 = 'http://example.com/context_3'
ident_uri4 | = 'http://example.com/context_4'
ctx = Context(ident=ident_uri)
ctx2 = Context(ident=ident_uri2)
ctx2_1 = Context(ident=ident_uri2_1)
ctx.add_import(ctx2)
ctx.add_import(ctx2_1)
ctx3 = Context(ident=ident_uri3)
ctx3.add_import(ctx)
last_ctx = Context(ident... |
PetePriority/home-assistant | homeassistant/helpers/state.py | Python | apache-2.0 | 8,174 | 0 | """Helpers that help with state related things."""
import asyncio
import datetime as dt
import json
import logging
from collections import defaultdict
from types import TracebackType
from typing import ( # noqa: F401 pylint: disable=unused-import
Awaitable, Dict, Iterable, List, Optional, Tuple, Type, Union)
from... | ()
return self.states
def __exit__(self, exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType]) -> None:
"""Add changes states to changes list."""
self.states.extend(get_changed_since(self.hass.state... | """Return list of states that have been changed since utc_point_in_time."""
return [state for state in states
if state.last_updated >= utc_point_in_time]
@bind_hass
def reproduce_state(hass: HomeAssistantType,
states: Union[State, Iterable[State]],
blocking: ... |
ESOedX/edx-platform | openedx/core/lib/api/authentication.py | Python | agpl-3.0 | 4,363 | 0.002521 | """ Common Authentication Handlers used across projects. """
from __future__ import absolute_import
import logging
import django.utils.timezone
from oauth2_provider import models as dot_models
from provider.oauth2 import models as dop_models
from rest_framework.exceptions import AuthenticationFailed
from rest_framewo... | EN_ERROR_EXPIRED,
u'developer_message': u'The provided access token has expired and is no longer valid.',
})
else:
return token.user, token
def get_access_token(self, access_token):
"""
Return a valid access token that exists in one of our OAuth2 libr... | _token) or self._get_dop_token(access_token)
def _get_dop_token(self, access_token):
"""
Return a valid access token stored by django-oauth2-provider (DOP), or
None if no matching token is found.
"""
token_query = dop_models.AccessToken.objects.select_related('user')
... |
alexandermendes/pybossa-github-builder | tests/__init__.py | Python | bsd-3-clause | 554 | 0.001805 | # -*- coding: utf8 -*-
import sys
import os
import pybossa_github_builder as plugin
from mock import patch
# Use the PyBossa test suite
sys.path.append(os.path.abspath("./pybossa/test"))
from default import with_context
def s | etUpPackage():
"""Setup the plugin."""
from default import flask_app
with flask_app.app_context():
settings = os.path.abspath('./settings_test.py')
flask_app.config.from_pyfile(settings)
plugin_dir = os.path.dirname(plugin.__file__)
plugin.PyBossaGitHubBu | ilder(plugin_dir).setup()
|
inuyasha2012/tornado-cat-example | example/main.py | Python | mit | 8,865 | 0.002237 | # coding=utf-8
from psycopg2.extras import NamedTupleCursor, Json
from tornado.web import Application, HTTPError
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from tornado.options import parse_command_line
import momoko
import os
from bank import SelectQuestion, get... | ire ON ans | wer.questionnaire_id = questionnaire.id
WHERE answer.questionnaire_id=%s
AND answer.session_key=%s;
""", (q_id, session_key)
)
# q_a的意思是questionnaire and answer
q_a = cursor.fetchone()
if not q_a:
cursor = yield self.db.execute("SELECT id, ... |
denys-zarubin/sweetheart_test | quiz/migrations/0012_auto_20170407_1442.py | Python | unlicense | 547 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-07 14:42
from __f | uture__ import unicode_literals
from django.conf import settings
from django.db import migrations
class Migration(migrations.Migration):
dependencies = | [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('quiz', '0011_auto_20170407_1440'),
]
operations = [
migrations.AlterUniqueTogether(
name='selectedanswer',
unique_together=set([('quiz', 'user'), ('question', 'answer')]),
),
]
|
FIDATA/database-draft | predefined-data/import.py | Python | gpl-3.0 | 4,368 | 0.027033 | #!/usr/bin/env python
# -*- coding, utf-8 -*-
# FIDATA. Open-source system for analysis of financial and economic data
# Copyright © 2013 Basil Peace
# This file is part of FIDATA.
#
# FIDATA is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | tr_type'] = I | nstrumentType.Currency
# FIDATA.instrument(row = row, write = True, tryGetFromDB = False)
# del reader
# commit()
# logging.info('Importing instruments')
# reader = DictReader(open('instruments.csv', 'r', encoding = 'UTF8'), delimiter = ';')
# for row in reader:
# FIDATA.instrument(row = row, write = True, tryGetFro... |
larsbegas/rip-master | sites/_minux_tst.py | Python | gpl-2.0 | 10,576 | 0.023166 | #!/usr/bin/python
from sys import exit
import sys
from site_imgsrc import imgsrc
from site_imgur import imgur
from site_deviantart import deviantart
from site_photobucket import photobucket
from site_flickr import flickr
from site_twitter import twitter
from site_tumblr import tumblr
from s... | 216.beta.photobucket.com/user/Liebe_Dich/prof | ile/')
#i = flickr('http://www.flickr.com/photos/beboastar/sets/72157630130722172/')
#i = flickr('https://secure.flickr.com/photos/peopleofplatt/sets/72157624572361792/with/6344610705/')
#i = flickr('http://www.flickr.com/photos/rphotoit/sets/72157631879138251/with/8525941976/')
#i = flickr('http:/... |
beqa2323/learntosolveit | languages/python/design_stack.py | Python | bsd-3-clause | 507 | 0.013807 | """
Implementation of stack data structure in Python.
"""
class Stack:
def __init__(self,*vargs):
self.stack | = list(vargs)
def __repr__(self):
return str(self.stack)
def top(self):
return self.stack[0]
def push(self,elem):
self.stack.insert(0,elem)
def pop(self) | :
return self.stack.pop(0)
if __name__ == '__main__':
stk = Stack(1,2,3,4)
print stk
print stk.top()
stk.push(10)
print stk
print stk.pop()
print stk
|
sburnett/seattle | seattlelib/tests/test_dylink_include.py | Python | mit | 1,136 | 0.033451 | """
Author: Armon Dadgar
Description:
This test checks that the dylink pre-processor methods are working properly by "including"
the sockettimeout library. We then check that the functions work.
This test uses the old "include" directive
"""
# Import the sockettimeout library
include sockettimeout
def new_conn... | comm
# This will throw an Attribute error if these are not set
check = timeout_openconn
check = timeout_waitforconn
check = timeout_stopcomm
# Get our ip
ip = getmyip()
port = 12345
# Setup a waitforconn
waith = timeout_waitforconn(ip,port,new_conn)
# Try to do a timeout openconn
sock = timeout... | # Set the timeout to 1 seconds, and try to read
sock.settimeout(1)
try:
data = sock.recv(16)
# We should timeout
print "Bad! Got data: ",data
except:
pass
# Close the socket, and shutdown
sock.close()
timeout_stopcomm(waith)
|
deepmind/acme | acme/jax/losses/impala.py | Python | apache-2.0 | 3,849 | 0.001299 | # Copyright 2018 DeepMind Technologies Limited. 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 ... | nce, initial_state) -> ((logits, value), state)
discount: The standard geometric discount rate to apply.
max_abs_reward: Optional symmetric reward clipping to apply.
b | aseline_cost: Weighting of the critic loss relative to the policy loss.
entropy_cost: Weighting of the entropy regulariser relative to policy loss.
Returns:
A loss function with signature (params, data) -> loss_scalar.
"""
def loss_fn(params: hk.Params,
sample: reverb.ReplaySample) -> jnp.... |
Fablab-Sevilla/ghPython101 | Día_002/01_EJ/T_002/Peter random walk final.py | Python | mit | 1,275 | 0.026709 | import rhinoscriptsyntax as rs
#Importamos random
import random as rn
#Creamos seed y listas para los puntos, lineas y triangulos
rn.seed(s)
pts = [pt0]
lines = []
triangles = []
newptList = [pt0]
#Iteramos para la creacion de cada punto linea y triangulo
for i in range(It):
#los puntos en polares con angulos y p... | os por un random
rnleng = ((rn.randint(3,5))/10)
z = rs.CurveN | ormal(line)
vector = rs.VectorCreate(a,b)
nor = rs.VectorCrossProduct(vector,z)
normal = rs.VectorScale(nor,rnleng)
trans1 = rs.XformTranslation(normal)
trans2 = rs.XformTranslation(rs.VectorReverse(normal))
#Desplazamos los puntos medios el vector normal escalado
newpts1 = rs.Poin... |
ares/robottelo | robottelo/cli/org.py | Python | gpl-3.0 | 6,156 | 0 | # -*- encoding: utf-8 -*-
"""
Usage::
hammer organization [OPTIONS] SUBCOMMAND [ARG] ...
Parameters::
SUBCOMMAND subcommand
[ARG] ... subcommand arguments
Subcommands::
add-computeresource Associate a resource
add-configtemplate Associ... | ))
@classmethod
def remove_environment(cls, options=None):
"""Removes an environment from an org"""
cls.command_sub = 'remove-environment'
return cls.execute(cls._construct_command(options))
@classmethod
def add_hostgroup(cls, options=None):
"""Adds a hostgroup to an or... | ""Removes a hostgroup from an org"""
cls.command_sub = 'remove-hostgroup'
return cls.execute(cls._construct_command(options))
@classmethod
def add_location(cls, options=None):
"""Adds a location to an org"""
cls.command_sub = 'add-location'
return cls.execute(cls._constr... |
mjirik/imtools | imtools/gt_lar_smooth.py | Python | mit | 14,966 | 0.00254 | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Generator of histology report
"""
import logging
logger = logging.getLogger(__name__)
# import funkcí z jiného adresáře
import sys
import os.path
path_to_script = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(path_to_script, "../../lar-cc/li... | y | = radius*sin(sign*u+shift)
# z = 0
# return SUM([ center, CAT((Q*[[x],[y],[z]]).tolist()) ])
# return circle0
#
#
# def __construct_cylinder_end(self, pts, id, node):
# """
# creates end of cylinder and prepares for joints
# """
# CVlist = []
# ... |
IsmaelRLG/simpbot | simpbot/irc.py | Python | mit | 16,036 | 0.000873 | # -*- coding: utf-8 -*-
# Simple Bot (SimpBot)
# Copyright 2016-2017, Ismael Lugo (kwargs)
import re
import sys
import ssl
import time
import logging
import socket
from six import binary_type
from six import string_types
from six import PY3 as python3
from six.moves import _thread
from six.moves import queue
from . ... | dict = {}
def __init__(self, netw, addr, port, nick, user, nickserv=None, sasl=None,
timeout=240, msgps=.5, wtime=30, servpass=None, prefix='!', lang=None,
plaintext={
'recv': ['msg', 'jpqk', 'mode'],
'send': ['msg', 'jpqk', 'mode']}):
# msg PRIVMSG, NOTI... | w)
if envvars.daemon is True:
fs = '%(asctime)s %(levelname)s: %(message)s'
handler = logging.FileHandler(envvars.logs.join(netw).lower(), 'a')
else:
fs = '%(levelname)s: irc-client(%(name)s): %(message)s'
handler = logging.StreamHandler(sys.stdout)
... |
jcftang/ansible | lib/ansible/module_utils/ios.py | Python | gpl-3.0 | 2,926 | 0.005126 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | urn responses
def load_config(module, commands):
assert isinstance(commands, list), 'commands must be a list'
rc, out, err = module.exec_command('configure terminal')
if rc != 0:
module.fail_json(msg='unable to enter configuration mode', err=err)
for command in commands:
if command ==... | ec_command(command)
if rc != 0:
module.fail_json(msg=err, command=command, rc=rc)
module.exec_command('end')
|
david-hoffman/scripts | test_imreg_dph.py | Python | apache-2.0 | 575 | 0 | import numpy as np
from imreg_dph import AffineTransform
from nose.tools import *
def test_translation():
"""make sure tranlation works"""
# AffineTransform Tests
af1 = AffineTransform(translation=(1, 2))
af2 = AffineTransform(translation=(5, 3))
af3 = af1 @ af2
assert np.array_equal(af3.trans... | af2 @ af1
def test_rotation():
"""Test that rotation works"""
af1 = AffineTransform(rotation=2)
af2 = AffineTransform(rotation=1)
af3 = af1 @ af2
| assert af3.rotation == 3
assert af3 == af2 @ af1
|
allenai/allennlp | allennlp/training/scheduler.py | Python | apache-2.0 | 3,040 | 0.003289 | from typing import Dict, Any
import torch
class Scheduler:
"""
A `Scheduler` is a generalization of PyTorch learning rate schedulers.
A scheduler can be used to update any field in an optimizer's parameter groups,
not just the learning rate.
During training using the AllenNLP `Trainer`, this is... | : int = -1
) -> None:
self.optimizer = optimizer
self.param_group_field = param_group_field
self._initial_param_group_field = f"initial_{param_group_field}"
if last_epoch == -1:
for i, group in enumerate(self.optimizer.param_groups):
| if param_group_field not in group:
raise KeyError(f"{param_group_field} missing from param_groups[{i}]")
group.setdefault(self._initial_param_group_field, group[param_group_field])
else:
for i, group in enumerate(self.optimizer.param_groups):
... |
luxnovalabs/enjigo_door | web_interface/keyedcache/test_app/manage.py | Python | unlicense | 668 | 0.005988 | #!/usr/bin/env python
import os.path
import sys
DIRNAME = os.path.dirname(__file__)
if not DIRNAME in sys.path:
sys.path.append(DIRNAME)
from django.core.management import execute_manager
try:
import settings # Assumed to be in the s | ame directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'l | l have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
|
chenke91/ihaveablog | app/__init__.py | Python | mit | 1,126 | 0.000888 | f | rom flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from config import config
bootstrap = Bootstrap()... | 'auth.login'
avatars = UploadSet('avatars', IMAGES)
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
moment.init_app(app)
db.init_app(app)
login_manager.init_app(app)
configure_uploa... |
alex/mongoengine | tests/document.py | Python | mit | 19,227 | 0.002236 | import unittest
from datetime import datetime
import pymongo
from mongoengine import *
from mongoengine.base import BaseField
from mongoengine.connection import _get_db
class DocumentTest(unittest.TestCase):
def setUp(self):
connect(db='mongoenginetest')
self.db = _get_db()
class Pe... | Animal}
self.assertEqual(Mammal._superclasses, mammal_superclasses)
dog_superclasses = {
'Animal': Animal,
'Animal.Mammal': Mammal,
}
self.assertEqual(Dog._superclasses, dog_superclasses)
def test_get_subclasses(self):
"""Ensure | that the correct list of subclasses is retrieved by the
_get_subclasses method.
"""
class Animal(Document): pass
class Fish(Animal): pass
class Mammal(Animal): pass
class Human(Mammal): pass
class Dog(Mammal): pass
mammal_subclasses = {
'Anim... |
kernel-sanders/arsenic-mobile | Dependencies/Twisted-13.0.0/doc/names/examples/testdns.py | Python | gpl-3.0 | 1,653 | 0 | #!/usr/bin/env python
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Prints the results of an Address record lookup, Mail-Exchanger record
lookup, and Nameserver record loo | kup for the given hostname for a
given hostname.
To run this script:
$ python testdns.py <hostname>
e.g.:
$ python testdns.py www.google.com
"""
import sys
from twisted.names import client
from twisted.internet import defer, reactor
from twisted.names import dns, error
r = client.Resolver('/etc/resolv.conf')
def ... | ERY_CLASSES.get(a.cls, 'UNKNOWN (%d)' % (a.cls,)),
a.payload]
lines.append(' '.join(str(word) for word in line))
return '\n'.join(line for line in lines)
def printError(f):
f.trap(defer.FirstError)
f = f.value.subFailure
f.trap(error.DomainError)
print f.value.__class__.__name... |
openmotics/gateway | src/gateway/apartment_controller.py | Python | agpl-3.0 | 9,287 | 0.0028 | # Copyright (C) 2021 OpenMotics BV
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribu... | rm = Apartment.select().where(Apartment.mailbox_rebus_id == mailbox_id).first()
if apartment_orm is None:
return None
apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm)
return apartment_dto
@staticmethod
def load_apartment_by_doorbell_id(doorbell_id):
# type: ... | orbell_id).first()
if apartment_orm is None:
return None
apartment_dto = ApartmentMapper.orm_to_dto(apartment_orm)
return apartment_dto
@staticmethod
def load_apartments():
# type: () -> List[ApartmentDTO]
apartments = []
for apartment_orm in Apartmen... |
ReconCell/smacha | smacha/src/smacha/templates/Base.tpl.py | Python | bsd-3-clause | 2,545 | 0.070334 | {% block meta %}
name: Base
description: SMACH base template.
language: Python
framework: SMACH
type: Base
tags: [core]
includes: []
extends: []
variables:
- - manifest:
description: ROS manifest name.
type: str
- - node_name:
description: ROS node name for the state machine.
type: str
- outcome... | n: A name for the main executable state machine function.
type: str
input_keys: []
output_keys: []
{% endblock met | a %}
{% from "Utils.tpl.py" import import_module, render_outcomes, render_userdata %}
{% set defined_headers = [] %}
{% set local_vars = [] %}
{% block base_header %}
#!/usr/bin/env python
{{ base_header }}
{% endblock base_header %}
{% block imports %}
{{ import_module(defined_headers, 'smach') }}
{{ imports }}
{%... |
davisjoe/joesrobotchallenge | expermients/hello Joe.py | Python | mit | 171 | 0.035088 | Python 3.4.2 (default, Oct 19 2 | 014, 13:31:11)
[GCC 4.9.1] on linux
Type "copyright", "credits" or | "license()" for more information.
>>> print("hello Joe")
hello Joe
>>>
|
balohmatevz/steamapi | steamapi/app.py | Python | mit | 6,268 | 0.002234 | __author__ = 'SmileyBarry'
from .core import APIConnection, SteamObject, store
from .decorators import cached_property, INFINITE
class SteamApp(SteamObject):
def __init__(self, appid, name=None, owner=None):
self._id = appid
if name is not None:
import time
self._cache = d... | use a match.
return hash((self.id, self._appid))
@property
def appid(self):
return self._appid
@property
def name(self):
return self._ | displayname
@property
def apiname(self):
return self._id
@cached_property(ttl=INFINITE)
def is_hidden(self):
response = APIConnection().call("ISteamUserStats",
"GetSchemaForGame",
"v2",
... |
ESOedX/edx-platform | lms/djangoapps/grades/migrations/0001_initial.py | Python | agpl-3.0 | 2,347 | 0.002983 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import django.utils.timezone
import model_utils.fields
from django.db import migrations, models
from opaque_keys.edx.django.models import CourseKeyField, UsageKeyField
from lms.djangoapps.courseware.fields import UnsignedBigIntAutoField
... | o_created=True, primary_key=True)),
('blocks_json', models.TextField()),
('hashed', models.CharField(unique=True, max_length=100)),
],
),
m | igrations.AddField(
model_name='persistentsubsectiongrade',
name='visible_blocks',
field=models.ForeignKey(to='grades.VisibleBlocks', db_column=b'visible_blocks_hash', to_field=b'hashed', on_delete=models.CASCADE),
),
migrations.AlterUniqueTogether(
name='... |
Stanford-Online/edx-platform | cms/djangoapps/contentstore/features/courses.py | Python | agpl-3.0 | 2,137 | 0.001872 | # pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument
from lettuce import step, world
from common import *
############### ACTIONS ####################
@step('There are no courses$')
def no_courses(step):
world.clear_courses()
create_studio_user()
@... | e)
@step('I see a link for adding a new section$')
def i_see_new_section | _link(step):
link_css = '.outline .button-new'
assert world.css_has_text(link_css, 'New Section')
|
AbhilashReddyM/GeometricMultigrid | example_FMG_defcor.py | Python | mit | 3,299 | 0.049712 | """
This is an example showing how to use the mgd2d solver.
A 4th order accurate solution is obtained with the 5pt stencil,
by using deferred correction.
"""
import numpy as np
import time
from mgd2d import FMG,V_cycle
#analytical solution
def Uann(x,y,n):
return np.sin(2*n*np.pi*x)*np.sin(2*n*np.pi*y)
#RHS corres... | . etc
# Number of points is based on the number of multigrid levels as
# N=A*2**(num_levels-1) where A is an integer >=4. Smaller A is better
# This is a cell centered discretization
NX = 4*2**(nlevels-1)
NY = 4*2**(nlevels-1)
#the grid has one layer of ghost cells to help apply the boundary condit... | = np.zeros_like(u)
corr = np.zeros_like(u)
#calcualte the RHS and exact solution
DX=1.0/NX
DY=1.0/NY
n=1 # number of waves in the solution
xc=np.linspace(0.5*DX,1-0.5*DX,NX)
yc=np.linspace(0.5*DY,1-0.5*DY,NY)
XX,YY=np.meshgrid(xc,yc,indexing='ij')
uann[1:NX+1,1:NY+1]=Uann(XX,YY,n)
f[1:NX+1,1:NY+1]=source(XX,YY,n)
... |
andresriancho/collector | aws_collector/utils/collect.py | Python | gpl-2.0 | 4,386 | 0.000912 | import os
import logging
import time
import ConfigParser
from fabric.operations import get
from fabric.api import sudo, local, lcd, cd, shell_env
from aws_collector.config.config import MAIN_CFG, S3_BUCKET
OUTPUT_FILE_FMT = '%s-%s-collect-output.tar'
S3_UPLOAD_CMD = 'aws s3 cp --region us-east-1 %s s3://%s/%s'
def... | version)
logging.info('Output statisti | cs:')
sudo('ls -lah %s' % performance_results)
sudo('du -sh %s' % performance_results)
logging.info('Compressing output...')
# performance_results looks like /tmp/collector/w3af-*
path, file_glob = os.path.split(performance_results)
with cd(path):
sudo('tar -cpvf /tmp/%s %s' % (output_f... |
rosenvladimirov/addons | partner_vat_search/models/__init__.py | Python | agpl-3.0 | 120 | 0 | # -*- coding: utf-8 -*-
# License AGPL-3.0 or later | (http://www.gnu.org/licenses/agpl.html).
from . import r | es_partner
|
lpramuk/robottelo | tests/foreman/endtoend/test_cli_endtoend.py | Python | gpl-3.0 | 12,481 | 0.001683 | """Smoke tests for the ``CLI`` end-to-end scenario.
:Requirement: Cli Endtoend
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: Hammer
:Assignee: gtalreja
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import pytest
from fauxfactory import gen_alphanumeric
from fauxfactory import... | he activation key
14. Create a new libvirt compute resou | rce
15. Create a new subnet
16. Create a new domain
17. Create a new hostgroup and associate previous entities to it
18. Provision a client ** NOT CURRENTLY PROVISIONING
:id: 8c8b3ffa-0d54-436b-8eeb-1a3542e100a8
:expectedresults: All tests should succeed and Content should be
... |
tolimit/tp-qemu | generic/tests/jumbo.py | Python | gpl-2.0 | 7,693 | 0.00052 | import logging
import commands
import random
from autotest.client.shared import error
from autotest.client import utils
from virttest import utils_misc
from virttest import utils_test
from virttest import utils_net
@error.context_aware
def run(test, params, env):
"""
Test the RX jumbo frame function of vnic... | large_frame_ping()
size_increase_ping()
# S | tress test
flood_ping()
verify_mtu()
finally:
# Environment clean
if session:
session.close()
if utils.system("grep '%s.*%s' /proc/net/arp" % (guest_ip, ifname)) == '0':
utils.run("arp -d %s -i %s" % (guest_ip, ifname))
logging.info("Remov... |
anton-golubkov/Garland | src/test/test_splitblock.py | Python | lgpl-2.1 | 4,345 | 0.008055 | #-------------------------------------------------------------------------------
# Copyright (c) 2011 Anton Golubkov.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Lesser Public License v2.1
# which accompanies this distribution, and is available at
#... | f.assertEqual(loaded_image.tostring(), test_loaded_image.tostring())
loaded_image = cv.LoadImage("files/test_split_out_2.png")
test_loaded_image = cv.LoadImage("files/test_split_2.png")
self.assertEqual(loaded_image.tostring(), test_loaded_image.tostring())
loaded_image... | oaded_image.tostring())
def test_zero_image(self):
zero_image = cv.CreateImage( (0, 0), cv.IPL_DEPTH_8U, 3)
self.block.input_ports["input_image"].pass_value(zero_image)
self.block.process()
zero_image_1c = cv.CreateImage( (0, 0), cv.IPL_DEPTH_8U, 1)
output_i... |
SUSE/azure-sdk-for-python | azure-mgmt-sql/azure/mgmt/sql/models/encryption_protector_paged.py | Python | mit | 918 | 0 | # 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 ... | tainer for iterating over a list of EncryptionProtector object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[EncryptionPr | otector]'}
}
def __init__(self, *args, **kwargs):
super(EncryptionProtectorPaged, self).__init__(*args, **kwargs)
|
eric/whisper-rb | lib/whisper/py/whisper.py | Python | mit | 21,690 | 0.026418 | #!/usr/bin/env python
# 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 ... | self.readCount += 1
debug('READ %d bytes #%d' % (bytes,self.readCount))
return file.read(self,bytes)
| def debug(message):
print 'DEBUG :: %s' % message
__timingBlocks = {}
def startBlock(name):
__timingBlocks[name] = time.time()
def endBlock(name):
debug("%s took %.5f seconds" % (name,time.time() - __timingBlocks.pop(name)))
def __readHeader(fh):
info = __headerCache.get(fh.name)
if info: r... |
beeftornado/sentry | src/sentry/integrations/jira/client.py | Python | bsd-3-clause | 8,782 | 0.001822 | from __future__ import absolute_import
import datetime
import jwt
import re
import logging
from six.moves.urllib.parse import parse_qs, urlparse, urlsplit
from sentry.integrations.atlassian_connect import get_query_hash
from sentry.shared_integrations.exceptions import ApiError
from sentry.integrations.client import... | """
Jira-Cloud requires GDPR compliant API usage so we have to use accountId
"""
return "accountId"
def user_query_param(self):
"""
Jira-Cloud requires GDPR compliant API usage so we have to use query
"""
return "query | "
def user_id_get_param(self):
"""
Jira-Cloud requires GDPR compliant API usage so we have to use accountId
"""
return "accountId"
class JiraApiClient(ApiClient):
# TODO: Update to v3 endpoints
COMMENTS_URL = "/rest/api/2/issue/%s/comment"
COMMENT_URL = "/rest/api/2/is... |
ScenK/Dev_Blog2 | blog/dispatcher/__init__.py | Python | bsd-3-clause | 18,473 | 0.000109 | # -*- coding: utf-8 -*-
import json
import datetime
import PyRSS2Gen
from werkzeug.security import generate_password_hash
from mongoengine.errors import NotUniqueError, ValidationError
from flask import make_response
from tasks.email_tasks import send_email_task
from config import Config
from model.models import (Use... | delete_user(self):
"""Delete User"""
return User.objects().first().delete()
def get_by_name(self, username):
" | ""Get user by username
Args:
username: string
Return:
user: user object
"""
return User.objects(name=username).first()
class CommentDispatcher(object):
"""Comment dispatcher.
Retuen comments functons helper.
"""
def add_comment(self, author, di... |
pcmoritz/ray-1 | python/ray/tune/tests/test_tune_server.py | Python | apache-2.0 | 5,470 | 0 | import os
import requests
import socket
import subprocess
import unittest
import json
import ray
from ray.rllib import _register_all
from ray.tune.trial import Trial, Resources
from ray.tune.web_server import TuneClient
from ray.tune.trial_runner import TrialRunner
def get_valid_port():
port = 4321
while Tru... | rials if t["status"] == Trial.RUNNING]), 1)
| tid = [t for t in all_trials if t["status"] == Trial.RUNNING][0]["id"]
client.stop_trial(tid)
runner.step()
all_trials = client.get_all_trials()["trials"]
self.assertEqual(
len([t for t in all_trials if t["status"] == Trial.RUNNING]), 0)
def testStopExperiment(sel... |
todddeluca/tfd | tfd/fasta.py | Python | mit | 21,889 | 0.004203 | #!/usr/bin/env python
'''
What is a FASTA format file/string?
This module follows the NCBI conventions: http://blast.ncbi.nlm.nih.gov/blastcgihelp.shtml
'''
import cStringIO
import math
def idFromName(line):
'''
line: a fasta nameline
returns: an id parsed from the fasta nameline. The id is the first
... | >sp|P27348|1433T_HUMAN
'''
# lines guaranteed to have no blank lines by filterBlanks()
# lines guaranteed to have have exactly one nameline as the first
# element (except possibly the first l | ines yielded, which might not
# have a nameline if the filehandle starts with a sequence line).
for lines in splitFastaOnNamelines(filterBlanks(filehandle)):
if lines[0][0] == '>' and len(lines) >= 2:
yield lines
def filterBlanks(lines):
'''
Yield each line in lines that contains n... |
fmierlo/django-default-settings | release/1.2/project/settings.py | Python | bsd-3-clause | 3,293 | 0.002126 | # Django settings for project project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS | = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', | # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', ... |
wallaceicy06/Eligibility | eligibility.py | Python | mit | 5,750 | 0.003304 | import argparse
import random
import time
import sys
parser = argparse.ArgumentParser('eligibility')
parser.add_argument('infile', \
help='the file containing the list of names to randomly sort')
parser.add_argument('-s', '--spots', metavar='num', required=True, type=int, \
help='the number of spots ... | dy.
ohhdhhd `.:ddmdddddddd- + o-. hdssyy/
`hdhyyhh -`-ymmmddddms..s-- hdhhhdh.
-hdyhydh /o:/mdmdmmdy: :h+ hyy | yhhh:
-hdshydd /ymddhhhoydhohy/:+h dhyyyhh:
`hdsyyddo /s+o-+hhhdmddddooy +ddysydh.
sdhhhddh/ ` +ddd+sdddy/+/ yddhyyh+`
.hdhyyyyys: .oyoydddo-+ddhs/. +ydddhyy-
+hsyhhddho` :yhodoo+yssddds. sddyyyhh/
+yyddhhdddy.`.-:/::+ymdhs:`` +hddhyhyy/
:-... |
Senseg/robotframework | atest/robot/output/html_output_stats.py | Python | apache-2.0 | 1,194 | 0.005863 | from __future__ import with_statement
from robot.api import logger
class WrongStat(AssertionError):
ROBOT_CONTINUE_ON_FAILURE = True
def get_total_stats(path):
return get_all_stats(path)[0]
def get_tag_stats(path):
return get_all_stats(path)[1]
def get_suite_stats(path):
return get_all_stat | s(path)[2]
def get_all_stats(path):
logger.info('Getting stats from <a href="file://%s">%s</a>' % (path, path),
html=True)
stats_line = _get_stats_line(path)
logger.debug('Stats line: %s' % stats_line)
total, tags, suite = eval(stats_line)
return total, tags, suite
def _get_stats_l... | efix):
return line[len(prefix):-2]
def verify_stat(stat, *attrs):
expected = dict(_get_expected_stat(attrs))
if stat != expected:
raise WrongStat('\n%-9s: %s\n%-9s: %s' % ('Got', stat, 'Expected', expected))
def _get_expected_stat(attrs):
for key, value in (a.split(':', 1) for a in... |
DigitalCampus/django-nurhi-oppia | oppia/api/media.py | Python | gpl-3.0 | 1,856 | 0.001078 | # oppia/api/media.py
from django.conf import settings
from django.contrib.auth import authenticate
from django. | http import HttpResponseRedirect, Http404, HttpResponse, JsonResponse
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from oppia.api.publish import get_messages_array
from oppia.av.models import UploadedMedia
from oppia.av... | ssages
get_messages_array(request)
if request.method != 'POST':
return HttpResponse(status=405)
required = ['username', 'password']
validation_errors = []
for field in required:
if field not in request.POST:
validation_errors.append("field '{0}' missing".format(field)... |
Vauxoo/server-tools | datetime_formatter/__manifest__.py | Python | agpl-3.0 | 666 | 0 | # Copyright 2015, 2017 Jairo Llopis <jairo.llopis@tecnativa.com>
# Copyright 2016 Tecnativa, S.L. - Vicent Cubells
# Copyright 2018 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
"name": "Date & Time Formatter",
"summary": "Helper functions to give correct format | to date[time] fields",
"version": "12.0.1.0.0",
"category": "Tools",
"website": "https://github.com/OCA/server-tools",
"author": "Grupo ESOC Ingeniería de Servicios, "
"Tecnativa, "
"Odoo Community Association (OCA)",
"license": "AGPL-3",
"installable": True,
"dep... | |
knxd/pKNyX | pyknyx/core/dptXlator/dptXlatorDate.py | Python | gpl-3.0 | 4,000 | 0.002255 | # -*- coding: utf-8 -*-
""" Python KNX framework
License
=======
- B{PyKNyX} (U{https://github.com/knxd/pyknyx}) is Copyright:
- © 2016-2017 Matthias Urlichs
- PyKNyX is a fork of pKNyX
- © 2013-2015 Frédéric Mantegazza
This program is free software; you can redistribute it and/or modify
it under the terms ... | - Y: Year [0:99]
| - r: reserved (0)
.
"""
DPT_Generic = DPT("11.xxx", "Generic", (0, 16777215))
DPT_Date = DPT("11.001", "Date", ((1, 1, 1969), (31, 12, 2068)))
def __init__(self, dptId):
super(DPTXlatorDate, self).__init__(dptId, 3)
def checkData(self, data):
if not 0x000000 <= data <= 0x... |
AutohomeOps/Assets_Report | api_server/api_server/urls.py | Python | apache-2.0 | 846 | 0 | """api_server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Func | tion views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='ho | me')
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
version = 'v1.0'
urlpatterns = [
url(r'^admin/', admi... |
dims/glance | glance/version.py | Python | apache-2.0 | 686 | 0 | # Copyright 2012 OpenStack Foundation
#
# Licensed | under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed un... | plied. See the
# License for the specific language governing permissions and limitations
# under the License.
import pbr.version
version_info = pbr.version.VersionInfo('glance')
|
agarbuno/deepdish | doc/source/codefiles/saveable_example.py | Python | bsd-3-clause | 542 | 0.001845 | import deepdish as dd
class Foo(dd.util.SaveableRegistry):
def __init__(self, x):
self.x = x
@class | method
def load_from_dict(self, d):
obj = Foo(d['x'])
return obj
| def save_to_dict(self):
return {'x': self.x}
@Foo.register('bar')
class Bar(Foo):
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def load_from_dict(self, d):
obj = Bar(d['x'], d['y'])
return obj
def save_to_dict(self):
return {'x': self... |
ClemsonSoCUnix/django-sshkey | django_sshkey/models.py | Python | bsd-3-clause | 5,547 | 0.008293 | # Copyright (c) 2014-2016, Clemson University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditio... | t = getattr(instance, 'request', None)
if request:
context_dict['request'] = request
context_dict['userkey_list_uri'] = request.build_absolute_uri(
reverse('django_sshkey.views.userkey_list'))
text_content = render_to_string('sshkey/add_key.txt', context_dict)
msg = EmailMultiAlternatives(
setti... | [instance.user.email],
)
if settings.SSHKEY_SEND_HTML_EMAIL:
html_content = render_to_string('sshkey/add_key.html', context_dict)
msg.attach_alternative(html_content, 'text/html')
msg.send()
|
genialis/resolwe-bio-py | src/resdk/utils/table_cache.py | Python | apache-2.0 | 2,205 | 0 | """Cache util functions for ReSDKTables."""
import os
import pickle
import sys
from shutil import rmtree
from typing import Any
from resdk.__about__ import __version__
def _default_cache_dir() -> str:
"""Return default cache directory specific for the current OS.
Code originally from Orange3.misc.environ.
... | duser("~/Library/Caches")
elif sys.platform == "win32":
base = os.getenv("APPDATA", os.path.expanduser("~ | /AppData/Local"))
elif os.name == "posix":
base = os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
else:
base = os.path.expanduser("~/.cache")
return base
def cache_dir_resdk_base() -> str:
"""Return base ReSDK cache directory."""
return os.path.join(_default_cache_dir()... |
olavopeixoto/plugin.video.brplay | resources/lib/modules/kodi_util.py | Python | gpl-3.0 | 563 | 0.001776 | import locale
import threading
from contextlib import contextmanager
LOCALE_LOCK = threading.Lock()
BR_DATESHORT_FORMAT = '%a, %d %b - %Hh%M'
@contextmanager
def setlocale(name):
with LOCALE_LOCK:
| saved = locale.setlocale(locale.LC_ALL)
try:
yield locale.setlocale(locale.LC_ALL, name)
except:
yield
finally:
locale.setlocale(locale.LC_ALL, saved)
def format_datetimeshort(date_time):
with setlocale('pt_BR'):
return date_time.strftime | (BR_DATESHORT_FORMAT).decode('utf-8')
|
bskari/pi-rc | host_files.py | Python | gpl-2.0 | 5,869 | 0.002045 | #!/bin/env python
"""Hosts files from the local directory using SSL."""
from __future__ import print_function
import signal
import socket
import ssl
import subprocess
import sys
import threading
killed = False
# pylint: disable=C0411
if sys.version_info.major < 3:
import SimpleHTTPServer
import SocketServer... | ecause doing SSL in C
# sounds hard
content_length = int(self.headers.get('Content-Length'))
post_data = self.rfile.read(content_length)
print(post_data)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
| sock.connect(('localhost', 12345))
sock.sendall(post_data)
except Exception as exc:
print('{}, sending 500'.format(exc))
self.send_response(500)
self.send_header('Content-type', 'text/plain; charset=utf-8')
self.end_h... |
ehopsolidaires/ehop-solidaires.fr | ehop/ehopSolidaire_providers_register/forms.py | Python | agpl-3.0 | 10,906 | 0.006877 | # -*- coding: utf-8 -*-
# @copyright (C) 2014-2015
#Developpeurs 'BARDOU AUGUSTIN - BREZILLON ANTOINE - EUZEN DAVID - FRANCOIS SEBASTIEN - JOUNEAU NICOLAS - KIBEYA AISHA - LE CONG SEBASTIEN -
# MAGREZ VALENTIN - NGASSAM NOUMI PAOLA JOVANY - OUHAMMOUCH SALMA - RIAND MORGAN - TREIMOLEIRO ALEX - TRULLA AUREL... | auth.models import User as django_User
from datetime import datetime
from django import forms
from django.contrib.gis.geos import Point
class LoginForm(forms.ModelForm):
class Meta:
model = User
widgets = {
'mail': forms.EmailInput(attrs={'aria- | invalid': 'true', 'pattern': 'email', 'required': 'required'}),
}
exclude = ['name', 'firstname', 'sex', 'city', 'zipCode', 'phone', 'idHomeAddress', 'idWorkAddress']
class EmailAuthBackend(object):
def authenticate(self,username=None, password=None):
try:
user = djan... |
hazrpg/calibre | src/calibre/srv/utils.py | Python | gpl-3.0 | 15,349 | 0.003192 | #!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import errno, socket, select, os
from Cookie import SimpleCookie
from contex... | reate socket pair. Works also on windows by using an ephemeral TCP port.'''
if hasattr(socket, 'socketpair'):
client_sock, srv_sock = socket.socketpair()
set_socket_inherit(client_sock, False), set_socket_inherit(srv_sock, False)
return client_sock, srv_sock
# | Create a non-blocking temporary server socket
temp_srv_sock = socket.socket()
set_socket_inherit(temp_srv_sock, False)
temp_srv_sock.setblocking(False)
temp_srv_sock.bind(('127.0.0.1', port))
port = temp_srv_sock.getsockname()[1]
temp_srv_sock.listen(1)
with closing(temp_srv_sock):
#... |
Jozhogg/iris | lib/iris/tests/test_analysis_calculus.py | Python | lgpl-3.0 | 26,634 | 0.003717 | # (C) British Crown Copyright 2010 - 2014, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any l... | s.calculus
import iris.cube
import iris.coord_systems
import iris.coords
import iris.tests.stock
from iris.coords import DimCoord
from iris.tests.test_interpolation import normalise_order
class TestCubeDelta(tests.IrisTest):
def test_invalid(self):
cube = iris | .tests.stock.realistic_4d()
with self.assertRaises(iris.exceptions.CoordinateMultiDimError):
t = iris.analysis.calculus.cube_delta(cube, 'surface_altitude')
with self.assertRaises(iris.exceptions.CoordinateMultiDimError):
t = iris.analysis.calculus.cube_delta(cube, 'altitude')
... |
treejames/erpnext | erpnext/stock/doctype/item_attribute/item_attribute.py | Python | agpl-3.0 | 1,275 | 0.025882 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
class ItemAttribute(Document):
def validate(self):
self.valid... | d.attribute_value in values:
frappe.throw | (_("{0} must appear only once").format(d.attribute_value))
values.append(d.attribute_value)
if d.abbr in abbrs:
frappe.throw(_("{0} must appear only once").format(d.abbr))
abbrs.append(d.abbr)
def validate_attribute_values(self):
attribute_values = []
for d in self.item_attribute_values:
attri... |
kelle/astropy | astropy/stats/lombscargle/implementations/tests/test_mle.py | Python | bsd-3-clause | 1,921 | 0.000521 | import pytest
import numpy as np
from numpy.testing import assert_allclose
from .....extern.six.moves import range
from ..mle import design_matrix, periodic_fit
@pytest.fixture
def t():
rand = np.random.RandomState(42)
return 10 * rand.rand(10)
@pytest.mark.parametrize('freq', [1.0, 2])
@pytest.mark.paramet... | range(4))
def test_multiterm_design_matrix(t, nterms): |
dy = 2.0
freq = 1.5
X = design_matrix(t, freq, dy=dy, bias=True, nterms=nterms)
assert X.shape == (t.shape[0], 1 + 2 * nterms)
assert_allclose(X[:, 0], 1. / dy)
for i in range(1, nterms + 1):
assert_allclose(X[:, 2 * i - 1], np.sin(2 * np.pi * i * freq * t) / dy)
assert_allclose... |
simontakite/sysadmin | pythonscripts/programmingpython/Preview/peoplegui--frame.py | Python | gpl-2.0 | 2,035 | 0.00344 | """
See peoplegui--old.py: the alternative here uses nedted row frames with fixed
widdth labels with pack() to acheive the same aligned layout as grid(), but it
takes two extra lines of code as is (though adding window resize support makes
the two techniques roughly the same--see later in the book).
"""
from tk... | t).pack(side=RIGHT)
return window
def fetchRecord():
key = entries['key'].get()
try:
record = db[key] # fetch by key, show in GUI
except:
showerror(title='Error', message='No such key!' | )
else:
for field in fieldnames:
entries[field].delete(0, END)
entries[field].insert(0, repr(getattr(record, field)))
def updateRecord():
key = entries['key'].get()
if key in db:
record = db[key] # update existing record
else:
... |
simvisage/oricreate | oricreate/mapping_tasks/__init__.py | Python | gpl-3.0 | 210 | 0 |
from .map_to_surface import \
MapToSurface
from .mapping_task import \
MappingTask
from .mask_task import \
MaskTask
from .move_task import \
| MoveTask
from .rotate_copy import \
RotateCopy
| |
memphis-iis/demo-track | demotrack/model.py | Python | apache-2.0 | 1,712 | 0.001168 | import logging
from .data import DefinedTable
logger = logging.getLogger(__name__)
def ensure_tables():
"""When called, ensure that all the tables that we need are created in the
database. The real work is supplied by the DefinedTable base class
"""
for tab in [Subject, ExpCondition]:
logge... | get_key_name(self):
return "subject_id"
def __init__(
self,
subject_id=None,
first_name=None,
last_name=None,
email=None,
exp_condition=None
):
self.subject_id = subj | ect_id
self.first_name = first_name
self.last_name = last_name
self.email = email
self.exp_condition = exp_condition
def errors(self):
if not self.subject_id:
yield "Missing subject ID"
if not self.exp_condition:
yield "Missing Experimental Co... |
mverwe/JetRecoValidation | PuThresholdTuning/python/akPu3CaloJetSequence15_cff.py | Python | cc0-1.0 | 1,328 | 0.03012 | import FWCore.ParameterSet.Config as cms
from HeavyIonsAnalysis.JetAnalysis.jets.akPu3CaloJetSequence_PbPb_mc_cff import *
#PU jets: type 15
akPu3Calomatch15 = akPu3Calomatch.clone(src = cms.InputTag("akPu3CaloJets15"))
akPu3Caloparton15 = akPu3Caloparton.clone(src = cms.InputTag("akPu3CaloJets15"))
akPu3Calocorr15 =... | genJetMatch = cms.InputTag("akPu3Calomatch15"),
genPartonMatch = cms.InputTag("akPu3Caloparton15"),
)
akPu3CaloJetAnalyzer15 = akPu3CaloJetAnalyzer.clone(jetTag = cms.InputTag("akPu3CalopatJets15"), doSubEvent = cms.untracked.bool(True) )
akPu3CaloJetS... | akPu3Caloparton15
*
akPu3Calocorr15
*
akPu3CalopatJets15
*
akPu3CaloJetAnalyzer15
)
|
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_liberation_patriot_rodian_female_01.py | Python | mit | 471 | 0.046709 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_liberation_patriot_rodian_female_01.iff"
result.attr | ibute_template_id | = 9
result.stfName("npc_name","rodian_base_female")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.