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 |
|---|---|---|---|---|---|---|---|---|
mpetyx/palmdrop | venv/lib/python2.7/site-packages/mptt/templatetags/mptt_tags.py | Python | apache-2.0 | 11,153 | 0.002242 | """
Template tags for working with lists of model instances which represent
trees.
"""
from django import template
from django.db.models import get_model
from django.db.models.fields import FieldDoesNotExist
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from django.utils.... | ument to %s tag must be 'with'") % bits[0])
if bits[6] != 'in':
rai | se template.TemplateSyntaxError(
_("if seven arguments are given, sixth argument to %s tag must be 'in'") % bits[0])
return DrilldownTreeForNodeNode(bits[1], bits[3], bits[5], bits[7])
elif len_bits == 9:
if bits[4] != 'cumulative':
raise template.TemplateSyntaxError(
... |
martolini/pythonstory | pythonstory/common/protocol.py | Python | mit | 2,331 | 0 | from twisted.internet import protocol, task
import struct
from . import decoder, packetreader, packets
class MapleProtocol(protocol.Protocol, object):
PING_TIME = 30
processor = None
def __init__(self):
self.reader = packetreader.PacketReader()
self.pingcall = task.LoopingCall(self.send_p... | ved(body)
elif len(body) > packetlength:
self.dataReceived(data[:4+packetlength])
self.dataReceived(data[packetlength+4:])
| def packet_received(self, packet):
packet = self.reader.process(self.decoder.decode(packet))
self.processor.handle_packet(packet, self)
def connectionMade(self):
print "New connection {} on {} ".format(
self.transport.getPeer().host,
self.__class__.__name__
... |
aurelieladier/openturns | python/test/t_MeixnerFactory_std.py | Python | lgpl-3.0 | 515 | 0.001942 | #! /usr/bin/env python
from __future__ import print_function
from openturns import *
TESTPREAMBLE()
try:
meixner = MeixnerFactory(10, 0.3)
for i in range(10):
print("meixner(", i, ")=", | meixner.build(i))
roots = meixner.getRoots(10)
print("meixner(10) roots=", repr(roots))
nodes, weights = meixner.getNodesAndWeights(10)
print("meixner(10) nodes=", nodes, "and we | ights=", weights)
except:
import sys
print("t_MeixnerFactory_std.py", sys.exc_info()[0], sys.exc_info()[1])
|
partofthething/home-assistant | tests/components/litejet/test_trigger.py | Python | apache-2.0 | 8,952 | 0.000112 | """The tests for the litejet component."""
from datetime import timedelta
import logging
from unittest import mock
from unittest.mock import patch
import pytest
from homeassistant import setup
import homeassistant.components.automation as automation
import homeassistant.util.dt as dt_util
from . import async_init_in... | .common import async_fire_time_changed, async_mock_service
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401
_LOGGER = logging.getLogger(__name__)
ENTITY_SWITCH = "switch.mock_switch_1"
ENTITY_SWITCH_NUMBER = 1
ENTITY_OTHER_SWITCH = "switch.mock_switch_2"
ENTITY_OTHER_SWITCH_NUMBER... | mulate_press(hass, mock_litejet, number):
"""Test to simulate a press."""
_LOGGER.info("*** simulate press of %d", number)
callback = mock_litejet.switch_pressed_callbacks.get(number)
with mock.patch(
"homeassistant.helpers.condition.dt_util.utcnow",
return_value=mock_litejet.start_time ... |
ancafarcas/superdesk-core | apps/publish/formatters/resource.py | Python | agpl-3.0 | 793 | 0 | # -*- 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
from superdesk.resource import Resource
class FormattersResource(Resource):
"""Formatters schema"""
endpoint_name = 'formatters'
resource_methods = ['GET', 'POST']
item_methods = []
resource_title = endpoint_name
schema = {
'article_id': {
... |
pyfisch/servo | tests/wpt/web-platform-tests/tools/ci/run_tc.py | Python | mpl-2.0 | 9,392 | 0.001491 | #!/usr/bin/env python
"""Wrapper script for running jobs in TaskCluster
This is intended for running test jobs in TaskCluster. The script
takes a two positional arguments which are the name of the test job
and the script to actually run.
The name of the test job is used to determine whether the script should be run
... | w") as f:
f.write(resp.read())
run(["sudo", "apt-get", "-qqy", "update"])
run(["sudo", "gdebi", "-qn", "/tmp/%s" % deb_archive])
def start_xvfb():
start(["sudo", "X | vfb", os.environ["DISPLAY"], "-screen", "0",
"%sx%sx%s" % (os.environ["SCREEN_WIDTH"],
os.environ["SCREEN_HEIGHT"],
os.environ["SCREEN_DEPTH"])])
start(["sudo", "fluxbox", "-display", os.environ["DISPLAY"]])
def get_extra_jobs(event):
body = None
... |
saltstack/salt | tests/pytests/functional/transport/ipc/test_subscriber.py | Python | apache-2.0 | 3,365 | 0.000297 | i | mport pathlib
import sys
import attr
import pytest
import salt.channel.server
import salt.ext.tornado.gen
import salt.transport.ipc
import salt.utils.platform
from salt.ext.tornado import locks
pytestmark = [
# Windows does not | support POSIX IPC
pytest.mark.skip_on_windows,
pytest.mark.skipif(
sys.version_info < (3, 6), reason="The IOLoop blocks under Py3.5 on these tests"
),
]
@attr.s(frozen=True, slots=True)
class PayloadHandler:
payloads = attr.ib(init=False, default=attr.Factory(list))
async def handle_payl... |
pombredanne/readthedocs.org | readthedocs/builds/models.py | Python | mit | 17,368 | 0.000979 | """Models for the builds app."""
from __future__ import absolute_import
import logging
import os.path
import re
from shutil import rmtree
from builtins import object
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_u... | u"Version %(version)s of %(project)s (%(pk)s)" % {
'version': self.verbose_name,
'project': self.project,
'pk': self.pk
})
@property
def commit_name(self):
"""
Return the branch name, the tag name or the revision identifier.
The result could ... | # name in verbose_name.
if self.slug == LATEST:
if self.project.default_branch:
return self.project.default_branch
return self.project.vcs_repo().fallback_branch
if self.slug == STABLE:
if self.type == BRANCH:
# Special case, as w... |
garygriswold/Bible.js | Versions/Release.2.x.x/py/UpdateVideo.py | Python | mit | 755 | 0.022517 | # This program reads files in data/KOGVideo and loads them into the Video table
# to populate the description column
import io
import os
import sqlite3
db = sqlite3.conne | ct("Versions.db")
cursor = db.cursor()
source = "data/KOGVideo/"
filelist = sorted(os.listdir(source))
for filename in filelist:
if filename[0:4] == 'KOG_':
#print filename
name = filename.split(".")[0]
par | ts = name.split("-")
mediaId = parts[0]
languageId = parts[1].lower()
print mediaId, languageId
input = io.open(source + filename, mode="r", encoding="utf-8")
description = input.read()
cursor.execute("UPDATE Video SET description = ? WHERE mediaId = ? AND languageId = ?",
(description, mediaId, language... |
tlksio/tlksio | env/lib/python3.4/site-packages/taggit/views.py | Python | mit | 1,751 | 0.001142 | from __future__ import unicode_literal | s
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
from django.views.generic.list import ListView
from taggit.models import Tag, TaggedItem
def tagged_object_list(request, slug, queryset, **kwargs):
if callable(queryset):
queryset = queryset()
... | .model)
kwargs["slug"] = slug
tag_list_view = type(
str('TagListView'),
(TagListMixin, ListView),
{
'model': queryset_model,
'queryset': queryset
}
)
return tag_list_view.as_view()(request, **kwargs)
class TagListMixin(object):
tag_suffix = '... |
Valars/Ragnar | code/main.py | Python | gpl-3.0 | 3,062 | 0.017417 | from tkinter import *
from noeud import *
from arete import *
from partie import *
from parsers import *
from majObjets import *
#simulation du retour serveur
def state() :# 1
return "STATE20... | plateau, etat["moves"])
#BOUCLE PRINCIPALE
while(T | rue) :
a = input()
if a == "fin" :
break
|
mvaled/sentry | src/sentry/plugins/bases/data_forwarding.py | Python | bsd-3-clause | 1,514 | 0.001321 | from __future__ import absolute_import
from sentry import tsdb, ratelimits
from sentry.api.serializers import serialize
from sentry.plugins.base import Plugin
from sentry.plugins.base.configuration import react_plugin_config
from sentry.plugins.status import PluginStatus
class DataForwardingPlugin(Plugin):
statu... | ayload):
"""
Forward the event and return a boolean if it was successful.
"""
raise NotImplementedError
def get_event_payload(self, event):
return serialize(event)
def get_plugin_type(self):
return "data-forwarding"
def post_process(self, event, **kw | args):
rl_key = u"{}:{}".format(self.conf_key, event.project.organization_id)
# limit segment to 50 requests/second
limit, window = self.get_rate_limit()
if limit and window and ratelimits.is_limited(rl_key, limit=limit, window=window):
return
payload = self.get_even... |
gVallverdu/pymatgen | pymatgen/ext/tests/test_matproj.py | Python | mit | 21,960 | 0.00082 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import platform
import re
import unittest
import warnings
import random
import sys
from pymatgen import SETTINGS, __version__ as pmg_version
from pymatgen.ext.matproj import MPRester, MPRestError, TaskType
from ... | pymatgen.electronic_structure.dos import CompleteDos
from pymatgen.electronic_structure.bandstructure import (
BandStructureSymmLine, BandStructure)
from pymatgen.entries.compatibility import MaterialsProjectCompatibility
from pymatgen.analysis. | phase_diagram import PhaseDiagram
from pymatgen.analysis.pourbaix_diagram import PourbaixEntry, PourbaixDiagram
from pymatgen.analysis.wulff import WulffShape
from pymatgen.analysis.reaction_calculator import Reaction
from pymatgen.io.cif import CifParser
from pymatgen.phonon.bandstructure import PhononBandStructureSym... |
vandenheuvel/tribler | Tribler/community/trustchain/community.py | Python | lgpl-3.0 | 20,318 | 0.003396 | """
The TrustChain Community is the first step in an incremental approach in building a new reputation system.
This reputation system builds a tamper proof interaction history contained in a chain data-structure.
Every node has a chain and these chains intertwine by blocks shared by chains.
"""
import logging
from rand... | 739b27051dc6ad1da743a463821fc8d3d1849191d5fb84fab1f3fe3ad44fb2b83f07d0c78a13b7ad1d" \
"311063069f49070cad7dc15620996cdd625c1abcdbfabf750727f1dec706f6f16cb28ce6946fdf39887a84fc457a5f9" \
"edc660adbe0a72ea5219f9578dd6432de825c167e80987ca4c6a2bf"
return [dispersy.get_membe... | ic_key=master_key.decode("HEX"))]
def initialize(self, tribler_session=None):
super(TrustChainCommunity, self).initialize()
if tribler_session:
self._live_edges_enabled = tribler_session.config.get_trustchain_live_edges_enabled()
def initiate_meta_messages(self):
"""
... |
mikolajb/cookery | cookery/lisp_parse.py | Python | mit | 2,890 | 0.001038 | from lisp_lex import CookeryLexer
import logging
from functools import reduce
from operator import sub, mul, truediv
from itertools import dropwhile
import ply.yacc as yacc
import ply.lex as lex
funs = {
'+': sum,
'-': lambda l: reduce(sub, l[1:], l[0]),
'*': lambda l: reduce(mul, l[1:], l[0]),
'/': la... | def p_forms(self, p):
'''forms : form
| form forms'''
p[0] = [p[1]]
if len(p) > 2:
p[0] | += p[2]
self.log.debug(p[0])
def p_form(self, p):
'''form : INTEGER
| FLOAT
| STRING
| EXP_BEGIN proc_call EXP_END
| EXP_BEGIN something EXP_END'''
# | EXP_BEGIN progn forms EXP_END
# if len(p) > 4:
# ... |
JazzeYoung/VeryDeepAutoEncoder | pylearn2/pylearn2/devtools/tests/test_via_pyflakes.py | Python | bsd-3-clause | 639 | 0.004695 | from __future__ import print_function
from pylearn2.devtools.run_pyflakes import run_pyflakes
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2010-2012, Universite de M | ontreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
__email__ = "pylearn-dev@googlegroups"
def test_via_pyflakes():
| d = run_pyflakes(True)
if len(d.keys()) != 0:
print('Errors detected by pyflakes')
for key in d.keys():
print(key+':')
for l in d[key].split('\n'):
print('\t',l)
raise AssertionError("You have errors detected by pyflakes")
|
LEWASatVT/leapi | leapi/models/user.py | Python | gpl-2.0 | 1,975 | 0.005063 | from leapi import db, app
from flask.ext.security import UserMixin, RoleMixin
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
roles_users = db.Table('roles_users',
... | s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
return s.dumps({'id': self.id})
@property
def username(self):
return self.email
@staticmethod
def verify_auth_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)... | xcept SignatureExpired:
return None # valid token, but expired
except BadSignature:
return None # invalid token
user = User.query.get(data['id'])
return user
|
studybuffalo/studybuffalo | study_buffalo/users/models.py | Python | gpl-3.0 | 641 | 0 | """Models for the Users app."""
from django.contrib.au | th.models import AbstractUser
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
class User(AbstractUser):
"""Extended User model."""
# First Name and Last Name do not cov | er name patterns
# around the globe.
name = models.CharField(_('Name of User'), blank=True, max_length=255)
def __str__(self):
return self.username
def get_absolute_url(self):
"""Override method to use Username for absolute URL."""
return reverse('users:detail', kwargs={'userna... |
sebdelsol/pyload | module/plugins/hoster/SockshareCom.py | Python | gpl-3.0 | 613 | 0.008157 | # -*- coding: utf-8 -*-
from module.plugins.internal.DeadHoster import DeadHoster, create_getInfo
class SockshareCom(DeadHoster):
__name__ = "So | ckshareCom"
__type__ = "hoster"
__version__ = "0.05"
__pattern__ = r'http:/ | /(?:www\.)?sockshare\.com/(mobile/)?(file|embed)/(?P<ID>\w+)'
__description__ = """Sockshare.com hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("jeix", "jeix@hasnomail.de"),
("stickell", "l.stickell@yahoo.it"),
("Walter Purcaro", "vuolter@gmail.... |
ebassett/base_addition | base_addition.py | Python | gpl-2.0 | 4,658 | 0.004938 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# base_addition - 2014-10-19 - ejb
from __future__ import print_function
import argparse
import sys
__version__ = '0.1'
'''
Revision history
0.1 Initial version
'''
DIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
debug = False
def parse_args():
parser = argparse... | e same number of digits, for simplicity
max_len = max(len(x), len(y))
x += (max_len - len(x)) * '0'
y += (max_len - len(y)) * '0'
log_debug('x padde | d: {}'.format(x))
log_debug('y padded: {}'.format(y))
out_str = ''
carry_in = 0
for i in range(max_len):
(carry_out, output) = divmod(digits.index(x[i]) + digits.index(y[i]), base)
output += carry_in
if output >= base:
(carry_out, outp... |
balle/airxploit | src/airxploit/fuckup/not_a_service.py | Python | gpl-2.0 | 308 | 0.006494 | '''
Created on 05.09.2010
@author: basti
'''
class NotAServi | ce(Exception):
"""
service unknown exception
"""
def __init__(self, what):
super(NotAService, self).__init__()
self.__msg = "Unknown s | ervice: " + str(what)
def __str__(self):
return self.__msg
|
adrianpaesani/odoo-argentina | l10n_ar_aeroo_stock/__openerp__.py | Python | agpl-3.0 | 1,827 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | 'l10n_ar_aeroo_base',
'l10n_ar_invoice',
'stock_voucher',
],
'external_dependencies': {
},
'data': [
'report_configuration_defaults_data.xml',
'report.xml',
'stock_picking_template.xml',
],
'demo': [
],
'test': [
],
'installable': True,
... | nt:tabstop=4:softtabstop=4:shiftwidth=4:
|
Kurpilyansky/street-agitation-telegram-bot | door_to_door_bot/bot.py | Python | gpl-3.0 | 21,674 | 0.003595 | from django.db.models import Q
from door_to_door_bot import bot_settings, models
from door_to_door_bot.common import *
from street_agitation_bot.emoji import *
from street_agitation_bot import utils
import traceback
import re
import collections
from datetime import datetime, date, timedelta
from telegram import (Rep... | update.callback_query
query.answer() |
if query.data == YES:
user_data['show_all_regions'] = True
elif query.data == NO:
user_data['show_all_regions'] = False
elif query.data == BACK:
del user_data['region_range']
else:
if query.data[0].isdigit():
user_data['region_id'] = int(query.data)
... |
mahajrod/MACE | scripts/old/extract_homozygous_chains.py | Python | apache-2.0 | 3,132 | 0.005428 | #!/usr/bin/env python
__author__ = 'Sergei F. Kliver'
import argparse
from collections import OrderedDict
from MACE.Parsers.VCF import CollectionVCF
from MACE.Parsers.CCF import RecordCCF, MetadataCCF, HeaderCCF, CollectionCCF
from MA | CE.General.G | eneralCollections import WDict
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input_vcf", action="store", dest="input", required=True,
help="Input vcf file.")
parser.add_argument("-o", "--output_prefix", action="store", dest="output_prefix", required=True,
hel... |
kohr-h/odl | odl/discr/discr_ops.py | Python | mpl-2.0 | 20,951 | 0 | # Copyright 2014-2020 The ODL contributors
#
# This file is part of ODL.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
"""Operators defined on `DiscretizedSpace`."... | s the interpolation
scheme per axis.
Supported values: ``'nearest'``, ``'linear'``
Examples
--------
Create two spaces with different number of points and a resampling
operator using nearest-neighbor interpolation:
>>> coarse_discr = odl.uniform_discr(0... | ')
>>> resampling.domain
uniform_discr(0.0, 1.0, 3)
>>> resampling.range
uniform_discr(0.0, 1.0, 6)
>>> resampling.interp
'nearest'
Apply the corresponding resampling operator to an element:
>>> print(resampling([0, 1, 0]))
[ 0., 0., 1., 1., ... |
pcu4dros/pandora-core | workspace/lib/python3.5/site-packages/sqlalchemy/sql/crud.py | Python | mit | 24,802 | 0 | # sql/crud.py
# Copyright (C) 2005-2016 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
"""Functions used by compiler.py to determine the parameters rendered
within INSERT and ... | returning column collections, used for default handling and ultimately
populating the ResultProxy's prefetch_cols() and postfetch_cols()
collections.
"""
compiler.postfetch = []
compiler.insert_prefetch = []
compiler.update_prefetch = []
compiler.returning = []
# no parameters in ... | return [
(c, _create_bind_param(
compiler, c, None, required=True))
for c in stmt.table.columns
]
if stmt._has_multi_parameters:
stmt_parameters = stmt.parameters[0]
else:
stmt_parameters = stmt.parameters
# getters - these are normally jus... |
seaotterman/tensorflow | tensorflow/compiler/tests/spacetobatch_op_test.py | Python | apache-2.0 | 10,234 | 0.00469 | # Copyright 2017 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... | + list(
np.arange(input_array.ndim - num_block_dims - 1) + 1 + num_block_dims
* 2)))
return permuted_reshaped_padded.reshape(output_shape)
class SpaceToBatchTest(XLATestCase):
"""Tests input-output pairs for the SpaceToBatch and BatchToSpace ops."""
def _testPad(self, inputs, paddings, bloc... | sess, self.test_scope():
for dtype in self.float_types:
# outputs = space_to_batch(inputs)
placeholder = array_ops.placeholder(dtype)
x_tf = gen_array_ops._space_to_batch(
placeholder, paddings, block_size=block_size)
self.assertAllEqual(sess.run(x_tf, {placeholder: inp... |
inveniosoftware/invenio-accounts | invenio_accounts/admin.py | Python | mit | 7,515 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Admin views for invenio-accounts."""
from flask import current_app, flash
from fl... | """Delete selected sessions."""
is_current = any(SessionActivity.is_current(sid_s=id_) for id_ in ids)
if is_current:
flash('You could not remove your current session', 'error')
return
| for id_ in ids:
delete_session(sid_s=id_)
db.session.commit()
class UserIdentityView(ModelView):
"""Flask-Admin view to manage user identities from invenio-accounts."""
can_view_details = True
can_create = False
column_list = (
'id',
'method',
'id_user'... |
pypa/warehouse | warehouse/integrations/github/tasks.py | Python | apache-2.0 | 862 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Li... | r express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from warehouse import tasks
from warehouse.integrations.github import utils
@tasks.task(ignore_result=True, acks_late=True)
def analyze_disclosure_task(request, disclosure_record, origin):
... | origin=origin,
)
|
tysonholub/twilio-python | twilio/rest/video/v1/composition/__init__.py | Python | mit | 20,700 | 0.002705 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import... | lf, status=values.unset, date_created_after=values.unset,
date_created_before=values.unset, room_sid=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of CompositionInstance records from the API.
... | Status status: Read only Composition resources with this status
:param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone
:param datetime date_created_before: Read only Composition resources cr... |
robneville73/OpenEcho | echo/views.py | Python | mit | 6,048 | 0.013062 | # Create your views here.
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.http import Http404
from echo.models import Comment, Reply, CategoryMeta
from echo.forms import RegistrationForm, ConfirmRegistration
from django.core.urlresolvers import reverse
from django.http im... | tegory' : category,
| 'comment' : comment},
context_instance=RequestContext(request))
@login_required
def postComment(request):
c = Comment()
c.body = request.POST['body']
c.category = request.POST['category']
u = request.user
c.commenter = u
... |
twilio/twilio-python | tests/integration/api/v2010/account/usage/test_trigger.py | Python | mit | 11,299 | 0.003363 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class TriggerTestCase(Integrati... | ": "price",
"trigger_value": "50",
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Triggers/UTaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"usage_category" | : "totalprice",
"usage_record_uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records?Category=totalprice"
}
'''
))
actual = self.client.api.v2010.accounts("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") \
.usage \... |
azul-cloud/serendipity | shopping/views.py | Python | mit | 6,846 | 0.006719 | import stripe
import json
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import TemplateView, DetailView, ListView
from carton.cart import Cart
from .models import Sale, SaleProduct, SaleError
from products.models import Product
... | y')
product = Product.objects.get(id=id)
SaleProduct.objects.create(
| product=product,
quantity=quantity,
price=product.price,
sale=sale
)
return render(request, "shoppingcontent/success.html",
{'sale': sale, 'email': email})
except Exception as e:
... |
mnorbury/scriptutil | src/scriptutil/command_line.py | Python | gpl-3.0 | 2,055 | 0.002433 | '''
command_line.py
Utility functions for reading command line arguments.
Author:
Martin Norbury
Novemeber 2013
'''
import inspect
import argparse
def command_line(fn):
'''
A decorator for functions intented to be run from the command line.
This decorator introspects the method signature of the ... | .
Can be called | from the command line as:-
> myfunction <a> [--b=value]
All arguments are assumed to be strings at this point.
'''
def wrapper_fn(*args, **kwargs):
# Get the original function's method signature
arguments, varargs, kwargs, defaults = inspect.getargspec(fn)
# Get required and ... |
jkachika/columbus | columbus/settings.py | Python | mit | 236 | 0.004237 | import socket
if socket.gethostname() == 'Jo_SpectreX':
from columbus.dev_set | tings import *
elif socket.gethostname() == 'columbus-dev-server':
from columbus.test_settings import *
e | lse:
from columbus.prod_settings import * |
TimothyHelton/strumenti | strumenti/__init__.py | Python | bsd-3-clause | 640 | 0 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
from pkg_resources import get_distribution, DistributionNotFound
import os.path as osp
from . import coordinate
from . import notify
f | rom . import packages
from . import plot
from . import psql
from . import system
__version__ = '1.0.2'
try:
_dist = get_distribution('strumenti')
dist_loc = osp.normcase(_dist.location)
here = osp.normcase(__file__)
if not here.startswith(osp.join(dist_loc, 'strumenti')):
raise DistributionNo... | with setup.py'
else:
__version__ = _dist.version
|
nicolashainaux/mathmaker | tests/integration/mental_calculation/05_yellow2/test_05_yellow2_perimeter_of_a_polygon.py | Python | gpl-3.0 | 1,673 | 0 | # -*- coding: utf-8 -*-
# Mathmaker creates automatically maths exercises sheets
# with their answers
# Copyright 2006-2018 Nicolas Hainaux <nh.techn@gmail.com>
# This file is part of Mathmaker.
# Mathmaker is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | l_calculation',
'05_yellow2',
'perimeter_of_a_polygon')),
pdf_output=True)
def test_perimeter_of_a_polygon_embedding_js():
"""Check this sheet is generated without any error."""
shared.machine.write_out(... | enable_js_form=True)),
pdf_output=True)
|
googleapis/python-bigquery | samples/load_table_uri_parquet.py | Python | apache-2.0 | 1,400 | 0.000714 | # 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | _dataset.your_table_name"
job_config = bigquery.LoadJobConfig(source_format=bigquery.SourceFormat.PARQUET,)
uri = "gs://cloud-samples-data/bigquery/us-states/us-states.parquet"
load_job = client.load_table_from_uri(
uri, table_id, job_config=job_config
) # Make an API request.
load_job.r... | ded {} rows.".format(destination_table.num_rows))
# [END bigquery_load_table_gcs_parquet]
|
proto-n/Alpenglow | python/test_alpenglow/evaluation/test_RrScore.py | Python | apache-2.0 | 964 | 0.001037 | import alpenglow as prs
import alpenglow.Getter as rs
import alpenglow.evaluation
import pandas as pd
import math
import unittest
class TestRrScore(unittest.TestCase):
def test_rrScore(self):
ranks = [102, 102, 102, 102, 3, 4, 102, 9, 102, 102, 102, 9, 102, 102, 102, 6, 102, 102, 102, 102, 102, 102, 102, ... | [
(i, i, 0, r if r <= 10 else None)
for i, r in enumerate(ranks)
],
columns=["id", "time", "prediction", "ra | nk"]
).set_index("id")
facRankings.top_k = 10
rr = alpenglow.evaluation.RrScore(facRankings).mean()
rrs = [1.0 / r if r <= 10 else 0 for r in ranks]
self.assertAlmostEqual(rr, sum(rrs) / len(rrs))
|
JazzeYoung/VeryDeepAutoEncoder | theano/sandbox/linalg/tests/test_linalg.py | Python | bsd-3-clause | 5,038 | 0.000198 | from __future__ import absolute_import, print_function, division
import numpy
import numpy.linalg
import theano
from theano import tensor, function
from theano.tensor.basic import _allclose
from theano.tests.test_rop import break_op
from theano.tests import unittest_tools as utt
from theano import config
from theano.t... | st the bound
eigen_val = numpy.linalg.eig(m)
assert (eigen_val[0].max() - radius_bound_theano) < tol
# test type errors |
xx = theano.tensor.vector()
ok = False
try:
spectral_radius_bound(xx, 5)
except TypeError:
ok = True
assert ok
ok = False
try:
spectral_radius_bound(x, 5.)
except TypeError:
ok = True
assert ok
# test value error
ok = False
try:
s... |
embali/windseed | windseed/apps/admin/handlers.py | Python | mit | 7,638 | 0 | import peewee
import tornado.web
import tornado.gen
from windseed.settings import env, db
from windseed.base import handler
from windseed.apps.admin import urls
from windseed.apps.admin.models import User
from windseed.apps.web.models import Record
class Handler(handler.Handler):
def get_current_user(self):
... | peewee.IntegrityError:
updated = None
if updated:
self.ajax_page('update')
else:
self.ajax_empty('not_updated')
elif delete is not None and \
uid is not None:
try:
with db.pool.atomic():
... | )\
.where(Record.uid == uid)\
.execute()
except peewee.IntegrityError:
deleted = None
if deleted:
self.ajax_page('delete')
else:
self.ajax_empty('not_deleted')
else:
s... |
mancoast/CPythonPyc_test | fail/331_test_io.py | Python | gpl-3.0 | 120,164 | 0.001406 | """Unit tests for the io module."""
# Tests of io are scattered over the test suite:
# * test_bufio - tests file buffering
# * test_memoryio - tests BytesIO and StringIO
# * test_fileio - tests FileIO
# * test_file - tests the file interface
# * test_io - tests everything else in the io module
# * test_univnewlines - ... | self, n=None):
res = super().read(n)
self.read_history.append(None if res is None else len(res))
return res
def readinto(self, b):
res = super().readinto(b)
self.read_history.append(res)
return res
class CMockFileIO( | MockFileIO, io.BytesIO):
pass
class PyMockFileIO(MockFileIO, pyio.BytesIO):
pass
class MockUnseekableIO:
def seekable(self):
return False
def seek(self, *args):
raise self.UnsupportedOperation("not seekable")
def tell(self, *args):
raise self.UnsupportedOperation("not se... |
thiagoss/transmageddon | src/which.py | Python | lgpl-2.1 | 13,269 | 0.002487 | #!/usr/bin/env python
# Copyright (c) 2002-2005 ActiveState Corp.
# See LICENSE.txt for license details.
# Author:
# Trent Mick (TrentM@ActiveState.com)
#
# Home:
# http://trentm.com/projects/which/
# http://code.google.com/p/which/
#
# Copyright (c) 2002-2005 ActiveState Corp.
#
# Permission is hereby granted, f... | registered = None
return registered
def _samefile(fname1, fname2):
if sys.platform.startswith('win'):
return ( os.path.normpath(os.path.normcase(fname1)) ==\
os.path.normpath(os.path.normcase(fname2)) )
else:
return os.path.samefile(fname1, fname2)
def _cull(potential, matches,... | rbose=0):
"""Cull inappropriate matches. Possible reasons:
- a duplicate of a previous match
- not a disk file
- not executable (non-Windows)
If 'potential' is approved it is returned and added to 'matches'.
Otherwise, None is returned.
"""
for match in matches: # don't yiel... |
ReactiveX/RxPY | reactivex/scheduler/mainloop/gtkscheduler.py | Python | mit | 4,394 | 0.000455 | from typing import Any, Optional, TypeVar, cast
from reactivex import abc, typing
from reactivex.disposable import (
CompositeDisposable,
Disposable,
SingleAssignmentDisposable,
)
from ..periodicscheduler import PeriodicScheduler
_TState = TypeVar("_TState")
class GtkScheduler(PeriodicScheduler):
"... | : typing.RelativeTime,
| action: typing.ScheduledPeriodicAction[_TState],
state: Optional[_TState] = None,
) -> abc.DisposableBase:
"""Schedules a periodic piece of work to be executed in the loop.
Args:
period: Period in seconds for running the work repeatedly.
action: Action to be ... |
cwahbong/onirim-py | tests/test_door.py | Python | mit | 2,159 | 0 | """
Tests for a door card.
"""
import pytest
from onirim import card
from onirim import component
from onirim import core
from onirim import agent
class DoorActor(agent.Actor):
"""
"""
def __init__(self, do_open):
self._do_open = do_open
def open_door(self, content, door_card):
retu... | undrawn_cards=[] | ,
hand=[card.key(card.Color.red)]),
component.Content(
undrawn_cards=[],
hand=[card.key(card.Color.red)],
limbo=[card.door(card.Color.red)]),
)
DRAWN_DO_OPEN = (
card.Color.red,
True,
component.Content(
undrawn_cards=[],
hand=[
card.key(ca... |
bcaine/maddux | maddux/examples/plot.py | Python | mit | 919 | 0.005441 | import numpy as np
from maddux.environment import Environment
from m | addux.objects import Ball, Target
from maddux.robots import simple_human_arm
def plot():
"""Generic plotting example given an environment with some
objects in it and a robot.
"""
# Create our arm
q0 = np.array([0.5, 0.2, 0, 0.5, 0, 0, 0])
human_arm = | simple_human_arm(2.0, 2.0, q0, np.array([2.0, 2.0, 0.0]))
# And our objects
ball = Ball(np.array([2.0, 0.0, 2.0]), 0.15)
target = Target(np.array([5.0, 8.0, 2.0]), 0.5)
env = Environment(dimensions=[10.0, 10.0, 10.0],
dynamic_objects=[ball],
static_object... |
adamrvfisher/TechnicalAnalysisLibrary | ChaikinMoneyFlowStrategy.py | Python | apache-2.0 | 1,949 | 0.015906 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 1 14:31:49 2017
@author: AmatVictoriaCuramIII
"""
import numpy as np
from pandas_datareader import data
import pandas as pd
ticker = '^GSPC'
window = 20
s = data.DataReader(ticker, 'yahoo', start='01/01/2000', end='01/01/2050')
s['LogRet'] = np.log(s['Adj Clo... | 37 threshold
s['Sustain'] = np.where(s['Sustain'].shift(1) == -1, -1,
s['Sustain'])
s['Sustain'] = np.where(s['CMF'] > 0.4, 0, s['Sustain']) #if RSI is greater than threshold, sustain is forced to 0
s['Sustain'] = np.where(s['CMF'] < -0.4, 0, s['Sustain']) #never actually true wh... | ].mean()-s['LogRet'].mean())/s['Strategy'].std()
s[['LogRet','Strategy']].cumsum().apply(np.exp).plot(grid=True,
figsize=(8,5))
Length = len(s['LogRet'])
Range = range(0,Length)
print(sharpe)
|
akvo/akvo-rsr | akvo/rsr/migrations/0057_auto_20160222_1015.py | Python | agpl-3.0 | 1,201 | 0.002498 | # -*- coding: utf-8 -*-
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('rsr', '0056_auto_20160219_1007'),
]
operations = [
migrations.AlterField(
model_name='iatiimport',
name='enabled',
field=models... | preserve_default=True,
),
migrations.AlterField(
model_name='iatiimport',
name='run_immediately',
field=models.BooleanField(default=False, help_text='Run the job immediately.', ve | rbose_name='run immediately'),
preserve_default=True,
),
]
|
UMWRG/pynsim | examples/trivial_demo/components/node.py | Python | gpl-3.0 | 2,510 | 0.007171 | # (c) Copyright 2014, University of Manchester
#
# This file is part of PyNSim.
#
# PyNSim 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 optio... | Get water requirements for this timestep based on my internal
requirements dictionary.
"""
self.demand = self._seasonal_water_req[timestamp]
class CitrusFarm(IrrigationNode):
_seasonal_water_req = {
"2014-01-01": 100,
"2014-02-01": 200,
"2014-03-01": 300,
... | ": 500,
}
class VegetableFarm(IrrigationNode):
_seasonal_water_req = {
"2014-01-01": 150,
"2014-02-01": 250,
"2014-03-01": 350,
"2014-04-01": 450,
"2014-05-01": 550,
}
class SurfaceReservoir(Node):
"""
Node from which all the other nodes get their water.... |
haad/ansible-modules-extras | storage/netapp/netapp_e_storage_system.py | Python | gpl-3.0 | 11,444 | 0.00402 | #!/usr/bin/python
# (c) 2016, NetApp, Inc
#
# 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.... | except:
err = get_exception()
| module.fail_json(msg="Error accessing storage-system with id [%s]. Error [%s]" % (ssid, str(err)))
array_exists = True
array_detail = resp
if rc == 200:
if state == 'absent':
changed = True
array_exists = False
elif state == 'present':
current_addre... |
hiteshagrawal/python | generator-decorator/decorator.py | Python | gpl-2.0 | 4,681 | 0.026276 | #!/usr/bin/python
"""
Since functions are function instances you can wrap them
Allow you to
- modify arguments
- modify function
- modify results
"""
call_count = 0
def count(func):
def wrapper(*args, **kw):
global call_count
call_count += 1
return func(*args, **kw)
return wrapper
def ... | ount() takes exactly 1 argument (0 given)
>>>
##Decorator Template
def decorator(func_to_decorate):
def wrapper(*args, **kwargs):
# do something before invocation
result = func_to_decorate(*args,**kwargs)
# do something after invocation
return result
#update wrapper.__doc__ and .func_name
# or functools.wr... |
return wrapper
##Decorators can also be classes, to have a class that Decorates
class decorator(object):
def __init__(self, function):
self.function = function
def __call__(self, *args, **kw):
# do something before invocation
result = self.function(*args, **kw)
# do something after
return result
##De... |
sio2project/oioioi | oioioi/suspendjudge/migrations/0001_initial.py | Python | gpl-3.0 | 760 | 0.002632 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contests', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='SuspendedProblem',
fields... | e_name='ID', serialize=False, auto_created=True, primary_key=True)),
('suspend_init_tests', models.BooleanField(default=True)),
('problem_instance', models.OneToOneField(related_name='suspended', to='contests.ProblemInstance', on_delete=models.CASCADE)),
],
option... | bases=(models.Model,),
),
]
|
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/test/tool_shed/functional/test_0120_simple_repository_dependency_multiple_owners.py | Python | gpl-3.0 | 8,820 | 0.019274 | from tool_shed.base.twilltestcase import ShedTwillTestCase, common, os
datatypes_repository_name = 'blast_datatypes_0120'
datatypes_repository_description = 'Galaxy applicable datatypes for BLAST'
datatypes_repository_long_description = 'Galaxy datatypes for the BLAST top hit descriptons tool'
tool_repository_name = '... | r_1_name,
| category_id=self.security.encode_id( category.id ),
strings_displayed=strings_displayed )
self.upload_file( repository,
filename='blast/blastxml_to_top_descr.tar',
filepath=None,
... |
Samathy/MinorityReport | get_percentages.py | Python | gpl-3.0 | 546 | 0.009158 | f = open("Sorted_Fi | les.csv")
j = open("File_Percentages.csv",'w')
lines = f.readlines()
lineCount = 0
percentages = []
print("How many months were there?")
total = input()
print(int(total))
for line in lines:
if lineCount == 0:
lineCount +=1
continue
num = line.split(",")[1]
fi = line.split(",")[0]
... | ercentages:
j.write(i[0]+","+i[1]+"\n")
f.close()
j.close()
|
GeoMop/PythonOCC_Examples | src/bspline_surface_pure.py | Python | gpl-2.0 | 5,550 | 0.001982 | """
Experiment with bezier surface and bspline surface
"""
from OCC.gp import *
from OCC.Geom import *
from OCC.TColGeom import *
from | OCC.TColgp import *
from OCC.TColStd import *
from OCC.GeomConvert import *
from OCC.BRepBuilderAPI import *
from OCC.TopoDS import *
from OCC.STEPControl import *
def bezier_surfaces(event=None):
"""
Create bezier surface, then create bspline surface from import
it and search, what is inside created bs... | 1))
array.SetValue(1, 2, gp_Pnt(2, 1, 2))
array.SetValue(1, 3, gp_Pnt(3, 1, 1))
array.SetValue(2, 1, gp_Pnt(1, 2, 1))
array.SetValue(2, 2, gp_Pnt(2, 2, 2))
array.SetValue(2, 3, gp_Pnt(3, 2, 0))
array.SetValue(3, 1, gp_Pnt(1, 3, 2))
array.SetValue(3, 2, gp_Pnt(2, 3, 1))
array.SetValue(3, ... |
uMag/nyaa | WSGI.py | Python | gpl-3.0 | 399 | 0.015038 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import gevent.monkey
gevent.monkey.patch_all()
from nyaa import app
if app.config["DEBUG"]:
from werkzeug.debug import DebuggedA | pplication
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
if __na | me__ == '__main__':
import gevent.pywsgi
gevent_server = gevent.pywsgi.WSGIServer(("localhost", 5000), app.wsgi_app)
gevent_server.serve_forever()
|
lvidarte/lai-client | tests/db/test_sqlite_database.py | Python | gpl-3.0 | 4,289 | 0.002098 | # Author: Leo Vidarte <http://nerdlabs.com.ar>
#
# This file is part of lai-client.
#
# lai-client is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# lai-client is distributed in the hope that it wi... | cs_count(), 1)
def test_get_doc_by_id(self):
new_doc = Document(sid=1, tid=2, data='sarlanga', users=['alfredo', 'maria'])
self.db.save(new_doc)
doc = self.db.get(1)
self.assertEqual(doc.data, 'sarlanga')
self.assertEqual(doc.sid, '1')
self.assertEqual(doc.tid, '2')
... | users, [u'alfredo', u'maria'])
def test_update(self):
new_doc = Document(data='1 2 3')
self.db.save(new_doc)
edit_doc = self.db.get(1)
edit_doc.data = '1 2 3 4'
self.db.save(edit_doc)
doc = self.db.get(1)
self.assertEqual(doc.data, '1 2 3 4')
def test_g... |
StellarCN/py-stellar-base | tests/operation/test_set_options.py | Python | apache-2.0 | 5,429 | 0.001658 | import pytest
from stellar_sdk import AuthorizationFlag, MuxedAccount, Operation, SetOptions, Signer
from stellar_sdk.utils import sha256
class TestSetOptions:
AUTHORIZATION_REQUIRED = 1
AUTHORIZATION_REVOCABLE = 2
AUTHORIZATION_IMMUTABLE = 4
AUTHORIZATION_CLAWBACK_ENABLED = 8
@pytest.mark.param... | assert from_instance.source is None
if clear_flags is not None:
assert isinstance(from_instance.clear_flags, AuthorizationFlag)
if set_flags is not None:
assert isinstance(from_instance.set_flags, AuthorizationFlag)
assert from_instance.clear_flags == clear_flags... | assert from_instance.set_flags == set_flags
assert from_instance.master_weight == master_weight
assert from_instance.low_threshold == low_threshold
assert from_instance.med_threshold == med_threshold
assert from_instance.high_threshold == high_threshold
assert from_instance.signe... |
pbokoc/pykickstart | tests/commands/displaymode.py | Python | gpl-2.0 | 2,251 | 0.000888 | # Andy Lindeberg <alindebe@redhat.com>
#
# Copyright 2009 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. This program is distributed in the hope that it
# will be use... | ied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PUR | POSE.
# 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, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat
# trademarks that are incorporate... |
anaumidis/SiMess | simess/server.py | Python | gpl-3.0 | 5,206 | 0.001153 | import socket
from time import gmtime, strftime
from simess.assets import server_strings
class SiMessServer():
def __init__(self, host="127.0.0.1", port=5000, buffer_size=4096, waiting_list=10):
self.host, self.port = host, port
self.buffer_size = buffer_size
self.waiting_list = waiting_... | )
def event_print(self, sock, event, nick, peer, timestamp):
print(server_strings.server_events_str["Server Event Print"].format(
event, nick, peer[0], peer[1], strftime("%d-%b-%Y %I:%M:%S %p", timestamp)
))
def event_share(self, sock, event, nick, peer, timestamp):
data ... | trings.server_events_str["Server Event Share"].format(
nick, peer[0], peer[1], event, strftime("%I:%M:%S %p", timestamp)
)).encode()
self.data_broadcast(sock, data)
def client_functions(self, func, sock):
functions = dict()
f = functions.get(func)
if f == "":... |
hayashizakitakaaki/Introduction_mysite | dailyreport/apps.py | Python | mit | 121 | 0 | # -*- coding: utf-8 -*-
from django.apps import A | ppConfig
class DailyReportConfig(AppConfig | ):
name = 'dailyreport'
|
troolee/quickbooks-python | quickbooks/__init__.py | Python | mit | 205 | 0 | # -*- coding: utf-8 -*-
#
# Author: Pavel Reznikov <pashka.reznikov@gmail.com>
# Created: 14-10-15
#
# Id: $Id$ |
from quickbooks import *
from massage import *
from reference import *
from report | import *
|
rainier-m/python-soccer | parseBBC-Leagues.py | Python | gpl-2.0 | 6,099 | 0.007706 | # -*- coding: utf-8 -*-
'''
Created on Jul 04, 2016
Modified on Aug 05, 2016
Version 0.01.b
@author: rainier.madruga@gmail.com
A simple Python Program to scrape the ESPN FC website for content.
### =========================================================================================== ###
### Change & Revision Log ... | elif inputMonth == 'Jul':
outputMonth = '07'
else:
print ('EXCEPTION: Invalid Month sent to Function.')
outputMonth = '99'
return outputMonth
# Parse out Fixtures
def parseFixtures(leagueLink):
leagueParse = base + leagueLink + '/fixtures'
if ((leagueParse != 'http://www.bbc.c... | se != 'http://www.bbc.com/sport/football/africa-cup-of-nations/fixtures')):
# Parse out URLs for each leagues' fixtures
getLeagueParse = requests.get(leagueParse)
getLeagueParse.raise_for_status()
parseSoup = BeautifulSoup(getLeagueParse.text, "html.parser")
parseContent = parseS... |
tuomas2/automate-wsgi | automate_wsgi/abstractwsgi.py | Python | gpl-3.0 | 4,163 | 0.001922 | # -*- coding: utf-8 -*-
# (c) 2015 Tuomas Airaksinen
#
# This file is part of automate-wsgi.
#
# automate-wsgi 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 opt... | tractUserService
class TornadoService(AbstractUserService):
"""
Abstract service that provides HTTP server for WSGI applications.
"""
#: Which ip address to listen. Use ``0.0.0.0`` (default) to listen to all local networking interfaces.
http_ipaddr = CStr("0.0.0.0")
#: HTTP (or HTTPS if u | sing SSL) port to listen
http_port = Int(3000)
#: Path to ssl certificate file. If set, SSL will be used.
#:
#: .. tip::
#:
#: You may use script scripts/generate_selfsigned_certificate.sh to generate a
#: self-signed openssl certificate.
ssl_certificate = CStr
#: Path to ssl p... |
jawilson/home-assistant | homeassistant/components/brother/__init__.py | Python | apache-2.0 | 2,597 | 0.001155 | """The Brother component."""
from __future__ import annotations
from datetime import timedelta
import logging
from brother import Brother, DictToObj, SnmpError, UnsupportedModel
import pysnmp.hlapi.asyncio as SnmpEngine
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, C... | ault(DATA_CONFIG_ENTRY, {})
hass.data[DOMAIN][DATA_CONFIG_ENTRY][entry.entry_id] = coordinator
hass.data[DOMAIN][SNMP] = snmp_engine
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> | bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN][DATA_CONFIG_ENTRY].pop(entry.entry_id)
if not hass.data[DOMAIN][DATA_CONFIG_ENTRY]:
hass.data[DOMAIN].pop(SNMP)
hass.dat... |
pombredanne/djangorestframework_extensions | djangorestframework_extensions/mixins.py | Python | bsd-2-clause | 1,649 | 0.000606 | from djangorestframework.mixins import ModelMixin | , CreateModelMixin, \
UpdateModelMixin
from djangorestframework_extensions.utils import user_pa | sses_test
__all__ = ['RoleBasedExclusion', 'RestrictedModelMixin',
'RestrictedCreateModelMixin', 'RestrictedUpdateModelMixin']
class RoleBasedExclusion(object):
def role_based_exclusion(self):
exclude = self.exclude
if not isinstance(exclude, dict):
return exclude or ()
... |
Levis0045/MetaLex | metalex/ocrtext/normalizeText.py | Python | agpl-3.0 | 11,920 | 0.010746 | #! usr/bin/env python
# coding: utf8
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
"""
metalex is general tool for lexicographic and metalexicographic activities
Copyright (C) 2017 by Elvis MBONING
This program is free software: you ... | : Correct OCR data',
attrs=['bold']), '--'*20))
debut = time.time()
filerule = FileRule(self.file_rules, typ='rule_wc')
self.data_rules = filerule.file_rule_unpack()
dfil | erule = time.time() - debut
if self.log: print("--> %30s: %10.5f seconds\n"
%("Durée d'extraction du fichier des règles", dfilerule))
def extract_correct(self, html):
"""Composed and saved all treatment processes to enhance quality of HTML articles
... |
openstack/python-ironicclient | ironicclient/tests/unit/common/test_utils.py | Python | apache-2.0 | 17,248 | 0 | # Copyright 2013 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | _ke | y_value_pairs_to_dict(self):
kv_list = ['str=foo', 'int=1', 'bool=true',
'list=[1, 2, 3]', 'dict={"foo": "bar"}']
d = utils.key_value_pairs_to_dict(kv_list)
self.assertEqual(
{'str': 'foo', 'int': 1, 'bool': True,
'list': [1, 2, 3], 'dict': {'foo': 'b... |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/python/kernel_tests/dynamic_partition_op_test.py | Python | apache-2.0 | 6,138 | 0.00668 | # 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... | outputs_grad = [7 * output for output in outputs_val]
grads = gradients_impl.gradients(outputs, [data_t, partitions_t],
output | s_grad)
self.assertEqual(grads[1], None) # Partitions has no gradients
self.assertAllEqual(7 * data, sess.run(grads[0]))
def testErrorIndexOutOfRange(self):
with self.test_session() as sess:
data = constant_op.constant([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11],
... |
CanonicalLtd/landscape-client | landscape/client/manager/scriptexecution.py | Python | gpl-2.0 | 14,754 | 0 | """
Functionality for running arbitrary shell scripts.
@var ALL_USERS: A token indicating all users should be allowed.
"""
import os
import sys
import os.path
import tempfile
import shutil
from twisted.internet.protocol import ProcessProtocol
from twisted.internet.defer import (
Deferred, fail, inlineCallbacks, r... | content
# It would be nice to use fchown(2) and fchmod(2), but they're not
# available in python and using it with ctypes is pretty tedious, not
# to mention we can't get errno.
os.chmod(filename, 0o700)
if uid is not None:
os.chown(filename, uid, gid)
script... | t = script.encode("utf-8")
script_file.write(script)
script_file.close()
def _run_script(self, filename, uid, gid, path, env, time_limit):
if uid == os.getuid():
uid = None
if gid == os.getgid():
gid = None
env = {
key: (
... |
Islandman93/reinforcepy | reinforcepy/handlers/__init__.py | Python | gpl-3.0 | 127 | 0 | from .parameters import Parameters
fro | m .framebuffer import FrameBuffer
from . | actionhandler import ActionHandler, ActionPolicy
|
miltonsarria/dsp-python | dsp2018/images/example2.py | Python | mit | 250 | 0.02 | import cv2
import numpy as np
import matplotlib | .pyplot as plt
img = cv2.imread('bookpage.jpg')
_, threshold = cv2.threshold(img, 5, 255, cv2.THRESH_BINARY)
plt.subplot(2,1,1)
plt.imshow(img)
plt.subplot(2, | 1,2)
plt.imshow(threshold)
plt.show()
#
|
ulisespereira/LearningSequences | fixedConnectivity/popModel/sequences_random.py | Python | gpl-2.0 | 4,644 | 0.060293 | import numpy as np
from scipy import sparse
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math as mt
# this is the transfer function
def phi(x,theta,uc):
myphi=nu*(x-theta)
myphi[x>uc]=nu*(uc-theta)
myphi[theta>x]=0.
return myphi
def phi_brunel(x,theta,uc):
myphi=nu_brunel*((x-theta... | nes(n/k) for i in range(k)])
diagonals=[mywmax,mysdel]
vuelta=np.zeros((n,n))
vuelta[0,-1]=0.1
return np.diag(diagonals[0],0)+np.diag(diagonals[1],-1)-w_inh*nu*np.ones((n,n))#+vuelta
#fields approximations
def field_tanh(x,t):
return net(wmax,sdel,n,k).dot(phi_tanh(x))-x-w_inh*np.dot(r1_matrix,phi_tanh(x))
def f... | theta,uc))-x-w_inh*np.dot(r1_matrix,phi_brunel(x,theta,uc))
#field true
def field_true_tanh(x,t):
n=len(x)
thefield=np.zeros(n)
thefield[0:n-1]=net(wmax,sdel,n-1,k).dot(phi_tanh(x[0:n-1]))-x[0:n-1]-w_inh*x[-1]*np.ones(n-1)
thefield[-1]=2.*(-x[-1]+np.ones(n-1).dot(phi_tanh(x[0:n-1])))
return thefield
def field_tr... |
juju-blender/roadrunner | roadrunner/core.py | Python | apache-2.0 | 5,171 | 0 | import exception
import logging
import os
import shlex
import subprocess
import time
import yaml
LOG = logging.getLogger('roadrunner.core')
class DefinitionSet(object):
"Set of definitions"
log = logging.getLogger('roadrunner.core.DefinitionSet')
def __init__(self, fpath):
self.dry_run = False... | al(self):
cmd = ['juju', 'upgrade-juju', '- | -version',
str(self.body['juju-upgrade']['version'])]
p = Process(cmd, dry_run=self.dry_run)
p.monitor()
assert p.returncode == 0
def add_juju_repo(self, version):
p = Process(['sudo', 'add-apt-repository', '-y',
'ppa:freyes/juju-%s' % version],... |
hkhamm/proj5-mongo | main.py | Python | artistic-2.0 | 4,383 | 0.001825 | """
Simple web-based list of dated memos kept in a MongoDB database accessed
with Flask.
@author H. Keith Hamm
@date: Fall 2015
"""
import flask
from flask import render_template
from flask import request
from flask import url_for
import json
import logging
import uuid
import CONFIG
import sys
# Date handling
im... | date = arrow.get(request.args.get('date', 0, type=str),
'YYYY/MM/DD').naive
text = request.args.get('text', 0, type=str)
record = {"type": "dated_memo",
"date": date,
"text": text}
result = collection.insert_one(record)
record... | worked = True
except:
message = 'Memo not added.'
record_id = ''
worked = False
return flask.jsonify(message=message, record_id=record_id, result=worked)
@app.route("/_remove_memo")
def remove_memo():
"""
Delete a memo from the database.
"""
try:
object_... |
pistruiatul/hartapoliticii | python/src/ro/vivi/news_parser/rss_parse_mediafax.py | Python | agpl-3.0 | 4,249 | 0.010355 | '''
Created on Sep 24, 2009
Parse the RSS feed from mediafax, gets the links from it and then fetches the
pages with the news.
The code:
- gets the rss feed from mediafax. That contains about the past 10 days.
- gets out the links and fetches the news content.
- saves the meta information plus the real content ... | '/daily_%04d%02d%02d.txt' % (d.year, d.month, d.day)
timedelta = now - d
if timedelta.days < NUM_DAYS_REWRITE:
if fname in open_files:
f = open(fname, 'a')
else:
f = open(fname, 'w')
f.write("<all>\n")
open_files.append(fname)
# 16 17 18 09 2009
news_time = '%02d %02d %02d ... | ur, d.minute, d.day, d.month, d.year)
f.write("<item>\n")
f.write(" <news_link>" + link + "</news_link>\n")
f.write(" <news_title>" + urllib.quote(title) + "</news_title>\n")
f.write(" <news_place></news_place>\n")
f.write(" <news_time>" + news_time + "</news_time>\n")
f.write(" <news_content>"... |
ybenitezf/nstock | models/plugin_package.py | Python | mit | 1,991 | 0.000502 | # -*- coding: utf-8 -*-
from plugin_package.content_package import ContentPackage
from gluon.tools import PluginManager
from plugin_ckeditor import CKEditor
if False:
from gluon import current
from gluon import Field
response = current.response
request = current.request
T = current.T
from db i... | tor(db=db)
tbl = db.define_table(
'plugin_package_content',
Field('item_list', 'list:string'),
Field('description', 'text'),
Field('item_id', 'string', length=64),
auth.signature, |
)
tbl.item_id.writable = False
tbl.item_id.readable = False
tbl.item_list.writable = False
tbl.item_list.readable = False
tbl.description.label = T('Description')
tbl.description.widget = editor.widget
tbl._enable_record_ve... |
orpinchasov/pycaer | pycaer/dvs128/process_packets.py | Python | gpl-3.0 | 731 | 0.008208 | """ Module for unpacking of events data. Handles bits
in order to increase processing speed to maximum.
"""
import struct
VALID_MARK_SHIFT = 0
VALID_MARK_MASK = 0x00000001
POLARITY_SHIFT = 1
POLARITY_MASK = 0x00000001
Y_ADDR_SHIFT = 2
Y_ADDR_MASK = 0x00007FFF
X_ADDR_SHIFT = 17
X_ADDR_MASK = 0x00007FFF
def _get_pola... | _data(data, VALID_ | MARK_SHIFT, VALID_MARK_MASK), \
_get_polarity_event_data(data, POLARITY_SHIFT, POLARITY_MASK), \
_get_polarity_event_data(data, Y_ADDR_SHIFT, Y_ADDR_MASK), \
_get_polarity_event_data(data, X_ADDR_SHIFT, X_ADDR_MASK))
|
ryanjulian/gail-tf | gailtf/baselines/trpo_mpi/run_mujoco.py | Python | mit | 2,970 | 0.008754 | #!/usr/bin/env python
# noinspection PyUnresolvedReferences
import mujoco_py # Mujoco must come before other imports. https://openai.slack.com/archives/C1H6P3R7B/p1492828680631850
from mpi4py import MPI
from gailtf.baselines.common import set_global_seeds
im | port os.path as osp
import gym
import logging
from gailtf.baselines import logger
from gailtf.baselines.ppo1.mlp_policy import MlpPo | licy
from gailtf.baselines.common.mpi_fork import mpi_fork
from gailtf.baselines import bench
from gailtf.baselines.trpo_mpi import trpo_mpi
def train(args):
import gailtf.baselines.common.tf_util as U
sess = U.single_threaded_session()
sess.__enter__()
rank = MPI.COMM_WORLD.Get_rank()
if rank != ... |
gkabbe/Python-Kurs2015 | Lösungen/Woche2/deutsch_englisch_dict.py | Python | gpl-2.0 | 279 | 0.010753 | #!/usr/bi | n/python
#encoding=utf-8
englisch_deutsch_dict = {"hello": "hallo", "world": "welt", "good bye": "auf wiedersehen"}
deutsch_englisch_dict = dict()
for key, value in englisch_deutsch_dict.items():
deutsch_englisch_dict[value] = key
print deutsch_englisch_dic | t
|
mfraezz/osf.io | website/prereg/views.py | Python | apache-2.0 | 508 | 0.003937 | """Back-end code to support the OSF Preregistration campaign
Keeping the code together in this file should make it easier to remove the
features added to the OSF specifically to support this initiative in the future.
Other resources that are | a part of the OSF Preregi | stration:
* website/static/js/pages/reg-landing-page.js
"""
from website.registries import views
def prereg_landing_page(**kwargs):
"""Landing page for osf prereg"""
return views._view_registries_landing_page('prereg', **kwargs)
|
citrix-openstack/build-ryu | ryu/tests/unit/ofproto/test_ofproto.py | Python | apache-2.0 | 2,429 | 0 | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 Isaku Yamahata <yamahata at private email ne jp>
#
# 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
#
# h... | proto(self):
# When new version of OFP support is added,
# this test must be updated.
import ryu.ofproto
reload(ryu.ofproto)
ofp_mod | ules = ryu.ofproto.get_ofp_modules()
import ryu.ofproto.ofproto_v1_0
import ryu.ofproto.ofproto_v1_2
import ryu.ofproto.ofproto_v1_3
eq_(set(ofp_modules.keys()), set([ryu.ofproto.ofproto_v1_0.OFP_VERSION,
ryu.ofproto.ofproto_v1_2.OFP_VERSION,
... |
seankelly/buildbot | master/buildbot/db/model.py | Python | gpl-2.0 | 38,375 | 0.000287 | # 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... | se, server_default='0'),
)
# logs
logs = sautils.Table(
'logs', metadata,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('name', sa.Text, nullable=False),
sa.Column('slug', sa.String(50) | , nullable=False),
sa.Column('stepid', sa.Integer,
sa.ForeignKey('steps.id', ondelete='CASCADE')),
sa.Column('complete', sa.SmallInteger, nullable=False),
sa.Column('num_lines', sa.Integer, nullable=False),
# 's' = stdio, 't' = text, 'h' = html, 'd' = deleted
sa... |
evilynux/fofix | setup.py | Python | gpl-2.0 | 17,079 | 0.00281 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*- #
#####################################################################
# #
# Frets on Fire X #
# Copyright (C) 20... | ound')
sys.stderr.write('Could not find re | quired program "%s".\n' % cmd)
if os.name == 'nt':
sys.stderr.write('(Check that you have the latest version of the dependency pack installed.)\n')
sys.exit(1)
print(path)
return path
# Find pkg-conf |
cpcloud/luigi | luigi/contrib/ftp.py | Python | apache-2.0 | 6,802 | 0.002058 | """
This library is a wrapper of ftplib. It is convenient to move data from/to FTP.
There is an example on how to use it (example/ftp_experiment_outputs.py)
You can also find unittest for each class.
Be aware that normal ftp do not provide secure communication.
"""
import os
import random
import ftplib
import luigi
... | folder = os.path.dirname(normpath)
# create paths if do not exists
for subfolder in folder.split(os.sep):
if subfolder and not subfolder in self.ftp | con.nlst():
self.ftpcon.mkd(subfolder)
self.ftpcon.cwd(subfolder)
# go back to ftp root folder
self.ftpcon.cwd("/")
# random file name
tmp_path = folder + os.sep + 'luigi-tmp-%09d' % random.randrange(0, 1e10)
self.ftpcon.storbinary('STOR %s' % tmp_... |
JustinWingChungHui/electionleaflets | electionleaflets/apps/core/context_processors.py | Python | mit | 467 | 0.002141 |
def settings(request) | :
"""
Add settings (or some) to the templates
"""
from django.conf import settings
tags = | {}
tags['GOOGLE_MAPS_KEY'] = settings.GOOGLE_MAPS_KEY
tags['GOOGLE_ANALYTICS_ENABLED'] = getattr(settings, 'GOOGLE_ANALYTICS_ENABLED', True)
tags['MAP_PROVIDER'] = settings.MAP_PROVIDER
if hasattr(settings, 'GOOGLE_ANALYTICS_KEY'):
tags['GOOGLE_ANALYTICS_KEY'] = settings.GOOGLE_ANALYTICS_KEY
... |
leanix/leanix-sdk-python | src/leanix/models/ServiceHasResource.py | Python | mit | 2,033 | 0.006394 | #!/usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2017 LeanIX GmbH
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,... | ER 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.
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
"""
| class ServiceHasResource:
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
self.swaggerTypes = {
'ID': 'str',
'resourceID': 'str',
'serviceID': 'str',
'commen... |
nielsbuwen/ilastik | ilastik/applets/objectClassification/objectClassificationDataExportGui.py | Python | gpl-3.0 | 7,930 | 0.012484 | ###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# mod... |
colors.append( QColor(255, 105, 180) ) #hot pink
colors.append( QColor(102, 205, 170) ) #dark aquamarine
colors.append( QColor(165, 42, 42) ) #brown
colors.append( QColor(0, 0, 128) ) #navy
colors.append( QColor(255, 165, 0) ) #orange
colors.append( QCol | or(173, 255, 47) ) #green-yellow
colors.append( QColor(128,0, 128) ) #purple
colors.append( QColor(240, 230, 140) ) #khaki
# colors.append( QColor(192, 192, 192) ) #silver
# colors.append( QColor(69, 69, 69) ) # dark grey
# colors.append( QColor( Qt.cyan ) )
assert len(colors) == 16
r... |
khushboo9293/Hyperkitty | hyperkitty/tests/views/test_accounts.py | Python | gpl-3.0 | 11,941 | 0.002512 | # -*- coding: utf-8 -*-
# Copyright (C) 1998-2012 by the Free Software Foundation, Inc.
#
# This file is part of HyperKitty.
#
# HyperKitty 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 t... | self.assertEqual(response.status_code, 200)
response = self.client.post(reverse("hk_user_registration"),
{"email": "newtestuser@example.com",
"password1": "test", "password2": "test"})
self.assertRedirects(response, reverse('hk_root'))
response = self.client.get(reve | rse('hk_root'))
self.assertContains(response, "newtestuser@example.com")
def test_votes(self):
self.client.login(username='testuser', password='testPass')
#User.objects.create(user=self.user, mailman_id=str(uuid.uuid1()))
## use a temp variable below because self.client.session is a... |
waterwoodwind/influxDB_web | main_web/views.py | Python | mit | 1,205 | 0.005809 | # coding:utf-8
# Create your views here.
from django.shortcuts import render
from django.http import HttpResponse
from arrow_time import today_date_for_influxd_sql
from arrow_time import ten_day_ago_for_influxd_sql
from influxdb_function import influxDB_interface
from aircraft_config import AC_WQAR_CONFIG
import json
... | index", "*", "index", where_str)
if sector_index <> {}:
df = s | ector_index['index']
result_json = df.to_json(orient="records")
return render(request, 'home.html', {'result_json': result_json,
'all_ac':all_aircraft_list})
else:
return render(request, 'home.html', {'result_json': {},
... |
aroberge/qt_py | pyqt_examples/integer_input_dialog1.py | Python | mit | 1,188 | 0.004209 | '''Simple integer input dialog'''
from PyQt4 import QtGui, QtCore
def integer_input(message="Choose a number", title="Title",
default_value=1, min_=0, max_=100, step=1):
"""Simple dialog to ask a user to select a number within a certain range
"""
app = QtGui.QApplication([])
flags = ... | guess = integer_input(message=message, title=title,
| default_value=guess, min_=min_ ,max_=max_)
if guess < answer:
title = "Too low"
min_ = guess
elif guess > answer:
title = "Too high"
max_ = guess
print("You got it! {} was the answer".format(guess))
|
honza/nigel | matchers/__init__.py | Python | bsd-2-clause | 453 | 0 | from brb import BrbMatcher
from greeter import GreetingMatcher
from sifter import SifterMatcher
from googleplus import ArthurGooglePlusMatcher
from gifter import GifterMatcher
from sandwich import Sand | wichMatcher
from cletus import CletusMatcher
from jenkins import JenkinsMatcher
from volunteer import VolunteerMatcher
from lunch import LunchMatcher
from timezones import Timezon | eMatcher
from points import PointsMatcher
from silly import SillyMatcher
|
alexisvincent/downy | app.py | Python | apache-2.0 | 2,858 | 0.005598 | #!/usr/bin/python2.5
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | eRobotApp(object):
"""WSGI application for serving an abstract robot.
This is just like the Robot class in the Wave api, but it uses the plain WebOb
request/response objects instead of the analogous AppEngine objects.
"""
def __init__(self, robot):
self._robot = robot
def capabilities(self):
xml ... | ponse
def profile(self):
xml = self._robot.GetProfileJson()
response = webob.Response(content_type='application/json', body=xml)
response.cache_control = 'Private' # XXX
return response
def jsonrpc(self, req):
json_body = req.body
logging.info('Incoming: %s', json_body)
context, even... |
staudt/python-template | app/start.py | Python | mit | 172 | 0.005814 | # -*- c | oding: utf-8 -*-
# pep8: disable-msg=E501
# pylint: disable=C0301
from app import __version__, log
import argparse
def main():
log.info("app v" + __version__) | |
ravenac95/virtstrap | virtstrap-local/tests/test_runner.py | Python | mit | 217 | 0.004608 | import sys
import os
import fudge
from virtstrap_local.runner | import VirtstrapProjectLocalR | unner
def test_runner_runs_commands_command():
runner = VirtstrapProjectLocalRunner()
runner.main(args=['commands'])
|
seungwonpark/SNU_physics_board_rss | update_general.py | Python | mit | 1,781 | 0.025828 | # import libraries
import urllib.request
from feedgen.feed import FeedGenerator
from post_parser import post_title, post_author, post_time, post_files_num
from misc import is_number
# info
baseurl = 'http://phya.snu.ac.kr/xe/underbbs/'
url ='http://phya.snu.ac.kr/xe/index.php?mid=underbbs&category=372' # notices + gen... | _notices = f.read().split(',')
f.close()
g = open('srl_general.txt','r')
num_general = g.read().split(',')
g.close()
g = open('srl_general.txt','a')
response = urllib.request.urlopen(url)
data = response.read()
text = data.decode('utf-8')
count_new = 0
srl_arr_general = []
text_splitted = text.split('document_srl=... | ot in srl_arr_general): # second statement : to prevent duplication
srl_arr_general.append(srl)
if(srl not in num_general):
count_new += 1
g.write(',' + srl)
print('New post found : ' + srl)
g.close()
if(count_new != 0):
print('Started generating feed...')
# make FeedGenerator
fg = FeedGenerator(... |
Uladox/ClusterMass | PYSTARS.py | Python | gpl-2.0 | 1,968 | 0.017785 | #This file is part of ClusterMass
#
# Copyright 2014 Uladox
#
# ClusterMass 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.... | ('X')
#plt.ylabel('Y')
#plt.title('Velocities')
#print(smallestnum)
#print(largestnum)
# xmin xmax ymin ymax
#plt.axis([smallestnum - 100, largestnum + 100, 0, | 0.0012])
#plt.show()
#print(linenum)
#print("largestnum: ")
#print(largestnum)
#print(" smallestnum: ")
#print(smallestnum)
|
Oisota/Breakout | breakout/tests/test_asset.py | Python | gpl-3.0 | 994 | 0.001006 | from unittest import TestCase
import pygame
from ..config import BRICK_IMAGES, START_LEVEL, BLIP
from .. import asset
class TestAsset(TestCase):
def setUp(self):
pygame.init()
def test_load_image(self):
img = asset.load_image(BRICK_IMAGES['red'])
self.assertTrue(False)
def test... | self.assertTrue(False)
def test_load_level(self):
level = asset.load_level(START_LEVEL)
self.assertIn('name', level)
self.assertIn('ball_speed', level)
self.assertIn('next', level)
self.assertIn('bricks', level)
self.assertEqual(10, len(level['bricks']))
for... | self.assertIn(color, BRICK_IMAGES)
def test_save_level(self):
self.assertTrue(False)
def tearDown(self):
pygame.quit()
|
CooperLuan/sasoup | sasoup/escape.py | Python | mit | 1,570 | 0.001911 | # encoding: utf8
"""
copy from tornado.escape.xhtml_unescape
"""
import re
import htmlentitydefs
if type('') is not type(b''):
def u(s):
return s
bytes_type = bytes
unicode_type = str
basestring_type = str
else:
def u(s):
return s.decode('unicode_escape')
bytes_type = str
un... | returned
unchanged. Otherwise it must be a byte string and is decoded as utf8.
"""
if isinstance(value, _TO_UNICODE_TYPES):
return value
if not isinstance(value, bytes_type):
raise TypeError(
"Expected bytes, unicode, or None; got %r" % type(value)
)
return valu... | ml_unescape(value):
"""Un-escapes an XML-escaped string."""
return re.sub(r"&(#?)(\w+?);", _convert_entity, _unicode(value))
|
dewaka/python-koans | python3/koans/about_inheritance.py | Python | mit | 2,719 | 0.001471 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutInheritance(Koan):
class Dog:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
def bark(self):
return "WOOF"
class Ch... | ------------------------------------------------
class Pug(Dog):
def __init__(self, name):
pass
class Greyhound(Dog):
def __init__(self, name):
super().__init__(na | me)
def test_base_init_does_not_get_called_automatically(self):
snoopy = self.Pug("Snoopy")
with self.assertRaises(AttributeError): name = snoopy.name
def test_base_init_has_to_be_called_explicitly(self):
boxer = self.Greyhound("Boxer")
self.assertEqual("Boxer", boxer.name)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.