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 |
|---|---|---|---|---|---|---|---|---|
alexschiller/osf.io | api/base/views.py | Python | apache-2.0 | 36,776 | 0.004215 | import weakref
from django.conf import settings as django_settings
from django.http import JsonResponse
from django.db import transaction
from rest_framework.decorators import api_view, throttle_classes
from rest_framework.response import Response
from rest_framework import generics
from rest_framework import status
fr... | ponse(ret).data
except Exception as e:
with transaction.atomic():
ret = view.handle_exception(e).data
# Allow request to be gc'd
ser._context = None
# Cache our final result
CACHE[self.request._request][_cache_key] = ret
... | xt(self):
"""Inject request into the serializer context. Additionally, inject partial functions
(request, object -> embed items) if the query string contains embeds. Allows
multiple levels of nesting.
"""
context = super(JSONAPIBaseView, self).get_serializer_context()
i... |
irmen/Pyro4 | examples/messagebus/messagebus/__init__.py | Python | mit | 260 | 0.007692 | """
Pyro MessageBus: a simple pub/sub message bus.
Provides a way of communicating where the sender and receivers are fully decoupled.
| Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.n | et).
"""
PYRO_MSGBUS_NAME = "Pyro.MessageBus"
|
kidaa/pixie | pixie/vm/test/test_hashmaps.py | Python | lgpl-3.0 | 221 | 0.004525 | import pixie.vm.rt as rt
from pixie.vm.primitives import nil
r | t.init()
def test_hashmap_create():
acc = rt.hashma | p(rt.wrap(1), rt.wrap(2))
val = rt._val_at(acc, rt.wrap(1), nil)
assert val.int_val() == 2
|
mpetazzoni/kazoocli | kazoocli/__main__.py | Python | apache-2.0 | 1,148 | 0.000871 | #!/usr/bin/env python
# Copyright (C) 2015 Maxime Petazzoni <maxime.petazzoni@bulix.org>
import argparse
import logging
import sys
from . import kazoocli
from .version import description
def main(args=None):
parser | = argparse.ArgumentParser(description=description)
parser.add_argument('server', nargs='?',
help='The ZooKeeper server to connect to',
default='localhost:2181')
parser.add_argument('-D', '--debug', action='store_const',
const=logging.DEBUG,... | , type=int,
help='Set connection timeout (default: 3 seconds)')
options = parser.parse_args(args=args)
logging.basicConfig(stream=sys.stderr, level=options.debug)
try:
kazoocli.KazooCli(options.server, options.timeout)
return 0
except:
if options.debug ==... |
SidWatch/pySIDWatch | Source/SendToSidWatchServer.py | Python | mit | 261 | 0.003831 | __author__ = 'briannelson'
from SID.Utilities import Conf | igUtility
from SIDClient.Co | ntrollers import SendToSidWatchServerController
config = ConfigUtility.load('./Config/sidwatch.cfg')
controller = SendToSidWatchServerController(config)
controller.start()
|
tabish121/quiver | python/brokerlib.py | Python | apache-2.0 | 11,350 | 0.001938 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | elivery.connection, self)
def forward_messages(self):
credit = sum([x.credit for x in self.consumers])
sent = 0
if credit == 0:
return
while sent < credit:
for consumer in self.consumers:
if consumer.credit == 0:
continue... | :
message = self.messages.popleft()
except IndexError:
self.consumers.rotate(sent)
return
consumer.send(message)
sent += 1
self.broker.notice("Forwarded {0} on {1} to {2}", message, self, consum... |
bossen/smartscale | main.py | Python | gpl-3.0 | 1,578 | 0.004436 | #!/bin/python2
import os, gzip, StringIO, time, csv, datetime
from flask import Flask, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from wtforms import Form, DecimalField, validators
class UpdateForm(Form):
weight = DecimalField('Weight', [validato | rs.DataRequired()])
fat = DecimalField('Body fat', [validators.DataRequired()])
water = DecimalField('Body water', [validators.DataRequired()])
muscle = DecimalField('Muscle', [validators.DataRequired()])
bonemass = DecimalField('Bone mass', [validators.DataRequired()])
calories = DecimalField('Calo... | ask(__name__)
CSV_FILENAME = "smartscale.csv"
types = ["weight", "fat", "water", "muscle", "bonemass", "calories"]
@app.route('/stats')
def stats():
with open(CSV_FILENAME) as f:
csv = f.read().splitlines()
data = [(line.split(',')) for line in csv]
return render_template('chart.html', types=type... |
strogo/djpcms | djpcms/views/specials.py | Python | bsd-3-clause | 963 | 0.006231 | from djpcms import sites
from djpcms.http import get_http
from djpcms.template import RequestContext, loader
from djpcms.views.baseview import djpcmsview
class badview(djpcmsview):
def __init__(self, template, httphandler):
self.template = template
self.httphandler = httphandler
super... | _()
def response(self, request):
t = loader.get_template(self.template)
c = {'request_path': request.path,
| 'grid': self.grid960()}
return self.httphandler(t.render(RequestContext(request, c)))
def http404view(request, *args, **kwargs):
http = get_http(sites.settings.HTTP_LIBRARY)
return badview('404.html',
http.HttpResponseNotFound).response(request)
def http500view(request, *args, *... |
khendarg/pdbtmtop | dbtool.py | Python | bsd-3-clause | 2,933 | 0.0358 | #!/usr/bin/env python2
from __future__ import print_function
import sys
import os
import urllib
import argparse
import xml.etree.ElementTree as ET
def warn(*msgs):
for x in msgs: print('[WARNING]:', x, file=sys.stderr)
class PDBTM:
def __init__(self, filename):
#self.tree = ET.parse(filename)
#self.root = self... | read())
db.close()
f.close()
def buil | d_database(fn, prefix):
print('Unpacking database...', file=sys.stderr)
f = open(fn)
db = f.read()
f.close()
firstline = 1
header = ''
entries = []
pdbids = []
for l in db.split('\n'):
if firstline:
header += l
firstline -= 1
continue
if 'PDBTM>' in l: continue
if l.startswith('<?'): continue
... |
nyarasha/firemix | lib/pattern_loader.py | Python | gpl-3.0 | 4,622 | 0.002813 | # This file is part of Firemix.
#
# Copyright 2013-2016 Jonathan Evans <jon@craftyjon.com>
#
# Firemix 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... | irectory for changes.")
self.observer.start()
def __del__(self):
self.observer.stop()
self.observer.join()
def all_patter | ns(self):
if not self._patterns_dict:
self._patterns_dict = self.load()
return self._patterns_dict
def load(self):
self._modules = []
self._patterns = []
log.info("Loading patterns...")
for f in os.listdir(os.path.join(os.getcwd(), "patterns")):
... |
marrow/web.command | web/command/output.py | Python | mit | 1,224 | 0.035131 | # encoding: utf-8
"""Interactive execution beautifiers.
Most definitely not intended for multiplexed (multithreaded) use.
"""
# Inspiration from: /lib/gentoo/functions.sh /lib64/rc/sh/functions.sh
import sys
from contextlib import contextmanager
TTY = sys.stdout.is_tty()
QUIET = False
DEBUG = False # Display ex... | artial = True
try:
yield
except:
pass
else:
pass
partial = False
@contextmanager
def einfo(message, newline=True):
with estatus('info', message, newline):
yield
def ewarn(newline=True):
with estatus('info', message, newline):
yield
@contextma | nager
def einfo(newline=True):
with estatus('info', message, newline):
yield
@contextmanager
def einfo(newline=True):
with estatus('info', message, newline):
yield
|
wrycu/DiscordGameManager | config_test/config_tests.py | Python | mit | 1,314 | 0.002283 | from jsonschema import validate, ValidationError
from json import load
from src.config_schema import config_schema
import unittest
class TestUM(unittest.TestCase):
def setUp(self):
pass
def test_Config1(self):
with open("config_test1.json") as data_file1:
data1 = load(data_file1)
... | ig4(self):
with open("config_test4.json") as data_file4:
data4 = load(data_file4)
with self.assertRaises(ValidationEr | ror):
validate(data4, config_schema)
def test_Config5(self):
with open("config_test5.json") as data_file5:
data5 = load(data_file5)
with self.assertRaises(ValidationError):
validate(data5, config_schema)
if __name__ == '__main__':
unittest.main() |
aymeric-spiga/planetoplot | examples/ppclass_reference/les_psfc.py | Python | gpl-2.0 | 360 | 0.025 | #! /usr/bin/env python
from ppclass import pp
les = pp(file="/hom | e/aymeric/Big_Data/LES_dd | /psfc_f18.nc",var="PSFC",y=["50,250"],x=["50","100"])
les.verbose = True
les.getplot()
les.x = None
les.y = ["200","250"]
les.t = "10"
les.getplot()
les.x = None
les.y = None
les.t = ["10"]
#les.stridex = 3
#les.stridey = 3
les.filename = "les_psfc"
les.getplot()
|
Mariaanisimova/pythonintask | BITs/2014/Borsheva_ V_O/task_7_6.py | Python | apache-2.0 | 1,044 | 0.036785 | #Задача 7. Вариант 6
#компьютер загадывает название одного из семи городов России, имеющих действующий метрополитен, а игрок должен его угадать.
#Борщёва В.О
#28.03.2016
import random
subways=('Москва','Санкт-Петербург','Нижний Новгород','Новосибирск','Самара','Екатери | нбург','Казань')
subway=random.randint(0,6)
rand=subways[subway]
ball=100
print('я загадал один город,имеющий дейстующий метрополитен')
#print(rand)
otvet=0
while (otvet)!=(rand):
otve | t=input("Введите один из городов:")
if(otvet)!=(rand):
print("Вы не угадали. Попробуйте снова.")
ball/=2
elif (otvet)==(rand):
print("Ваш счет:"+ str(ball))
break
input(" Нажмите Enter для выхода")
|
SebKuzminsky/linuxcnc-mirror | src/hal/user_comps/vismach/hexagui.py | Python | lgpl-2.1 | 6,317 | 0.027545 | #!/usr/bin/env python
# Copyright 2007 Ben Lipkowitz
# You may distribute this software under the GNU GPL v2 or later
#
# Hexapod visualization.
# In HAL, you must link axis.* to cartesian coordinates from
# halui, because I am too lazy to implement inverse kinematics.
# This causes some mismatch between the struts an... | ],0,0,-strut_length)
workpiece = Translate([workpiece],0,0,-strut_length | )
#myhud = Hud()
#myhud.show("welcome!")
#myhud.debug_track = 0
model = Collection([platform, struts, base, workpiece, foo])
#main(model, tool_coords, work_coords, size=30, hud=myhud)
main(model, tool_coords, work_coords, size=30)
|
fedspendingtransparency/data-act-broker-backend | dataactcore/migrations/versions/65ce5d505f12_add_error_severity.py | Python | cc0-1.0 | 851 | 0.010576 | """add_error_severity
Revision ID: 65ce5d505f12
Revises: ebe2d7673a81
Create Date: 2016-07-26 13:39:13.003391
"""
# revision identifiers, used by Alembic.
revision = '65ce5d505f12'
down_revision = '50faca665f9c'
branch_labels = N | one
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade(engine_name):
globals()["upgrade_%s" % engine_name]()
def downgrade(engine_name):
globals()["downgrade_%s" % engine_name]()
def upgrade_data_broker():
### commands auto generated by Alembic - please adjust! ###
op... | c - please adjust! ###
op.drop_column('error_metadata', 'severity_id')
### end Alembic commands ###
|
ufocoder/py-GithubArt | github_art/github.py | Python | mit | 1,567 | 0.001914 | import subprocess
import os
from datepoints import GithubDatePoints
from pixelsets import LettersPixelSet
class Github(object):
def __init__(self, string, cwd, dictionary):
self.__string = string
self.__dictionary = dictionary
self.__cwd = os.path.abspath(cwd)
self.commands = []
... |
def initialite(self):
pixel_set = LettersPixelSet(self.__string, self.__dictionary).get_pixel_set()
| date_points = GithubDatePoints(pixel_set).get_date_points()
self.__git_init()
for date_point in date_points:
self.__git_commit(date_point)
def set_account(self, username, proejct):
github_url = 'https://' + username + '@github.com/' + username + '/' + proejct + '.git'
... |
ownport/storages | storages/packages/peewee.py | Python | apache-2.0 | 136,615 | 0.000915 | # May you do good and not evil
# May you find forgiveness for yourself and forgive others
# May you share freely, never taking more than you give. -- SQLite source code
#
# As we enjoy great advantages from the inventions of others, we should be glad
# of an opportunity to serve others by an invention of ours, and thi... | ue, tb=None):
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
elif PY2:
unicode_type = unicode
string_type = basestring
binary_construct = buffer
def print_(s):
sys.stdout.write(s)
sys.stdout.write('\n')
exec('def reraise(tp, v... | aise RuntimeError('Unsupported python version.')
# By default, peewee supports Sqlite, MySQL and Postgresql.
try:
import sqlite3
except ImportError:
try:
from pysqlite2 import dbapi2 as sqlite3
except ImportError:
sqlite3 = None
try:
from psycopg2cffi import compat
compat.register()... |
openzim/zimfarm | dispatcher/backend/src/routes/workers/__init__.py | Python | gpl-3.0 | 366 | 0 | from routes import API_PATH
from routes.base import BaseBlueprint
from routes.workers.worker import WorkersRoute, WorkerCheckinRoute
class Blueprint(BaseBlueprint):
def __init__(self):
super().__init__("workers", __name__, | url_prefix=f"{API_PATH}/workers")
self.register_route(WorkersRoute())
self.register_route(WorkerCheckinRoute())
| |
seankelly/buildbot | master/buildbot/configurators/janitor.py | Python | gpl-2.0 | 3,367 | 0.001485 | # This file is part of Buildbot. Buildbot 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.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | = ["logHorizon"]
def __init__(self, logHorizon):
BuildStep.__init__(self)
self.logHorizon = logHorizon
@defer.inlineCallbacks
def run(self):
older_than_timestamp = datetime2epoch(now() - self.logHorizon)
deleted = yield self.master.d | b.logs.deleteOldLogChunks(older_than_timestamp)
self.descriptionDone = ["deleted", str(deleted), "logchunks"]
defer.returnValue(SUCCESS)
class JanitorConfigurator(ConfiguratorBase):
def __init__(self, logHorizon=None, hour=0, **kwargs):
ConfiguratorBase.__init__(self)
self.logHoriz... |
cvast/arches | arches/app/utils/geo_utils.py | Python | agpl-3.0 | 1,092 | 0.002747 | from django.contrib.gis.geos import GEOSGeometry, GeometryCollection
from arches.a | pp.utils.betterJSONSerializer import JSONSerializer, JSONDeserializer
class GeoUtils(object):
def create_geom_collection_from_geojson(self, geojson):
geoms = []
for feature in geojson['features']:
geoms.append(GEOSGeometry(JSONSerializer().serialize(feature['geometry'])))
retu... | on(s) and returns the coordinates of
the extent of the polygons.
"""
geom_collection = self.create_geom_collection_from_geojson(geojson)
bounds = geom_collection.extent
return bounds
def get_centroid(self, geojson):
"""
Takes a geojson object with polygon(s)... |
Titan-C/sphinx-gallery | sphinx_gallery/tests/tinybuild/examples/plot_second_future_imports.py | Python | bsd-3-clause | 694 | 0 | " | ""
Testing future statements across examples
-----------------------------------------
This example runs after plot_future_statements.py (alphabetical ordering within
subsection) and should be unaffected by the __future__ import in
plot_future_statements.py.
"""
# sphinx_gallery_thumbnail_path = '_static/demo.png'
im... | info[0] == 2
expected = 1 if PY2 else 1.5
assert 3/2 == expected
# Make sure print is a keyword not a function. Note: need to use exec because
# otherwise you get a SyntaxError on Python 3
if PY2:
exec('print "test"')
|
henryneu/Python | sample/string_io.py | Python | apache-2.0 | 480 | 0.002252 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
fr | om io import StringIO
from io import BytesIO
# 内存中读写字符
f = StringIO()
f.write('Hello')
f.write(' ')
f.write('World!')
print(f.getvalue())
f = StringIO('Hello!\nHi!\nGoodBye!')
while True:
s = f.readline()
| if s == '':
break
print(s.strip())
# 内存中读写二进制数
f = BytesIO()
f.write('中文'.encode('utf-8'))
print(f.getvalue())
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
print(f.read()) |
OpenNumismat/open-numismat-tracker | OpenNumismat/ListView.py | Python | gpl-3.0 | 27,712 | 0.000686 | import operator
import pickle
import os.path
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, pyqtSignal, QSortFilterProxyModel
from PyQt5.QtSql import QSqlQuery
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from OpenNumismat.EditCoinDialog.EditCoinDialog import EditCoinDialog
from OpenNumismat.Collect... | f model(self):
if not super(ListView, self).model():
return None
return self.proxyModel.sourceModel()
def rowInserted(self, index):
insertedRowIndex = self.proxyModel.mapFromSource(index)
self.selectRow(insertedRowIndex.row())
self.scrollTo(insertedRowIndex)
... | elf.li |
dmdm/PySite | pysite/plugins/eventlist/__init__.py | Python | agpl-3.0 | 4,369 | 0.000687 | # -*- coding: utf-8 -*-
import os
import datetime
from pysite.lib import load_site_config
NAME = "eventlist"
TITLE = "Loads a list of events."
DESCR = """
*************
The Eventlist
**** | *********
Basic Format
============
An eventlist is a YAML mapping. The field ``EVENTS`` contains the list of
events.
Each event is a mapping which has at least fields ``date_from`` and ``date_to``.
Both dates must be strings, preferrably as ISO dates: YYYY-MM-DD.
An event may have arbitrary additional | fields. Their meaning depends on the
used Jinja template.
The order of the fields or of events is not relevant. The list is
automatically sorted by ``date_from``.
Sample::
EVENTS:
- date_from: 2012-10-09
date_to: 2012-10-12
title: Breakfast by Tiffany
- date_from: 2012-11-01
date_to: 20... |
ShopRunner/jupyter-notify | setup.py | Python | bsd-3-clause | 1,019 | 0.001963 | # -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open('README.rst') as r:
readme = r.read()
with open('AUTHORS.txt') as a:
# reSt-ify the authors list
authors = ''
for author in a.read(). | split('\n'):
authors += '| '+author+'\n'
with open('LICENSE.txt') as l:
license = l.read()
setup(
name='jupyternotify',
version='0.1.15',
description='A Jupyter Notebook %%magic for Browser N | otifications of Cell Completion',
long_description=readme+'\n\n'+authors+'\nLicense\n-------\n'+license,
author='Michelangelo D\'Agostino',
author_email='mdagostino@shoprunner.com',
url='https://github.com/shoprunner/jupyter-notify',
license='BSD-3-Clause',
packages=find_packages(exclude=('tests... |
esaezgil/aiohttp | aiohttp/errors.py | Python | apache-2.0 | 4,390 | 0 | """HTTP related errors."""
from asyncio import TimeoutError
__all__ = (
'DisconnectedError', 'ClientDisconnectedError', 'ServerDisconnectedError',
'HttpProcessingError', 'BadHttpMessage',
'HttpMethodNotAllowed', 'HttpBadRequest', 'HttpProxyError',
'BadStatusLine', 'LineTooLong', 'InvalidHeader',
... | ch expected fingerprint."""
def | __init__(self, expected, got, host, port):
self.expected = expected
self.got = got
self.host = host
self.port = port
def __repr__(self):
return '<{} expected={} got={} host={} port={}>'.format(
self.__class__.__name__, self.expected, self.got,
self.ho... |
Anderson0026/mapproxy | mapproxy/util/coverage.py | Python | apache-2.0 | 7,709 | 0.001167 | # This file is part of the MapProxy project.
# Copyright (C) 2010 Omniscale <http://omniscale.de>
#
# 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... | it('\n'))
if len(polygons) == 1:
geom = polygons[0]
else:
geom = shapely.geometry.MultiPolygon(polygons)
return GeomCoverage(geom, srs, clip=True)
class MultiCoverage(object):
clip = False
"""Aggregates multiple coverages"""
def __init__(self, co... | self.bbox = self.extent.bbox
@cached_property
def extent(self):
return reduce(operator.add, [c.extent for c in self.coverages])
def intersects(self, bbox, srs):
return any(c.intersects(bbox, srs) for c in self.coverages)
def contains(self, bbox, srs):
return any(c.conta... |
jma/multivio_server | setup.py | Python | gpl-2.0 | 1,080 | 0.011111 | #!/usr/bin/env python
from distutils.core import setup, Extension
poppler_install_path = '/usr'
import multivio
setup(
name='multivio',
version=multivio.__version__,
description='Multivio server.',
long_description='''Multivio is a project...''',
license=multivio.__license__,
url='http://www.m... | ppler/mypoppler.i'],
swig_opts=['-c++', '-modern', '-I%s/include' % poppler_install_path],
extra_compile_args=['-I%s/include/poppler' % poppler_install_path],
| extra_link_args=['-lpoppler'])],
py_modules=['multivio.poppler.mypoppler'],
packages=[
'multivio'
],
scripts=[
'tools/multivio_server.py', 'tools/mvo_config_example.py'
],
keywords=['multivio'],
classifiers=[
'Development Status :: Beta',
'Environment :: Console',
'Inte... |
JshWright/home-assistant | tests/test_setup.py | Python | apache-2.0 | 14,933 | 0 | """Test component/platform setup."""
# pylint: disable=protected-access
import asyncio
import os
from unittest import mock
import threading
import logging
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.const import EVENT_HOMEASSISTANT_START
import homeassistant.config as config_ut... | s import discovery
from tests.common import \
get_ | test_home_assistant, MockModule, MockPlatform, \
assert_setup_component, get_test_config_dir
ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE
VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE)
_LOGGER = logging.getLogger(__name__)
class TestSetup:
"""Test the bootstrap utils."""
hass... |
tboch/mocpy | mocpy/moc/plot/wcs.py | Python | gpl-3.0 | 3,529 | 0.001984 | import numpy as np
from astropy import coordinates
from astropy import wcs
import astropy.units as u
from matplotlib.pyplot import figure
class World2ScreenMPL:
"""
Create a World2ScreenMPL for vizualizing a MOC in a matplotlib axis.
Parameters
----------
fig : `~matplotlib.pyplot.figure`
... | 5, fill=True, color | ="green")
... moc.border(ax=ax, wcs=wcs, alpha=0.5, color="black")
>>> plt.xlabel('ra')
>>> plt.ylabel('dec')
>>> plt.grid(color="black", linestyle="dotted")
"""
def __init__(self,
fig,
fov,
center=coordinates.SkyCoord(0, 0, unit="deg", fram... |
madmath/sous-chef | src/billing/tests.py | Python | agpl-3.0 | 4,079 | 0 | from django.test import TestCase
from order.factories import OrderFactory, OrderItemFactory
from billing.models import Billing, calculate_amount_total, BillingManager
import datetime
from member.factories import ClientFactory, RouteFactory
from order.models import Order
from django.core.urlresolvers import reverse
from... | self.client.logout()
bill = BillingFactory()
response = self.client.get(
rev | erse(
'billing:view',
kwargs={'pk': bill.id}
)
)
self.assertRedirects(
response,
reverse('page:login') + '?next=' + reverse('billing:view',
kwargs={'pk': bill.id}),
stat... |
setsulla/minicapy | minicapy/stream.py | Python | mit | 4,798 | 0.005002 | import os
import socket
import threading
from itsdangerous import bytes_to_int
from Queue import Queue
from minicapy.log import LOG as L
from minicapy.banner import Banner
MAX_SIZE = 5
class MinicapStream(object):
__instance = None
__mutex = threading.Lock()
def __init__(self, ip="127.0.0.1", port=1313)... | elif read_banner_bytes in [10, 11, 12, 13]:
self.banner.real_height += (bytes_to_int(reallen[cursor]) << ((read_banner_bytes - 10) * 8)) >> 0;
elif read_banner_bytes in [14, 15, 16, 17]:
self.banner.virtual_width += (bytes_to_int(real... | r_bytes in [18, 19, 20, 21]:
self.banner.virtual_height += (bytes_to_int(reallen[cursor]) << ((read_banner_bytes - 18) * 8)) >> 0;
elif read_banner_bytes == 22:
self.banner.orientation = bytes_to_int(reallen[cursor]) * 90
elif read_... |
houssine78/addons | resource_activity/models/partner.py | Python | agpl-3.0 | 949 | 0.006322 | # -*- coding: utf-8 -*-
# Copyright 2018 Coop IT Easy SCRLfs.
# License AGPL-3.0 | or later (http://www.gnu.org/licenses/agpl.html).
from openerp import _, api, fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
@api.multi
def _resource_activity_count(self):
for partner in self:
partner.activity_count = len(partner.resource_activiti... | lds.Boolean(string="Trainer")
is_partner = fields.Boolean(string="Partner")
resource_activities = fields.One2many('resource.activity','partner_id', string="Activities")
activity_count = fields.Integer(string='# of Activities', compute=_resource_activity_count)
resource_location_guide = fields.Many2o... |
dashea/anaconda | pyanaconda/ui/gui/spokes/user.py | Python | gpl-2.0 | 24,175 | 0.001448 | # User creation spoke
#
# Copyright (C) 2013-2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed i... | self, user, data):
GUIObject.__init__(self, data)
saveButton = self.builder.get_object("save_button")
GUIDialogInputCheckHandler.__init__(self, saveButton)
self._user = user
# Track whether the user has requested | a home directory other
# than the default. This way, if the home directory is left as
# the default, the default will change if the username changes.
# Otherwise, once the directory is set it stays that way.
self._origHome = None
if self._user.homedir:
self._homeSet ... |
GAM-team/GAM | src/gam/gapi/directory/privileges.py | Python | apache-2.0 | 1,061 | 0 | from gam.var import GC_Values, GC_CUSTOMER_ID
from gam import display
from gam import gapi
from gam.gapi import directory as gapi_directory
def flatten_privilege_list(privs, parent=None):
flat_privs = []
for priv i | n privs:
children = []
if parent:
priv['parent'] = parent
if priv.get('childPrivileges'):
children = flatten_privilege_list(priv['childPrivileges'],
parent=priv['privilegeN | ame'])
priv['children'] = ' '.join(
[child['privilegeName'] for child in children])
del priv['childPrivileges']
flat_privs = flat_privs + children
flat_privs.append(priv)
return flat_privs
def print_(return_only=False):
cd = gapi_directory.build()
pr... |
modoboa/modoboa | modoboa/limits/migrations/0001_squashed_0004_auto_20160413_1312.py | Python | isc | 2,070 | 0.002415 | # Generated by Django 2.0.13 on 2020-01-04 17:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import modoboa.limits.models
class Migration(migrations.Migration):
replaces = [
('limits', '0001_initial'),
('limits', '0002_auto_20151114... | limits.models.ObjectLimitMixin, models.Model),
),
migrations.AlterUniqueTogether(
name='domainobjectlimit',
unique_together=set( | [('domain', 'name')]),
),
]
|
hep-gc/cloudscheduler | unit_tests/user_requests_setup.py | Python | apache-2.0 | 3,368 | 0.003563 | #!/usr/bin/env python3
"""
Unit tests.
"""
from unit_test_common import execute_csv2_request, initialize_csv2_request, ut_id, generate_secret
from sys import argv
import user_requests_cleanup
def main(gvar):
if not gvar:
gvar = {}
if len(argv) > 1:
initialize_csv2_request(gvar, select... | execute_csv2_request(
gvar, 0, None, 'user "{}" successfully added.'.format(ut_id(gvar, 'utu4')),
'/user/add/', form_data={
'username': ut_id(gvar, 'utu4'),
'password': gvar['user_secret'],
'cert_cn': '%s test user four' % ut_id(gvar, 'user'),
'group_n... | peruser': 1
}
)
# user to be deleted in test_user_delete
execute_csv2_request(
gvar, 0, None, 'user "{}" successfully added.'.format(ut_id(gvar, 'utu5')),
'/user/add/', form_data={
'username': ut_id(gvar, 'utu5'),
'password': gvar['user_secret']
}
... |
gmarciani/pyprof | profile/parser_profiler.py | Python | mit | 7,000 | 0.010571 | from control.profile.base.baseprofiler import baseprofiler
from output.__init__ import OUTPUT_DIR
from exception.exceptions import UnsupportedParserError
from control.parse.c_element_tree import cElementTreeParser as cElementTree
from control.parse.element_tree import ElementTreeParser as ElementTree
from control.parse... | ERS:
print "\t{} . . .".format(str(PARSERS_NAME[parser]))
params["parser"] = parser
dataset.append(self.profile(params)[0])
return dataset
def plot_data(self, dataset, directory = PARAMS["output_dir"]):
"""
Stores to the specified directory a MathPlot... | : the dataset to be plotted.
@type directory: string
@param directory: directory to store the computed MatPlotLib plot.
"""
max_input = dataset[0]["Max Input"]
file_name = " ".join([data["Parser"] for data in dataset]) + " " + str(max_input)
file_path = os.path.jo... |
huaxz1986/git_book | chapters/Kaggle/grid_search.py | Python | gpl-3.0 | 1,955 | 0.035319 | import scipy
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from data_clean import current_time
from sklearn.model_selection import train_test_split
from data_preprocess import Data_Preprocesser,Data_Cleaner
de... | lassifier(),tuned_parameters,cv=10,scoring="roc_auc")
| clf.fit(X_train,y_train)
print("Best parameters set found:",clf.best_params_)
print("Randomized Grid scores:")
for params, mean_score, scores in clf.grid_scores_:
print("\t%0.3f (+/-%0.03f) for %s" % (mean_score, scores.std() * 2, params))
print("Optimized Score:",clf.score(X_test,y_test))... |
nearlyfreeapps/python-googleadwords | tests/adspygoogle/adwords/ad_param_service_unittest.py | Python | apache-2.0 | 6,640 | 0.006777 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#
# Copyright 2010 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... | NDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Unit tests to cover AdParamService."""
__author__ = 'api.sgrinberg@gmail.com (Stan Grinberg)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..... | on import Utils
from tests.adspygoogle.adwords import HTTP_PROXY
from tests.adspygoogle.adwords import SERVER_V201109
from tests.adspygoogle.adwords import TEST_VERSION_V201109
from tests.adspygoogle.adwords import VERSION_V201109
from tests.adspygoogle.adwords import client
class AdParamServiceTestV201109(unittest.T... |
NewAcropolis/api | app/routes/emails/schemas.py | Python | mit | 3,656 | 0 | from app.models import EMAIL_TYPES
from app.schema_validation.definitions import uuid, datetime, date
def email_types():
pattern = '|'.join(EMAIL_TYPES)
return {
"type": "string",
"pattern": pattern,
"validationMessage": "is not an email type",
}
post_create_email_schema = {
... | },
"timestamp": datetime
},
"required": ["id", "timestamp"]
}
post_import_emails_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST schema for importing emails",
"type": "array" | ,
"items": {
"type": "object",
"$ref": "#/definitions/email"
},
"definitions": {
"email": post_import_email_schema
}
}
post_import_email_member_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "POST schema for importing emails",
"type"... |
rexzhang/rpress | rpress/__init__.py | Python | gpl-3.0 | 116 | 0 | #!/usr/bin/env python
# coding=utf-8
from .application import create_ | app
__version | __ = '0.8'
app = create_app()
|
priestd09/mopidy | mopidy/local/translator.py | Python | apache-2.0 | 3,919 | 0 | from __future__ import absolute_import, unicode_literals
import logging
import os
import re
import urllib
import urlparse
from mopidy import compat
from mopidy.models import Track
from mopidy.utils.encoding import locale_decode
from mopidy.utils.path import path_to_uri, uri_to_path
M3U_EXTINF_RE = re.compile(r'#EXT... | ', locale_decode(error))
return tracks
if not contents:
return tracks
extended = contents[0].decode('latin1').startswith('#EXTM3U')
track = Track()
for line in contents:
line = line.strip().decode('latin1')
if line.startswith('#'):
if extended and line.sta... | .urlsplit(line).scheme:
tracks.append(track.copy(uri=line))
elif os.path.normpath(line) == os.path.abspath(line):
path = path_to_uri(line)
tracks.append(track.copy(uri=path))
else:
path = path_to_uri(os.path.join(media_dir, line))
tracks.append... |
codedread/scour | scour/scour.py | Python | apache-2.0 | 178,584 | 0.00238 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Scour
#
# Copyright 2010 Jeff Schiller
# Copyright 2010 Louis Simard
# Copyright 2013-2014 Tavendo GmbH
#
# This file is part of Scour, http://www.codedread.com/scour/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this fil... | es?
# - only remove unreferenced elements if they are not children of a referenced | element
# - add an option to remove ids if they match the Inkscape-style of IDs
# - investigate point-reducing algorithms
# - parse transform attribute
# - if a <g> has only one element in it, collapse the <g> (ensure transform, etc are carried down)
from __future__ import division # use "true" division inst... |
jaklinger/nesta_dataflow | collect_data/utils/uae/courses/gen_courses_in_uae.py | Python | mit | 6,461 | 0.00031 | import requests
from bs4 import BeautifulSoup
from bs4.element import Comment
import re
from utils.common.nlp import tokenize_alphanum
from utils.common.datapipeline import DataPipeline
from utils.common.browser import SelfClosingBrowser
from utils.common.db_utils import read_all_results
_pattern = re.compile('[\W_]+'... | _url].ap | pend(url)
print("Skipping", n_skip, ", doing", n_todo)
# Read UCAS courses
ucas_results = read_all_results(config, "input_db", "input_table_ucas")
ucas_courses = set(x[0] for x in ucas_results)
# Filter out long courses
ucas_courses = list(filter(lambda x: len(x.split()) < 6, ucas_courses))
... |
ssarangi/spiderjit | src/optimizer/inst_combining.py | Python | mit | 1,791 | 0.001117 | """
The MIT License (MIT)
Copyright (c) <2015> <sarangis>
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,... | INGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT O | R OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from src.ir.function import *
from src.ir.constants import Number
from src.ir.base_ir_visitor import IRBaseVisitor
from src.ir.irbuilder import IRBuilder
from src.optimizer.pass_support import *
from... |
open-synergy/opnsynid-l10n-indonesia | l10n_id_taxform_daftar_bukti_potong_pph_d113205/models/__init__.py | Python | agpl-3.0 | 174 | 0 | # -*- coding: | utf-8 -*-
# Copyright 2017 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import daftar_bukti_potong_ | pph_d113205
|
theyosh/TerrariumPI | hardware/relay/remote_relay.py | Python | gpl-3.0 | 1,365 | 0.019048 | from . import terrariumRelay, terrariumRelayDimmer, terrariumRelayLoadingException
from terrariumUtils import terrariumUtils
class terrariumRelayRemote(terrariumRelay):
HARDWARE = 'remote'
NAME = 'Remote power switch (API)'
def _loa | d_hardware(self):
if terrariumUtils.parse_url(self.address):
return self.address
raise | terrariumRelayLoadingException(f'Invalid url for relay {self}')
# Overrule the main set_hardware_state function, as this is not yet possible (maybe a post action)
def set_hardware_state(self, state, force = False):
pass
def _get_hardware_value(self):
data = terrariumUtils.get_remote_data(self.device)
... |
threatstream/mnemosyne | test/test_webapi/test_d/dorks_test.py | Python | gpl-3.0 | 4,675 | 0.001925 | # Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk>
#
# 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 ... | r)
def test_get_dorks(self):
sut = DorkTest.sut
res = sut.get('/aux/dorks')
result = json.loads(res.body)['dorks']
expected = [{'content': '/jamesBond.php', 'count': 1, 'type': 'inurl',
'timestamp': | '2011-01-01T00:00:00'},
{'content': '/some/path', 'count': 2, 'type': 'inurl',
'timestamp': '2012-02-02T00:00:00'},
{'content': '/no/fjords/here', 'count': 3,
'type': 'inurl', 'timestamp': '2013-03-03T00:00:00'}]
#TODO: Compare t... |
dasbruns/PrismaIO | RulesContainer.py | Python | gpl-2.0 | 667 | 0.001499 | #!/usr/bin/env python
class RulesContainer(object):
def __init__(self):
self.rules = {}
def __str__(self):
s = ''
for key in self.rules:
for value in self.rules[key]:
s += str(value) + ', '
return s[:- | 2]
def __getitem__(self, key):
return self.rules[key]
def __iter__(self):
return self.rules.items().__iter__()
def keys(self):
return self.rules.keys()
def __len__(self):
return len(self.rules)
def add(self, rule):
if rule.hist not in self.rules:
... | e)
|
ghchinoy/tensorflow | tensorflow/contrib/ffmpeg/__init__.py | Python | apache-2.0 | 1,369 | 0.00073 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | l_util import remove_undocumented
_allowed_symbols = ['decode_audio', ' | encode_audio', 'decode_video']
remove_undocumented(__name__, _allowed_symbols)
|
davguez/malodos | src/data/__init__.py | Python | gpl-3.0 | 445 | 0 | '''
Created on 21 juin 2010. Copyright 2010, David GUEZ
@author: david guez (guezdav@gmail.com)
This file is a part of the source code of the MALODOS project.
You can use and distribute it freely, but have to conform to the license
attached to this project (LICE | NSE.txt file)
=====================================================================
'''
import imageData
from database import theConfig
theData = imageDa | ta.imageData()
|
canpolat/bookbinder | bookbinder/templates.py | Python | gpl-3.0 | 2,011 | 0.002486 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#--------------------------------------------------------------------
# Copyright (c) 2014 Eren Inan Canpolat
# Author: Eren Inan Canpolat <eren.canpolat@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General... | root.maxlevel}" />
<meta name="dtb:totalPageCount" content="0" />
<meta name="dtb:maxPageNumber" content="0" />
</head>
<docTitle>
<text>{book.title}</text>
</docTitle>
{navmap}
</ncx>"""
container_xml = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<container xmlns="urn:oasis:names:tc:... | on/oebps-package+xml"/>
</rootfiles>
</container>
"""
|
andrewleech/SickRage | sickbeard/notifiers/nma.py | Python | gpl-3.0 | 2,876 | 0.003825 | # coding=utf-8
from __future__ import print_function, unicode_literals
import sickbeard
from sickbeard import logger, common
from pynma import pynma
class Notifier(object):
def test_notify(self, nma_api, nma_priority):
return self._sendNMA(nma_api, nma_priority, event="Test", message="Testing NMA setti... | gs[common.NOTIFY_DOWNLOAD],
message=ep_name)
def notify_subtitle_download(self, ep_name, lang):
if sickbeard.NMA_NOTIFY_ONSUBTITLEDOWNLOAD:
self._sendNMA(nma_api=None, nma_priority=None, event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD],
... | update_text = common.notifyStrings[common.NOTIFY_GIT_UPDATE_TEXT]
title = common.notifyStrings[common.NOTIFY_GIT_UPDATE]
self._sendNMA(nma_api=None, nma_priority=None, event=title, message=update_text + new_version)
def notify_login(self, ipaddress=""):
if sickbeard.USE_NMA... |
lixiangning888/whole_project | modules/signatures_orginal_20151110/infostealer_keylog.py | Python | lgpl-3.0 | 1,168 | 0.004281 | # Copyright (C) 2014 Optiv, Inc. (brad.spengler@optiv.com)
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.
from lib.cuckoo.common.abstracts i | mport Signature
class KeyLogger(Signature):
name = "infostealer_keylog"
description = "Sniffs keystrokes"
severity = 3
categories = ["infostealer"]
authors = ["Optiv"]
minimum = "1.2"
evented = True
filter_apinames = set(["SetWindowsHookExA","SetWindowsHookExW","GetAsyncKeyState"])
... | ocess):
if call["api"] == "GetAsyncKeyState":
# avoid an IE false positive
keycode = int(self.get_argument(call, "KeyCode"), 10)
# whitelist a-z, 0-9
if (keycode >= 0x30 and keycode <= 0x39) or (keycode >= 0x4a and keycode <= 0x5a):
return True
... |
google/nitroml | nitroml/automl/autotrainer/subpipeline.py | Python | apache-2.0 | 6,444 | 0.002328 | # Copyright 2020 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, ... | aining and evaluation (required).
transform_graph: An optional Channel of 'TransformPath' type, serving as
the input transform graph if present.
schema: An optional Channel of 'SchemaPath' type, serving as the schem | a
of training and eval data.
train_steps: Number of steps (batches) to train for.
eval_steps: Number of steps (batches) to evaluate.
use_keras: When `True`, uses Keras Models, otherwise uses Estimators.
enable_tuning: When `True`, performs hyperparameter tuning using the
built-in... |
matthewrmshin/cylc | doc/src/conf.py | Python | gpl-3.0 | 5,004 | 0 | # THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2019 NIWA & British Crown (Met Office) & Contributors.
#
# 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 th... | : "#0000EE;",
"headbgcolor": "white",
| "headtextcolor": "#FF5966",
"linkcolor": "#0000EE;",
"visitedlinkcolor": "#551A8B;",
"headlinkcolor": "#0000EE;",
"codebgcolor": "#ebf9f6",
}
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'**': ['globaltoc.html', 'searchbox.html', 'sourcelink.html'],
'... |
zmbc/shakespearelang | shakespearelang/_character.py | Python | mit | 702 | 0 | fr | om .errors import ShakespeareRuntimeError
from ._utils import normalize_name
class Character:
"""A character in an SPL play."""
def __init__(self):
self.value = 0
self.stack = []
def __str__(self):
return f'{self.value} ({" ".join([str(v) for v in self.stack][::-1])})'
def p... | character's stack."""
self.stack.append(newValue)
def pop(self):
"""Pop a value off the character's stack, and set the character to
that value."""
if len(self.stack) == 0:
raise ShakespeareRuntimeError("Tried to pop from an empty stack.")
self.value = self.stack.... |
lociii/googleads-python-lib | examples/adspygoogle/dfp/v201306/get_all_placements.py | Python | apache-2.0 | 1,625 | 0.003077 | #!/usr/bin/python
#
# Copyright 2013 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either... | un
create_placement.py."""
__author__ = 'api.shamjeff@gmail.com (Jeff Sham)'
# 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 c... |
dockerera/func | funcweb/funcweb/tests/test_model.py | Python | gpl-2.0 | 841 | 0 | # If your project uses a database, you can set up database tests
# similar to what you see below. Be sure to set the db_uri to
# an appropriate uri for your testing database. sqlite is a good
# choice for testing, because you can use an in-memory database
# which is very fast.
from turbogears import testutil, database... | t YourDataClass, User
# database.set_db_uri("sqlite:///:memory:")
# class TestUser(testutil.DBTest):
# def get_model(self):
# return User
# def test_creation(self):
# "Object creation should set the name"
# obj = User(user_name = "creosote",
# email_address = "spa... | ame == "Mr Creosote"
|
pfalcon/micropython | tests/strict/mod.py | Python | mit | 248 | 0 | print(__name__)
val = 1
def foo():
print("foo")
# This module is supposed to be imported, no | t run directly. But run-tests
# script will run it, so add d | ummy __main__() and corresponding .exp file.
def __main__():
print("Shouldn't run")
|
ysig/BioClassSim | test/BioTest/UCNEs/UCNES_Class.py | Python | apache-2.0 | 4,554 | 0.01581 | import numpy as np
import os
import sys
import math
#import class files
# sys.path.append('../../../')
from source import bioRead as br
from source import classify as cl
#import PyInsect for measuring similarity
#sys.path.append('../../../../')
from PyINSECT import representations as REP
from PyINSECT import comparator... | sts('SimilaritiesAndDictionaries/UCNE.npz'):
# Use them
npz = np.load('SimilaritiesAndDictionaries/UCNE.npz')
hd = npz['hd']
cd = npz['cd']
S = npz['S']
l1 = npz['l1']
l2 = npz['l2']
l = npz['l']
L = np.append(np.zeros(l1),np.ones(l2),axis=0)
print "WARNING: Using cached data!"
e... | UCNEs-10.fasta')
hd = sr.getDictionary()
print "Gained Human Dictionary"
# Get Chicken UCNE fasta data
sr.read('./biodata/UCNEs/galGal3_UCNEs.fasta')
# sr.read('./biodata/UCNEs/galGal3_UCNEs-10.fasta')
cd = sr.getDictionary()
print "Gained Chicken Dictionary"
# Set n-gram graph analy... |
hyperNURb/ggrc-core | src/ggrc_workflows/settings/development.py | Python | apache-2.0 | 270 | 0 | # Copyright (C) 2013 Goog | le Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: dan@reciprocitylabs.com
# Main | tained By: dan@reciprocitylabs.com
EXTENSIONS = ['ggrc_workflows']
|
OompahLoompah/HackerWatch | HackerWatch/api.py | Python | mit | 1,718 | 0.005239 | from urllib2 import Request, urlopen, URLError
import json
print("Test")
class api():
def __init__(self):
print("test1")
def GetTopStories(self):
try:
stories = self.GetURL('https://hacker-news.firebaseio.com/ | v0/topstories.json')
return stories
except URLError, e:
return int(1)
def GetItem(self, story_id):
try:
item = self.GetURL('https://hacker-news.firebaseio.com/v0/item/' + str(story_id) + '.json')
return item
except URLError, e:
ret... | + '.json')
return user
except URLError, e:
return int(1)
def GetJobStories(self):
try:
jobs = self.GetURL('https://hacker-news.firebaseio.com/v0/jobstories.json')
return jobs
except URLError, e:
return int(1)
def GetShowStori... |
Clarify/clarify_brightcove_sync | clarify_brightcove_sync/clarify_brightcove_bridge.py | Python | mit | 6,892 | 0.002467 | from collections import Counter
from clarify_python.helper import get_embedded_items, get_link_href
MAX_METADATA_STRING_LEN = 2000
def default_to_empty_string(val):
return val if val is not None else ''
class ClarifyBrightcoveBridge:
def __init__(self, clarify_client, bc_client):
self.clarify_clie... | KIPPING: No suitable video src url for video {0} {1}'.format(video['id'], | video['name']))
return
self.log('Creating bundle for video {0} {1}'.format(video['id'], video['name']))
if not self.dry_run:
external_id = video['id']
name = video.get('original_filename')
metadata = self._metadata_from_video(video)
self.clar... |
txtbits/daw-python | ficheros/temperaturas.py | Python | mit | 1,471 | 0.010966 | # -*- coding: utf-8 -*-
'''
Crea un programa que analice el fichero y muestre:
- Los años y sus temperaturas (máxima, mínima y media), ordenados por año
- Los años y su tempertura media, ordenados por temperatura en orden descendente
- Crea un fichero html:
Encabezado: Temperaturas de Zaragoza
Fuente: (la url,... | lit()
listado.append(registro)
return listado
def listado_anio(f):
listado = obtener_listado(f)
listado.sort()
| for x in listado:
print x[0:4]
def listado_temp(f):
listado = obtener_listado(f)
listado.sort(key=itemgetter(1), reverse=True)
for x in listado:
if not '-' in x[1:4]:
print x[0:4]
def crear_html(f):
import sys
from operator import itemgetter
try:
# Instrucción... |
Mega-DatA-Lab/mxnet | example/rcnn/rcnn/tools/reeval.py | Python | apache-2.0 | 2,273 | 0.00308 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | distributed under 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
# specif | ic language governing permissions and limitations
# under the License.
import argparse
import cPickle
import os
import mxnet as mx
from ..logger import logger
from ..config import config, default, generate_config
from ..dataset import *
def reeval(args):
# load imdb
imdb = eval(args.dataset)(args.image_set,... |
s0riak/pi-led-control | src/server/programs/scheduledprogram.py | Python | agpl-3.0 | 1,953 | 0.000512 | # Copyright (c) 2016 Sebastian Kanis
# This file is part of pi-led-control.
# pi-led-control 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 ve... | rrentDay
else:
sleepDuration = self._timeOfDay + 3600 * 24 - secondsInCurrentDay
logging.getLogger("main").info("sleeping for " + str(sleepDuration) + " seconds")
self._waitIfNotStopped(sleepDuration)
self._program.run()
| def setThreadStopEvent(self, threadStopEvent):
self.threadStopEvent = threadStopEvent
self._program.setThreadStopEvent(threadStopEvent)
def setColorSetter(self, colorSetter):
self._colorSetter = colorSetter
self._program.setColorSetter(colorSetter)
def getCurrentColor(self):
... |
lcpt/xc | verif/tests/elements/shell/test_shell_mitc4_15.py | Python | gpl-3.0 | 3,522 | 0.037489 | # -*- coding: utf-8 -*-
'''Verification test taken from example 2-005 of
the SAP 2000 verification manual.'''
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__copyright__= "Copyright 2015, LCPT and AOO"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com"
# feProblem.setVerbosit... | Cross section depth expressed in inches.
unifLoad= 0.0001 # Uniform load in lb/in2.
ptLoad= 0.0004 # Punctual load in lb.
nLoad= unifLoad*CooMaxX*CooMaxY/NumDivI/NumDivJ # Tributary load on each node
import xc_base
import geom
import xc
from solution impo | rt predefined_solutions
from model import predefined_spaces
from materials import typical_materials
# Problem type
feProblem= xc.FEProblem()
preprocessor= feProblem.getPreprocessor
nodes= preprocessor.getNodeHandler
modelSpace= predefined_spaces.StructuralMechanics3D(nodes)
# Define materials
elast= typical_material... |
raccoongang/socraticqs2 | mysite/pages/tasks.py | Python | apache-2.0 | 496 | 0 | from django.template import Context, loader
from dja | ngo.core.mail import EmailMessage
from models import InterestedPlugin
def form_send(interested_form):
"""
Send interested form
"""
tmp = loader.get_template('pages/mail/interested_mail.html')
cntx = Context({'form': interested_form})
mail_body = tmp.render(cntx)
email_to = InterestedPlugi... | o])
email.send()
|
anhstudios/swganh | data/scripts/templates/object/tangible/space/story_loot/shared_loot_naboo_borvo.py | Python | mit | 472 | 0.04661 | #### 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(ke | rnel):
result = Tangible()
result.template = "object/tangible/space/story_loot/shared_loot_naboo_borvo.iff"
result.attribute_template_id = -1
result.stfName("space/story_loot_n","loot_naboo_borvo")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
liefdiy/bite-project | tools/bugs/server/appengine/providers/provider.py | Python | apache-2.0 | 816 | 0.003676 | # Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | e 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.
"""Defines the available providers."""
__auth | or__ = 'jason.stredwick@gmail.com (Jason Stredwick)'
class Provider(object):
"""Define available providers."""
DATASTORE = 'datastore'
ISSUETRACKER = 'issuetracker'
|
curlyjr25/FrogWebsite | frogs/apps/frogblog/models.py | Python | bsd-3-clause | 521 | 0.078695 | from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.no | w)
published_date = models.DateTimeField(
blank=True, null=True)
def published (self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
| |
joaduo/python-simplerpc | simplerpc/common/abstract/decorators/context_singleton.py | Python | bsd-3-clause | 1,380 | 0.006522 | # -*- coding: utf-8 -*-
'''
Copyright (c) 2013, LastSeal S.A.
Copyright (c) 2011-2012, Joaquin G. Duo
All rights reserved.
This code is distributed under BSD 3-clause License.
For details check the LICENSE file in the root of the project.
'''
class context_singleton(object):
'''
Singleton pattern decorator... | msg = "You should always provide a context for class: %r" % self.class_.__class__.__name__
raise RuntimeError(msg)
if not context.has_config('singleton', self.class_):
context.set_config('singl | eton', self.class_(context=context, *a, **ad), self.class_)
return context.get_config('singleton', self.class_)
def smokeTestModule():
from simplerpc.common.context.base import ContextBase
class Context(ContextBase):
def _loadInitConfig(self):
pass
ctx = Context('smoke test')
... |
imperial-genomics-facility/data-management-python | ehive/runnable/jobfactory/FastqFileFactory.py | Python | apache-2.0 | 2,589 | 0.027037 | import os,re,fnmatch
from ehive.runnable.IGFBaseJobFactory import IGFBaseJobFactory
class FastqFileFactory(IGFBaseJobFactory):
'''
A job factory class for creating fan jobs for demultilexed fastq files
'''
def param_defaults(self):
params_dict=super(FastqFileFactory,self).param_defaults()
params_dict.u... | =list() # create empty output list
for root, _, files in os.walk(top=fastq_dir):
for file in files:
if fnmatch.fnmatch(file, '*.fastq.gz'): | # only consider fastq.gz files for now
if re.search(read_pattern,file): # skip if its not R1 and R2 reads and not illumina format name
if required_keyword and fnmatch.fnmatch(file, required_keyword ):
fastq_list.append({'fastq_file... |
liuxuyang/tools | debugtools/debugtools.py | Python | apache-2.0 | 16,859 | 0.003025 | import os
import sys
import subprocess
import time
import logging
import argparse
import ConfigParser
version = "1.1.0"
CFG_PATH = 'config.cfg'
CFG_SECTION_GLOBAL = 'global'
CFG_OPTION_PROJECT_NAME = "PROJECT_NAME"
CFG_OPTION_APP_NAME = "APP_NAME"
CFG_OPTION_APP_PKG_NAME = "APP_PKG_NAME"
CFG_OPTION_CONFIG_PATH = "C... | OG_PATH, os.path.join(os. | environ['HOME'], ".log/monkey"))
config.set(CFG_SECTION_GLOBAL, CFG_OPTION_GRADLE_PATH,
os.path.join(os.environ['HOME'], '.gradle/wrapper/dists/'))
config.set(CFG_SECTION_GLOBAL, CFG_OPTION_APK_BUILD_PATH, "app/build/outputs/apk/")
config.set(CFG_SECTION_GLOBAL, CFG_OPTION_APK... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/hotshot/stats.py | Python | unlicense | 2,053 | 0.001948 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: stats.py
"""Statistics analyzer for HotShot."""
import profile
import pstats
import hotshot.log
from hotshot.log import ENTER, EXIT
def load(filenam... | , (filename, lineno, funcname), tdelta = event
if tdelta > 0:
taccum += tdelta
if what == ENTER:
frame = self.new_frame(filename, lineno, funcname)
p.trace_dispatch_call(frame, taccum * 1e-06)
taccum = 0
| elif what == EXIT:
frame = self.pop_frame()
p.trace_dispatch_return(frame, taccum * 1e-06)
taccum = 0
return pstats.Stats(p)
def new_frame(self, *args):
try:
code = self._code[args]
except KeyError:
code = FakeCod... |
shubhmsng/Codes | python codes/gui.py | Python | gpl-2.0 | 823 | 0.012151 | from graphics import *
def main():
winWidth = 200 # give a name to the window width
winHeight = 150 # and height
win = GraphWin('Face', winWidth, winHeight) # give title and dimensions
win.setCoords(0, 0, winWidth, winHeight) # make right side up coordinates!
head = Circle(Point(40,100), 25) # set c... | s
eye2.setWidth(3)
eye2.draw(win)
mouth = Oval(Point(3 | 0, 90), Point(50, 85)) # set corners of bounding box
mouth.setFill("red")
mouth.draw(win)
message = Text(Point(winWidth/2, 20), 'Click anywhere to quit.')
message.draw(win)
win.getMouse()
win.close()
main()
|
0x0mar/king-phisher | king_phisher/configuration.py | Python | bsd-3-clause | 7,045 | 0.020582 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/configuration.py
#
# 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, th... | _file_ext(self):
"""
The extension o | f the current configuration file.
"""
return os.path.splitext(self.configuration_file)[1][1:]
def _serializer(self, operation, *args):
if not self.configuration_file_ext in SERIALIZER_DRIVERS:
raise ValueError('unknown file type \'' + self.configuration_file_ext + '\'')
function = SERIALIZER_DRIVERS[self.c... |
albert-chin/yowsup | yowsup/common/http/httpproxy.py | Python | gpl-3.0 | 3,283 | 0.006701 | '''
Copyright (c) <2012> Tarek Galal <tare2.galal@gmail.com>
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... | LE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import os, base64
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlpars... | :
self.address = address
self.username = username
self.password = password
def __repr__(self):
return repr(self.address)
def handler(self):
return HttpProxyHandler(self)
@staticmethod
def getFromEnviron():
url = None
for key in ('http_proxy', 'h... |
materialsproject/pymatgen | pymatgen/io/tests/test_cssr.py | Python | mit | 1,796 | 0 | # Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
Created on Jan 24, 2012
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Jan 24, 2... | 0.7071
10 O 0.0966 0.2500 0.7413
11 O 0.1657 0.0461 0.2854
12 O 0.1657 0.4539 0.2854
13 O 0.3343 0.5461 0.7854
14 O 0.3343 0.9539 0.7854
15 O 0.4034 0.7500 0.2413
16 O 0.4566 0.2500 0.2071
17 O 0.5434 0.7500 0.7929
18 O 0.5966 0.2500 0.7587
19 O 0.6657 0.0461 0.2146
20 O 0.6657 0.4539 0.2146
21 O 0. | 8343 0.5461 0.7146
22 O 0.8343 0.9539 0.7146
23 O 0.9034 0.7500 0.2587
24 O 0.9566 0.2500 0.2929"""
self.assertEqual(str(self.cssr), expected_string)
def test_from_file(self):
filename = os.path.join(PymatgenTest.TEST_FILES_DIR, "Si.cssr")
cssr = Cssr.from_file(filename)
self.assert... |
levilucio/SyVOLT | UMLRT2Kiltera_MM/transformation/models/State2CProcDef_MDL.py | Python | mit | 142,227 | 0.020186 | """
__State2CProcDef_MDL.py_____________________________________________________
Automatically generated AToM3 Model File (Do not modify directly)
Author: gehan
Modified: Wed Feb 11 16:35:42 2015
____________________________________________________________________________
"""
from stickylink import *
from widthXfillXd... | etValue('State')
# cardinality
self.obj105.cardinality.setValue('+')
self.obj105.graphClass_= graph_State
if self.genGraphics:
new_obj = graph_State(180.0,60.0,self.obj105)
new_obj.DrawObject(self.UMLmodel)
self.UMLmodel.addtag_withtag("State", new_obj.tag)
new_obj.layConst... | t Constraints
new_obj.layConstraints['Text Scale'] = 1.0
new_obj.layConstraints['scale'] = [1.0, 1.0]
else: new_obj = None
|
iulian787/spack | var/spack/repos/builtin/packages/py-google-pasta/package.py | Python | lgpl-2.1 | 648 | 0.00463 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
clas | s PyGooglePasta(PythonPackage):
"""pasta is an AST | -based Python refactoring library."""
homepage = "https://github.com/google/pasta"
url = "https://pypi.io/packages/source/g/google-pasta/google-pasta-0.1.8.tar.gz"
version('0.1.8', sha256='713813a9f7d6589e5defdaf21e80e4392eb124662f8bd829acd51a4f8735c0cb')
depends_on('py-setuptools', type='build'... |
stuart-knock/tvb-framework | tvb/adapters/creators/__init__.py | Python | gpl-2.0 | 1,469 | 0.006807 | # -*- coding: utf-8 -*-
#
#
# TheVirtualBrain-Framework Package. This package holds all Data Management, and
# Web- | UI helpful to run b | rain-simulations. To use it, you also need do download
# TheVirtualBrain-Scientific Package (for simulators). See content of the
# documentation-folder for more details. See also http://www.thevirtualbrain.org
#
# (c) 2012-2013, Baycrest Centre for Geriatric Care ("Baycrest")
#
# This program is free software; you can ... |
zorchenhimer/NoudaEngine | lib/Level.py | Python | mit | 9,721 | 0.002572 | #!/usr/bin/python
import pygame
import random
import math
from lib.GameObjects import Player, Enemy
from lib.Globals import Vars, FixPath, UnitType, TileImage
from lib.Pathing import MovementPath
from lib.EventHandler import JoyHandler, KeyHandler
from lib.Effects import Explosion
from lib.Menu import *
from lib.Logge... | tle('Game Over')
self.GameOverMenu.add_item(1, 'Return to main menu', self.show_main_menu)
self.GameOverMenu.add_item(2, 'Exit', self.m_exit)
Info('LevelControl init finished.')
self.show_main_menu()
def show_level_menu(self):
self.LevelState = LevelState.MENU
self... | ars()
vars.CurrentHandler = self.LevelMenu.KeyHandle
vars.CurrentHandler_js = self.LevelMenu.JoyHandle
bg = pygame.Surface(pygame.display.get_surface().get_size())
self.CurrentLevel.draw(bg)
self.LevelMenu.set_background(bg)
def show_game_over_menu(self):
self.LevelS... |
Chibin/gpdb | gpMgmt/bin/gppylib/test/unit/test_cluster_gpsegstart.py | Python | apache-2.0 | 1,956 | 0.004601 | #!/usr/bin/env python
import os, sys
import unittest
from gppylib import gplog
from gpsegstart import GpSegStart
from mock import patch
logger = gplog.get_unittest_logger()
class GpSegStartTestCase(unittest.TestCase):
@patch('gpsegstart.GpSegStart.getOverallStatusKeys', return_value=[])
@patch('gpsegstart.g... | ----------------- Mainline ----------------- | ---------------
if __name__ == '__main__':
unittest.main()
|
MKridler/pyxley | pyxley/charts/mg/mg.py | Python | mit | 1,107 | 0.00271 | from ..charts import Chart
class MG(Chart):
def __init__(self, chart_id, url, params, api_route):
opts = {
"url": url,
"chart_id": chart_id,
"params": params
}
super(MG, self).__init__("MetricsGraphics", opts, api_ | route)
class OptionHelper(object):
def __init__(self):
self.options = {}
def set_float(self, option, value):
if not isinstance(value, float):
raise TypeError("Inflator must be a float")
self.options[option] = valu | e
def set_integer(self, option, value):
try:
int_value = int(value)
except ValueError as err:
print(err.args)
self.options[option] = value
def set_boolean(self, option, value):
if not isinstance(value, bool):
raise TypeError("%s must be a bo... |
kurtrr/open-numismat | OpenNumismat/Collection/Import/CoinManagePredefined.py | Python | gpl-3.0 | 7,605 | 0.001315 | # -*- coding: utf-8 -*-
import datetime, decimal
try:
import pyodbc
except ImportError:
pass
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QFileDialog
import OpenNumismat
from OpenNumismat.Collection.Import import _Import, _DatabaseServerError
class ImportCoinManagePredefined(_Import):
C... | hasattr(row, 'Type ID'):
value = getattr(row, 'UseGraphic')
country = getattr(row, 'Country')
typeId = ge | tattr(row, 'Type ID')
if value and country:
dir_ = QtCore.QDir(self.imgDir)
dir_.cd(country)
image = QtGui.QImage()
if image.load(dir_.absoluteFilePath(value)):
record.setValue('obverseimg', image)
if typeId and ... |
TurtleRockStudios/renderdoc_public | docs/python_api/examples/renderdoc_intro.py | Python | mit | 763 | 0.001311 | import renderdoc as rd
# Open a capture file handle
cap = rd.OpenCaptureFile()
# Open a particular file - see also OpenBuffer to load from memory
st | atus = cap.OpenFile('test.rdc', '', None)
# Make sure the file opened succ | essfully
if status != rd.ReplayStatus.Succeeded:
raise RuntimeError("Couldn't open file: " + str(status))
# Make sure we can replay
if not cap.LocalReplaySupport():
raise RuntimeError("Capture cannot be replayed")
# Initialise the replay
status,controller = cap.OpenCapture(None)
if status != rd.ReplayStatus.... |
hectormartinez/rougexstem | taln2016/icsisumm-primary-sys34_v1/nltk/nltk-0.9.2/nltk/inference/__init__.py | Python | apache-2.0 | 469 | 0.002132 | # Natural | Language Toolkit: Inference
#
# Copyright (C) 2001-2008 University of Pennsylvania
# Author: Dan Garrette <dhgarrette@gmail.com>
# Ewan Klein <ewan@inf.ed.ac.uk>
#
# URL: <http://nltk.sf.net>
# For license information, see LICENSE.TXT
"""
Classes and interfaces for theorem proving and model buil... | rt *
|
spiralsyzygy/django-drf-base-app | users/migrations/0001_initial.py | Python | mit | 2,755 | 0.003993 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-15 08:06
from __future__ import unicode_literals
import django.contrib.auth.validators
from django.db import migrations, models
import users.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0008... | gnates whether the user can log into this admin site.', verbose_name='staff status')),
| ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('email', models.EmailField(max_length=255, unique=True, verbose_name='email')),
('last_login', mode... |
liulion/mayavi | mayavi/components/grid_plane.py | Python | bsd-3-clause | 6,556 | 0.001373 | """A grid plane component.
"""
# Author: Prabhu Ramachandran <prabhu_r@users.sf.net>
# Copyright (c) 2005-2006, Enthought, Inc.
# License: BSD Style.
# Enthought library imports.
from traits.api import Instance, Enum, Int, Range
from traitsui.api import View, Group, Item
from tvtk.api import tvtk
from apptools.persis... | ect.
view = View(Group(Item(name='axis'),
Item(name='position', enabled_when='_high > 0'))
)
######################################################################
# `object` interface
######################################################################
def _... | elf).__get_pure_state__()
# These traits are dynamically created.
for name in ('plane', '_low', '_high'):
d.pop(name, None)
return d
def __set_pure_state__(self, state):
state_pickler.set_state(self, state)
self._position_changed(self.position)
############... |
mdhaman/superdesk-core | superdesk/__init__.py | Python | agpl-3.0 | 5,286 | 0.001324 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
"""Superdesk... | n exception occured while running the command...')
logger.exception(ex)
return 1
def get_headers(self, environ=None):
"""Fix CORS for abort responses.
todo(petr): put in in custom flask error handler instead
"""
return [
('Content-Type', 'text/html'),
('Access-... | (resource, res_config):
"""Register domain resource"""
DOMAIN[resource] = res_config
def command(name, command):
"""Register command"""
COMMANDS[name] = command
def blueprint(blueprint, app, **kwargs):
"""Register flask blueprint.
:param blueprint: blueprint instance
:param app: flask a... |
rspavel/spack | var/spack/repos/builtin/packages/namd/package.py | Python | lgpl-2.1 | 5,399 | 0.000741 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform
import sys
import os
from spack import *
class Namd(MakefilePackage):
"""NAMDis a parallel molecular... |
depends_on('charmpp@6.8.2', when="@2.13") |
depends_on('charmpp@6.7.1', when="@2.12")
depends_on('fftw@:2.99', when="fftw=2")
depends_on('fftw@3:', when="fftw=3")
depends_on('intel-mkl', when="fftw=mkl")
depends_on('tcl', when='interface=tcl')
depends_on('tcl', when='interface=python')
depends_on('python', when='interface=python'... |
orbkit/orbkit | orbkit/libcint_interface/__init__.py | Python | lgpl-3.0 | 174 | 0 | from .ao_integrals imp | ort AOIntegrals, ao2mo
from .mo_integrals import FCIDUMP
from .mo_integrals import load as load_fcidump
from .fcidump_generator import generate_f | cidump
|
h-mayorquin/camp_india_2016 | tutorials/Spatial Coding/makecmap.py | Python | mit | 452 | 0.028761 | from pylab import *
import matplotlib.cm as cmx
| import matplotlib.colors as colors
def MakeColourMap(N, colormap='jet'):
'''
To make colour map with N possible colours. Interpolated from map 'colormap'
'''
### Colour map for cells (if you want to plot multiple cells)
values = range(N)
jet = cm = plt.get_cmap(colormap)
cNorm = colors.Normalize(vmin=0, vmax=... | return scalarMap |
MiroK/dolfin | site-packages/dolfin_utils/documentation/indextemplates.py | Python | gpl-3.0 | 2,146 | 0.001864 | # Copyright (C) 2011 Anders Logg, Kristian Oelgaard, and Marie E. Rognes
#
# This file is part of DOLFIN.
#
# DOLFIN 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.
#
# DOLFIN 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 Lesse... | see <http://www.gnu.org/licenses/>.
#
# First added: 2011-05-23
# Last changed: 2011-05-27
library_index_cpp_template = """\
.. _programmers_reference_index:
#############################################
C++ Programmer's reference for DOLFIN-%s
#############################################
.. toctree::
:glob:
... |
tndatacommons/tndata_backend | tndata_backend/officehours/migrations/0004_revise_schedule_format.py | Python | mit | 1,178 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-02-06 16:30
from __future__ import unicode_literals
from django.db import migrations
def refactor_schedule_times(apps, schema_editor):
"""Change the JSON data in OfficeHours.schedule so that it goes from this:
{'DAY': [[from, to], [from, to], .... | "OfficeHours")
for obj in OfficeHours.objects.filter(schedule__gt={}):
new_schedule = {}
for day, hours_list in obj.schedule.items():
new_schedule[day] = [
{'from': from_time, 'to': to_time}
for | from_time, to_time in hours_list
]
obj.schedule = new_schedule
obj.save()
class Migration(migrations.Migration):
dependencies = [
('officehours', '0003_auto_20170201_0133'),
]
operations = [
migrations.RunPython(refactor_schedule_times),
]
|
VoltBit/ellida | settings.py | Python | mit | 2,756 | 0.001451 | """
Module | used to keep settings such as IP addresses and ports.
"""
import random
class EllidaSettings(object):
| ENGINE_SOCKET = 27999
MANAGER_SOCKET = 27998
UI_SOCKET = 27997
DAEMON_SOCKET = 27990
EXTERN = {
'u': "ellida.go.ro",
'd': "192.168.160.137",
'e': "ellida.go.ro",
}
INTERN = {
'u': "192.168.160.137",
'd': "192.168.160.137",
'e': "192.168.160.137... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.