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 |
|---|---|---|---|---|---|---|---|---|
mkermani144/sudo-make-me-a-sandwitch | trending-repos.py | Python | mit | 1,796 | 0 | '''
This script opens top today's trending github repos in your browser
if you have not previously visited them.
Repos are selected based on https://github.com/trending.
'''
import requests
import bs4
import webbrowser
import os
from optparse import OptionParser
parser = OptionParser('usage: trending-repos [options]')... | add_option(
'-n', | '--number-of-repos',
dest='num_of_repos',
default='6',
type='int',
help='set number of trending repos to be opened in the browser')
parser.add_option(
'-f', '--force',
action='store_true',
dest='is_forced',
help='open all of trending repos, including previously-visited ones.'
)
options,... |
antoinecarme/pyaf | tests/model_control/detailed/transf_None/model_control_one_enabled_None_ConstantTrend_Seasonal_WeekOfYear_SVR.py | Python | bsd-3-clause | 161 | 0.049689 | import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['None' | ] , ['ConstantTrend'] | , ['Seasonal_WeekOfYear'] , ['SVR'] ); |
milanjelisavcic/milanbot | milanbot/__init__.py | Python | unlicense | 743 | 0 | import json
# T | ransliteration map from Cyrillic to Latin script
with open('mi | lanbot/transliteration.json') as json_file:
cyrillic_transliteration = json.load(json_file)
# Supported languages that 'MilanBot' works with
with open('milanbot/languages.json') as json_file:
languages = json.load(json_file)
sparql_disambiguation = \
'SELECT ?item WHERE {?item wdt:P31 wd:Q4167410 }'
sparq... |
nguyenla/Spelling | Game3Controller.py | Python | gpl-2.0 | 7,003 | 0.008282 | #!/usr/bin/env python
import os
from Game3View import Game3View
from HomeView import HomeView
import HomeController
import sys
from gi.repository import Gtk
from gi.repository import Gdk
from random import randint
from random import shuffle
class Game3Controller:
def __init__(self, view, parent):
self.vie... | self.view.resultLabel.set_markup("<span size='10000'><b>INCORRECT! " + str(self.numGuesses) + " left.</b></span>")
| self.numGuesses -= 1
#the player answered enough correctly to move on.
if len(self.definitions) <= 5:
self.level += 1
self.totalScore +=10
self.endLevel()
#hides the variables to display the results from the level
def endLevel(self):
self.vie... |
Edraak/edx-platform | lms/envs/aws.py | Python | agpl-3.0 | 36,831 | 0.004236 | # -*- coding: utf-8 -*-
"""
This is the default template for our main set of AWS servers. This does NOT
cover the content machines, which use content.py
Common traits:
* Use memcached, and cache-backed sessions
* Use a MySQL 5.1 database
"""
# We intentionally define lots of variables that aren't used, and
# want to ... | URL)
# Hardcode to the Arabic name, even in English layout, check the previous commits to see other failed scripts
PLATFORM_NAME = u'إدراك'
# Fo | r displaying on the receipt. At Stanford PLATFORM_NAME != MERCHANT_NAME, but PLATFORM_NAME is a fine default
PLATFORM_TWITTER_ACCOUNT = ENV_TOKENS.get('PLATFORM_TWITTER_ACCOUNT', PLATFORM_TWITTER_ACCOUNT)
PLATFORM_FACEBOOK_ACCOUNT = ENV_TOKENS.get('PLATFORM_FACEBOOK_ACCOUNT', PLATFORM_FACEBOOK_ACCOUNT)
SOCIAL_SHARING_... |
ecino/compassion-modules | intervention_compassion/models/compassion_intervention.py | Python | agpl-3.0 | 31,310 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | ("Level 2", _("Level 2")),
("Level 3", _("Level 3")),
], required=True, readonly=True, states={
| 'on_hold': [('readonly', False)],
'sla': [('readonly', False)],
})
hold_amount = fields.Float(readonly=True, states={
'on_hold': [('readonly', False)],
'sla': [('readonly', False)],
}, track_visibility='onchange')
expiration_date = fields.Date(readonly=True, states={
'on_... |
dufferzafar/critiquebrainz | critiquebrainz/frontend/profile/applications/forms.py | Python | gpl-2.0 | 1,318 | 0.00607 | from flask_wtf import Form
from flask_babel import gettext
from wtforms import StringField, validators
class ApplicationForm(Form):
name = StringField(gettext('Application name'), [
validators.DataRequired(message=gettext("Application name field is empty.")),
validators.Length(min=3, message=gette... | on name needs to be at least 3 characters long.")),
validators.Length(max=64, message=gettext("Application name needs to be at most 64 characters long."))])
desc = StringField(gettext('Description'), [
validators.DataRequired(message=gettext("Client description field is empty.")),
validators... | aracters long.")),
validators.Length(max=512, message=gettext("Client description needs to be at most 512 characters long."))])
website = StringField(gettext('Homepage'), [
validators.DataRequired(message=gettext("Homepage field is empty.")),
validators.URL(message=gettext("Homepage is not a... |
SebastiaanPasterkamp/dnd-machine | app/views/monster.py | Python | gpl-3.0 | 2,730 | 0.001465 | # -*- coding: utf-8 -*-
from flask import request, abort
from views.baseapi import BaseApiBlueprint, BaseApiCallback
class MonsterBlueprint(BaseApiBlueprint):
@property
def datamapper(self):
return self.basemapper.monster
@property
def campaignmapper(self):
return self.basemapper.camp... | js[:] = [
obj
for obj in objs
if obj.user_id == request.user.id \
| or obj.campaign_id in campaign_ids
]
@BaseApiCallback('api_copy.original')
@BaseApiCallback('api_get.object')
def adminOrGenericSingle(self, obj):
if self.checkRole(['admin']):
return
campaign_ids = self.get_allowed_campaign_ids(
request.user.id
... |
damdam-s/account-financial-tools | account_move_line_search_extension/__init__.py | Python | agpl-3.0 | 1,056 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open | Source Management Solution
#
# Copyright (c) 2013-2015 Noviat nv/sa (www.noviat.com).
| #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that... |
xuanthuong/golfgame | models/hole.py | Python | mit | 1,532 | 0.013055 | # -*- coding: utf-8 -*-
# Description: gmf_hole table
# By Thuong.Tran
# Date: 31 Aug 2017
from sqlalchemy import create_engine, Table, Column, MetaData, Integer, Text, DateTime, Float
from sqlalchemy import select
class hole():
def __init__(self, db_url):
_engine = create_engine(db_url)
_connection = _en... | Column("HOLE_DT", DateTime),
Column("WK_DY", Text),
Column("GRP_ | TP", Text),
Column("WRKR_1_ID", Integer),
Column("WRKR_2_ID", Integer),
Column("SCRE_NO", Float))
_metadata.create_all(_engine)
self.connection = _connection
self.gmf_hole = _gmf_hole
pass
def insert_to(self, data):
i... |
PaulWay/insights-core | insights/parsers/messages.py | Python | apache-2.0 | 3,079 | 0.001949 | """
Messages - file ``/var/log/messages``
=====================================
Reads the ``/var/log/messages`` file as a standard LogFileOutput class parser.
The important function is ``get(s)``, which finds all lines with the string
**s** and parses them into dictionaries with the following keys:
* ``timestamp`` -... | e': msg,
'raw_message': l
}
info_splits = info.split()
if len(info_splits) == 5:
msg_info['timestamp'] = ' '.join(info_splits[:3])
msg_info['hostname'] = info_splits[3]
| msg_info['procname'] = info_splits[4]
r.append(msg_info)
return r
|
chienlieu2017/it_management | odoo/addons/payment_buckaroo/tests/test_buckaroo.py | Python | gpl-3.0 | 7,079 | 0.002684 | # -*- coding: utf-8 -*-
from lxml import objectify
import urlparse
import odoo
from odoo.addons.payment.models.payment_acquirer import ValidationError
from odoo.addons.payment.tests.common import PaymentAcquirerCommon
from odoo.addons.payment_buckaroo.controllers.main import BuckarooController
from odoo.tools import ... | GE': u'Transaction successfully processed',
'BRQ_TEST': u'true',
'BRQ_TIMESTAMP': u'2014-05-08 12:41:21',
'BRQ_TRANSACTIONS': u'D6106678E1D54EEB8093F5B3AC42EA7B',
'BRQ_WEBSITEKEY': u'5xTGyGyPyl',
}
# should raise error about unknown tx
with self.a... | rror):
self.env['payment.transaction'].form_feedback(buckaroo_post_data, 'buckaroo')
tx = self.env['payment.transaction'].create({
'amount': 2240.0,
'acquirer_id': self.buckaroo.id,
'currency_id': self.currency_euro.id,
'reference': 'SO004',
... |
Ruide/angr-dev | cle/cle/memory.py | Python | bsd-2-clause | 10,840 | 0.00369 | import bisect
import struct
import cffi
__all__ = ('Clemory',)
# TODO: Further optimization is possible now that the list of backers is sorted
class Clemory(object):
"""
An object representing a memory space. Uses "backers" and "updates" to separate the concepts of loaded and written
memory and make look... |
while i < len(self._backers) and data:
start, backer_data = self._backers[i] # self._backers is always sorted
size = len(backer_data)
stop = start + size
if | pos >= start:
if pos < stop:
if pos + len(data) > stop:
new_backer_data = backer_data[ : pos - start] + data[ : stop - pos]
self._backers[i] = (start, new_backer_data)
# slicing data
dat... |
biddyweb/merchant | billing/gateways/stripe_gateway.py | Python | bsd-3-clause | 8,557 | 0.000467 | from billing import Gateway, GatewayNotConfigured
from billing.signals import transaction_was_successful, transaction_was_unsuccessful
from billing.utils.credit_card import InvalidCard, Visa, MasterCard, \
AmericanExpress, Discover, CreditCard
import stripe
from django.conf import settings
class StripeGateway(Ga... | card = credit_card
if isinstance(credit_card, CreditCard):
if not self.validate_card(credit_card):
raise InvalidCard("Invalid Card")
card = {
'number': credit_card.number,
'exp_month': credit_card.month,
'exp_year': c... | }
try:
plan_id = options['plan_id']
self.stripe.Plan.retrieve(options['plan_id'])
try:
response = self.stripe.Customer.create(
card=card,
plan=plan_id
)
transaction_was_successful.sen... |
yeyanchao/calibre | src/calibre/library/server/browse.py | Python | gpl-3.0 | 35,184 | 0.005088 | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import operator, os, json, re
from binascii import hexlify, unhexlify
from collections import OrderedDict
import cherrypy
... | page = list(ids[:delta])
pages.append((page, pos))
ids = ids[delta:]
pos += len(page)
page_template = u'''\
<div class="page" id="page{0}">
<div class="load_data" title="{1}">
<span class="url" title="{prefix}/browse/booklist_page"></span>
... | ass="start" title="{start}"></span>
<span class="end" title="{end}"></span>
</div>
<div class="loading"><img src="{prefix}/static/loading.gif" /> {2}</div>
<div class="loaded"></div>
</div>
'''
pagelist_template = u'''\
... |
faircloth-lab/rhino | rhino/core.py | Python | bsd-3-clause | 2,759 | 0.006162 |
import os
import sys
import json
import time
import numpy
import dendropy
from collections import defaultdict
import pdb
def parse_site_rates(rate_file, correction = 1, test = False, count = 0):
"""Parse the site rate file returned from hyphy to a vector of rates"""
# for whatever reason, when run in a virt... | ick')
return pth, correction_factor
def get_net_pi_for_periods(pi, times):
"""Sum across the PI values for the requested times"""
sums = numpy.nansum(pi, axis=1)[times]
return dict(zip(times, sums))
def get_informative_sites(alignment, threshold=4):
"""Returns a list, where True indicates a site... | ath(alignment, 'nexus')
results = defaultdict(int)
for cells in taxa.vectors():
assert len(cells) == taxa.vector_size # should all have equal lengths
for idx, cell in enumerate(cells):
results[idx] += 1 if str(cell).upper() in "ATGC" else 0
return numpy.array([1 if results[x] >= ... |
sunfounder/SunFounder_PiSmart | pismart/SpeakPython/SpeakPythonJSGFLexer.py | Python | gpl-2.0 | 38,081 | 0.012815 | # $ANTLR 3.4 SpeakPythonJSGF.g 2015-09-25 20:19:04
import sys
from antlr3 import *
#from antlr3.compat import set, frozenset
from sets import Set as set, ImmutableSet as frozenset
# for convenience in actions
HIDDEN = BaseRecognizer.HIDDEN
# token types
EOF=-1
ARROW=4
AT=5
AT_GLOBAL_OPTIONS=6
AT_OPTIONS=7
AT_RESULT... | tion end |
finally:
pass
# $ANTLR end "START_DQUOTE_STRING"
# $ANTLR start "INSIDE_SQUOTE_STRING"
def mINSIDE_SQUOTE_STRING(self, ):
try:
# SpeakPythonJSGF.g:227:30: ({...}? => (~ ( '\\'' ) )* )
# SpeakPythonJSGF.g:227:31: {...}? => (~ ( '\\'' ) )*
... |
mincoin-project/mincoin | qa/rpc-tests/disablewallet.py | Python | mit | 1,874 | 0.00587 | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Copyright (c) 2015-2019 The Mincoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Exercise API with -disablewallet.
#
from test_... | self.sync_all()
def run_test (self):
# Check regression: https://github.com/bitcoin/bitcoin/issues/6963#issuecomment-1545488 | 80
x = self.nodes[0].validateaddress('3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
assert(x['isvalid'] == False)
x = self.nodes[0].validateaddress('mneYUmWYsuk7kySiURxCi3AGxrAqZxLgPZ')
assert(x['isvalid'] == True)
# Checking mining to an address without a wallet
try:
... |
zephyrplugins/zephyr | zephyr.plugin.jython/jython2.5.2rc3/Lib/encodings/johab.py | Python | epl-1.0 | 1,023 | 0.006843 | #
# johab.py: Python Unicode Codec for JOHAB
#
# Written by Hye-Shik Chang <perky@FreeBSD.org>
#
import _codecs_kr, codecs
import _multibytecodec as mbc
codec = _codecs_kr.getcodec('johab')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.MultibyteIncrement... | oder(mbc.MultibyteIncrementalDecoder,
codecs.IncrementalDecoder):
| codec = codec
class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):
codec = codec
class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):
codec = codec
def getregentry():
return codecs.CodecInfo(
name='johab',
encode=Codec().encode,
decode=C... |
mdecourse/2016fallcadp | data/pyIGES/docs/examples/benchmarks/__init__.py | Python | agpl-3.0 | 1,103 | 0.00816 | #!python3.3
# -*- coding: utf-8 -*-
"""
.. module:: examples.benchmarks
:platform: Agnostic, Windows
:synopsis: Full suite of benchmarks
Created on 10/08/2013
"""
def standard_iges_setup(system, filename):
system.StartSection.Prolog = " "
system.GlobalSection.IntegerBits = int(32)
syst... | ductIdentificationFromSender
system.GlobalSection.AuthorOrg = "Queensland Uni. of Tech."
system.GlobalSection.NameOfA | uthor = "Rodney Persky"
|
statX/nz-houses | analysis/listing_text.py | Python | bsd-2-clause | 1,824 | 0.061952 |
import cPickle
import nz_houses_dao as dao
from nltk.corpus import stopwords
import re
import gzip
class Residential:
distionary
def
def __init__():
pass
def generate_word_lists(descriptions):
descriptions_features = {}
i = 0
for listingId in descriptions.keys():
a = descriptions[listingId... | f)
i = 0
for listingId in reversed(descriptions_features.keys()):
print listingId
print_words(descriptions_features[listingId])
print '-----------'
i += 1
if i == 10:
| break
|
eduNEXT/edunext-ecommerce | ecommerce/core/management/commands/tests/test_sync_hubspot.py | Python | agpl-3.0 | 9,618 | 0.002911 | """
Test the sync_hubspot management command
"""
from datetime import datetime, timedelta
from io import StringIO
from django.core.management import call_command
from django.core.management.base import CommandError
from factory.django import get_model
from mock import patch
from slumber.exceptions import HttpClientE... | command, '_install_hubspot_ecommerce_bridge', return_value=True), \
patch.object(sync_command, '_define_hubspot_ecommerce_settings', return_value=True):
# if _upsert_hubspot_objects raises an exception
mocked_hubspot.side_effect = HttpClientError
output = self._get_co... | @patch.object(sync_command, '_hubspot_endpoint')
def test_install_hubspot_ecommerce_bridge(self, mocked_hubspot):
"""
Test _install_hubspot_ecommerce_bridge function.
"""
with patch.object(sync_command, '_define_hubspot_ecommerce_settings', return_value=False):
output ... |
wez3/domoboard | modules/api.py | Python | gpl-3.0 | 2,175 | 0.006437 | #!/usr/bin/python
# Provides all the API functionality callable through "/api"
from flask import request
from flaskext.auth import login_required
import json, os, sys
import security, charts, plugins, webconfig, domoticz
apiDict = {}
modules = {}
def init():
global modules
modules = plugins.loadPlugins()
... | hart()
elif custom == "modify_config" | :
idx = request.args.get('idx', '')
page = request.args.get('page', '')
component = request.args.get('component', '')
description = request.args.get('description', '')
extra = request.args.get('extra', '')
webconfig.writeToConfig(idx, page, component, description, extra)
... |
heromod/migrid | mig/cgi-bin/mv.py | Python | gpl-2.0 | 1,092 | 0.002747 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# --- BEGIN_HEADER ---
#
# mv - [insert a few words of module description on this line]
# Copyright (C) 2003-2009 The MiG Project lead by Brian Vinter
#
# This file is part of MiG.
#
# MiG is free software: you can redistribute it and/or modify
# it under the terms of the GN... | ftware Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# MiG is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more d... | h Floor, Boston, MA 02110-1301, USA.
#
# -- END_HEADER ---
#
import cgi
import cgitb
cgitb.enable()
from shared.functionality.mv import main
from shared.cgiscriptstub import run_cgi_script
run_cgi_script(main)
|
agry/NGECore2 | scripts/object/tangible/painting/painting_bestine_lucky_despot.py | Python | lgpl-3.0 | 86 | 0.081395 | import sys |
def setup(core, object):
return
#Painting of the | Lucky Despot Wreckage |
previtus/MGR-Project-Code | Downloader/VisualizeHistory.py | Python | mit | 7,469 | 0.006293 | import matplotlib, os, errno
# IF WE ARE ON SERVER WITH NO DISPLAY, then we use Agg:
#print matplotlib.get_backend()
if not('DISPLAY' in os.environ):
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
def visualize_history(hi, show=True, save=False, save_path='', show_also='', custom_title=N... | 00.0
#y_min = 100.0
#for i in whiskered_boxes_data:
# y_max = max(max(i),y_max)
# y_min = min(min(i),y_min)
axes = plt.axes()
import matplot | lib.ticker as ticker
axes.yaxis.set_major_locator(ticker.MultipleLocator(np.abs(y_max-y_min)/10.0))
axes.yaxis.set_minor_locator(ticker.MultipleLocator(np.abs(y_max-y_min)/100.0))
#meanpointprops = dict(linewidth=0.0)
meanpointprops = dict(linewidth=1.0)
boxplot = plt.boxplot(whiskered_boxes_data... |
2947721120/thumbor | vows/point_vows.py | Python | mit | 4,575 | 0.000656 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
from pyvows import Vows, expect
from thumbor.point import FocalPoint... | alPoint.from_alignment('right', 'bottom', 300, 200)
def should_have_x_of_300(self, topic):
expect(topic.x).to_equal(300)
def should_have_y_of_200(self, topic):
expect(topic.y).to_equal(200)
def should_have_weight_of_1(self, topic):
| expect(topic.weight).to_equal(1.0)
|
kianby/stacosys | stacosys/db/dao.py | Python | gpl-3.0 | 1,576 | 0.001269 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from datetime import datetime
from stacosys.model.comment import Comment
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
def find_comment_by_id(id):
return Comment.get_by_id(id)
def notify_comment(comment: Comment):
comment.notified = datetime.now().strftime(TIME_FORMAT)
co... | nt.published.is_null(False)).count()
def create_comment(url, author_name, author_site, author_gravatar, message):
created = datetime.now().strftime("%Y-%m-%d %H:%M | :%S")
comment = Comment(
url=url,
author_name=author_name,
author_site=author_site,
author_gravatar=author_gravatar,
content=message,
created=created,
notified=None,
published=None,
)
comment.save()
return comment
|
chainside/btcpy | btcpy/structs/hd.py | Python | lgpl-3.0 | 10,848 | 0.002397 | # Copyright (C) 2017 chainside srl
#
# This file is part of the btcpy package.
#
# It is subject to the license terms in the LICENSE.md file found in the top-level
# directory of this distribution.
#
# No part of btcpy, including this file, may be copied, modified,
# propagated, or distributed except according to the t... | # using net_name here would ignore the mainnet=None flag
return Constants.get('xprv.version')['mainnet' if mainnet else 'testnet']
@staticmethod
def decode_key(keydata):
return PrivateKey(keydata[1:])
@staticmethod
def _check_decode(string):
if string[:4] not in (Constants... | ('Non matching prefix: {}'.format(string[:4]))
def __init__(self, key, chaincode, depth, pfing, index, hardened=False):
if not isinstance(key, PrivateKey):
raise TypeError('ExtendedPrivateKey expects a PrivateKey')
super().__init__(key, chaincode, depth, pfing, index, hardened)
def... |
idrogeno/IdroMips | lib/python/Screens/About.py | Python | gpl-2.0 | 21,987 | 0.031109 | from Screen import Screen
from Components.config import config
from Components.ActionMap import ActionMap
from Components.Sources.StaticText import StaticText
from Components.Harddisk import harddiskmanager
from Components.NimManager import nimmanager
from Components.About import about
from Components.ScrollLabel impor... | t("\n")
infomap = {}
for x in infolines:
l = x.split(': ')
if len(l) != 2:
continue
(type, value) = l
infomap[type] = value
print infomap
self["key_ | red"] = Button(_("Cancel"))
self["TranslationInfo"] = StaticText(info)
translator_name = infomap.get("Language-Team", "none")
if translator_name == "none":
translator_name = infomap.get("Last-Translator", "")
self["TranslatorName"] = StaticText(translator_name)
self["actions"] = ActionMap(["SetupActions... |
Greymerk/python-rpg | src/abilities/explosion.py | Python | gpl-3.0 | 3,489 | 0.048438 | from random import randint
from projectiles import Star
from math import sqrt
from pygame.color import THECOLORS
class Explosion(object):
range = 6
radius = 4
damage = 2, 5
heal = False
name = "Explosion"
icon = "firebolt"
cooldown = 7
def __init__(self, caster, location, item):
self.item = item
self.r... | urn True
done = True
for star in self.explosion:
if star.done:
continue
star.update()
if star.done:
e = self.caster.world.getEntityFromLocation(star.end)
if e is not None:
e.inflict(self.caster, randint(self.damage[0], self.damage[1]))
else:
done = False
i | f done:
self.done = True
return done
def draw(self, surface, position, visible):
if not self.done:
if not self.projectile.done:
self.projectile.draw(surface, position, visible)
if self.explosion:
for star in self.explosion:
star.draw(surface, position, visible)
@staticmethod
def g... |
furlongm/patchman | arch/admin.py | Python | gpl-3.0 | 882 | 0 | # Copyright 2012 VPAC, http://www.vpac.org
# Copyright 2013-2021 Marcus Furlong <furlongm@gmail.com>
#
# This file is part of Patchman.
#
# Patchman 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 3 on... | <http://www.gnu.org/licenses/>
| from django.contrib import admin
from arch.models import PackageArchitecture, MachineArchitecture
admin.site.register(PackageArchitecture)
admin.site.register(MachineArchitecture)
|
tcstewar/2015-Embodied_Benchmarks | code/benchmark.py | Python | gpl-2.0 | 5,094 | 0.001767 | import argparse
import importlib
import inspect
import logging
import os
import shelve
import time
import matplotlib.pyplot
import numpy as np
import nengo
def find_offset(a, b):
assert len(a) == len(b)
corr = np.correlate(a, b, 'full')
index = np.argmax(corr[len(a):])
return index
class Benchmark(... | :
f.write(text)
print(text)
db = shelve.open(fn + '.db')
db['trange'] = sim.trange()
for k, v i | n inspect.getmembers(self):
if isinstance(v, nengo.Probe):
db[k] = sim.data[v]
db.close()
if p.show_figs:
plt.show()
return result
|
mulkieran/pyudev | pyudev/monitor.py | Python | lgpl-2.1 | 20,793 | 0.000192 | # -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, ... | self, ensure_byte_string(tag))
self._libudev.udev_monitor_filter_update(self)
def remove_filter(self):
"""
Remove any filters installed with :meth:`filter_by()` or
:meth:`filter_by_tag()` from this monitor.
.. warning::
Up to udev 181 (and possibly even ... | ys raises
:exc:`~exceptions.ValueError`.
Raise :exc:`~exceptions.EnvironmentError` if removal of installed
filters failed.
.. versionadded:: 0.15
"""
self._libudev.udev_monitor_filter_remove(self)
self._libudev.udev_monitor_filter_update(self)
def enable... |
plotly/python-api | packages/python/plotly/plotly/validators/histogram/_ycalendar.py | Python | mit | 1,058 | 0.000945 | import _plotly_utils.basevalidators
class YcalendarValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="ycalendar", parent_name="histogram", **kwargs):
super(YcalendarValidator, self).__init__(
plotly_name=plo | tly_name,
| parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
role=kwargs.pop("role", "info"),
values=kwargs.pop(
"values",
[
"gregorian",
"chinese",
"coptic",
"disc... |
CDSP/zephserver | docs/conf.py | Python | gpl-3.0 | 9,276 | 0.006037 | # -*- coding: utf-8 -*-
#
# zephserver documentation build configuration file, created by
# sphinx-quickstart on Thu Oct 8 10:50:38 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
... | rce_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'zephserver'
copyright = u'2015, cdsp'
author = u'cdsp'
# The version info for the project you're... | X.Y version.
version = '0.1.25'
# The full version, including alpha/beta/rc tags.
release = '0.1.25'
# 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" fro... |
crypt3lx2k/Imageboard-Web-Interface | defaults.py | Python | mit | 363 | 0.019284 | """
This file holds the default values for the various programs.
"""
import sys
__all__ = ['defaults']
defaults = {
# filenames
'cache_file' : 'bin/cache.bin',
'log_file' : sys.stderr,
# values
'num_threads' : 16,
# flags
'debug' : False,
| 'https' | : False,
'offline' : False,
'quiet' : False
}
|
sacharya/nova | nova/tests/virt/hyperv/db_fakes.py | Python | apache-2.0 | 5,743 | 0.001219 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Cloudbase Solutions Srl
#
# 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/LICE... | : str(uuid.uuid4()),
'reservation_id': utils.generate_uid('r'),
'image_ref': values['image_ref'],
'kernel_id': values['kernel_id'],
'ramdisk_id': values['ramdisk_id'],
'vm_state': vm_states.BUILDING,
'task_state': task_states.SCHEDULING,
| 'user_id': values['user_id'],
'project_id': values['project_id'],
'instance_type': instance_type,
'memory_mb': instance_type['memory_mb'],
'vcpus': instance_type['vcpus'],
'mac_addresses': [{'address': values['mac_address']}],
'root_gb': instanc... |
stephanie-wang/ray | python/ray/tune/examples/logging_example.py | Python | apache-2.0 | 1,989 | 0 | #!/usr/bin/env python
import argparse
import json
import os
import random
import numpy as np
from ray import tune
from ray.tune import Trainable, run
class TestLogger(tune.logger.Logger):
def on_result(self, result):
print("TestLogger", result)
def trial_str_creator(trial):
return "{}_{}_123".for... | ) as f:
f.write(json.dumps({"timestep": self.timestep}))
return path
def _restore(self, checkpoint_path):
with open(checkpoint_path) as f:
self.timestep = json.loads(f.read())["timestep"]
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argu... | --smoke-test", action="store_true", help="Finish quickly for testing")
args, _ = parser.parse_known_args()
trials = run(
MyTrainableClass,
name="hyperband_test",
num_samples=5,
trial_name_creator=trial_str_creator,
loggers=[TestLogger],
stop={"training_iteration"... |
stutivarshney/Bal-Aveksha | WebServer/manage.py | Python | gpl-3.0 | 807 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "WebServer.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that th... | ther
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
" | forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
Mariatta/clone_ndb_entity | clone_ndb_entity.py | Python | mit | 1,677 | 0.005963 | """
clone an ndb entity
"""
from google.appengine.ext import ndb
def construct_clone_keys_from_entity_key(entity_key, clone_kind):
"""
:param entity_key: the entity key (ndb.Key)
:param clone_kind: the kind of the clone model
:return: the key for the entity clone model
"""
keys = [(clone_kind... | roperties as e
"""
entity_dict = entity_to_clone.to_dict()
new_props = {}
for k, v in entity_to_clone.__class__.__dict__.iteritems():
if isinstance(v, ndb.Property) and not isinstance(v, ndb.ComputedProperty): # can't clone ComputedProperty
new_props[k] = entity_dict[k]
new_prop... | tity.key = key
return new_entity
|
felipenaselva/repo.felipe | plugin.video.specto/resources/lib/sources/disabled/directdl_tv.py | Python | gpl-2.0 | 4,247 | 0.011773 | # -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
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 l... | ing('realdedrid_user') == '' and control.setting('premiumize_u | ser') == ''): raise Exception()
query = base64.urlsafe_b64decode(self.search_link) + urllib.quote_plus(url)
query = urlparse.urljoin(self.base_link, query)
result = client.request(query)
result = json.loads(result)
title, hdlr = re.compile('(.+?) (S\d*E\d*)... |
will-Do/tp-libvirt_v2v | libvirt/tests/src/virsh_cmd/network/virsh_net_list.py | Python | gpl-2.0 | 6,096 | 0.000164 | import re
import os
from autotest.client.shared import error
from virttest import virsh
from provider import libvirt_version
def run(test, params, env):
"""
Test command: virsh net-list.
The command returns list of networks.
1.Get all parameters from configuration.
2.Get current network's status(... | irt version.")
# Create a transient network.
try:
if persistent == "no":
virsh.net_dumpxml(net_name, to_file=tmp_xml, ignore_status=False)
if net_current_status == "inactive":
virsh.net_destroy(net_name, ignore_status=False)
virsh.net_undefine(net_nam... | , ignore_status=False)
virsh.net_create(tmp_xml, ignore_status=False)
except error.CmdError:
raise error.TestFail("Transient network test failed!")
# Prepare network's status for testing.
if net_status == "active":
try:
if not virsh.net_state_dict()[net_name]['active... |
wolfy1339/Python-IRC-Bot | utils/irc.py | Python | mit | 2,432 | 0.002467 | import time
from typing import List, Optional
from utils import tasks
from zirc.event import Event
from utils.database import Database
from zirc.wrappers import connection_wrapper
def chunks(l: List, n: int):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n... | ")
if len(args_list) == 1:
| users = args_list[0]
elif len(args_list) >= 2:
users = args_list[:-1]
return users
def get_user_host(userdb: Database, channel: str, nick: str):
return userdb.get_user_host(channel, nick)
def get_info_tuple(event: Event, args: List[str], userdb: Optional[Database]=None):
if arg... |
ericremoreynolds/reynolds.mappings | Reynolds.Mappings/Mapping.py | Python | mit | 22,598 | 0.03297 | #----
MAX_N = 6
#----
import sys
from CodeGen import *
codegen_begin("Mapping.cs")
stmt("using System")
stmt("using System.Collections")
stmt("using System.Collections.Generic")
stmt("using System.Threading")
stmt("using System.Linq")
with block("namespace Reynolds.Mappings"):
for n in range(1, MAX_N):
if n ==... | ner")
with block("public LazyMapping(InstantiateDelegate instantiator, ContainsDelegate contains = null)"):
stmt("_inner = new DictionaryMapping<$TKeys$, TValue>()")
stmt("_instantiator = instantiator")
stmt("_contains = contains")
| with block("public LazyMapping(InstantiateDelegate instantiator, ContainsDelegate contains, $IEqualityComparer<TKeys> comparers$)"):
stmt("_inner = new DictionaryMapping<$TKeys$, TValue>(" + ("comparer" if n == 1 else ", ".join(("comparer%i" % (i+1) for i in range(n)))) + ")")
stmt("_instantiator = instantia... |
QISKit/qiskit-sdk-py | qiskit/pulse/pulse_lib/__init__.py | Python | apache-2.0 | 570 | 0 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | opyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module fo | r builtin pulse_lib."""
from .discrete import *
|
6112/project-euler | problems/066.py | Python | mit | 2,117 | 0.002867 | # encoding=utf-8
## SOLVED 2014/11 | /29
## 661
# Consider quadratic Diophantine equations of the form:
# x^2 – Dy^2 = 1
# For example, when D=13, the minimal solution in x is 649^2 – 13×180^2 = 1.
# It can be assumed that there are no solutions in positive integers when D is
# square.
# By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we o... | g:
# 3^2 – 2×2^2 = 1
# 2^2 – 3×1^2 = 1
# 9^2 – 5×4^2 = 1
# 5^2 – 6×2^2 = 1
# 8^2 – 7×3^2 = 1
# Hence, by considering minimal solutions in x for D ≤ 7, the largest x is
# obtained when D=5.
# Find the value of D ≤ 1000 in minimal solutions of x for which the largest
# value of x is obtained.
from math import sqrt
L... |
JNeiger/robocup-software | soccer/gameplay/plays/restarts/our_corner_kick.py | Python | apache-2.0 | 3,158 | 0.0019 | import standard_play
import behavior
import skills
import tactics
import robocup
import constants
import main
import enum
class OurCornerKick(standard_play.StandardPlay):
MinChipRange = 0.3
MaxChipRange = 3.0
ChipperPower = 0.5
TargetSegmentWidth = 1.5
MaxKickSpeed = 0.5
MaxKickAccel = 0.5
... | all backwards
self.kicker.setup_ball_avoid = constants.Field.CenterRadius - constants.Robot.Radius
self.kicker.drive_around_dist = constants.Field.CenterRadius - constants.Robot.Radius
self.center1 = skills.move.Move()
s | elf.add_subbehavior(self.center1,
'center1',
required=False,
priority=4)
self.center2 = skills.move.Move()
self.add_subbehavior(self.center2,
'center2',
requi... |
laudney/tinyrpc | tinyrpc/transports/tcp.py | Python | mit | 4,970 | 0.00161 | import logging
log = logging.getLogger('StreamTransport')
import Queue
import gevent
from gevent import socket
from . import ServerTransport, ClientTransport
class StreamServerTransport(ServerTransport):
"""TCP socket transport.
This transport has a few peculiarities: It must be run in a thread,
greenle... | data = sock.recv(self._config_buffer)
except socket.timeout:
sock_error = True
data = None
log.debug('StreamServerTransport:socket timeout from %s', address)
except socket.error:
sock_error = True
data = None
log.debug('... | socket error from %s', address)
return data, sock_error
def _get_msg(self, sock, address):
sock_error = False
chunks = []
while True:
data, sock_error = self._get_data(sock, address)
if not data:
break
chunks.append(data)
... |
anhstudios/swganh | data/scripts/templates/object/tangible/medicine/crafted/shared_medpack_damage_e.py | Python | mit | 466 | 0.04721 | #### NOTICE: T | HIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/medicine/crafted/shared_medpack_damage_e.iff"
result.attribute_template_id = 7
r... | #### END MODIFICATIONS ####
return result |
vmartinezf/ptavi-p2 | calc.py | Python | gpl-2.0 | 980 | 0.00102 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Vamos a programar una calculadora
import sys
# convierto el operando sea int o float a float
def numerical_float(operando):
return float(operando)
def suma(sum1, sum2):
return sum1 + sum2
def resta(rest1, rest2):
return rest1 - rest2
def resultado(o | peracion, num1, num2):
if (operacion == "suma") | :
result = suma(num1, num2)
elif (operacion == "resta"):
result = resta(num1, num2)
else:
sys.exit("Error: the operation is incorrect")
return result
if __name__ == "__main__":
try:
numero1 = sys.argv[1]
operacion = sys.argv[2]
numero2 = sys.argv[3]
... |
eaglgenes101/universalSmashSystem | engine/subactions/control/nextFrame.py | Python | gpl-3.0 | 339 | 0.00885 | from engine.subaction import *
# Go to the next frame in the action
class nextFrame(SubAction):
subact_group = 'Control'
fields = []
def execute(self, _action, _actor):
SubAct | ion.execute(self, _action, _actor)
_action.frame += 1
def getDisplayName(self):
| return 'Next Frame'
|
anhstudios/swganh | data/scripts/templates/object/mobile/shared_jabba_the_hutt.py | Python | mit | 445 | 0.047191 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR E | XAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_jabba_the_hutt.iff"
result.attribute_template_id = 9
result.stfName("theme_park_name","jabba_the_hutt")
#### BEGIN MODIFICATIONS ####
| #### END MODIFICATIONS ####
return result |
EdDev/vdsm | tests/network/func_net_basic_test.py | Python | gpl-2.0 | 11,637 | 0 | #
# Copyright 2016-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | NETREMOVE = {NETWORK_NAME: {'remove': True}}
with self.assertRaises(SetupNetworksError) as cm:
with self.setupNetworks(NETREMOVE, {}, NOCHK):
pass
self.assertEqual(cm.exception.status, ne.ERR_BAD_BRIDGE)
def test_add_net_based_on_vlan(self):
with dummy_de... | with self.setupNetworks(NETCREATE, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NETCREATE[NETWORK_NAME])
def test_remove_net_based_on_vlan(self):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'vlan': VLANID,
'swi... |
Calzzetta/Simple-Django-REST-Framework-Demo | simpledrf/urls.py | Python | mit | 825 | 0 | """simpledrf URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... | contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.url | s),
url(r'^employee/', include('employee.urls')),
]
|
JH72/Embedded-Programming | Capstone2/med_simulator/device.py | Python | mit | 2,581 | 0.046881 | #device.py
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient as AWS #To connect to AWS IOT
#Initializes AWS IOT client
myAWS = AWS("asus-simon")
#Sets the url that is receiving the data
host = "a3f84gpf4vy7nu.iot.us-west-2.amazonaws.com"
portAWS = 8883
myAWS.configureEndpoint(host, portAWS)
#Configures credential... | or = 360.0
tf = int((t0+dt) * factor)
t0 = int(t0 * factor)
fileName = "database/mitdb/100"
record = None
try:
record = wfdb.rdsamp(fileName, sampfrom=t0, sampto=tf, channels=[0,1], physical=False)
except ValueError:
print("ValueError1")
try:
record = wfdb.r | dsamp(fileName, sampfrom=t0, channels=[0,1], physical=False)
except ValueError:
print("ValueError2")
stop = True
return None
x = record.d_signals[:,0]
print("record = {}".format(record.d_signals[0,0]))
print(x[0])
if(x is None):
print("None error")
x_filtered = record.d_signals[:,1]
x = intify(x)
... |
JesseLivezey/plankton | pylearn2/datasets/semi_plankton.py | Python | bsd-3-clause | 3,794 | 0.006589 | """
Plankton dataset wrapper for semi-supervised networks.
"""
__authors__ = "Jesse Livezey"
import numpy as N
np = N
import cPickle, h5py, os
from theano.compat.six.moves import xrange
from pylearn2.datasets import semi_supervised, dense_design_matrix
from pylearn2.utils.rng import make_np_rng
from pylearn2.utils imp... | )
with h5py.File(os.path.join(folder,'train.h5'), 'r') as f:
topo_view = f['X'].value[...,np.newaxis]/255.
y = f['y'].value
| self.ids = f['id'].value
n_examples = topo_view.shape[0]
perm = rng.permutation(n_examples)
topo_view = topo_view[perm]
y = y[perm]
with h5py.File(os.path.join(folder,'test.h5'), 'r') as f:
self.unlabeled = f['X'].value[...,np.newaxis]/255.
self.ids_... |
lucienfostier/gaffer | python/GafferTest/StringInOutNode.py | Python | bsd-3-clause | 2,820 | 0.026241 | ##########################################################################
#
# Copyright (c) 2012, John Haddon. 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 so... | DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR 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 O... | HE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import IECore
import Gaffer
class StringInOutNode( Gaffer.ComputeNode ) :
def __init__( self, name="StringInOutNode", defaultValue="", substitutions = IECore.StringAlgo.Substitutions.AllSubstitutions ) :
G... |
shanemikel/beets | beetsplug/scrub.py | Python | mit | 5,220 | 0 | # This file is part of beets.
# Copyright 2015, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... |
# Some Mutagen metadata subclasses (namely, ASFTag) do not
# support .delete(), presumably because it is impossible to
| # remove them. In this case, we just remove all the tags.
for tag in f.keys():
del f[tag]
f.save()
except IOError as exc:
self._log.error(u'could not scrub {0}: {1}',
util.displayable_path(path), exc)
... |
hyunchel/redis-dump-load | tests/util.py | Python | bsd-2-clause | 1,620 | 0.005556 | import sys
py3 = sys.version_info[0] == 3
# python 2/3 compatibility
if py3:
# borrowed from six
def b(s):
'''Byte literal'''
return s.encode("latin-1")
def u(s):
'''Text literal'''
| return s
else:
# borrowed from six
def b(s):
'''Byte literal'''
return s
# Workaround for standalone backslash
def u(s):
'''Text literal'''
return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
# backport for python 2.6
def get_subprocess_check_output():
imp... | |
cuauv/software | vision/modules/deprecated/Bins_SVM.py | Python | bsd-3-clause | 12,569 | 0.004058 | from collections import namedtuple
import pickle
from math import sin, cos, radians
import os
import time
import cv2
import numpy as np
from caffew import caffe_classifier
import shm
from vision.modules import ModuleBase, gui_options
capture_source = 'downward'
vision_options = [gui_options.BooleanOption('debugging... | ]), int(offset[1] + rrect[0][1]))
| p2 = (int(-offset[0] + rrect[0][0]), int(-offset[1] + rrect[0][1]))
cv2.line(final, p1, p2, (0, 255), 2)
shm_group_cover = shm.shape_handle
shm_group_cover.p.set(best_cover_contour.probability)
shm_group_cover.x.set(int(rrect[0][0]))
... |
waldenilson/TerraLegal | project/servidor/restrito/contratoservidor.py | Python | gpl-2.0 | 6,591 | 0.017448 | from django.contrib.auth.decorators import login_required, permission_required,\
user_passes_test
from django.shortcuts import render_to_response, get_object_or_404
from django.template.context import RequestContext
from project.tramitacao.forms import FormTipoCaixa
from django.http import HttpResponseRedirect
from... | '
ods.save(response)
return response
else:
return HttpR | esponseRedirect( response_consulta )
@permission_required('sicop.tipo_caixa_consulta', login_url='/excecoes/permissao_negada/', raise_exception=True)
def relatorio_csv(request):
# montar objeto lista com os campos a mostrar no relatorio/pdf
lista = request.session[nome_relatorio]
if lista:
response... |
getfleety/coralillo | coralillo/lua/__init__.py | Python | mit | 512 | 0.001953 | import os
SCRIPT_PATH = os.path.dirname(__file__)
class Lua:
def __init__(self, redis):
self.redis = redis
scripts = filter(lambda s: s.endswith('.lua'), os.listdir(SCRIPT_PATH))
for scriptname in scripts:
| with open(os.path.join(SCRIPT_PATH, scriptname)) as script:
setattr(self, scriptname.split('.')[0], redis.register_script(script.read()))
def register(self, name, contents):
setattr(self, name, self.redis.register_scri | pt(contents))
|
nnscr/nnscr.de | blog/migrations/0002_post_slug.py | Python | mit | 608 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.3 | on 2016-03-03 01:08
from __future__ import unicode_literals
from django.db import migrations, models
from blog.models import Post
def slugify_all_posts(*args):
for post in Post.objects.all():
post.save()
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
... | ),
migrations.RunPython(slugify_all_posts)
]
|
sio2project/oioioi | oioioi/exportszu/forms.py | Python | gpl-3.0 | 584 | 0 | fr | om django import forms
from django.utils.translation import ugettext_lazy as _
class ExportSubmissionsForm(forms.Form):
round = forms.ModelChoiceField(
queryset=None,
required=False,
empty_label=_("All rounds"),
label=_("Choose round"),
)
only_final = forms.BooleanField(
... | it__(self, request, *args, **kwargs):
super(ExportSubmissionsForm, self).__init__(*args, **kwargs)
self.fields['round'].queryset = request.contest.round_set
|
ryanrdetzel/pjsip | tests/pjsua/scripts-sendto/160_err_duplicate_replaces.py | Python | gpl-2.0 | 552 | 0.016304 | # $Id: 160_err_duplicate_replaces.py 2066 2008-06-26 19:51:01Z bennylp $
import inc_sip as sip
import inc_sdp as sdp
sdp = \
"""
v=0
o=- 0 0 IN IP4 127.0.0.1
s=pjmedia
c=IN IP4 127.0.0.1
t=0 0
m=audio 4000 RTP/AVP 0
"""
pjsu | a_args = "--null-audio --auto-answer 200"
extra_headers = "Replaces: abcd;from_tag=1\r\nReplaces: efgh;from_tag=2\r\n"
include = []
exclude = []
sendto_cfg = sip.SendtoCfg("D | uplicate replaces header", pjsua_args, sdp, 400,
extra_headers=extra_headers,
resp_inc=include, resp_exc=exclude)
|
RedXBeard/chessQuest | chessQuest/__init__.py | Python | gpl-3.0 | 724 | 0.004144 | from chessQuest.movements import left_right_cross, right_left_cross, horizontal, vertical, knight_move
FREE = 0
FORBIDDEN = 1
KI | NG = 'K'
QUEEN = 'Q'
ROOK = 'R'
BISHOP = 'B'
KNIGHT = 'N'
PIECES_ORDER = [QUEEN, KING, ROOK, BISHOP, KNIGHT]
# Do not need an actual class for pieces.
PIECES = {
KING: {
'movements': [left_right_cross(1), right_left_cross(1), horizontal(1), vertical(1)],
},
QUEEN: {
'movements': [left_righ... | movements': [left_right_cross(), right_left_cross()],
},
KNIGHT: {
'movements': [knight_move]
}
}
|
sadig/DC2 | components/dc2-dhcp-appserver/dc2/dhcp/__init__.py | Python | gpl-2.0 | 908 | 0.001103 | # -*- coding: utf-8 -*-
#
# (DC)² - DataCenter Deployment Control
# Copyright (C) 2010, 2011, 2012, 2013, 2014 Stephan Adig <sh@sourcecode.de>
# 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; eit... | ERCHANTABILITY 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floo | r, Boston, MA 02110-1301 USA.
#
__import__('pkg_resources').declare_namespace(__name__)
|
darongliu/Lstm_Turing_LM_tf | exp_model_composition/fix/lstm+attention_fix+pretrained+entropy/reader.py | Python | mit | 7,849 | 0.009938 | """
modifier: Da-Rong Liu
Date: 2/01/2017
In this implementation, sentences of the same length are put into one bucket.
This helps to avoid doing padding.
Refenrence: https://github.com/ketranm/RMN/blob/master/text/TextProcessor.lua
"""
import collections
import os
import sys
import pickle
import numpy as np
from ra... | word]
except:
word_vector = np.random.uniform(-1/np.sqrt(300),1/np.sqrt(300),[300])
embedding_matrix[idx] = word_vector
return embedding_matrix
""" -------STATIC METHOD------- """
def establish_vocab(self):
print('loading train text file...')
... | (self.train_file)
all_words = []
count = 0
for sentence in train_data :
words = sentence.split()
if len(words) <= self.max_seq_length and len(words) >= self.min_seq_length :
all_words = all_words + words
count += 1
print 'finish p... |
weiawe/django | tests/timezones/tests.py | Python | bsd-3-clause | 54,664 | 0.001994 | from __future__ import unicode_literals
import datetime
import re
import sys
import warnings
from unittest import skipIf
from xml.dom.minidom import parseString
from django.contrib.auth.models import User
from django.core import serializers
from django.core.urlresolvers import reverse
from django.db.models import Max... | .replace(tzinfo=EAT), dt)
# This combination is no longer possible since timezone support
# was removed from the SQLite backend -- it didn't work.
@skipUnlessDBFeature('supports_timezones')
@skipUnlessDBFeature('needs_datetime_string_cast')
def test_aware_datetime_in_utc_unsupported(self):
... | rtIsNone(event.dt.tzinfo)
# django.db.backends.utils.typecast_dt will just drop the
# timezone, so a round-trip in the database alters the data (!)
# interpret the naive datetime in local time and you get a wrong value
self.assertNotEqual(event.dt.replace(tzinfo=EAT), dt)
# inter... |
shub0/algorithm-data-structure | python/strong_password_checker.py | Python | bsd-3-clause | 2,441 | 0.004506 | '''
A password is considered strong if below conditions are all met:
1. It has at least 6 characters and at most 20 characters.
2. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
3. It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "... | PasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0.
Insertion, deletion or replace of any one character are all considered as one change.
'''
class Solution(object):
def strongPasswordChecker(self, s):
| """
:type s: str
:rtype: int
"""
size = len(s)
missing_type = 3
if any('a' <= c <= 'z' for c in s):
missing_type -= 1
if any('A' <= c <= 'Z' for c in s):
missing_type -= 1
if any(c.isdigit() for c in s):
missing_typ... |
RHInception/talook | test/test_listhostshandler.py | Python | mit | 899 | 0 |
try:
import json
except ImportError:
import simplejson as json
from . import TestCase
from server import ListHostsHandler
class TestListHostsHandler(TestCase):
def setUp(self):
"""
Create an instance each time for testing.
"""
self.instance = ListHostsHandler()
def ... | fer = {}
def start_response(code, headers):
buffer['code'] = code
buffer['headers'] = headers
result = self.instance.__call__(environ, start_response)
assert buffer['code'] == '200 OK'
assert buffer['headers'] == [("Content-Type", "application/json")]
as... | |
adafruit/micropython | py/makemoduledefs.py | Python | mit | 3,304 | 0.000605 | #!/usr/bin/env python
# This pre-processor parses provided objects' c files for
# MP_REGISTER_MODULE(module_name, obj_module, enabled_define)
# These are used to generate a header with the required entries for
# "mp_rom_map_elem_t mp_builtin_module_table[]" in py/objmodule.c
from __future__ import print_function
imp... | file or None
"""
c_file = None
relative_c_file = os.path.splitext(obj_file)[0] + ".c"
relative_c_file = relative_c_file.lstrip('/\\')
for p in vpath:
possible_c_file = os.path.join(p, relative_c_file)
if os.path.exist | s(possible_c_file):
c_file = possible_c_file
break
return c_file
def find_module_registrations(c_file):
""" Find any MP_REGISTER_MODULE definitions in the provided c file.
:param str c_file: path to c file to check
:return: List[(module_name, obj_module, enabled_define)]
... |
google/report2bq | application/classes/sa360_reports.py | Python | apache-2.0 | 3,492 | 0.012314 | """
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... | lse:
_value = value
try:
for _element in _path_elements:
if not _data:
if field.is_list or field.ordinal:
_data = { _element: [_value] }
else:
_data = { _element: _value }
else:
_data = {_element: _data }
except KeyError as k:
... | turn _data
def prepare(self,
template: Dict[str, Any],
values: Dict[str, Any]) -> Dict[str, Any]:
_parameters = template['parameters']
_report = template['report']
for _parameter in _parameters:
_param = SA360ReportParameter(**_parameter)
with suppress(KeyError):... |
beeftornado/sentry | tests/acceptance/test_project_user_feedback.py | Python | bsd-3-clause | 1,515 | 0.00198 | from __future__ import absolute_import
from django.utils import timezone
from sentry.testutils import AcceptanceTestCase
class ProjectUserFeedbackTest(AcceptanceTestCase):
def setUp(self):
super(ProjectUserFeedbackTest, self).setUp()
self.user = self.create_user("foo@example.com")
self.o... | me="Mariachi Band", members=[self.user]
)
self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal")
self.login_as(self.user)
self.path | = u"/{}/{}/user-feedback/".format(self.org.slug, self.project.slug)
self.project.update(first_event=timezone.now())
def test(self):
group = self.create_group(project=self.project, message="Foo bar")
self.create_userreport(
date_added=timezone.now(),
group=group,
... |
refeed/coala | coalib/bearlib/languages/definitions/Java.py | Python | agpl-3.0 | 325 | 0 | from coalib.bearli | b.languages.Language import Language
@Language
class Java:
extensions = '.java',
comment_delimiter = '//'
multiline_comment_delimiters = {'/*': '*/'}
string_delimiters = {'"': '"'}
multiline_string_delimiters = {}
indent | _types = {'{': '}'}
encapsulators = {'(': ')', '[': ']'}
|
windskyer/k_nova | paxes_nova/objects/network/dom_kvm.py | Python | apache-2.0 | 30,773 | 0 | #
# =================================================================
# =================================================================
class IPAddress(object):
"""
An IP Address stores the level 3 information about a logical ethernet port.
The data can be ipv4 or ipv6.
"""
def __init__(self, ad... | faces, this class would be an interface.
"""
def __init__(self, name, state=None):
self.name = name
self.state = state
self.ip_addresses = []
def __eq__(self, other):
# Verify passed object is the same type
if type | (self) is not type(other):
return False
return self.__dict__ == other.__dict__
class PhysicalPort(LogicalEthernetPort):
"""
Represents a physical ethernet port on the system that a wire is connected
to. Typically, logical devices (bridges, bonds, vSwitches) are put on top
of thes... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/encodings/koi8_r.py | Python | unlicense | 1,888 | 0.003519 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: koi8_r.py
""" Python Character Mapping Code | c koi8_r gene | rated from 'MAPPINGS/VENDORS/MISC/KOI8-R.TXT' with gencodec.py.
"""
import codecs
class Codec(codecs.Codec):
def encode(self, input, errors='strict'):
return codecs.charmap_encode(input, errors, encoding_table)
def decode(self, input, errors='strict'):
return codecs.charmap_decode(input, err... |
X455u/SNLP | bin/python/sortclusters.py | Python | mit | 3,748 | 0.00587 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import ConfigParser
import unicodecsv
import json
import sys
import re
### FUNCTIONS FOR COUNTING CLUSTER STATISTICS ###
def text_statistics(texts):
lencount = 0
minlen = sys.maxint
maxlen = 0
for t in texts:
l = len(t.split())
... | some statistics
with open(config.get('clusters', 'clustertexts'),"w") as f:
for i in range(len(clusters)):
c = clusters[i]
# Ignore filler clusters
if len(c) > 1:
# Writing cluster info
f.write("Cluster: " + str(i+1) + " Texts: " + str(len(c) | ) + "\n")
stats = text_statistics(c)
f.write("Avg len: " + str(stats[0]) + " Min len: " + str(stats[2]) + " Max len: " + str(stats[1]) + "\n" )
# Sort the term counts by amount
sortedcounts = sort_counts(termclusters[i], termheader)
for am, t in sortedc... |
ljx0305/ice | python/test/Ice/application/Client.py | Python | gpl-2.0 | 1,738 | 0.001726 | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... | ased)")
self.sleep(5)
self.shutdownOnInterrupt()
print("Test shutdown on destroy. Press CT | RL+C to shutdown & terminate")
self.communicator().waitForShutdown()
print("ok")
return False
app = Client()
sys.exit(app.main(sys.argv))
|
ksmit799/Toontown-Source | toontown/hood/TrashcanInteractiveProp.py | Python | mit | 10,127 | 0.004542 | from direct.actor import Actor
from direct.directnotify import DirectNotifyGlobal
from toontown.hood import InteractiveAnimatedProp
from toontown.hood import GenericAnimatedProp
from toontown.toonbase import ToontownGlobals, ToontownBattleGlobals, TTLocalizer
class TrashcanInteractiveProp(InteractiveAnimatedProp.Inter... | 0,
0),
('tt_a_ara_ddl_trashcan_idleAwesome3',
| 1,
1,
None,
0,
0))}
ZoneToIdleIntoFightAnims = {ToontownGlobals.ToontownCentral: 'tt_a_ara_ttc_trashcan_idleIntoFight',
Toontown... |
atsaki/libcloud | libcloud/compute/types.py | Python | apache-2.0 | 9,475 | 0 | # 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 use ... | CLOUDFRAMES = 'cloudframes'
EXOSCALE = 'exoscale'
IKOULA = 'ikoula'
OUTSCALE_SAS = 'outscale_sas'
OUTSCALE_INC = 'outscale_inc'
VSPHERE = 'vsphere'
PROFIT_BRICKS = 'profitbricks'
VULTR = 'vultr'
AURORACOMPUTE = 'aurora_compute'
CLOUDWATT = 'cloudwatt'
PACKET = 'packet'
RUN... | ONAPP = 'onapp'
# Deprecated constants which are still supported
EC2_US_EAST = 'ec2_us_east'
EC2_EU = 'ec2_eu_west' # deprecated name
EC2_EU_WEST = 'ec2_eu_west'
EC2_US_WEST = 'ec2_us_west'
EC2_AP_SOUTHEAST = 'ec2_ap_southeast'
EC2_AP_NORTHEAST = 'ec2_ap_northeast'
EC2_US_WEST_OREGON =... |
lthurlow/Network-Grapher | proj/external/matplotlib-1.2.1/lib/mpl_examples/pylab_examples/major_minor_demo1.py | Python | mit | 1,660 | 0.00241 | #!/usr/bin/env python
"""
Demonstrate how to use major and minor tickers.
The two relevant userland classes are Locators and Formatters.
Locators determine where the ticks are and formatters control the
formatting of ticks.
Minor ticks are off by default (NullLocator and NullFormatter). You
can turn minor ticks on w... | ormatting but
don't label minor ticks
The MultipleLocator ticker class is used to place ticks on multiples of
some base. The FormatStrFormatter uses a string format string (eg
'%d' or '%1.2f' or '%1.1f cm' ) to format the tick
| The pylab interface grid command changes the grid settings of the
major ticks of the y and y axis together. If you want to control the
grid of the minor ticks for a given axis, use for example
ax.xaxis.grid(True, which='minor')
Note, you should not use the same locator between different Axis
because the locator st... |
vishnu-kumar/PeformanceFramework | tests/unit/plugins/openstack/scenarios/cinder/test_utils.py | Python | apache-2.0 | 15,937 | 0 | # Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | k.return_value,
update_resource=self.mock_get_from_manager.mock.return_value,
timeout=CONF.benchmark.cinder_volume_create_timeout,
check_interval=CONF.benchmark.cinder_volume_create_poll_interval
)
self.mock_resource_is.mock.assert_called_ | once_with("available")
self.mock_get_from_manager.mock.assert_called_once_with()
self.assertEqual(self.mock_wait_for.mock.return_value, return_volume)
self._test_atomic_action_timer(self.scenario.atomic_actions(),
"cinder.create_volume")
@mock.patch("r... |
ixs/dss_cli | DSS_Scraper.py | Python | gpl-2.0 | 28,370 | 0.005886 | #!/usr/bin/python
#
# A Python module to control an Open-E DSS Filer.
# Copyright (C) 2013 Andreas Thienemann <andreas@bawue.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the version 2 of the GNU General Public License
# as published by the Free So... | rver, "disp", moduleName, id, urllib.urlencode(args), random.random()))
else:
self.br.open("%s/XhrModuleLoader.php?opt=%s&_moduleName=%s&id=%s&__rand=%s" % (self.server, "disp", moduleName, id, random.random()))
return self.br.response().read()
def tree_index(self, id):
r"""Fetc... | module = self.module_list(id)
return dict(map(lambda x: (x["name"], x["dataLink"]), module["trees"]))
def tree_items(self, datalink):
r"""Parse the tree items included in a tree pane referenced by a dataLink URL"""
self.br.open("%s/%s&text=1&_rn=%s" % (self.server, datalink, random.random... |
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/sql/__init__.py | Python | mit | 1,376 | 0.00218 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | rceType
sql_custom = CliCommandType(operations_tmpl='azure.cli.command | _modules.sql.custom#{}')
super(SqlCommandsLoader, self).__init__(cli_ctx=cli_ctx,
custom_command_type=sql_custom,
resource_type=ResourceType.MGMT_SQL)
def load_command_table(self, args):
from azure.cli.c... |
gacarrillor/QGIS | tests/src/python/test_qgsserver_wfs.py | Python | gpl-2.0 | 39,125 | 0.003169 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsServer WFS.
From build dir, run: ctest -R PyQgsServerWFS -V
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the Licen... | (reference_path, 'rb')
expected = f.read()
f.close()
response = re.sub(RE_STRIP_UNCHECKABLE, b'', response)
expected = re.sub(RE_STRIP_UNCHECKABLE, b'', expected)
self.assertXMLEqual( | response, expected, msg="request %s failed.\n Query: %s" % (
query_string, request))
return header, body
def test_operation_not_supported(self):
qs = '?MAP=%s&SERVICE=WFS&VERSION=1.1.0&REQUEST=NotAValidRequest' % urllib.parse.quote(self.projectPath)
self._assert_status_code(501,... |
evanhenri/RNN-Trading-Bot | pyTrader/file_check.py | Python | mit | 3,068 | 0.003259 | import os, sqlite3
from sys import exit
missing_auth_dir = ' neural-network-trading-bot/pyTrader/auth not found.\n' \
' auth directory has been created'
missing_data_dir = ' neural-network-trading-bot/pyTrader/data not found.\n' \
' data directory has been created'
missing... | al-network-trading-bot/pyTrader/auth/api-credentials.json not found.\n' \
' Credentials json format should be\n' \
' {"api_secret": "your-account-secret", "api_key": "your-api-key"}'
missing_directory = []
missing_data = []
parent_dir = os.path.dirname(os.pa... |
def notify_missing_directory():
for directory in missing_directory:
print(directory + '\n')
def notify_missing_data():
for files in missing_data:
print(files + '\n')
def check_data_files():
if not os.path.exists('auth'):
os.makedirs('auth')
missing_directory.append(missing... |
josenavas/QiiTa | qiita_pet/handlers/study_handlers/tests/test_ebi_handlers.py | Python | bsd-3-clause | 1,996 | 0 | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | h File(demux_fp, "w") as f:
to_hdf5(fna_fp, f)
BaseHandler.get_current_user = Mock(return_value=User("admin@foo.bar"))
response = self.get("/eb | i_submission/2")
self.assertEqual(response.code, 200)
def test_get_no_admin(self):
response = self.get("/ebi_submission/2")
self.assertEqual(response.code, 403)
def test_get_no_exist(self):
response = self.get('/ebi_submission/100')
self.assertEqual(response.code, 404)
... |
mscuthbert/abjad | abjad/tools/scoretools/test/test_scoretools_Measure_should_scale_contents.py | Python | gpl-3.0 | 544 | 0.001838 | # -*- encoding: utf-8 -*-
from abjad import *
def test_scoretools_Measure_should_scale_contents_01():
tuplet = Tuplet((2, 3), "c'8 d'8 e'8 f'8 g'8")
measure = Measure((5, 12), [tuplet], implicit_scaling=False)
assert systemtools.TestManager.c | ompare(
measure,
r'''
{
\time 5/12
\tweak #'edge-height #'(0.7 . 0)
\times 2/3 {
c'8
d'8
e | '8
f'8
g'8
}
}
'''
) |
Ali-aqrabawi/ezclinic | lib/djangae/contrib/gauth/backends.py | Python | mit | 482 | 0.006224 | """This file exists for backwards compatability.
Pleas | e use the separate backends found in either `djangae.contrib.gauth.datastore.backends` or
`djangae.contrib.gauth.sql.backends`.
"""
import warnings
from djangae.contrib.gauth.datastore.backends impo | rt AppEngineUserAPIBackend
warnings.warn(
'AppEngineUserAPI is deprecated. Please use the specific backends from gauth.datastore '
'or gauth.sql instead.'
)
class AppEngineUserAPI(AppEngineUserAPIBackend):
pass
|
weiting-chen/manila | contrib/tempest/tempest/api/share/admin/test_share_servers_negative.py | Python | apache-2.0 | 4,715 | 0 | # Copyright 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2 | .0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an... | s and limitations
# under the License.
from tempest_lib.common.utils import data_utils # noqa
from tempest_lib import exceptions as lib_exc # noqa
from tempest.api.share import base
from tempest import clients_share as clients
from tempest import test
class ShareServersNegativeAdminTest(base.BaseSharesAdminTes... |
samwhelp/demo-libchewing | python/prototype/chewing_userphrase_remove/20-module/main.py | Python | mit | 211 | 0.030303 | #!/usr/bin/e | nv python3
from chewing import userphrase
def main():
phrase = '內稽'
bopomofo = 'ㄋㄟˋ ㄐㄧ'
rtn = userphrase.remove(phrase, bopomofo)
pri | nt(rtn)
if __name__ == '__main__':
main()
|
Wintellect/WintellectWebinars | 2019-06-06-ten-tips-python-web-devs-kennedy/code/top_10_web_explore/ex02_ngrok/pypi_org/app.py | Python | apache-2.0 | 680 | 0 | import | os
import flask
import pypi_org.data.db_session as db_session
app = flask.Flask(__name__)
def main():
register_blueprints()
setup_db()
app.run(debug=True)
def setup_db():
db_file = os.path.join(
os.path.dirname(__file__),
'db',
'pypi.sqlite')
db_session.global_init(db_ | file)
def register_blueprints():
from pypi_org.views import home_views
from pypi_org.views import package_views
from pypi_org.views import cms_views
app.register_blueprint(package_views.blueprint)
app.register_blueprint(home_views.blueprint)
app.register_blueprint(cms_views.blueprint)
if __... |
goldsborough/your_app | setup.py | Python | mit | 1,451 | 0.024121 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
setup.py script for setuptools.
"""
import re
from setuptools import setup, find_packages
version = ''
with open('your_app/__init__.py') as init:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
init.read(), re.MULTILINE).group(1)
with open('R... | ogramming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Pyt | hon :: 3.4',
],
keywords='your_app',
include_package_data=True,
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
install_requires=requirements,
test_suite="tests",
tests_require=test_requirements
)
|
raviagarwal7/buck | docs/soy2html.py | Python | apache-2.0 | 3,176 | 0.000315 | #!/usr/bin/env python
#
# This script is designed to be invoked by soy2html.sh.
# Usage:
#
# buck/docs$ python soy2html.py <output_dir>
#
# This will write all of the static content to the specified output directory.
# You may want to verify that things worked correctly by running:
#
# python -m SimpleHTTPServer ... | _subdir)
return os.path.join(output_dir, path)
def copy_to_output_dir(path, output_dir, content):
output_file = ensure_dir(path, output_dir)
with open(output_file, 'w') as f:
f.write(content)
def pollForServerReady():
SERVER_START_POLL = 5
print 'Waiting for server to start.'
for _ ... | 0:
return
time.sleep(1)
print 'Server failed to start after %s seconds.' % SERVER_START_POLL
if __name__ == '__main__':
output_dir = sys.argv[1]
pollForServerReady()
main(output_dir)
|
dparalen/dva | dva/test/testcase_03_running_services.py | Python | gpl-2.0 | 1,272 | 0.003931 | """ This module contains testcase_03_running_services test """
from testcase import Testcase
import yaml
class testcase_03_running_services(Testcase):
"""
Check for running services
| """
stages = ['stage1']
tags = ['default']
def test(self, connection, params):
""" Perform test """
prod = params['product'].upper()
ve | r = params['version']
with open(self.datadir + '/running_services.yaml') as expected_services_fd:
all_services = yaml.safe_load(expected_services_fd)
try:
expected_services = all_services['%s_%s' % (prod, ver)]
except KeyError:
self.log.append({
... |
damoti/shipmaster | shipmaster/plugins/ssh/__init__.py | Python | bsd-3-clause | 54 | 0 | plugin_class = " | shipmaster.plugins.ssh.ssh.SS | HPlugin"
|
repotvsupertuga/tvsupertuga.repository | script.module.streamtvsupertuga/lib/resources/lib/sources/en/ultrahd.py | Python | gpl-2.0 | 6,083 | 0.013809 | # -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want wit... | url = {'imdb': imdb, 'title': title, 'year': year}
url = urllib.urlencode(url)
return url
except:
failure = traceback.format_exc()
log_utils.log('UltraHD - Exception: \n' + str( | failure))
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
if url == None: return sources
if debrid.status() is False: raise Exception()
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] els... |
alphagov/digitalmarketplace-api | migrations/versions/1280_tidy_up_latent.py | Python | mit | 633 | 0.004739 | """tidy_up_latent
Tidy up a latent migration not previously picked up by alembic or ignored.
Revision ID: 1280
Revises: | 1270
Create Date: 2019-06-10 15:51:48.661665
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1280'
down_revision = '1270'
def upgrade():
# this field not has a "unique index" instead of a "unique constraint"
op.drop_constraint('uq_direct_award_proje... | .create_unique_constraint('uq_direct_award_projects_external_id', 'direct_award_projects', ['external_id'])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.