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 |
|---|---|---|---|---|---|---|---|---|
ryanss/holidays.py | holidays/countries/ethiopia.py | Python | mit | 5,162 | 0 | # -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: dr-prodigy <maurizio.... | fat Day*
# - Moulad El Naby*
# | *only if hijri-converter library is installed, otherwise a warning is
# raised that this holiday is missing. hijri-converter requires
# Python >= 3.6
# is_weekend function is there, however not activated for accuracy.
class Ethiopia(HolidayBase):
country = "ET"
def __init__(self, **kwargs):
Holiday... |
danbar/qr_decomposition | qr_decomposition/tests/test_householder_reflection.py | Python | mit | 1,155 | 0 | """
Python unit-test
"""
import unittest
import numpy as np
import numpy.testing as npt
from .. import qr_decomposition
class TestHouseholderReflection(unittest.TestCase):
"""Test case for QR decomposition using Householder reflection."""
def test_wikipedia_example1( | self):
"""Test of Wikipedia example
The example for the foll | owing QR decomposition is taken from
https://en.wikipedia.org/wiki/Qr_decomposition#Example_2.
"""
A = np.array([[12, -51, 4],
[6, 167, -68],
[-4, 24, -41]], dtype=np.float64)
(Q, R) = qr_decomposition.householder_reflection(A)
Q_des... |
mschurenko/ansible-modules-core | cloud/amazon/rds.py | Python | gpl-3.0 | 40,638 | 0.005807 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | version_added: "1.3"
short_description: create, delete, or modify an Amazon rds instance
description:
- Creates, deletes, or modifies rds instances. When creating an instance it can be either a new instance or a read-only rep | lica of an existing instance. This module has a dependency on python-boto >= 2.5. The 'promote' command requires boto >= 2.18.0. Certain features such as tags rely on boto.rds2 (boto >= 2.26.0)
options:
command:
description:
- Specifies the action to take.
required: true
default: null
aliases:... |
nickoala/telepot | telepot/aio/api.py | Python | mit | 5,062 | 0.003951 | import asyncio
import aiohttp
import async_timeout
import atexit
import re
import json
from .. import exception
from ..api import _methodurl, _which_pool, _fileurl, _guess_filename
_loop = asyncio.get_event_loop()
_pools = {
'default': aiohttp.ClientSession(
connector=aiohttp.TCPConnector(limit... | )}
else:
raise RuntimeError("_proxy has invalid length")
async def _close_pools():
global _pools
for s in _pools.values():
await s.close()
atexit.register(lambda: _loop.create_task(_close_pools())) # have to wrap async function
def _create_onetime_pool():
return aiohttp.ClientSession... | ut(req, **user_kw):
token, method, params, files = req
if method == 'getUpdates' and params and 'timeout' in params:
# Ensure HTTP timeout is longer than getUpdates timeout
return params['timeout'] + _default_timeout(req, **user_kw)
elif files:
# Disable timeout if uploading files. ... |
francislpx/myblog | blog/admin.py | Python | gpl-3.0 | 297 | 0.003367 | from django.contrib import admin
from .models import Post, Category, Tag
class PostAdmin(admin.ModelAdmin):
list_disp | lay = ['title', 'create_time', 'modified_time', 'category', 'author', 'views']
admin.site.register(Post, PostAdmin)
admin.site.regi | ster(Category)
admin.site.register(Tag)
|
atumanov/ray | python/ray/rllib/models/model.py | Python | apache-2.0 | 10,512 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from collections import OrderedDict
import gym
from ray.rllib.models.misc import linear, normc_initializer
from ray.rllib.models.preprocessors import get_preprocessor
from ray.rllib.utils.annotations import P... | # Default attribute values for the non-RNN case
self.state_init = []
self.state_in = state_in or []
self.state_out = []
self.obs_spac | e = obs_space
self.action_space = action_space
self.num_outputs = num_outputs
self.options = options
self.scope = tf.get_variable_scope()
self.session = tf.get_default_session()
if seq_lens is not None:
self.seq_lens = seq_lens
else:
self.s... |
pld/bamboo | bamboo/tests/controllers/test_datasets_update_with_aggs.py | Python | bsd-3-clause | 2,876 | 0 | import simplejson as json
from bamboo.models.dat | aset import Dataset
from bamboo.tests.controllers.test_abstract_datasets_update import\
TestAbstractDatasetsUpdate
class TestDatasetsUpdateWithAggs(TestAbstractDatasetsUpdate):
def setUp(self):
TestAbstractDatasetsUpdate.setUp(self)
self._create_original_datasets()
self._add_common_ca... | an(amount)': 'median of amount',
'min(amount)': 'min of amount',
'ratio(amount, gps_latitude)': 'ratio of amount and gps_latitude',
'sum(amount)': 'sum of amount',
}
for aggregation, name in aggregations.items():
self.calculations.create(
... |
sebasmagri/mezzanine_polls | mezzanine_polls/admin.py | Python | bsd-2-clause | 271 | 0.00369 | from django.contrib import a | dmin
from mezzanine.pages.admin import PageAdmin
from .models import Poll, Choice
class ChoiceInline(admin.TabularInline):
model = | Choice
class PollAdmin(PageAdmin):
inlines = (ChoiceInline, )
admin.site.register(Poll, PollAdmin)
|
google-research/google-research | reset_free_learning/reset_free.py | Python | apache-2.0 | 43,220 | 0.004766 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... | tion')
flags.DEFINE_integer('goal_relabel_type', 0, '0->final, 1-> random future')
flags.DEFINE_integer( |
'num_relabelled_goals', 5,
'number of relabelled goals per episode, use with random future goal relabelling'
)
flags.DEFINE_integer('relabel_offline_data', 0,
'relabel with every intermediate state as a goal')
# point mass environment properties
flags.DEFINE_string('point_mass_env_type', ... |
ESOedX/edx-platform | lms/djangoapps/program_enrollments/tests/factories.py | Python | agpl-3.0 | 1,400 | 0 | """
Factories for Program Enrollment tests.
"""
from __future__ import absolute_import
from uuid import uuid4
| import factory
from factory.django import DjangoModelFactory
from opaque_keys.edx.keys import CourseKey
from lms.djangoapps.program_enrollments import models
from student.tests.factories impor | t CourseEnrollmentFactory, UserFactory
class ProgramEnrollmentFactory(DjangoModelFactory):
""" A Factory for the ProgramEnrollment model. """
class Meta(object):
model = models.ProgramEnrollment
user = factory.SubFactory(UserFactory)
external_user_key = None
program_uuid = factory.LazyFun... |
matrix-org/synapse | synapse/handlers/room.py | Python | apache-2.0 | 64,472 | 0.001411 | # Copyright 2016-2021 The Matrix.org Foundation C.I.C.
#
# 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... | t random
import string
from collections import OrderedDict
from ty | ping import (
TYPE_CHECKING,
Any,
Awaitable,
Collection,
Dict,
List,
Optional,
Tuple,
)
import attr
from typing_extensions import TypedDict
from synapse.api.constants import (
EventContentFields,
EventTypes,
GuestAccess,
HistoryVisibility,
JoinRules,
Membership,... |
pernici/sympy | sympy/functions/special/tests/test_spec_polynomials.py | Python | bsd-3-clause | 3,248 | 0.009544 | from sympy import (legendre, Symbol, hermite, chebyshevu, chebyshevt,
chebyshevt_root, chebyshevu_root, assoc_legendre, Rational,
roots, sympify, S, laguerre_l, laguerre_poly)
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) =... | generalized Laguerre polynomials:
assert laguerre_l(0, alpha, x) == 1
assert laguerre_l(1, alpha, x) == -x + alpha + 1
assert laguerre_l(2, alpha, x).expand() == (x**2/2 - (alpha+2)*x + (alpha+2)*(alpha+1)/2).expand()
assert lague | rre_l(3, alpha, x).expand() == (-x**3/6 + (alpha+3)*x**2/2 - (alpha+2)*(alpha+3)*x/2 + (alpha+1)*(alpha+2)*(alpha+3)/6).expand()
# Laguerre polynomials:
assert laguerre_l(0, 0, x) == 1
assert laguerre_l(1, 0, x) == 1 - x
assert laguerre_l(2, 0, x).expand() == 1 - 2*x + x**2/2
assert laguerre_l(3, 0... |
btenaglia/hpc-historias-clinicas | hpc-historias-clinicas/epicrisis/migrations/0003_auto_20150510_1157.py | Python | bsd-3-clause | 469 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db i | mport models, migrations
class Migration(migrations.Migration):
dependencies = [
('epicrisis', '0002_auto_20150510_1155'),
]
operations = [
migrations.AlterField(
model_name='epicrisis',
name='historia',
field=models.ForeignKey(to='historias.Historias'... | ),
]
|
duskat/python_training_mantis | test/test_login.py | Python | apache-2.0 | 147 | 0.013605 | __author__ = | 'Dzmitry'
def test_login(app):
app.session.login("administrator", "root | ")
assert app.session.is_logged_in_as("administrator") |
giliam/turbo-songwriter | backend/songwriter/urls.py | Python | mit | 5,095 | 0.001963 | # coding: utf-8
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from songwriter import views
urlpatterns = [
url(r'^$', views.api_root,
name="root"),
url(r'^songs/list/$', views.SongList.as_view(),
name="songs_list"),
url(r'^songs/list/pagin... | t_author,
name="songs_without_author"),
url(r'^songs/without/editor/$', views.get_ | songs_without_editor,
name="songs_without_editor"),
url(r'^songs/with/latex/code/$', views.get_songs_with_latex_code,
name="songs_with_latex_code"),
url(r'^songs/without/page/number/$', views.get_songs_without_page_number,
name="songs_without_page_number"),
url(r'^copyrights/extract... |
skosukhin/spack | var/spack/repos/builtin/packages/scalasca/package.py | Python | lgpl-2.1 | 2,845 | 0.000703 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | - in particular those concerning communication and
synchroniz | ation - and offers guidance in exploring their causes.
"""
homepage = "http://www.scalasca.org"
url = "http://apps.fz-juelich.de/scalasca/releases/scalasca/2.1/dist/scalasca-2.1.tar.gz"
version('2.3.1', 'a83ced912b9d2330004cb6b9cefa7585')
version('2.2.2', '2bafce988b0522d18072f7771e491ab9')
v... |
sparkslabs/kamaelia_ | Sketches/TG/old_shard/cshard/shardclasstest.py | Python | apache-2.0 | 2,606 | 0.02878 | # -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lic... | t here')
for l in fs.code:
print l,
print
## moduleShard
from ModuleShard import *
imps = ['lala', 'doo', 'ming']
impfrs = {'wheee': ['huphup', 'pop', 'pip'], 'nanoo': ('noom', )}
ms = moduleShard('moduletest', importmodules = imps, importfrom = impfrs, shards = [fs], docstring = 'module doc')
for l in ms.code:
... | int l,
print
## funcAppShard
from FuncAppShard import *
ps = ['lala', 'doo', 'ming']
kws = {'wheee': "[huphup, 'pop', 'pip', 1]", 'nanoo': '"noom"', 'a': '1'}
app = funcAppShard('testcall', funcObj = None, args = ps, kwargs = kws)
for ln in app.code:
print ln,
print
app = funcAppShard('testcall', funcObj = 'testob... |
godfryd/pylint | test/input/func_noerror_used_before_assignment.py | Python | gpl-2.0 | 236 | 0.016949 | # pylint: disable = lin | e-too-long, multiple-statements, missing-module-attribute
"""https://bitbucket.org/logilab/pylint/issue/111/false-positive-used-before-assignment-with"""
try: raise IOError(1, "a")
except IOError, err: prin | t err
|
pmaigutyak/mp-shop | offers/migrations/0001_initial.py | Python | isc | 1,897 | 0.004744 | # Generated by Django 3.0.13 on 2021-05-19 21:21
from django.conf | import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('products', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migratio... | oductPriceOffer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.CharField(choices=[('not_reviewed', 'Not reviewed'), ('processing', 'Processing'), ('canceled', 'Canceled'), ('completed', 'Complete... |
sfu-fas/coursys | oldcode/planning/teaching_equiv_forms.py | Python | gpl-3.0 | 1,982 | 0.007568 | from django import forms
from .models import TeachingEquivalent
from django.forms.widgets import TextInput, Textarea
from django.core import validators
from django.core.exceptions import ValidationError
from fractions import Fraction
class TeachingCreditField(forms.Field):
def to_python(self, value):
... | number or a proper fraction')
except ZeroDivisionError:
raise ValidationError('Denominator of fraction cannot be zero')
return value
class TeachingEquivForm( | forms.ModelForm):
credits = TeachingCreditField(help_text='The number of credits this equivalent is worth')
class Meta:
model = TeachingEquivalent
exclude = ('status', 'instructor', 'credits_numerator', 'credits_denominator')
widgets = {
'summary': TextInput(attrs={'si... |
plotly/python-api | packages/python/plotly/plotly/validators/violin/_spanmode.py | Python | mit | 516 | 0 | import _ | plotly_utils.basevalidators
class SpanmodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="spanmode", parent_name="violin", **kwargs):
super(SpanmodeValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | )
|
nojero/pod | src/pod/test.py | Python | gpl-3.0 | 12,327 | 0.028717 |
import os
import sys
import time
import math
import networkx
import ptnet
import pes
import sat
import z3
from util import *
from log import *
from folding import *
from pod import *
def test1 () :
n = ptnet.net.Net (True)
n.read (sys.stdin, 'pnml')
n.write (sys.stdout, 'pnml')
def test2 () :
u = p... | ng ())
print 'value m[y].as_long', m[y].as_long ()
n = z3.Int ('new_var')
print m[n]
def test9 () :
s = z3.Solver ()
x = z3.Int ('x')
y = z3.Int ('y')
z = z3.Int | ('z')
p = z3.Bool ('p')
s.add (p == (x == y))
s.add (x == y)
#s.add (z3.Not (p))
s.add (0 <= sum ([y, z], x))
s.add (True)
s.add (z3.Distinct ([x, y, z]))
print 'solving', s
r = s.check ()
print 'result:', r
if r == z3.sat :
m = s.model ()
print 'model:', m... |
apagac/cfme_tests | cfme/fixtures/pytest_store.py | Python | gpl-2.0 | 6,454 | 0.002169 | """Storage for pytest objects during test runs
The objects in the module will change during the course of a test run,
so they have been stashed into the 'store' namespace
Usage:
# imported directly (store is pytest.store)
from cfme.fixtures.pytest_store import store
store.config, store.pluginmanager, sto... | pressing stdout/err, turn that off for a moment
with diaper:
store.capturemanager.suspendcapture()
| # terminal reporter knows whether or not to write a newline based on currentfspath
# so stash it, then use rewrite to blow away the line that printed the current
# test name, then clear currentfspath so the test name is reprinted with the
# write_ensure_prefix call. shenanigans!
cfp =... |
DAInamite/uav_position_controller | rqt_position_controller/src/rqt_position_controller/position_controller.py | Python | gpl-3.0 | 4,618 | 0.008662 | #
# Author: Christopher-Eyk Hrabia
# [email protected]
#
import os
import rospy
import rospkg
from qt_gui.plugin import Plugin
from python_qt_binding import loadUi
from python_qt_binding.QtGui import QWidget
from python_qt_binding.QtGui import QVBoxLayout
from pid_controller import PIDConfiguration... | help="Put plugin in silent mode")
args, unknowns = parser.parse_known_args(context.argv())
if not args.quiet:
print 'arguments: ', args
print 'unknowns: ', unknowns
# Create QWidget
self._widget = QWidget()
# Get path to UI file which should be in t... | pkg.RosPack().get_path('rqt_position_controller'), 'resource', 'configuration.ui')
# Extend the widget with all attributes and children from UI file
loadUi(ui_file, self._widget)
# Give QObjects reasonable names
self._widget.setObjectName('ControllerUi')
self.__pids = de... |
stefanp312/chat-bot | run.py | Python | mit | 1,264 | 0.000791 | from flask import Flask, request, redirect, session
import twilio.twiml
import navigation
SECRET_KEY = 'donuts'
logging = True
app = Flask(__name__)
app.config.from_object(__name__)
def log(mesagge=""):
if logging:
print mesagge
@app.route("/", methods=['GET', 'POST'])
def main_reply():
# Log value... | rom twilio and add reply as message body
resp = twilio.twiml.Response()
resp.message(reply.encode("utf-8"))
# log server reply
log(reply)
# store previous queries of the user in a cookie
searchs = session.get('searchs', [])
searchs.append(recieved_message)
replies = session.get('searchs'... | (resp)
if __name__ == "__main__":
app.run(debug=True)
|
ChildMindInstitute/HBN-wearable-analysis | docs/conf.py | Python | apache-2.0 | 5,181 | 0.001737 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# HBN Wearable Analysis documentation build configuration file, created by
# sphinx-quickstart on Wed Jun 28 15:25:14 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are presen... | as'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y | version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the comm... |
zyantific/continuum | continuum/client.py | Python | mit | 4,170 | 0.002158 | """
This file is part of the continuum IDA PRO plugin (see zyantific.com).
The MIT License (MIT)
Copyright (c) 2016 Joel Hoener <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software")... | ORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import absolute_import, print_function, division
import sys
import asyncore
from idc import *
from idautils import *
from .proto import ProtoMixin
from PyQt5.QtCore impor... | core.dispatcher_with_send):
"""Client class for the localhost network."""
client_analysis_state_updated = pyqtSignal([str, str]) # idb_path, state
sync_types = pyqtSignal([bool]) # purge_non_indexed
def __init__(self, sock, core):
asyncore.dispatcher_with_send.__init__(self, sock=sock)
... |
dgm816/simple-index | nntp/nntp.py | Python | mit | 11,160 | 0.000538 | import re
import socket
import ssl
class MyNntp:
def __init__(self, server, port, use_ssl):
"""Constructor
Pass in the server, port, and ssl usage value for connect.
"""
# just store the values for now
self.server = server
self.port = port
self.ssl = use_s... | elds:
print("%s" % field)
# remove line
line, self.data = self.data.split("\r\n", | 1)
# if we have not finished...
if not eot:
# receive more data from server
self.data += self.s.recv(1024)
# all went well, return true
return True
def zver(self, low, high):
"""Compressed overview
Get compressed headers for... |
javiere/GPXCardio | GPXCardio.py | Python | gpl-2.0 | 4,530 | 0.010375 | """
Reads the cardio data from GPX files and generates plots with it.
Requires the following libraries:
* matplotlib
Author: Javier Espigares Martin
Email: [email protected]
GNU v2.0 License
"""
from datetime import datetime, date, time
class GPXCardio():
"""
GPX Cardio class. Opens the filename gi... | in__":
# compare_hr_run(
# 'data/Garmin.gpx', 'data/Microsoft.gpx', 'Garmin' | , 'MS Band')
|
FireballDWF/cloud-custodian | tools/c7n_azure/c7n_azure/constants.py | Python | apache-2.0 | 4,200 | 0.00119 | # Copyright 2019 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 applicable law or agreed to in wri... | RINCIPAL_TYPE_JMES_PATH = 'data.authorization.evidence.principalType'
EVENT_GRID_PRINCIPAL_ROLE_JMES_PATH = 'data.authorization.evidence.role'
EVENT_GRID_EVENT_TIME_PATH = 'eventTime'
"""
Environment Variables
"""
ENV_TENANT_ID = 'AZURE_TENANT_ID'
ENV_CLIENT_ID = 'AZURE_CLIENT_ID'
ENV_SUB_ID = 'AZURE_SUBSCRIPTION_ID'... | '
ENV_USE_MSI = 'AZURE_USE_MSI'
ENV_FUNCTION_TENANT_ID = 'AZURE_FUNCTION_TENANT_ID'
ENV_FUNCTION_CLIENT_ID = 'AZURE_FUNCTION_CLIENT_ID'
ENV_FUNCTION_CLIENT_SECRET = 'AZURE_FUNCTION_CLIENT_SECRET'
ENV_FUNCTION_SUB_ID = 'AZURE_FUNCTION_SUBSCRIPTION_ID'
ENV_FUNCTION_MANAGEMENT_GROUP_NAME = 'AZURE_FUNCTION_MANAGEMENT_GR... |
PyKudos/KudoEdit | KudoEdit/KudoEdit.py | Python | mit | 12,273 | 0.011081 | import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtGui import *
import os
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.filename = None
self.initUI()
def initUI(self):
self.italic_flag = False
... | tabsClosable()
textEditf = QFont()
|
layout = QVBoxLayout(tab)
QtCore.QObject.connect(self.tab_widget,
QtCore.SIGNAL('tabCloseRequested(int)'),
self.close_tab)
self.setCentralWidget(self.tab_widget)
self.statusBar()
self.toolbar = self.addToolBar('Ne... |
rezoo/chainer | chainer/datasets/concatenated_dataset.py | Python | mit | 939 | 0 | from chainer.dataset import dataset_mixin
class ConcatenatedDataset(dataset_mixin.DatasetMixin):
"""Dataset which concatenates some base datasets.
This dataset wraps some base datasets and works as a concatenated dataset.
For example, if a base dataset with 10 samples and
another base dataset with 2... | m__`.
"""
def __init__(self, *datasets):
self._datasets = datasets
def __len__(self):
return sum(len(dataset) for dataset in self._datasets)
def get_example(self, i):
if i < 0:
raise IndexError
for dataset in self._datase | ts:
if i < len(dataset):
return dataset[i]
i -= len(dataset)
raise IndexError
|
basmot/futsal_management | base/models/account_transaction.py | Python | apache-2.0 | 1,157 | 0.001729 | ##############################################################################
#
# Copyright 2015-2016 Bastien Mottiaux
#
# 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 Lic | ense at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language go... | #######
from django.db import models
from django.contrib import admin
from django.utils import timezone
class AccountTransactionAdmin(admin.ModelAdmin):
list_display = ('account', 'transaction')
class AccountTransaction(models.Model):
account = models.ForeignKey('Account')
transaction = models.Fo... |
LuoZijun/uOffice | temp/pydocxx/docx/opc/pkgreader.py | Python | gpl-3.0 | 10,107 | 0 | # encoding: utf-8
"""
Provides a low-level, read-only API to a serialized Open Packaging Convention
(OPC) package.
"""
from __future__ import absolute_import
from .constants import RELATIONSHIP_TARGET_MODE as RTM
from .oxml import parse_xml
from .packuri import PACKAGE_URI, PackURI
from .phys_pkg import PhysPkgReade... | _srels
self._sparts = sparts
@staticmethod
def from_file(pkg_file):
"""
Return a |PackageReader| instance loaded with contents of *pkg_file*.
"""
phys_reader = PhysPkgReader(pkg_file)
content_types = _ContentTypeMap.from_xml(phys_reader.content_types_xml)
... | _reader.close()
return PackageReader(content_types, pkg_srels, sparts)
def iter_sparts(self):
"""
Generate a 4-tuple `(partname, content_type, reltype, blob)` for each
of the serialized parts in the package.
"""
for s in self._sparts:
yield (s.partname, s... |
fsimkovic/cptbx | conkit/io/_parser.py | Python | gpl-3.0 | 3,072 | 0.001953 | # BSD 3-Clause License
#
# Copyright (c) 2016-19, University of Liverpool
# 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 notic... | ontactMap
from conkit.core.contactfile import ContactFile
from conkit.core.sequence import Sequence
from conkit.core.sequencefile import SequenceFile
class Parser(ABC):
"""Abstract class for all parsers
"""
@abc.abstractmethod
def read(self):
pass
@abc.abstractmethod
def write(sel | f):
pass
@classmethod
def _reconstruct(cls, hierarchy):
"""Wrapper to re-construct full hierarchy when parts are provided"""
if isinstance(hierarchy, ContactFile):
h = hierarchy
elif isinstance(hierarchy, ContactMap):
h = ContactFile("conkit")
... |
letsencrypt/letsencrypt | certbot-apache/certbot_apache/_internal/override_suse.py | Python | apache-2.0 | 670 | 0 | """ Distribution specific override class for OpenSUSE | """
from certbot_apache._internal import configurator
from certbot_apache._internal.configurator import OsOptions
class OpenSUSEConfigurator(configurator.Apache | Configurator):
"""OpenSUSE specific ApacheConfigurator override class"""
OS_DEFAULTS = OsOptions(
vhost_root="/etc/apache2/vhosts.d",
vhost_files="*.conf",
ctl="apachectl",
version_cmd=['apachectl', '-v'],
restart_cmd=['apachectl', 'graceful'],
conftest_cmd=['apa... |
johnttaylor/Outcast | bin/scm/rm.py | Python | bsd-3-clause | 1,756 | 0.007403 | # Short help
def display_summary():
print("{:<13}{}".format( 'rm', "Removes a previously copied SCM Repository" ))
# DOCOPT command line definition
USAGE="""
Removes a previously 'copied' repository
===============================================================================
usage: evie [common-opts] rm [option... | the command is successful
get-error-msg Returns a SCM specific message that informs the end user
of additional action(s) that may be required when
the c | ommand fails
Options:
-p PKGNAME Specifies the Package name if different from the <repo>
name
-b BRANCH Specifies the source branch in <repo>. The use/need
of this option in dependent on the <repo> SCM type.
Options:
-h, --... |
rsmz/copyright | test/test_walk.py | Python | gpl-3.0 | 2,190 | 0.00137 | import os
import unittest
from copyright import Walk
class TestWalk(unittest.TestCase):
DIRS = [
'./tmp/dir1/dir2',
'./tmp/dir3'
]
FILES = [
'./tmp/f',
'./tmp/dir1/f1',
'./tmp/dir3/f3',
'./tmp/dir1/dir2/f2'
]
def setUp(self):
... | r2']
for f i | n Walk(include=include):
files.append(f)
self.assertFalse(self.FILES[0] in files)
self.assertTrue(self.FILES[1] in files)
self.assertFalse(self.FILES[2] in files)
self.assertTrue(self.FILES[3] in files)
def test_include_regex(self):
files = []
... |
tszym/ansible | lib/ansible/modules/network/netscaler/netscaler_gslb_site.py | Python | gpl-3.0 | 14,153 | 0.00318 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Citrix Systems
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
... | WN'
- 'MEPDOWN_SVCDOWN'
description:
- >-
| Specify the conditions under which the GSLB service must be monitored by a monitor, if one is bound.
Available settings function as follows:
- "* C(ALWAYS) - Monitor the GSLB service at all times."
- >-
* C(MEPDOWN) - Monitor the GSLB service only when the excha... |
jbms/beancount-import | beancount_import/source/ofx_test.py | Python | gpl-2.0 | 2,503 | 0.0004 | import os
import pytest
from . import ofx
from .source_test import check_source_example
testdata_dir = os.path.realpath(
os.path.join(
os.path.dirname(__file__), '..', '..', 'testdata', 'source', 'ofx'))
examples = [
('test_vanguard_basic', 'vanguard.ofx'),
('test_vanguard_matching', 'vanguard.o... | ('Assets:Vanguard:401k:PreTax:VGI1', 1),
('Assets:Vanguard:401k:PreTax', 1),
('Assets:Vanguard:401k:VG1', 1),
('Assets:Vanguard:401k', 1),
('Assets:Vanguard:Unknown', None),
('Assets:Vanguard:401k:PreTax:Excessive:VGI1', None),
]:
assert ofx.find_o | fx_id_for_account(account, ofx_ids) == want, account
|
daftspaniel/daftpyweek17 | jsonpickle/pickler.py | Python | bsd-3-clause | 10,329 | 0.000775 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2008 John Paulett (john -at- paulett.org)
# Copyright (C) 2009, 2011, 2013 David Aguilar (davvid -at- gmail.com)
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
import operator... | """Recursively call flatten() and return json-fri | endly dict
"""
if data is None:
data = obj.__class__()
flatten = self._flatten_key_value_pair
for k, v in sorted(obj.items(), key=operator.itemgetter(0)):
flatten(k, v, data)
# the collections.defaultdict protocol
if hasattr(obj, 'default_factory... |
MrSurly/micropython | tests/micropython/extreme_exc.py | Python | mit | 3,386 | 0.001181 | # test some extreme cases of allocating exceptions and tracebacks
import micropython
# Check for stackless build, which can't call functions without
# allocating a frame on the heap.
try:
def stackless():
pass
micropython.heap_lock()
stackless()
micropython.heap_unlock()
except RuntimeError:... | 0,
)
micropython.heap_unlock()
print(repr(e))
| # create an exception with a long formatted error message while heap is locked
# should use emergency exception buffer and truncate the message
def f():
pass
micropython.heap_lock()
try:
f(
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCD... |
Anislav/Stream-Framework | feedly/tests/managers/redis.py | Python | bsd-3-clause | 493 | 0 | from feedly.feed_managers.base import Feedly
from feedly.feeds.base import UserBaseFeed
from feedly.feeds.redis import RedisFeed
from feedly.tests.managers.base import | BaseFeedlyTest
import pytest
class RedisUserBaseFeed(UserBaseFeed, RedisFeed):
pass
class RedisFeedly(Feedly):
feed_classes = {
'feed': RedisFeed
}
user_feed_class = RedisUserBaseFeed
@pytest.mark.usefixtures("redis_reset")
class RedisFeedlyTest(BaseFeedlyTest) | :
manager_class = RedisFeedly
|
couchbaselabs/litmus | lib/pymongo/database.py | Python | apache-2.0 | 28,121 | 0.000071 | # Copyright 2009-2010 10gen, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | ``connection`` is now a property rather than a method.
"""
return self.__connection
@property
def name(self):
"""The name of this :class:`Database`.
.. versionchanged:: 1.3
``name`` is now a property | rather than a method.
"""
return self.__name
@property
def incoming_manipulators(self):
"""List all incoming SON manipulators
installed on this instance.
.. versionadded:: 2.0
"""
return [manipulator.__class__.__name__
for manipulator in... |
camptocamp/QGIS | python/plugins/GdalTools/tools/doExtractProj.py | Python | gpl-2.0 | 7,191 | 0.038798 | # -*- coding: utf-8 -*-
"""
***************************************************************************
doExtractProj.py
---------------------
Date : August 2011
Copyright : (C) 2011 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
************... | ct( self.buttonBox, SIGNAL( "rejected()" ), self.reject )
self.okButton.setEnabled( True )
# ----------------------------------------------------------------------
def extractProjection( filename, createPrj ):
raster = gdal.Open( unicode( filename ) )
crs = raster.GetPro | jection()
geotransform = raster.GetGeoTransform()
raster = None
outFileName = os.path.splitext( unicode( filename ) )[0]
# create prj file requested and if projection available
if crs != "" and createPrj:
# convert CRS into ESRI format
tmp = osr.SpatialReference()
tmp.ImportFromWkt( crs )
t... |
sprin/heroku-tut | worker/word_count.py | Python | mit | 1,663 | 0.007817 | from collections import defaultdict
import re
import sys
from stop_words import STOP_WORD_SET
from collections import Counter
PUNCTUATION_RE = re.compile("[%s]" % re.escape(
"""!"&()*+,-\.\/:;<=>?\[\\\]^`\{|\}~]+"""))
DISCARD_RE = re.compile("^('{|`|git@|@|https?:)")
def remove_stop_words(word_seq, stop_words):
... | e_punc_inner(word):
return PUNCTUATION_RE.sub("", word)
removed = map(remove_punc_inner, word_seq)
# Remove emptry strings
return [w for | w in removed if w]
def filter_discards(word_seq):
def discard(word):
return not DISCARD_RE.match(word)
return filter(discard, word_seq)
def count_words_from_seq(word_seq):
word_count = defaultdict(int)
for word in word_seq:
word_count[word] += 1
return word_count
def keep_top_n_wo... |
psycofdj/xtdpy | xtd/core/logger/__init__.py | Python | gpl-3.0 | 419 | 0.019093 | # -*- coding: utf-8
#------------------------------------------------------------------#
__author__ = "Xavier MARCELET <[email protected]>"
#------------------------------------------------------------------#
import logging
from . import formatter, manager
from .tools import get, debug, info, warning, err... | tical, exception, log
#------------------------------------------------------------ | ------#
|
dstufft/warehouse | warehouse/migrations/versions/10cb17aea73_default_hosting_mode_to_pypi_only.py | Python | apache-2.0 | 1,098 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except i | n 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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Default hosting mode to pypi-only
Revision ID: 10c... |
apache/incubator-airflow | tests/providers/google/cloud/operators/test_workflows.py | Python | apache-2.0 | 12,510 | 0.00032 | # 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... | gc | p_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
result = op.execute({})
mock_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_hook.return_value.get_workflow.assert_called... |
DlutCS/nserver_py | views/api/news.py | Python | unlicense | 2,540 | 0.007899 | # -*- coding: utf-8 -*-
from views.api import api, restful, error
from flask import request, render_template
from utils.consts import *
from models.news import News
from models.category import Category
@restful('/category/')
def get_categorys():
data = {}
categorys = Category.get_all()
data['categories | '] = categorys
data['total'] = len(categorys)
return data
@restful('/news/<id>/')
def get_news(id): |
if id.isdigit():
news = News.get(id=id)
else:
news = News.get_by_alias(alias=id)
if not news:
return error(10003, 'news id not found')
return news
@restful('/newslist/')
@restful('/newslist/latest/')
def news_latest():
data = {}
start = request.args.get('start', 0)
... |
Jackevansevo/basic-utils | tests/test_core.py | Python | mit | 2,606 | 0 | from unittest.mock import MagicMock, Mock, mock_open, patch
import pytest # type: ignore
from basic | _utils.core import (
clear,
getattrs,
map_getattr,
rgetattr,
rsetattr,
slurp,
to_string
)
def test_slurp() -> None:
"""Tests that slurp reads in contents of a file as a string"""
data = "In the face of ambiguity, refuse the temptation to guess."
with patch("builtins.open", mo | ck_open(read_data=data)) as mock_file:
file_contents = slurp('text.txt')
mock_file.assert_called_once_with('text.txt', 'r')
assert file_contents == data
@pytest.mark.parametrize("platform, expected", [
('posix', 'clear'),
('nt', 'cls')
])
def test_clear(platform: str, expected: str) ->... |
JOUR491-NewsApplications/JOUR491-FoodOnCampus | food/food/urls.py | Python | mit | 314 | 0.006369 | from django.conf.urls import patterns, include, url
from django.contrib im | port admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'menu.views.home', name='home'),
url(r'^hall/(?P<slug>[-\w]+)/$', 'menu.views.halldetail', name='halldetail'),
url(r | '^admin/', include(admin.site.urls)),
)
|
robin1885/algorithms-exercises-using-python | source-code-from-author-book/Listings-for-Second-Edition/listing_1_10.py | Python | mit | 244 | 0.004098 | class LogicGate | :
def __init__(self,n):
self.label = n
self.output = None
def getLabel(self):
re | turn self.label
def getOutput(self):
self.output = self.performGateLogic()
return self.output
|
timothypage/etor | etor/samples/admin.py | Python | mit | 182 | 0.005495 | from sample | s.models import Insurance, Patient, Specimen
from django.contrib import admin
admin.site.register(Insurance)
admin.site.register(Patient)
admin.site.register(Sp | ecimen)
|
Nanolx/bashstyle-ng | ui/args.py | Python | gpl-3.0 | 3,457 | 0.000579 | # coding=utf-8
# ##################################################### #
# #
# This is BashStyle-NG #
# #
# Licensed under GNU GENERAL PUBLIC LICENSE v3 #
# ... | lation prefix and ex | it")
)
parser.add_option(
"-P", "--python", dest="python", action="store_true",
default=False, help=_("print used Python interpreter; \
if additional args are given they will be passed to the used Python \
interpreter.")
)
parser.add_option(
"-d", "--doc", dest="doc", action="s... |
mccorkle/seds-utils | Sbs.py | Python | gpl-3.0 | 13,196 | 0.003107 | class Sbs:
def __init__(self, sbsFilename, sbc_filename, newSbsFilename):
import xml.etree.ElementTree as ET
import Sbc
self.mySbc = Sbc.Sbc(sbc_filename)
self.sbsTree = ET.parse(sbsFilename)
self.sbsRoot = self.sbsTree.getroot()
self.XSI_TYPE = "{http://www.w3.or... | rules
# TODO: look through the whole entityBase for 6 thrusters, a power supply, and at least one block not owned by pirates
thrusterCount = 0
powerSource = 0
controlSurface = 0
gyroCount = 0
| turretCount = 0
ownerCount = 0
ownedThings = 0
ownerList = []
cubeBlocks = entityBase.find('CubeBlocks')
for myCubeBlock in cubeBlocks.iter('MyObjectBuilder_CubeBlock'):
... |
proyectos-analizo-info/pybossa-analizo-info | pybossa/sched.py | Python | agpl-3.0 | 7,472 | 0.00348 | # -*- coding: utf8 -*-
# This file is part of PyBossa.
#
# Copyright (C) 2013 SF Isle of Man Limited
#
# PyBossa 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... | see <http://www.gnu.org/licenses/>.
#import json
#from flask import Blueprint, request, url_for, flash, redirect, abort
#from flask import abort, request, make_response, current_app
from sqlalchemy.sql import text
import pybossa.model as model
from pybossa.core import db
import random
def new_task(app_id, user_id=No... | task by calling the appropriate scheduler function.
'''
app = db.session.query(model.app.App).get(app_id)
if not app.allow_anonymous_contributors and user_id is None:
error = model.task.Task(info=dict(error="This project does not allow anonymous contributors"))
return error
else:
... |
SHA2017-badge/micropython-esp32 | tests/jni/system_out.py | Python | mit | 144 | 0.006944 | try:
import jni
System = jni.cls("java/lang/System")
except:
prin | t("SKIP")
raise Sys | temExit
System.out.println("Hello, Java!")
|
yrchen/CommonRepo | config/urls.py | Python | apache-2.0 | 7,139 | 0.003502 | # -*- coding: utf-8 -*-
#
# Copyright 2016 edX PDR Lab, National Central University, Taiwan.
#
# http://edxpdrlab.ncu.cc/
#
# 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://w... | l(r'^download/$', TemplateView.as_view(template_name='pages/download.html'), name="download"),
url(r'^dashboard/$', MainViews.DashboardView.as_view(), name="dashboard"),
# Django Admin
url(r'^admin/filebrowser/', include(site.urls)), # django-filebrowser
url(r'^grappelli/', include('grappelli.urls'))... | e(admin.site.urls)),
# User management
url(r'^users/', include("commonrepo.users.urls", namespace="users")),
url(r'^accounts/', include('allauth.urls')),
url(r'^avatar/', include('avatar.urls')),
# Message
url(r'^messages/', include('messages_extends.urls')), # django-messages-extends
# ... |
SKIRT/PTS | modeling/build/models/stars.py | Python | agpl-3.0 | 41,196 | 0.004345 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | r bulge"
titles[old_component_name] = "Evolved stellar disk"
titles[young_component_name] = "Young stars"
titles[ionizing_component_name] = "Ionizing stars"
# -----------------------------------------------------------------
component_name_for_map_name = dict()
component_name_ | for_map_name["old_disk"] = old_component_name
component_name_for_map_name["young"] = young_component_name
component_name_for_map_name["ionizing"] = ionizing_component_name
# -----------------------------------------------------------------
class StarsBuilder(GeneralBuilder, GalaxyModelingComponent):
"""
... |
annayqho/TheCannon | code/lamost/xcalib_5labels/make_tr_file_list.py | Python | mit | 797 | 0.016311 | import numpy as np
import glob
from lamost import load_spectra
allfiles = np.array(glob.glob("example_LAMOST/Data_All/*fits"))
# we want just the file names
allfiles = np.char.lstrip(allfiles, 'example_LAMOST/Data_All/')
dir_dat = "example_LAMO | ST/Data_All"
ID, wl, flux, ivar = load_spectra(dir_dat, allfiles)
npix = np | .array([np.count_nonzero(ivar[jj,:]) for jj in range(0,11057)])
good_frac = npix/3626.
SNR_raw = flux * ivar**0.5
bad = SNR_raw == 0
SNR_raw = np.ma.array(SNR_raw, mask=bad)
SNR = np.ma.median(SNR_raw, axis=1)
# we want to have at least 94% of pixels, and SNR of at least 100
good = np.logical_and(good_frac > 0.94, S... |
CaliOpen/CaliOpen | src/backend/main/py.main/caliopen_main/common/helpers/normalize.py | Python | gpl-3.0 | 1,991 | 0.003516 | # -*- coding: utf-8 -*-
"""Normalization functions for different values."""
from __future__ import absolute_import, unicode_literals
import re
import logging
from email.utils import parseaddr
log = logging.getLogger(__name__)
mastodon_url_regex = '^https:\/\/(.*)\/@(.*)'
mastodon_url_legacy_regex = '^https:\/\/(.*)\/... | log.info(exc)
# unicode everywhere
return (u'%s@%s' % (name, domain), email)
def clean_twitter_address(addr):
return addr.strip('@').lower()
def clean_mastodon_address(addr):
return addr.strip('@').lower().split('@')
def parse_mastodon_url(url):
"""extract username and domain from a mas... | t https://instance.tld/@username
:return: tuple (server, username)
"""
matches = re.findall(mastodon_url_regex, url)
if len(matches) != 1 or len(matches[0]) != 2:
# try legacy fallback
matches = re.findall(mastodon_url_legacy_regex, url)
if len(matches) != 1 or len(matches[0]) ... |
erikjwaxx/python-gitlab-1 | setup.py | Python | gpl-3.0 | 502 | 0.041833 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "python-gitl | ab",
version = "0.1", |
packages = find_packages(),
install_requires = ['requests', 'markdown'],
# metadata for upload to PyPI
author = "Itxaka Serrano Garcia",
author_email = "[email protected]",
description = "See the README.md file for more information",
license = "GPL3",
keywords = "gitlab git wrappe... |
andyfangdz/My-SAT-Life | satlife/settings.py | Python | unlicense | 2,253 | 0.000444 | """
Django settings for satlife project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djang | oproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
STATICFILES_DIRS = ( os.path.join('static'), )
# Quick-start development settings - unsuit... | ET_KEY = '-^%-%r3noa6z$b8jv(d3qr2r!06y+po-k^aofop=mjgr2m3i8k'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
# Application definition
INSTALLED_APPS = (
'django_admin_bootstrapped.... |
drunz/parabench | src/ppc/Template.py | Python | gpl-3.0 | 2,742 | 0.007659 | # Parabench - A parallel file system benchmark
# Copyright (C) 2009-2010 Dennis Runz
# University of Heidelberg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Licens... | brick_map, line.split()[1]))
# Else replace the options and add to code
else:
for key, value in brick_map['body'].iteritems():
line = line.replace(key, value)
code.write(line)
body_file.close()
| return code.getvalue()
def name(self):
return self._template_name
|
fredojones/chess | main.py | Python | mit | 145 | 0.013793 | #!/usr/ | local/bin/python3
from chess.app import App
def main():
app = App(curses=True)
app.run()
if __name__ == '__main__':
ma | in()
|
whateverpal/coinmetrics-tools | coincrawler/storage/postgres.py | Python | mit | 3,897 | 0.024378 | from coincrawler.storage import IStorage, IBlockStorageAccess, IPriceStorageAccess
mineableCurrencyColumns = ["height", "timestamp", "txVolume", "txCount", "generatedCoins", "fees", "difficulty"]
nonmineableCurrencyColumns = ["height", "timestamp", "txVolume", "txCount", "fees"]
class PostgresStorage(IStorage):
def... | encyColumns if currency != "xem" else nonmineableCurrencyColumns
return PostgresStorageBlockAccess(currency, columns, self)
def getPriceStorageAccess(self, currency):
return PostgresPriceStorageAccess(currency, self)
class PostgresStorageBlockAccess(IBlockStorageAccess):
BLOCK_T | ABLE_COLUMNS = {
"height": "INTEGER PRIMARY KEY",
"timestamp": "TIMESTAMP",
"txVolume": "NUMERIC",
"txCount": "INTEGER",
"generatedCoins": "NUMERIC",
"fees": "NUMERIC",
"difficulty": "NUMERIC",
}
def __init__(self, ticker, columns, db):
self.db = db
self.ticker = ticker
self.columns = columns
s... |
bendykst/deluge | deluge/plugins/WebUi/setup.py | Python | gpl-3.0 | 1,489 | 0.002686 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Damien Churchill <[email protected]>
#
# Basic plugin template created by:
# Copyright (C) 2008 Martijn Voncken <[email protected] | om>
# Copyright (C) 2007-2009 Andrew Resch <[email protected]>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#
from setuptools import ... | e__ = "WebUi"
__author__ = "Damien Churchill"
__author_email__ = "[email protected]"
__version__ = "0.1"
__url__ = "http://deluge-torrent.org"
__license__ = "GPLv3"
__description__ = "Allows starting the web interface within the daemon."
__long_description__ = """"""
__pkg_data__ = {"deluge.plugins." + __plugin_name__.l... |
songtao-yang/ProjectEuler-Python | 9.Special Pythagorean triplet/problem_9.py | Python | mit | 626 | 0.003221 | # -*- coding: ut | f-8 -*-
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
#
# a² + b² = c²
# For example, 3² + 4² = 9 + 16 = 25 = 52.
#
# There exists exactly one Pythagorean tripl | et for which a + b + c = 1000.
# Find the product abc.
def resolve(n):
for a in range(1, n / 2 - 2):
for b in range(a, n / 2 - 1):
c = n - a - b
if not c > b:
continue
if a ** 2 + b ** 2 == c ** 2:
return a, b, c
return None
if __nam... |
hradec/gaffer | python/GafferImageTest/FormatDataTest.py | Python | bsd-3-clause | 3,696 | 0.040855 | ##########################################################################
#
# Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
######... | ##################
import unittest
import imath
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class FormatDataTest( GafferImageTest.ImageTestCase ) :
def test( self ) :
f1 = GafferImage.Format( imath.Box2i( imath.V2i( 0 ), imath.V2i( 200, 100 ) ), 0.5 )
f2 = GafferImage.Format( imath.... |
teemulehtinen/a-plus | userprofile/tests.py | Python | gpl-3.0 | 7,964 | 0.004646 | from datetime import timedelta
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
from django.conf import settings
from course.models import Course, CourseInstance
from exercise.models import LearningObjectCategory
from userprofile.models import UserProfile
... | plus.com", is_superuser=True)
self.superuser.set_password("superuserPassword")
self | .superuser.save()
self.superuser_profile = self.superuser.userprofile
self.course = Course.objects.create(
name="test course",
code="123456",
url="Course-Url"
)
self.today = timezone.now()
self.tomorrow = self.today + timedelta(days=1)
... |
oomlout/oomlout-OOMP | old/OOMPpart_RESE_0805_X_O271_67.py | Python | cc0-1.0 | 243 | 0 | import OOMP
newPart = OO | MP.oompItem(9452)
newPart.addTag("oompType", "RESE")
newPart.addTag("oompSize", "0805")
newPart.addTag("oompColor", "X")
newPart. | addTag("oompDesc", "O271")
newPart.addTag("oompIndex", "67")
OOMP.parts.append(newPart)
|
rbiswas4/simlib | scripts/make_simlib_enigma.py | Python | mit | 2,405 | 0.00499 | from __future__ import absolute_import, division, print_function
import opsimsummary as oss
import opsimsummary.summarize_opsim as so
from sqlalchemy import create_engine
import pandas as pd
import time
import os
script_start = time.time()
log_str = 'Running script with opsimsummary version {}\n'.format(oss.__VERSION... | ting simlib for {0} input to outfile {1}\n'.format(description,
simlibFileName)
print(log_val)
log_str += log_val
opSummary.writeSimlib(simlibFileName)
log_val = 'Done simlib calculation at {0} and simlib written to {1}\n'.\
format(time.time(), simlibFileName)
print(log_val)
... | ../opsimsummary/example_data/',
'Enigma_1189_DDF.simlib')
CombSimlib = os.path.join('../opsimsummary/example_data/',
'Enigma_1189_Combined.simlib')
_writeSimlibFor([366], DDFSimlib, description='DDF')
_writeSimlibFor([364], WFDSimlib, description='WFD')
_wri... |
ruchee/vimrc | vimfiles/bundle/vim-python/submodules/pylint/tests/functional/y/yield_inside_async_function_py36.py | Python | mit | 327 | 0.006116 | """Test that `yield` or `yield from` | can't be used inside an async function."""
# pylint: disable=missing-docstring, unused-variable
async def g | ood_coro():
def _inner():
yield 42
yield from [1, 2, 3]
async def bad_coro():
yield 42
yield from [1, 2, 3] # [yield-inside-async-function]
|
rahulunair/nova | nova/tests/functional/test_metadata.py | Python | apache-2.0 | 7,360 | 0 | # Copyright 2016 Rackspace Australia
# 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 requi... | d_ip_by_address',
fake_get_fixed_ip_by_address))
def test_lookup_metadata_root_url(self):
res = requests.request('GET', self.md_url, timeout=5)
self.assertEqual(200, res.status_code)
def test_lookup_metadata_openstack_url(self):
url = '%sopenstack' % self. | md_url
res = requests.request('GET', url, timeout=5,
headers={'X-Forwarded-For': '127.0.0.2'})
self.assertEqual(200, res.status_code)
def test_lookup_metadata_data_url(self):
url = '%sopenstack/latest/meta_data.json' % self.md_url
res = requests.reques... |
hkariti/ansible | lib/ansible/utils/module_docs_fragments/vca.py | Python | gpl-3.0 | 2,634 | 0.001519 | # (c) 2016, Charles Paul <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | equired: false
default: None
api_version:
description:
- The api version to be used with the vca.
required: false
default: "5.7"
service_type:
| description:
- The type of service we are authenticating against.
required: false
default: vca
choices: [ "vca", "vchs", "vcd" ]
state:
description:
- If the object should be added or removed.
required: false
default: present
choices: [ "present", "absent"... |
praekelt/django-scaler | scaler/middleware.py | Python | bsd-3-clause | 6,116 | 0 | import time
import re
from django.http import HttpResponseRedirect
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.conf import settings
# In-memory caches are used since different processes do not necessarily
# exhibit the same response times, even though they may share a ... | if t is not None:
# Diff in milliseconds
diff = int((time.time() - t) * 1000)
# Fetch values
prefix = request.META['PATH_INFO'] + '-scaler-'
key_stamp = prefix + 'stamp'
key_hits = prefix + 'hits'
key_trend = prefix + 'trend'
| stamp = _cache.get(key_stamp, 0)
hits = _cache.get(key_hits, 0)
trend = _cache.get(key_trend, [])
# Set values
_cache[key_stamp] = stamp + diff
_cache[key_hits] = hits + 1
trend_size = settings.DJANGO_SCALER.get('trend_size', 100)
... |
miroli/frenchy | frenchy/utils.py | Python | mit | 651 | 0.001536 | import os
import pandas as pd
from .config import BASE_URL
dirname = os.path.dirname(os.path.abspath(__file__))
df = pd.read_pickle(os.path.join(dirname, 'data.p'))
def get_geo(code, year):
row = df[df['insee_code'] == code]
return ro | w.to_dict('records')[0]
def url_resolver(code, year, region_code, department_code):
zero_pad = lambda num: f'0{str(num)}'
if year == 2012:
reg_code = zero_pad(region_code)
dep_code = zero_pad(depar | tment_code)
com_code = zero_pad(code)
url = (f'{BASE_URL}elecresult__PR2012/(path)/PR2012/'
f'{reg_code}/{dep_code}/{com_code}.html')
return url
|
alphagov/notifications-utils | notifications_utils/request_helper.py | Python | mit | 4,607 | 0.002822 | from flask import abort, current_app, request
from flask.wrappers import Request
class NotifyRequest(Request):
"""
A custom Request class, implementing extraction of zipkin headers used to trace request through cloudfoundry
as described here: https://docs.cloudfoundry.org/concepts/http-routing.htm... | #zipkin-headers
"""
@property
def request_id(self):
return self.trace_id
@property
def trace_id(self):
"""
The "trace id" (in zipkin terms) assigned to this request, if present (None otherwise)
"""
if not hasattr(self, "_trace_id"):
self._tra... | rrent_app.config['NOTIFY_TRACE_ID_HEADER'])
return self._trace_id
@property
def span_id(self):
"""
The "span id" (in zipkin terms) set in this request's header, if present (None otherwise)
"""
if not hasattr(self, "_span_id"):
# note how we don't generate... |
danielru/pySDC | pySDC/implementations/problem_classes/GrayScott_1D_FEniCS_implicit.py | Python | bsd-2-clause | 6,141 | 0.001791 | from __future__ import division
import dolfin as df
import numpy as np
import random
import logging
from pySDC.core.Problem import ptype
from pySDC.core.Errors import ParameterError
# noinspection PyUnusedLocal
class fenics_grayscott(ptype):
"""
Example implementing the forced 1D heat equation with Dirichlet... |
Args:
t (float): current time
Returns:
dtype_u: exact solution
"""
class InitialConditions(df.Expression):
def __init__(self):
# fixme: why do we need this?
random | .seed(2)
pass
def eval(self, values, x):
values[0] = 1 - 0.5 * np.power(np.sin(np.pi * x[0] / 100), 100)
values[1] = 0.25 * np.power(np.sin(np.pi * x[0] / 100), 100)
def value_shape(self):
return 2,
uinit = InitialConditi... |
ESSolutions/ESSArch_Core | ESSArch_Core/tags/tests/test_search.py | Python | gpl-3.0 | 22,665 | 0.001853 | import time
from datetime import datetime
from pydoc import locate
from unittest import SkipTest
from countries_plus.models import Country
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import override_settings, tag
fro... |
StructureUnit,
StructureUnitType,
Tag,
TagStructure,
TagVersion,
TagVersionType,
)
User = get_user_model | ()
def get_test_client(nowait=False):
client = get_es_connection('default')
# wait for yellow status
for _ in range(1 if nowait else 5):
try:
client.cluster.health(wait_for_status="yellow")
return client
except ConnectionError:
time.sleep(0.1)
else:... |
harry-7/addons-server | src/olympia/devhub/forms.py | Python | bsd-3-clause | 33,216 | 0 | # -*- coding: utf-8 -*-
import os
from django import forms
from django.conf import settings
from django.db.models import Q
from django.forms.models import BaseModelFormSet, modelformset_factory
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
from django.utils.translati... | odelFormSet):
def clean(self):
if any(self.errors):
return
# cleaned_data could be Non | e if it's the empty extra form.
data = filter(None, [f.cleaned_data for f in self.forms
if not f.cleaned_data.get('DELETE', False)])
if not any(d['role'] == amo.AUTHOR_ROLE_OWNER for d in data):
raise forms.ValidationError(
ugettext('Must have at ... |
michaelBenin/sqlalchemy | lib/sqlalchemy/dialects/postgresql/__init__.py | Python | mit | 1,233 | 0.004866 | # postgresql/__init__.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from . import base, psycopg2, pg8000, py | postgresql, zxjdbc
base.dialect = psycopg2.dialect
from .base import \
INTEGER, BIGINT, SMALLINT, VARCHAR, CHAR, TEXT, NUMERIC, FLOAT, REAL, \
INET, CIDR, UUID, BIT, MACADDR, OID, DOUBLE_PRECISION, TIMESTAMP, TIME, \
DATE, BYTEA, BOOLEAN, INTERVAL, ARRAY, ENUM, dialect, array, Any, All, \
TSV | ECTOR
from .constraints import ExcludeConstraint
from .hstore import HSTORE, hstore
from .json import JSON, JSONElement
from .ranges import INT4RANGE, INT8RANGE, NUMRANGE, DATERANGE, TSRANGE, \
TSTZRANGE
__all__ = (
'INTEGER', 'BIGINT', 'SMALLINT', 'VARCHAR', 'CHAR', 'TEXT', 'NUMERIC',
'FLOAT', 'REAL', 'IN... |
mfherbst/spack | var/spack/repos/builtin/packages/r-xde/package.py | Python | lgpl-2.1 | 1,935 | 0.000517 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at | the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please als | o see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# This program is distributed in the hope ... |
pwillworth/galaxyharvester | catchupMail.py | Python | gpl-3.0 | 5,380 | 0.021004 | #!/usr/bin/env python3
"""
Copyright 2020 Paul Willworth <[email protected]>
This file is part of Galaxy Harvester.
Galaxy Harvester 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 ... | try:
mailer.send_message(message)
result = 'email sent'
except SMTPRecipientsRefused as e:
result = 'email failed'
sys.stderr.write('Email failed - ' + str(e))
trackEmailFailure(datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S"), emailIndex)
mailer.quit()
# update alert st... | OW() WHERE alertID=' + str(alertID) + ';')
else:
result = 'Invalid email.'
cursor.close()
def main():
emailIndex = 0
# check for command line argument for email to use
if len(sys.argv) > 1:
emailIndex = int(sys.argv[1])
conn = ghConn()
# try sending any backed up alert mails
retryPendingMail(conn, emai... |
voetsjoeba/pyjks | tests/expected/unicode_passwords.py | Python | mit | 5,713 | 0.008927 | public_key = b"\x30\x81\x9f\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x03\x81\x8d\x00\x30\x81\x89\x02\x81\x81\x00\xaf\x15\xe8" + \
b"\x75\x00\x06\xe4\xc5\xd5\xda\x2c\xc5\x63\x6a\xef\xa3\x06\x81\x99\x19\x8f\x2a\xb5\xd3\x2e\x50\x76\x94\xe1\xc1\x5a\xa2\x84\xd7\xad" + \
| b"\x91\x2b\xbf\x42\xe6\xb1\x08\x2f\x15\x53\x80\xc1\xa7\xa9\xaf\x22\xd7\x81\x95\xc4\x1e\xea\x4b\x60\x60\xf8\x00\xe5\x9e\x9d\x8a\xe1" + \
b"\x4f\x37\x41\xe7\x4d\xc6\x2e\x9c\xbb\x5c\x03\x5e\x60\x04\x9b\x8b\x3f\x8c\x27\xfc\x1c\x9c\x82\xec\xec\xa1\x30\x0e\x42\x9c\xd3\xaa" + | \
b"\x91\x8a\xf4\xcf\x0c\x60\x9b\xb3\xb4\x77\x14\x24\xe3\x22\xcb\xb8\x79\xa6\x3c\x20\xe3\x8d\x09\x28\x34\xda\x78\xfe\x8d\x02\x03\x01" + \
b"\x00\x01"
private_key = b"\x30\x82\x02\x78\x02\x01\x00\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00\x04\x82\x02\x62\x30\x82\x02\x5e\x02\x0... |
Macpotty/logRobocon | logRobocon/apps/blog/migrations/0005_auto_20160522_1754.py | Python | gpl-3.0 | 496 | 0 | # -*- co | ding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-05-22 09:54
from __future__ import unicode_literals
import ckeditor.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
| ('blog', '0004_blogpost_loggeneral'),
]
operations = [
migrations.AlterField(
model_name='blogpost',
name='logContent',
field=ckeditor.fields.RichTextField(verbose_name='日志正文'),
),
]
|
WhiteMagic/JoystickGremlin | gremlin/ui/dialogs.py | Python | gpl-3.0 | 45,199 | 0.000509 | # -*- coding: utf-8; -*-
# Copyright (C) 2015 - 2019 Lionel Ott
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# T... | ety of options."""
def __init__(self, parent=None):
"""Creates a new options UI instance.
:param parent the parent of this widget
"""
super().__init__(parent)
# Actual configuration object being managed
self.config = gremlin.config.Configuration()
self.setM... |
self.main_layout.addWidget(self.tab_container)
self._create_general_page()
self._create_profile_page()
self._create_hidguardian_page()
def _create_general_page(self):
"""Creates the general options page."""
self.general_page = QtWidgets.QWidget()
self.gener... |
haard/quarterapp | quarterapp/account.py | Python | mit | 6,524 | 0.011649 | #
# Copyright (c) 2013 Markus Eliasson, http://www.quarterapp.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... |
username = self.get_argument("email", "")
error = False
if len(username) == 0:
error = "empty"
if not username_unique(self.application.db, username):
error = "not_unique"
if not error:
try:
code = os.urandom(16).encode("base... | send_signup_email(username, code):
signup_user(self.application.db, username, code, self.request.remote_ip)
self.render(u"public/signup_instructions.html")
else:
self.render(u"public/signup.html", error = error, username = username)
... |
hassaanm/stock-trading | src/pybrain/rl/learners/meta/meta.py | Python | apache-2.0 | 196 | 0.005102 | __author_ | _ = 'Tom Schaul, [email protected]'
from pybrain.rl.learners.learner import Learner
class MetaLearner(Learner):
""" Learners that make use of other Learners, or learn how to learn. """ | |
nkgilley/home-assistant | homeassistant/components/smarthab/light.py | Python | apache-2.0 | 1,765 | 0.001133 | """Support for SmartHab device integration."""
from datetime import timedelta
import logging
import pysmarthab
from requests.exceptions import Timeout
from homeassistant.components.light import LightEntity
from . import DATA_HUB, DOMAIN
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=60)
... | HUB]
devices = hub.get_device_list()
_LOGGER.debug("Found a total of %s devices", str(len(devices)))
entities = (
SmartHabLight(light) for light in devices if isinstance(light, pysmarthab.Light)
)
add_entities(entities, T | rue)
class SmartHabLight(LightEntity):
"""Representation of a SmartHab Light."""
def __init__(self, light):
"""Initialize a SmartHabLight."""
self._light = light
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return self._light.device_id
@propert... |
manqala/erpnext | erpnext/setup/setup_wizard/install_fixtures.py | Python | gpl-3.0 | 14,628 | 0.021192 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
default_lead_sources = ["Existing Customer", "Reference", "Advertisement",
"Cold Calling", "Exhibition", "Supplie... | ype': 'Leave Type', 'leave_type_name': _('Compensatory Off'), 'name' | : _('Compensatory Off'),
'is_encash': 0, 'is_carry_forward': 0, 'include_holiday': 1},
{'doctype': 'Leave Type', 'leave_type_name': _('Sick Leave'), 'name': _('Sick Leave'),
'is_encash': 0, 'is_carry_forward': 0, 'include_holiday': 1},
{'doctype': 'Leave Type', 'leave_type_name': _('Privilege Leave'), 'name':... |
arximboldi/jpblib | test/jpb_coop.py | Python | gpl-3.0 | 15,395 | 0.006042 | # -*- coding: utf-8 -*-
#
# File: jpb_coop.py
# Author: Juan Pedro Bolívar Puente <[email protected]>
# Date: Fri Jan 20 16:12:23 2012
# Time-stamp: <2012-01-25 20:21:45 jbo>
#
#
# Copyright (C) 2012 Juan Pedro Bolívar Puente
#
# This file is part of jpblib.
#
# jpblib is free software: you... | of the
# License, or (at your option) any later version.
#
# jpblib is distributed in the hope that it will be useful,
# but WITHOU | T ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Tes... |
waseem18/oh-mainline | vendor/packages/scrapy/scrapy/contrib/spiders/sitemap.py | Python | agpl-3.0 | 2,111 | 0.002369 | import re
from scrapy.spider import BaseSpider
from scrapy.http import Request, XmlResponse
from scrapy.utils.sitemap import Sitemap, sitemap_urls_from_robots
from scrapy.utils.gz import gunzip
from scrapy import log
class SitemapSpider(BaseSpider):
sitemap_urls = ()
sitemap_rules = [('', 'parse')]
sitem... | def __init__(self, *a, **kw):
super(SitemapSpider, self).__init__(*a, **kw)
self._cbs = []
for r, c in self.sitemap_rules:
if isinstance(c, basestring):
c = getattr(self, c)
self._cbs.append((regex(r), c))
self._follow = [regex(x) for x in self... | sponse):
if response.url.endswith('/robots.txt'):
for url in sitemap_urls_from_robots(response.body):
yield Request(url, callback=self._parse_sitemap)
else:
if isinstance(response, XmlResponse):
body = response.body
elif is_gzipped(resp... |
PaavoJokinen/molli | ncurses.py | Python | gpl-3.0 | 460 | 0.017391 | #!/Users/pjjokine/an | aconda/bin/python3
import curses
import os
import signal
from time import sleep
stdscr = curses.initscr()
curses.noecho()
begin_x = 20; begin_y = 7
height = 5; width = 40
win = curses.newwin(height, width, begin_y, begin_x)
count = 5
for x in ran | ge(0,20):
for y in range (0,5):
win.addstr(y, x, "a", curses.A_BLINK)
win.refresh()
sleep(3)
#signal.pause()
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
curses.endwin()
|
h2oai/h2o-3 | h2o-py/tests/testdir_algos/gam/pyunit_PUBDEV_7611_early_stop_gam_binomial.py | Python | apache-2.0 | 4,548 | 0.010994 | from __future__ import division
from __future__ import print_function
from past.utils import old_div
import sys
sys.path.insert(1, "../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gam imp | ort H2OGeneralizedAdditiveEstimator
# In this test, we check that we can do early-stopping with GAM. In particular, we check the following conditions
# 1. run the model without early stopping and check that model with early st | opping runs for fewer iterations
# 2. for models with early stopping, check that early stopping is correctly done.
# 3. when lambda_search is enabled, early stopping should be disabled
def test_gam_model_predict():
print("Checking early-stopping for binomial")
print("Preparing for data....")
h2o_data = h2o.... |
UCL-INGI/INGInious | inginious/frontend/pages/course_admin/statistics.py | Python | agpl-3.0 | 13,926 | 0.005674 | # -*- coding: utf-8 -*-
#
# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
# more information about the licensing of this file.
""" Utilities for computation of statistics """
from collections import OrderedDict
import flask
from inginious.frontend.pages.course_admin.utils import make_... | project = {
"year": {"$year": "$submitted_on"},
"month": {"$month": "$submitted_on"},
"day": {"$dayOfMonth": "$submitted_on"},
"result": "$result"
}
groupby = {"year": "$year", "month | ": "$month", "day": "$day"}
method = "day"
if (daterange[1] - daterange[0]).days < 7:
project["hour"] = {"$hour": "$submitted_on"}
groupby["hour"] = "$hour"
method = "hour"
min_date = daterange[0].replace(minute=0, second=0, microsecond=0)
max_date =... |
oisinmulvihill/stats-service | stats_service/service/restfulhelpers.py | Python | mit | 7,229 | 0.000692 | # -*- coding: utf-8 -*-
"""
Useful classes and methods to aid RESTful webservice development in Pyramid.
PythonPro Limited
2012-01-14
"""
import json
import httplib
import logging
import traceback
#from decorator import decorator
from pyramid.request import Response
def get_log(e=None):
return logging.getLogge... | e, and handle all exceptions.
"""
try:
res = f(*args, **kw)
return status_body(message=res, to_json=False)
except Exception, e:
tb = traceback.format_exc()
get_log().exception(tb)
return status_err(e, tb)
def notfound_404_view(request):
"""A custom 404 view retu... | ead of HTML.
:returns: a JSON response with the body::
json.dumps(dict(error="URI Not Found '...'"))
"""
msg = str(request.exception.message)
get_log().info("notfound_404_view: URI '%s' not found!" % str(msg))
request.response.status = httplib.NOT_FOUND
request.response.content_type =... |
uhuramedia/django-portlet | portlet/tests/runtests.py | Python | bsd-3-clause | 2,032 | 0.001476 | #!/usr/bin/env python
"""
This script is a trick to setup a fake Django environment, since this reusable
app will be developed and tested outside any specifiv Django project.
Via ``settings.configure`` you will be able to set all necessary settings
for your app and run the tests as if you were calling ``./manage.py te | st``.
Taken from https://github.com/mbrochh/tdd-with-django-reusable-app
"""
import os
import sys
from django.conf import settings
EXTERNAL_APPS = [
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
| 'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.sitemaps',
'django.contrib.sites',
]
INTERNAL_APPS = [
'portlet',
'django_nose',
]
INSTALLED_APPS = EXTERNAL_APPS + INTERNAL_APPS
COVERAGE_MODULE_EXCLUDES = [
'tests$', 'settings$', 'urls$', 'locale$',
'migrations', 'f... |
cisco/xr-telemetry-m2m-web | src/m2m_demo/frontend/web.py | Python | apache-2.0 | 2,569 | 0.002336 | # =============================================================================
# m2m_demo_plugin.py
#
# Set up the web service.
#
# December 2015
#
# Copyright (c) 2015 by cisco Systems, Inc.
# All rights reserved.
# =============================================================================
import os, re
from twis... | self.files = {}
for root, dirs, files in os.walk(static_dir):
for filename in files:
if not filename.startswith('!'):
fullpath = os.path.join(root, filename)
self.files[filename] = File(fullpath)
| def handle_static(self, request):
r = re.search(r'.*/(.+)', request.path)
if r and r.group(1) in self.files:
return self.files[r.group(1)]
return None
def start(web_cfg):
"""
Start the web service
"""
static = Static(web_cfg)
root_resource = Root(web_cfg, stati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.