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 |
|---|---|---|---|---|---|---|---|---|
hellux/3d-projection | legacy/renderer_py/lib/matrix.py | Python | unlicense | 2,040 | 0.007353 | def matrix_multiply(A, B):
"""returns the product (matrix) of matrices A and B
or number A and vector B"""
if isinstance(A, (tuple, list)) and isinstance(B, (tuple, list)):
return _mm_multiply(A, B)
elif isinstance(A, (int, float)) and isinstance(B, (tuple, list)):
return _nm_multiply(A,... | C) == ((0.6000000000000001, -0.700000000000 | 0001), (-0.2, 0.4))
print('All tests were successful, no errors!')
if __name__ == '__main__':
test()
|
pingviini/pikacon | docs/source/conf.py | Python | gpl-3.0 | 8,016 | 0.007111 | # -*- coding: utf-8 -*-
#
# Pikacon documentation build configuration file, created by
# sphinx-quickstart on Wed Apr 3 22:19:40 2013.
#
# 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.
#
# All... | age file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as s | tyle sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#htm... |
google-research/xtreme | third_party/evaluate_retrieval.py | Python | apache-2.0 | 30,770 | 0.01287 | # coding=utf-8
# Copyright The XTREME Benchmark Authors.
# Copyright (c) 2018, NVIDIA CORPORATION. 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.apa... | e))
num_sents = len(sent_toks)
all_embeds = [np.zeros(shape=(num_sents, args.embed_size), dtype=np.float32) for _ in range(num_embeds)]
for i in tqdm(range(num_batch), desc='Batch'):
start_index = i * batch_size
end_index = min((i + 1) * batch_size, num_sents)
batch, pool_mask = prepare_batch(sent_to... | args.device,
args.max_seq_length,
lang=lang,
langid=langid,
pool_skip_special_token=args.pool_skip_special_token)
with torch.no_grad():
outputs = model(**b... |
Aravinthu/odoo | addons/calendar/wizard/__init__.py | Python | agpl-3.0 | 126 | 0 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file fo | r full copyright and licensing details | .
from . import mail_invite
|
JoseALermaIII/python-tutorials | pythontutorials/books/CrackingCodes/Ch22/PracticeQuestions.py | Python | mit | 1,117 | 0.006267 | """Chapter 22 Practice Questions
Answers Chapter 22 Practice Questions via Python code.
"""
from pythontutorials.b | ooks.CrackingCodes.Ch18.vigenereCipher import decryptMessage
def main():
# 1. How many prime numbers are there?
# Hint: Check page 322
message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 2. What are ... | grd." # Encrypted with key "NOTCALLEDEVENS"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 3. What are two algorithms for finding prime numbers?
# Hint: Check page 323
# Encrypted with key "ALGORITHMS"
message = "Tsk hyzxl mdgzxwkpfz gkeo ob kpbz ngov gfv: bkpmd dtbwjqhu, eaegk cw Mk... |
taigaio/taiga-back | taiga/events/backends/rabbitmq.py | Python | agpl-3.0 | 2,914 | 0.004461 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-present Taiga Agile LLC
#
# 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 ver... | self.url)
log.error(err_msg, exc_ | info=True)
else:
try:
message = AmqpMessage(message)
rchannel = connection.channel()
rchannel.exchange_declare(exchange=channel, type="topic", auto_delete=True)
rchannel.basic_publish(message, routing_key=routing_key, exchange=channel)... |
saradbowman/osf.io | api_tests/nodes/views/test_node_children_list.py | Python | apache-2.0 | 29,554 | 0.00159 | import pytest
from api.base.settings.defaults import API_BASE
from framework.auth.core import Auth
from osf.models import AbstractNode, NodeLog
from osf.utils import permissions
from osf.utils.sanitize import strip_html
from osf_tests.factories import (
NodeFactory,
ProjectFactory,
OSFGroupFactory,
Reg... | nt, private_project, private_project_url):
# test_return_private_node_children_list_logged_out
res = app.get(private_project_url, expect_errors=True)
assert res.status_code == 401
assert 'detail' in res.json['errors'][0]
# test_return_priv | ate_node_children_list_logged_in_non_contributor
non_contrib = AuthUserFactory()
res = app.get(
private_project_url,
auth=non_contrib.auth,
expect_errors=True)
assert res.status_code == 403
assert 'detail' in res.json['errors'][0]
# test_return_... |
HenriqueLR/payments | app/conf/middleware.py | Python | mit | 627 | 0.030303 | from django.conf import settings
from django.utils import translation
|
class MenuLeft(object):
'''
Middleware init leftmenu status
'''
def process_request(self, request):
if not request.session.has_key('leftmenu'):
request.session['leftmenu'] = True
class ForceDefaultLanguage(object):
'''
Force language default settings
'''
def process_request(self, request):
if request... | '):
del request.META['HTTP_ACCEPT_LANGUAGE']
request.LANG = getattr(settings, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)
translation.activate(request.LANG)
request.LANGUAGE_CODE = request.LANG |
916253/Kurisu | addons/auto_probation.py | Python | apache-2.0 | 354 | 0.002825 | class AutoProbation:
"""
Logs join and leave messages.
"""
def __init__(self, bot):
self.bot = b | ot
print('Addo | n "{}" loaded'.format(self.__class__.__name__))
async def on_member_join(self, member):
await self.bot.add_roles(member, self.bot.probation_role)
def setup(bot):
bot.add_cog(AutoProbation(bot))
|
ebukoz/thrive | erpnext/support/doctype/issue/issue.py | Python | gpl-3.0 | 16,641 | 0.023436 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
import json
from frappe import _
from frappe import utils
from frappe.model.document import Document
from frappe.utils import now, time_di... | f set_response_and_resolution_time(self, priority=None, service_level_agreement=None):
service_level_agreement = get_active_service_level_agreement_for(priority=priority,
customer=self.customer, service_level_agreement=service_level_agreement)
if not service_level_agreement:
if frappe.db.get_value("Issue", s... | f.service_level_agreement))
return
if (service_level_agreement.customer and self.customer) and not (service_level_agreement.customer == self.customer):
frappe.throw(_("This Service Level Agreement is specific to Customer {0}").format(service_level_agreement.customer))
self.service_level_agreement = service_... |
SpaceGroupUCL/qgisSpaceSyntaxToolkit | esstoolkit/external/networkx/algorithms/asteroidal.py | Python | gpl-3.0 | 5,811 | 0 | """
Algorithms for asteroidal triples and asteroidal numbers in graphs.
An asteroidal triple in a graph G is a set of three non-adjacent vertices
u, v and w such that there exist a path between any two of them that avoids
closed neighborhood of the third. More formally, v_j, v_k belongs to the same
connected component... | kx as nx
from networkx.utils import not_implemented_for
__all__ = ["is_at_free", "find_asteroidal_triple"]
@not_implemented_for("directed")
@not_implemented_for("multigraph")
def find_asteroidal_triple(G):
r"""Find an asteroidal triple in the given graph.
An asteroidal triple is a triple of non-adjacent ver... | such that
there exists a path between any two of them which avoids the closed
neighborhood of the third. It checks all independent triples of vertices
and whether they are an asteroidal triple or not. This is done with the
help of a data structure called a component structure.
A component structure ... |
ardekantur/pyglet | pyglet/app/cocoa.py | Python | bsd-3-clause | 7,023 | 0.002421 | # ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistribu... | OF L | IABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------------
'''
'''
from __future__ import with_st... |
lokik/sfepy | tests/test_functions.py | Python | bsd-3-clause | 5,962 | 0.010902 | # c: 14.04.2008, r: 14.04.2008
from __future__ import absolute_import
import numpy as nm
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/2d/square_unit_tri.mesh'
def get_pars(ts, coors, mode=None, extra_arg=None,
equations=None, term=None, problem=None, **kwargs):
if mode == 'special'... | problem.domain.get_mesh_coors()
assert_(nm.all(coors[:,0] == mat1.get_data(None, 'x_0')))
conf_mat2 = conf.get_item_by_name('materials', 'mf2')
mat2 = Material.from_conf(conf_mat2, problem.functions)
mat2.time_update(ts, None, mode='normal', problem=problem)
assert_(nm.all(coor... | problem=problem)
mat3 = materials['mf3']
key = mat3.get_keys(region_name='Omega')[0]
assert_(nm.all(mat3.get_data(key, 'a') == 10.0))
assert_(nm.all(mat3.get_data(key, 'b') == 2.0))
assert_(mat3.get_data(None, 'c') == 'ahoj')
return True
def test_ebc_funct... |
stdlib-js/stdlib | lib/node_modules/@stdlib/complex/float32/benchmark/python/benchmark.py | Python | apache-2.0 | 2,166 | 0 | #!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | summary(REPEATS, REPEATS)
def main():
"""Run the benchmark."""
benchmark()
if __name__ == "__main__":
ma | in()
|
andres-erbsen/rrtcp | results/scripts/plotting.py | Python | apache-2.0 | 1,242 | 0.005636 | """
Demo of the histogram (hist) function used to plot a cumulative distribution.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import mlab
def plot_loss_over_time(file_name):
with open(file_name, 'r') as f:
lines = f.readlines()
events = order_events(lines)
packets_sent ... | nt)
plt.plot(time_stamps, packet_percent)
plt.show()
def order_events(lines):
events = []
for line in lines:
split_line = line.split(" ")
send_time = int(split_line[0])
recv_time = int(split_line[1])
events.append((send_time, 's'))
events.append((recv_time, 'r... | ")
# 1. time on x-axis, percent packets received on y-axis
# 2. loss percentage on x-axis, 90 percentile latency on y-axis
# time packet sent, time packet received in nanoseconds
|
ciudadanointeligente/votainteligente-portal-electoral | elections/migrations/0021_auto_20151008_1526.py | Python | gpl-3.0 | 928 | 0.001078 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def from_election_to_elections(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Election = a... | ns.RunPython(from_el | ection_to_elections),
]
|
Talvalin/server-client-python | tableauserverclient/server/request_options.py | Python | mit | 1,429 | 0.0014 | class RequestOptions(object):
class Operator:
Equals = 'eq'
GreaterThan = 'gt'
GreaterThanOrEqual = 'gte'
LessThan = 'lt'
| LessThanOrEqual = 'lte'
In = 'in'
class Field:
CreatedAt = 'createdAt'
LastLogin = 'lastLogin'
Name = 'name'
OwnerName = 'ownerName'
SiteRole = 'siteRole'
Tags = 'tags'
| UpdatedAt = 'updatedAt'
class Direction:
Desc = 'desc'
Asc = 'asc'
def __init__(self, pagenumber=1, pagesize=100):
self.pagenumber = pagenumber
self.pagesize = pagesize
self.sort = set()
self.filter = set()
def page_size(self, page_size):
self.... |
Aravinthu/odoo | addons/account/models/account_analytic_line.py | Python | agpl-3.0 | 3,182 | 0.0044 | # -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from math import copysign
class AccountAnalyticLine(models.Model):
_inherit = 'account.analytic.line'
_description = 'Analytic Line'
_order = 'date desc'
amount = fields.Monetary(currency_field='company_currency_id')
product_uom_id ... | n the related account currency if not equal to the company one.", readonly=True)
| partner_id = fields.Many2one('res.partner', related='account_id.partner_id', string='Partner', store=True, readonly=True)
def _get_analytic_amount_currency(self):
for line in self:
line.analytic_amount_currency = abs(line.amount_currency) * copysign(1, line.amount)
@api.v8
@api.onc... |
ai-ku/langvis | jython-2.1/Lib/test/zxjdbc/runner.py | Python | mit | 4,782 | 0.031159 |
# Jython Database Specification API 2.0
#
# $Id: runner.py,v 1.1 2001/12/14 04:20:03 bzimmer Exp $
#
# Copyright (c) 2001 brian zimmer <bzimmer@ziclix.com>
"""
To run the tests, simply invoke this script from the commandline:
jython runner.py <xml config file> [vendor, ...]
If no vendors are given, then all vendor... | e'], getattr(__builtin__, attrs['type'])(self.value(attrs['value']))))
else:
f.arguments.append((attrs['name'], self.value(attrs['value'])))
def start_keyword(self, attrs):
f = self.factory()
if attrs.has_key('type'):
f.keywords[attr | s['name']] = getattr(__builtin__, attrs['type'])(self.value(attrs['value']))
else:
f.keywords[attrs['name']] = self.value(attrs['value'])
def start_ignore(self, attrs):
t = self.testcase()
t.ignore.append(attrs['name'])
def start_testcase(self, attrs):
c = self.test()
c.tests.append(Testcase(attrs['fro... |
58daojia-dba/mysqlbinlog_flashback | joint_sql.py | Python | apache-2.0 | 10,015 | 0.021486 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
v0.1.2 2016/12/19 yilai 建表改成utf8mb4字符集
v0.1.1 2016/09/21 yilai 加了些参数
v0.1.0 2016/07/20 yilai created
"""
from datetime import datetime,date,timedelta
from decimal import Decimal
import traceback
import logging
from pymysqlreplication import BinLogStreamReader
... | columns)
statment_value=",".join(values)
sql=u"insert into "+table_name+"("+statment_column+ ") va | lues("+statment_value+")"
logger.debug(sql)
return sql
def generate_keep_data_dict(target,prefix,row):
for key in row:
target[u""+prefix+"_"+ke |
Haellsigh/yawl | settings.py | Python | mit | 3,170 | 0.024921 | MONGO_HOST = 'localhost'
MONGO_PORT = 27017
X_DOMAINS = '*'
X_HEADERS = ['Content-Type']
CACHE_CONTROL = 'no-cache'
CACHE_EXPIRES = 0
IF_MATCH = False
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
XML = False
EMBEDDING = True
## ## ## ## ##
## animes definition
## ## ... | ama","Ecchi","Fan | tasy","Game","Harem","Hentai","Historical","Horror","Josei","Kids","Magic","Martial Arts","Mecha","Military","Music","Mystery","Parody","Police","Psychological","Romance","Samurai","School","Sci-Fi","Seinen","Shoujo","Shoujo Ai","Shounen","Shounen Ai","Slice of Life","Space","Sports","Super Power","Supernatural","Thril... |
brandoncurtis/Anmr | bin/anmr_platform_win.py | Python | gpl-3.0 | 6,305 | 0.018239 | #from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar2
from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar2
import subprocess
import shlex
import re
import posixpath
from anmr_common import *
# use hub4com ?
USE_SERIAL_PIPE=False
#external hel... | 'home', 'home'),
('Back', 'Back to previous view','back', 'back'),
('Forward', 'Forward to next view','forward', 'forward'),
('Pan', 'Pan axes with left mouse, zoom with | right', 'move','pan'),
('Zoom', 'Zoom to rectangle','zoom_to_rect', 'zoom'),
(None, None, None, None),
# ('Subplots', 'Configure subplots','subplots.png', 'configure_subplots'),
('Save', 'Save the figure','filesave', 'save_figure'),
)
#windows specific count serial ports:
def ... |
baritone-snake-studios/flappyturtle | flappyturtle/objects/collision.py | Python | mit | 505 | 0.00198 | """
Pixel perfect collision algorithm
From http: | //www.pygame.org/wiki/FastPixelPerfect?parent=CookBook
"""
import pygame
def pixel_perfect_check_collision(obj1, obj2):
| image_mask = pygame.mask.from_surface(obj1.image)
otherimage_mask = pygame.mask.from_surface(obj2.image)
offset_x = obj1.rect.left - obj2.rect.left
offset_y = obj1.rect.top - obj2.rect.top
if image_mask.overlap(otherimage_mask, (offset_x, offset_y)) is not None:
return True
else:
... |
gavinfish/leetcode-share | python/126 Word Ladder II.py | Python | mit | 3,018 | 0.002319 | '''
Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the word list
For example,
Given:
beginWord = "hit"
endWord = "cog"
word... | end(path)
return
if word in path_dic:
for item in path_dic[word]:
construct_path(item, end_word, path_dic, path + [item], paths)
front_level, end_level = {beginWord}, {endWord}
path_dic = {}
bfs(front_level, end_level, True... | e__ == "__main__":
assert Solution().findLadders("hit", "cog", {"hot", "dot", "dog", "lot", "log"}) == [
["hit", "hot", "dot", "dog", "cog"],
["hit", "hot", "lot", "log", "cog"]
] |
TransientObject/labMTComparison | labMT-simple/labMTsimple/data/NRC/load_NRC.py | Python | apache-2.0 | 1,238 | 0.010501 | # coding: utf-8
f = open("Sentiment140-Lexicon-v0.1/unigrams-pmilexicon.txt","r")
unigrams = dict()
for line in f:
word,score,poscount,negcount = line.rstrip().split("\t")
unigrams[word] = score
f.close()
# len(unigrams)
f = open("Sentiment140-Lexicon-v0.1/bigrams-pmilexicon.txt","r")
bigrams = dict()
for line... | igrams[word] = score
f.close()
# len(bigrams)
f = open("Sentiment140-Lexicon-v0.1/pairs-pmilexicon.txt","r")
pairs = dict()
for line in f:
| word,score,poscount,negcount = line.rstrip().split("\t")
pairs[word] = score
f.close()
# len(pairs)
# len(pairs)+len(bigrams)+len(unigrams)
# all = unigrams.copy()
# len(all)
# all.update(bigrams)
# all.update(pairs)
# len(all)
# pos_words = [word for word in all if all[word] > 0]
# neg_words = [word for w... |
kubeflow/pipelines | components/kubeflow/pytorch-launcher/sample.py | Python | apache-2.0 | 6,178 | 0.000486 | import json
from typing import NamedTuple
from collections import namedtuple
import kfp
import kfp.dsl as dsl
from kfp import components
from kfp.dsl.types import Integer
def get_current_namespace():
"""Returns current namespace if available, else kubeflow"""
try:
current_namespace = open(
... | b.com/kubeflow/website/issues/2011
"sidecar.istio.io/inject": "false"
}
},
"spec": {
"containers": [
{
# To override default command
# "command": [
# ... | # "/opt/mnist/src/mnist.py"
# ],
"args": [
"--backend",
"gloo",
],
# Or, create your own image from
# https://github.com/kubeflow/pytorch-op... |
carschar/socketio-demo | simple/pingping_proj/settings.py | Python | unlicense | 5,136 | 0.00331 | # Django settings for pingpong project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', ... | n': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'console':{
... | 'class':'logging.StreamHandler',
'formatter': 'simple'
},
},
'loggers': {
'django': {
'handlers':['console'],
'propagate': True,
'level':'INFO',
},
'socketio': {
'handlers':['console'],
'propagate': True,
... |
pombredanne/sortinghat | tests/test_matcher_email.py | Python | gpl-3.0 | 15,326 | 0.002153 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2015 Bitergia
#
# 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 la... | with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Authors:
# Santiago Dueñas <sduenas@bitergia.com>
#
from __future__ import unicode_literals
import sys
import unittest
if not '..' in s | ys.path:
sys.path.insert(0, '..')
from sortinghat.db.model import UniqueIdentity, Identity, MatchingBlacklist
from sortinghat.matching.email import EmailMatcher, EmailIdentity
class TestEmailMatcher(unittest.TestCase):
def test_match(self):
"""Test match method"""
# Let's define some identi... |
henkelis/sonospy | sonospy/brisa/upnp/control_point/__init__.py | Python | gpl-3.0 | 561 | 0 | # L | icensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2007-2008 Brisa Team <brisa-develop@garage.maemo.org>
""" Provides a UPnP control point API.
"""
from brisa.upnp.control_point.control_point import ControlPoint
from brisa.upnp.control_point.control_point_av import ControlPoint... | evice
from brisa.upnp.control_point.msearch import MSearch
|
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/services/webapp/tests/test_navigation.py | Python | agpl-3.0 | 3,377 | 0.000592 | # Copyright 2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
from zope.component import (
ComponentLookupError,
getMultiAdapter,
)
from zope.configuration import xmlconfig
from zope.interface import (
im... | DefaultBrowserLayer()), IBrowserPublisher, name='')
other_navigation = getMultiAdapter(
(Thing(), OtherLayer()), IBrowserPublisher, name='')
self.assertNotEqual(navigation, other_navigation)
def tearDown(self):
TestCase.tearDown(self)
cleanUp()
class DefaultBrowserLaye... | class IThing(Interface):
pass
class Thing(object):
implements(IThing)
class ThingNavigation(Navigation):
usedfor = IThing
class OtherThingNavigation(Navigation):
usedfor = IThing
class IOtherLayer(Interface):
pass
class OtherLayer:
implements(IOtherLayer)
this = "lp.services.webapp.t... |
cberner/rospilot | src/rospilot/msg/__init__.py | Python | apache-2.0 | 103 | 0 | from ._Attitu | de import *
from ._BasicStatus import *
from ._BasicMode import | *
from ._RCState import *
|
pkkao/musicbot | cogs/economy.py | Python | gpl-3.0 | 25,638 | 0.006514 | import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from collections import namedtuple, defaultdict
from datetime import datetime
from random import randint
from random import choice as randchoice
from copy import deepcopy
from .utils import checks
from __main__ import send_cmd_help
imp... | user = ctx.message.author
credits = 0
if ctx.message.server.id in self.settings:
credits = self.settings[ctx.message.server.id].get("REGISTER_CREDITS", 0)
try:
account = self.bank.create_account(user, initial_balance= | credits)
await self.bot.say("{} Account opened. Current balance: {}".format(user.mention,
account.balance))
except AccountAlreadyExists:
await self.bot.say("{} You already have an account at the goodchat bank.".format(user.mention))
@_bank.command(pass_context=True)
... |
ghchinoy/tensorflow | tensorflow/python/tpu/ops/tpu_ops.py | Python | apache-2.0 | 18,915 | 0.002855 | # 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... | the source column. Also it must
only appear once in the target column.
For the replica id not in the target column, this op returns a zero tensor
with the same shape an | d dtype of the input x.
For example, suppose there are 4 TPU instances: `[A, B, C, D]`. Passing
source_target_pairs=`[[0,1],[1,2],[2,3]]` gets the outputs:
`[0, A, B, C]`.
Args:
x: The local tensor to be permuted.
source_target_pairs: 2d int lists with shape [num_pairs, 2].
source_target_pairs[i... |
nobukatsu/deep-learning-from-scratch | ch04/train_neuralnet.py | Python | mit | 2,006 | 0.005513 | import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
import matplotlib.pyplot as plt
from dataset.mnist import | load_mnis | t
from two_layer_net import TwoLayerNet
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)
network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)
train_loss_list = []
train_acc_list = []
test_acc_list = []
# ハイパーパラメータ
iters_num = 10000
train_size = x_train.shape[0]... |
qedi-r/home-assistant | tests/components/homematicip_cloud/test_device.py | Python | apache-2.0 | 4,403 | 0.001363 | """Common tests for HomematicIP devices."""
from homeassistant.const import STATE_ON, STATE_UNAVAILABLE
from homeassistant.helpers import device_registry as dr, entity_registry as er
from .conftest import get_mock_hap
from .helper import async_manipulate_test_data, get_and_check_entity_basics
async def test_hmip_rem... | _block_till_done()
assert len(device_registry.devices) == pre_device_count
assert len(entity_registry.entities) == pre_entity_count - 1
assert len(default_mock_hap.hmip_device_by_entity_id) == pre_mapping_count - 1
async def test_all_devices_unavailable_when_hap_not_connected(hass, default_mock_hap):
... | all devices unavaulable when hap is not connected."""
entity_id = "light.treppe"
entity_name = "Treppe"
device_model = "HmIP-BSL"
ha_state, hmip_device = get_and_check_entity_basics(
hass, default_mock_hap, entity_id, entity_name, device_model
)
assert ha_state.state == STATE_ON
a... |
SerpentCS/purchase-workflow | product_supplierinfo_discount/models/product_supplierinfo.py | Python | agpl-3.0 | 753 | 0 | # -*- coding: utf-8 -*-
# © 2014 Serv. Tecnol. Avanzados | (http://www.servic | iosbaeza.com)
# Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>
# © 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
import openerp.addons.decimal_precision as dp
class ProductSupplierInfo(models.Model):
_inheri... |
maxive/erp | addons/report_intrastat/tests/test_report_intrastat.py | Python | agpl-3.0 | 1,119 | 0.002681 | # -*- coding: utf-8 -*-
from odoo import tools
fr | om odoo.tests import common
from odoo.modules.module import get_module_resource
class RepoortIntrastatTest(common.TransactionCase):
def _load(self, module, *args):
tools.convert_f | ile(self.cr, 'report_intrastat',
get_module_resource(module, *args),
{}, 'init', False, 'test', self.registry._assertion_report)
def setUp(self):
super(RepoortIntrastatTest, self).setUp()
self._load('account', 'test', 'account_minimal_test.xml'... |
csdms/bmi-live-2017 | .totally-hidden-directory/bmi_diffusion.py | Python | mit | 7,347 | 0.000136 | """Basic Model Interface (BMI) for the Diffusion model."""
import numpy as np
from basic_modeling_interface import Bmi
from .diffusion import Diffusion
class BmiDiffusion(Bmi):
"""BMI for the Diffusion model."""
_name = 'Diffusion model'
_input_var_names = ('plate_surface__temperature',)
_output_va... | ion model that's ready for initialization."""
self._model = None
self._values = {}
self._var_units = {}
self._grids = {}
self._grid_type = {}
def initialize(self, filename=None):
"""Initialize the Diffusion model.
Parameters
----------
filena... | fig_file=filename)
self._values = {
'plate_surface__temperature': self._model.temperature,
}
self._var_units = {
'plate_surface__temperature': 'K'
}
self._grids = {
0: ['plate_surface__temperature']
}
self._grid_type = {
... |
Ecpy/ecpy | exopy/instruments/drivers/driver_decl.py | Python | bsd-3-clause | 10,506 | 0 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015-2018 by Exopy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------... | fault_architecture(self):
"""Default value grabbed from parent if not provided explicitely.
"""
return self._get_inherited_member('architecture')
def _default_starter(self):
"""Default value grabbed from parent if not provided explicitely.
"""
return self._get_inhe... | rom parent if not provided explicitely.
"""
return self._get_inherited_member('connections')
def _default_settings(self):
"""Default value grabbed from parent if not provided explicitely.
"""
return self._get_inherited_member('settings')
def _get_inherited_member(self... |
algorhythms/LeetCode | 097 Interleaving String.py | Python | mit | 2,718 | 0.001472 | """
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
"""
__author__ = 'Danyang'
class Solution(object):
def isInterleave(self, s1, s2, s3):
... | if self.isInterleave(s1[1:], s2, s3[1:]):
return True
if s2 and s2[0] == letter:
if self.isInterleave(s1, s2[1:], s3[1:]):
return True
return False
if __name__ == "__main__":
assert Solution().isInterleave("aa", "ab", "abaa") == Tru | e
assert Solution().isInterleave("aabcc", "dbbca", "aadbbcbcac") == True
assert Solution().isInterleave("aabcc", "dbbca", "aadbbbaccc") == False |
Diacamma2/asso | diacamma/asso/docs/fr/conf.py | Python | gpl-3.0 | 9,294 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Diacamma Asso documentation build configuration file, created by
# sphinx-quickstart on Tue Dec 22 17:11:37 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 thi... | ue
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pages = {}
# If false, no module index is generated.
html_domain_indices = True
# If false, no index is generated.
... | to the pages.
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = True
# If true, an OpenSearch description file will be output, and all... |
Jakeable/Ralybot | plugins/imgur.py | Python | gpl-3.0 | 4,408 | 0.001588 | import re
import random
from imgurpython import ImgurClient
from contextlib import suppress
from ralybot import hook
from ralybot.util import web
# imgurpython has an issue where it does not allow anonymous album creation
# to fix this we monkeypatch logged_in to disable login checking
# yes, it's kinda dirty, but ... | memes / random - returns a link to a random imgur image based
on your input. if | no input is given the bot will get an image from the imgur frontpage """
text = text.strip().lower()
if not imgur_api:
return "No imgur API details"
if text == "apicredits":
return imgur_api.credits
items, is_reddit = get_items(text)
if not items:
return "No results foun... |
wijnandb/CodeCult-Scratch | tests/unit/common_locales.py | Python | apache-2.0 | 2,868 | 0.000349 | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | ))
def test_rejects_invalid_syntax(self):
self.assertEqual(
[('el', 1.0), ('fr', 1.0)],
locales.parse_accept_language('el,-us,en-,12-34,fr'))
class LocalesTests(unittest.TestCase):
"""Unit tests for the locale helper functions."""
def test_supported_locale_count(self):
... | w locale.
self.assertEquals(59, len(locales.get_system_supported_locales()))
def test_localized_display_name(self):
self.assertEquals('Deutsch (de)', locales.get_locale_display_name('de'))
|
VillanCh/g3ar | g3ar/utils/ipwhois/rdap.py | Python | bsd-2-clause | 22,912 | 0.000131 | # Copyright (c) 2013, 2014, 2015, 2016 Philip Hane
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this li... | val: The value to parse.
"""
ret = {
'type': None,
'value': None
}
try:
ret['type'] = val[1]['type']
except (IndexError, KeyError, ValueError, TypeError):
pass
ret['value'] = val[3].strip()
... | ne'].append(ret)
except AttributeError:
self.vars['phone'] = []
self.vars['phone'].append(ret)
def _parse_email(self, val):
"""
The function for parsing the vcard email addresses.
Args:
val: The value to parse.
"""
... |
anlar/prismriver | prismriver/cli.py | Python | mit | 3,443 | 0.002324 | import json
from prismriver import util, main
class SongJsonEncoder(json.JSONEncoder):
def default(self, o):
return o.__dict__
def format_output(songs, output_format, txt_template=None):
if output_format == 'txt':
formatted_songs = []
for song in songs:
lyrics_txt = ''
... | list_plugins()
elif params.cleanup:
main.cleanup_cache(config)
else:
result = main.search(params.artist, params.title, config)
if result:
print(format_output(result, params.format, p | arams.output))
|
coxmediagroup/googleads-python-lib | examples/dfp/v201505/proposal_line_item_service/get_proposal_line_items_for_proposal.py | Python | apache-2.0 | 2,425 | 0.007423 | #!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | o get proposal line items from.
PROPOSAL_ID = 'INSERT_PROPOSAL_ID_HERE'
def main(client, proposal_id):
# Initialize appropriate service.
proposal_line_item_service = client.GetService(
'ProposalLineItemService', version='v201505')
# Create statement object to only select proposal line items belonging to ... |
values = [{
'key': 'proposalId',
'value': {
'xsi_type': 'NumberValue',
'value': proposal_id
}
}]
query = 'WHERE proposalId = :proposalId ORDER BY id ASC'
statement = dfp.FilterStatement(query, values)
while True:
# Get proposal line items by statement.
response ... |
JeunessesScientifiques/ClientsMPD | python/simple.py | Python | bsd-2-clause | 1,802 | 0.000556 | #!/usr/bin/env python3
import socket
HOST = '131.urlab.be'
PORT = 6600
def parse(response):
result = {}
for line in response:
if ':' in line:
name, value = line.split(': ', 1)
result[name] = value
return result
def readline(s):
buffer = ''
while True:
bu... | onse(s)
def main():
s = socket.socket()
s.connect((HOST, PORT))
get_response(s)
while True:
order = input('Que faire ? ')
if order == 'play':
play(s)
elif order == 'pause':
pause(s) |
elif order == 'suivant':
next(s)
elif order == 'morceau':
print(currentsong(s)['Title'])
elif order == 'artiste':
print(currentsong(s)['Artist'])
elif order == 'position':
print(status(s)['elapsed'])
elif order in ('repetition', 'r... |
neo-layout/neo-layout | grafik/bilder-einzeln/flat/generate-graphics.py | Python | gpl-3.0 | 4,077 | 0 | #!/usr/bin/env python
import sys
import re
import subprocess
from jinja2 import Template
import replacements
TEMPLATENAME = "base.svg.template"
# modifiers for layers in order as in keymap
MODIFIERS = [
[],
["SHIFT"],
["MOD3"],
["MOD3", "SHIFT"],
["MOD4"],
["MOD4", "... | out.write(template.render(layerdict))
# - caps-lock images
for layer in 0, 1:
# create a dict with the replacements from replacements.py
layerdict = {a: make_caps_lock(b[layer]) for a, b in keymap.items()}
# color modifiers accordingly
for x in | MODIFIERS[layer]:
layerdict[x] = " pressed"
write_image(LAYERNAMES[layer] + 'caps', layerdict)
# - "leer" image
write_image('leer', {})
|
zhuyue1314/simuvex | simuvex/plugins/plugin.py | Python | bsd-2-clause | 1,953 | 0.005632 | import ana
import weakref
default_plugins = { }
# This is a base class for SimState plugins. A SimState plugin will be copied along with the state when the state is branched. They
# are intended to be use | d for things such | as tracking open files, tracking heap details, and providing storage and persistence for SimProcedures.
class SimStatePlugin(ana.Storable):
#__slots__ = [ 'state' ]
def __init__(self):
self.state = None
# Sets a new state (for example, if the state has been branched)
def set_state(self, state... |
faun/django_test | tests/regressiontests/middleware_exceptions/urls.py | Python | bsd-3-clause | 312 | 0.003205 | # | coding: utf-8
from django.conf.urls.defaults import *
import views
urlpatterns = patterns('',
(r'^view/$', views.normal_view),
(r'^not_found/$', views.not_found),
(r'^error/$', views.server_error),
(r'^null_view/$', views.null_view),
(r'^permission_denied/$', views.permission_denied | ),
)
|
keflavich/TurbuStat | turbustat/statistics/delta_variance/__init__.py | Python | mit | 66 | 0 | fro | m delta_variance import DeltaVariance, DeltaVariance_Distan | ce
|
jmbr/diffusion-maps | diffusion_maps/clock.py | Python | mit | 1,831 | 0 | """Clock for keeping track of the wall time.
"""
__all__ = ['ClockError', 'Clock', 'log']
import datetime
import logging
import time
from typing import Optional # noqa: F401. Used for mypy.
class ClockError(Exception):
"""Invalid clock operation."""
pass
class Clock:
"""Clock for keeping track ... | ""
self.start = time.monotonic()
self.stop = None
def toc(self) -> None:
"""Stop the clock."""
assert self.start is not None
self.stop = time.monotonic()
def __str__(self) -> str:
"""Human-readable representation of elapsed time."""
if self.start is None... | has not been started')
else:
start = datetime.datetime.fromtimestamp(self.start)
if self.stop is None:
stop = datetime.datetime.fromtimestamp(time.monotonic())
else:
stop = datetime.datetime.fromtimestamp(self.stop)
delta = stop - start
retu... |
hrpt-se/hrpt | apps/accounts/migrations/0002_usedactivationkeys.py | Python | agpl-3.0 | 922 | 0.003254 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-05-09 14:11
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migr | ation(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('accounts', '0001_initial'),
]
operations | = [
migrations.CreateModel(
name='UsedActivationKeys',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('activation_key', models.CharField(db_index=True, max_length=40, verbose_name='activation k... |
AlanLynn/sublime-copy-cut-paste-lines | main.py | Python | mit | 11,915 | 0.001343 | """Replacements for clipboard commands that prefer to operate on full lines of code.
Replaces: Copy, Cut, Paste, and Duplicate Lines
Note: For selections within a single line, commands work as normal, operating
only on the selection and not on the full line.
"""
import sublime, sublime_plugin
class ExpandedRe... | d('copy')
return |
expanded_selection = get_expanded_selection(view)
copy_selection_lines(expanded_selection, view)
class CcplCutCommand(sublime_plugin.TextCommand):
"""Cuts all lines containing a selection.
Exception: Does a normal cut for a selection within a single line.
Behavior:
-Clipboard is se... |
appleseedhq/gaffer | startup/GafferDispatch/requirementsCompatibility.py | Python | bsd-3-clause | 3,463 | 0.026278 | ##########################################################################
#
# Copyright (c) 2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | return plug.getName() == "preTasks" and isinstance( plug.parent(), GafferDispat | ch.TaskNode )
def __preTasksPlugGetItemWrapper( originalGetItem ) :
def getItem( self, key ) :
if isinstance( key, str ) and __isPreTasksPlug( self ) :
if key not in self :
key = key.replace( "requirement", "preTask" )
return originalGetItem( self, key )
return getItem
def __preTasksPlugAddChildWrapp... |
WSULib/eulfedora | test/test_fedora/test_models.py | Python | apache-2.0 | 62,832 | 0.002928 | # file test_fedora/test_models.py
#
# Copyright 2011 Emory University Libraries
#
# 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
#
... | NS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from datetime import datetime, timedelta
import logging
from lxml import etree
from mock impor | t patch, Mock
import os
from rdflib import URIRef, Graph as RdfGraph, XSD, Literal
from rdflib.namespace import Namespace
import re
import tempfile
import six
from eulfedora import models
from eulfedora.api import ApiFacade
from eulfedora.rdfns import relsext, model as modelns
from eulfedora.util import RequestFailed... |
beni55/sentry | tests/sentry/tasks/check_update/tests.py | Python | bsd-3-clause | 1,970 | 0.001015 | import json
import mock
from sentry.plugins.helpers import get_option, set_option
from sentry.testutils import TestCase
from sentry.models import set_sentry_version, Option
from sentry.tasks.check_update import check_update, PYPI_URL
class CheckUpdateTest(TestCase):
OLD = '5.0.0'
CURRENT = '5.5.0-DEV'
... |
def test_set_sentry_version_empty_latest(self):
set_sentry_version(latest=self.NEW)
self.assertEqual(get_option(key=self.KEY), self.NEW)
def test_set_sentry_version_new(self):
set_option(self.KEY, self.OLD)
with mock.patch | ('sentry.get_version') as get_version:
get_version.return_value = self.CURRENT
set_sentry_version(latest=self.NEW)
self.assertEqual(Option.objects.get_value(key=self.KEY), self.NEW)
def test_set_sentry_version_old(self):
set_option(self.KEY, self.NEW)
with mock.pa... |
mifth/mifthtools | blender/addons/2.7/io_simple_3dcoat/__init__.py | Python | bsd-3-clause | 3,677 | 0.003264 | # BEGIN GPL LICENSE BLOCK #####
#
# 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 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 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.
#
# END GPL LICENSE BLOCK #####
bl_info = {
"name": "Simple 3D-Coat Applink",
"author": "Kalle-Samuli Riihikoski (h... |
hryamzik/ansible | lib/ansible/modules/network/cloudengine/ce_file_copy.py | Python | gpl-3.0 | 12,627 | 0.001742 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... | exist.
The maximum length of I(local_file) is C(4096).
required | : true
remote_file:
description:
- Remote file path of the copy. Remote directories must exist.
If omitted, the name of the local file will be used.
The maximum length of I(remote_file) is C(4096).
file_system:
description:
- The remote file sy... |
divick/cookiecutter-django-vagrant-ansible | {{cookiecutter.project_slug}}/manage.py | Python | gpl-3.0 | 272 | 0.003676 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{cookiecutter.project_slug}}.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv | )
| |
HybridF5/jacket | jacket/compute/scheduler/filters/exact_disk_filter.py | Python | apache-2.0 | 1,856 | 0 | # Copyright (c) 2 | 014 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 appli... | e License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from jacket.compute.scheduler import filters
LOG... |
xbmcmegapack/plugin.video.megapack.dev | resources/lib/menus/home_languages_faroese.py | Python | gpl-3.0 | 1,111 | 0.002705 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as publi | shed 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 it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
... | |
Pathel/deuterium | game/gamesrc/conf/examples/oobfuncs.py | Python | bsd-3-clause | 1,435 | 0.000697 | """
OOB configuration.
This module should be included in (or replace) the
default module set in sett | ings.OOB_PLUGIN_MODULES
All functions defined in this module are made available
to be called by the OOB handler.
See src/server/oob_msdp.py for more information.
|
function execution - the oob protocol can execute a function directly on
the server. The available functions must be defined
as global functions via settings.OOB_PLUGIN_MODULES.
repeat func execution - the oob protocol can request a given function be
... |
wmde/do-index | crowdsourcing/views.py | Python | gpl-3.0 | 27,746 | 0.000432 | from __future__ import absolute_import
import csv
from datetime import datetime
import httplib
from itertools import count
import logging
import smtplib
from xml.dom.minidom import Document
from django.conf import settings
from django.core.exceptions import FieldError
from django.core.mail import EmailMultiAlternativ... | based on the survey, the user, and the user's entries. """
survey = _get_survey_or_404(slug, request)
if not survey.is_open and survey.can_have_public_submissions():
return _survey_results_redirect(request, survey)
need_login = (survey.is_open
and survey.require_login
... | ):
if request.method == 'POST':
return _survey_submit(request, survey)
forms = forms_for_survey(survey, request)
elif need_login:
forms = ()
elif survey.can_have_public_submissions():
return _survey_results_redirect(request, survey)
else: # Survey is closed with p... |
magul/pywikibot-core | pywikibot/families/wikisource_family.py | Python | mit | 4,148 | 0 | # -*- coding: utf-8 -*-
"""Family module for Wikisource."""
#
# (C) Pywikibot team, 2004-2017
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
from pywikibot import family
# The Wikimedia family that is known as Wikisource
class Family(family.SubdomainFam... | , 'ar', 'cs',
'pt', 'www', 'fa', 'hu', 'ml', 'ko', 'sv', 'gu', 'sr', 'bn', 'sl',
'sa', 'te', 'el', 'ro', 'fi', 'uk', 'vi', 'ja', 'th', 'az', 'hy',
'ca', 'ta', 'kn', 'br', 'hr', 'nl', 'is', 'la', 'no', 'vec', 'eo',
'tr', 'be', 'et', 'mk' | , 'yi', 'id', 'da', 'bg', 'li', 'mr', 'as',
'or', 'bs', 'sah', 'lt', 'gl', 'sk', 'cy', 'pa', 'zh-min-nan',
'fo',
]
super(Family, self).__init__()
self.category_redirect_templates = {
'_default': (),
'ar': ('قالب:تحويل تصنيف',),
'en': ... |
NAU-CFL/CFL_Website | app/views.py | Python | mit | 1,376 | 0.006541 | from app import app
from flask import render_template, make_response, redirect
# Route decorators to referance urls
@app.route('/')
def index():
user = {'nickname': 'Kemal'} # fake user
posts = [ # fake array of posts
{
'author': {'nickname': 'John'},
'body': 'Beautiful day in... | ml')
# Blog page will be linked to jekyll-markdown blog
@app.route('/blog')
def blog():
re | turn redirect('http://eneskemalergin.github.io')
@app.route('/contact')
def contact():
return render_template('contact.html')
# Error Handlers
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template(... |
prior/webinars | webinars_web/webinars/models/cms_form.py | Python | apache-2.0 | 4,543 | 0.008144 | from django.db import models
from hubspot import pool
from sanetime import time
# all forms that are actually tied to a legit landing page
SQL_ALL_FORMS = ""
SQL_ALL_FORMS_FOR_HUB_ID = ""
SQL_ALL_FORMS_FOR_FORM_GUID = ""
# all forms that are actually tied to an external landing page with submissions in the past 30 da... | new lps
| for url in set(remote_map[guid]['lps'])-set(local_map[guid]['lps']):
remote_lp_info = remote_map[guid]['lps'][url]
remote_lp_info['cms_form_id'] = guid
remote_lp_info['url'] = url
lp_dse.insert(remote_lp_info)
... |
sunlightlabs/django-locksmith | locksmith/auth/management/commands/resetkeys.py | Python | bsd-3-clause | 582 | 0.001718 | import datetime
from urlparse import urljoin
fro | m django.core.management.base import NoArgsCommand, CommandError
from django.conf import settings
from locksmith.common import apicall
class Command(NoArgsCommand):
help = "reset | all keys, triggering a request for all keys from the hub"
def handle_noargs(self, **options):
print 'resetting all keys for %s' % settings.LOCKSMITH_API_NAME
endpoint = urljoin(settings.LOCKSMITH_HUB_URL, 'reset_keys/')
apicall(endpoint, settings.LOCKSMITH_SIGNING_KEY,
ap... |
cheral/orange3 | Orange/widgets/model/owtree.py | Python | bsd-2-clause | 4,165 | 0.00048 | """Tree learner widget"""
from AnyQt.QtCore import Qt
from collections import OrderedDict
from Orange.data import Table
from Orange.modelling.tree import TreeLearner
from Orange.widgets import gui
from Orange.widgets.settings import Setting
from Orange.widgets.utils.owlearnerwidget import OWBaseLearner
class OWTree... | elf.settings_changed,
checkCallback=self.settings_changed, controlWidth=80)
def add_classification_layout(self, box):
for label, check, setting, minv, maxv in self.classification_spin_boxes:
gui.spin(box, self, setting, minv, maxv,
label=label, checked=... | checkCallback=self.settings_changed)
def learner_kwargs(self):
# Pylint doesn't get our Settings
# pylint: disable=invalid-sequence-index
return dict(
max_depth=(None, self.max_depth)[self.limit_depth],
min_samples_split=(2, self.min_internal)[self.limit_min_intern... |
hrayr-artunyan/shuup | shuup/admin/modules/contacts/forms.py | Python | agpl-3.0 | 3,844 | 0.002341 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from django import forms
from django.utils.encoding import force_text
from d... | CompanyContactBaseForm(ContactBaseFormMixin, forms.ModelForm):
class Meta:
model = CompanyContact
fields = list(FIELDS_BY_MODEL_NAME["CompanyContact"]) + list(FIELDS_BY_MODEL_NAME["Contact"])
def init_fields(self):
super(CompanyContactBaseForm, self).init_fields()
members_field... | (object.pk, force_text(object)) for object in self.instance.members.all()
]
self.fields["members"] = members_field
class AddressForm(forms.ModelForm):
class Meta:
model = MutableAddress
fields = (
"prefix", "name", "suffix", "name_ext",
"p... |
solvebio/solvebio-python | setup.py | Python | mit | 2,475 | 0.000404 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from setuptools import setup, find_packages
import sys
import warnings
VERSION = 'undefined'
install_requires = ['six', 'pyprind']
extra = {}
with open('solvebio/version.py') as f:
for row in f.readlines():
if row.startswith('... | lvebio = solvebio.cli.main:main',
's | olvebio-recipes = recipes.sync_recipes:sync_recipes']
},
classifiers=[
'Intended Audience :: Science/Research',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Scientific/Eng... |
bernoullio/toolbox | tests/indicators/__init__.py | Python | mit | 18 | 0 | from . | import ik | h
|
larsyencken/cjktools | cjktools/__init__.py | Python | bsd-3-clause | 385 | 0 | # -*- coding: utf-8 -*-
#
# __init__.py |
# cjktools
#
"""
This package contains various tools for Japanese NLP tasks, although some
may be applicable to any python project. See documentation of each module for
details.
"""
__all__ = [
'alternations',
'common',
'enum',
'exceptions',
'kana_table',
'm | aps',
'scripts',
'smart_cache',
'resources',
]
|
progagtudo/matemate | model/permission/right.py | Python | lgpl-3.0 | 200 | 0.005 | fr | om run import db
class Right(db.Model):
right_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, unique=True, nullable=False)
description = db.Column(db.String)
| |
pschmitt/home-assistant | tests/components/powerwall/test_binary_sensor.py | Python | apache-2.0 | 2,454 | 0.002445 | """The binary sensor tests for the powerwall platform."""
from homeassistant.components.powerwall.const import DOMAIN
from homeassistant.const import STATE_ON
from homeassistant.setup import async_setup_component
from .mocks import _mock_get_config, _mock_powerwall_with_fixtures
from tests.async_mock import patch
... | endly_name": "Powerwall Status",
"device_class": "power",
}
# Only test for a subset of attributes in case
# HA changes the implementation and a new one appears
assert all(item in state.attributes.items() for item in expected_attributes.items())
| state = hass.states.get("binary_sensor.powerwall_connected_to_tesla")
assert state.state == STATE_ON
expected_attributes = {
"friendly_name": "Powerwall Connected to Tesla",
"device_class": "connectivity",
}
# Only test for a subset of attributes in case
# HA changes the implemen... |
mirumee/google-measurement-protocol | google_measurement_protocol/event.py | Python | bsd-2-clause | 378 | 0.010582 | from typing import Dict, Generator
def event(
category: str, action: str, label: str=None, value: int=None,
**extra_data) -> Generator[Dict, None, None]:
payload = {'t': 'event', 'ec': category, 'ea': action}
| if label:
payload['el'] = label
if value:
payload['ev'] = s | tr(int(value))
payload.update(extra_data)
yield payload
|
birsoyo/conan | conans/model/profile.py | Python | mit | 3,409 | 0.00088 | import copy
from collections import OrderedDict
from collections import defaultdict
from conans.model.env_info import EnvValues
from conans.model.options import OptionsValues
from conans.model.values import Values
class Profile(object):
"""A profile contains a set of setting (with values), environment variables
... | pend("%s:%s=%s" % (package, name, value))
result.append("[options]")
result.append(self.options.dumps())
result.append("[ | build_requires]")
for pattern, req_list in self.build_requires.items():
result.append("%s: %s" % (pattern, ", ".join(str(r) for r in req_list)))
result.append("[env]")
result.append(self.env_values.dumps())
return "\n".join(result).replace("\n\n", "\n")
def update(self... |
chrisdickinson/nojs | build/android/gyp/create_apk_operations_script.py | Python | bsd-3-clause | 2,636 | 0.00607 | #!/usr/bin/env python
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import os
import string
import sys
SCRIPT_TEMPLATE = string.Template("""\
#!/usr/bin/env python
#
# This file was ge... | ambda p: p if p is None else os.path.abspath(os.path.join(
script_directory, p))
sys.path.append(resolve(${APK_OPERATIONS_DIR}))
import apk_operations
output_dir = resolve(${OUTPUT_DIR})
try:
apk_operations.Run(
output_dir,
resolve(${APK_PATH}),
resolve(${INC_JSON_PATH}),
... | elpath(sys.argv[0], output_dir)
sys.stderr.write('Script out-of-date. Rebuild via:\\n')
sys.stderr.write(' ninja -C %s %s\\n' % (rel_output_dir, rel_script_path))
return 1
if __name__ == '__main__':
sys.exit(main())
""")
def main(args):
parser = argparse.ArgumentParser()
parser.add_argument('--sc... |
fin/froide | froide/problem/moderation_urls.py | Python | mit | 143 | 0 | from django.urls impor | t path
from .views import moderation_view
urlp | atterns = [
path("", moderation_view, name="problem-moderation"),
]
|
miptliot/edx-platform | lms/djangoapps/lti_provider/tests/test_users.py | Python | agpl-3.0 | 9,455 | 0.001692 | """
Tests for the LTI user management functionality
"""
import string
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from django.test.client import RequestFactory
from mock import MagicMock, patch
import lti_provider.users as users
fro... | rovider.users.authenticate', return_value=self.new_user):
users.switch_user(self.request, self.lti_user, self.lti_consumer)
login_mock.assert_called_with(self.request, self.new_user)
def test_random_username_generator(self):
for _idx in range(1000):
username = users.gene... | r in range(len(username)):
self.assertIn(
username[char], string.ascii_letters + string.digits,
"Username has forbidden character '{}'".format(username[char])
)
@patch('lti_provider.users.switch_user', autospec=True)
@patch('lti_provider.users.cr... |
hipgraphics/godot | platform/x11/detect.py | Python | mit | 5,057 | 0.054776 |
import os
import sys
def is_active():
return True
def get_name():
return "X11"
def can_build():
if (os.name!="posix"):
return False
if sys.platform == "darwin":
return False # no x11 on mac for now
errorval=os.system("pkg-config --version > /dev/null")
if (errorval):
print("pkg-co... | ):
env.Append(CCFLAGS=['-g2', '-Wall','-DDEBUG_ENABLED','-DDEBUG_MEMORY_ENABLED'])
en | v.ParseConfig('pkg-config x11 --cflags --libs')
env.ParseConfig('pkg-config xinerama --cflags --libs')
env.ParseConfig('pkg-config xcursor --cflags --libs')
if (env["openssl"]=="yes"):
env.ParseConfig('pkg-config openssl --cflags --libs')
if (env["freetype"]=="yes"):
env.ParseConfig('pkg-config freetype2 --c... |
SuLab/scheduled-bots | scheduled_bots/geneprotein/GOBot.py | Python | mit | 14,190 | 0.003524 | """
example microbial protein:
https://www.wikidata.org/wiki/Q22291171
example yeast protein:
https://www.wikidata.org/wiki/Q27553062
Data source: Quickgo mongo
"""
import argparse
import json
import os
import traceback
from collections import defaultdict
from datetime import datetime
from functools import partial
fr... | ultiple_parties_and_presented_through_multiple_aggregation_services.29
:param item_wdid: The protein item's wikidata item that will have GO terms added/updated
:param uniprot_id: protein item' | s uniprot id
:param this_go: pandas df containing GO annotations for this protein
:param retrieved: date that the GO annotations were retrieved
:param go_map: mapping of GO terms from GOID -> wdid
:param pmid_map: mapping of PMIDs to wdid
:param external_id:
:param login: wdi_core login instance... |
cortical-io/python-client-sdk | tests/unit/testExpressionsApi.py | Python | bsd-2-clause | 3,216 | 0.004975 | # -*- coding: utf-8 -*-
"""
/*******************************************************************************
* Copyright (c) cortical.io GmbH. All rights reserved.
*
* This software is confidential and proprietary information.
* You shall use it only in accordance with the terms of the
* license agreement you en... | stExpressions(self):
fp = self.api.resolveExpression(conf.RETINA_NAME, oneTermInputJSON, sparsity=0.5)
self.assertGreater(len(fp.positions), 100)
def testContexts(sel | f):
contexts = self.api.getContextsForExpression(conf.RETINA_NAME, oneTermInputJSON, get_fingerprint=True, start_index=0, max_results=3, sparsity=1.0)
self.assertTrue(contexts != None)
self.assertEqual(3, len(contexts))
c0 = contexts[0]
self.assertGreater(len(c0.fingerprint.posit... |
HackerspaceWroclaw/wlokalu | wlokalu/views.py | Python | gpl-3.0 | 1,663 | 0.012026 | #!/usr/bin/python
from django.http import HttpResponse
from django.template import RequestContext, loader
from django.views.decorators.csrf import csrf_exempt
import django.shortcuts
from wlokalu.api import presence
#-----------------------------------------------------------------------------
from wlokalu.logging ... | ---------------------------------------------------------------------
@csrf_exempt
def list(request, nick = None):
template = loader.get_template("list.html")
from django.core.urlresolvers import reverse
from forms import PresenceForm
form = PresenceForm()
if nick is not None:
form.initial['nick'] = nic... | list, kwargs = {'nick': nick})
else:
form_target = reverse(list)
if request.POST.get('nick', '') != '':
context = {
'address': request.META['REMOTE_ADDR'],
'uri': request.META['REQUEST_URI'],
}
if 'enter' in request.POST:
presence.person_entered(request.POST['nick'], context)
... |
n7jti/machine_learning | adaboost/newsgroups.py | Python | apache-2.0 | 4,192 | 0.037452 | #!/usr/bin/python2
from scipy import *
import scipy.sparse as sp
import scipy.linalg as la
#See http://scikit-learn.org/stable/modules/feature_extraction.html
import sklearn.feature_extraction as fe
import tok
import dstump as ds
import pylab as pl
import numpy as np
import operator
from datetime import datetime
def ... | ames()
m = 30
#This shouldn't take more than 20m.
A, H, I , TE = adaboost_train(ftr, ytr, m)
for i in range(m):
print "T", i, "index:", I[i], "feature name:", feature_names[I[i]]
# Plot
pl.subplot(2,1,1)
pl.xlabel('steps of adaboost')
pl.ylabel('magnitude of alpha')
pl.plot(np.abs(A),'o')
pl.... | list.__add__, map(lambda x: x[600:800], corpus))
yva = zeros(len(cva)); yva[:200] = -1; yva[200:] = 1
#tfidf tokenizer is not trained here.
fva = tfidf.transform(cva).tocsc()
#<Validation code goes here>
HE, t = adaboost_find_t(A,H,I,fva, yva)
print "t", t
A = A[:t]
H = H[:t]
I = I[:t]
S = np.vs... |
sunghan-chang/TizenRT | external/protobuf/python/setup.py | Python | apache-2.0 | 10,629 | 0.009314 | #! /usr/bin/env python
#
# See README for usage instructions.
import glob
import os
import subprocess
import sys
import platform
# We must use setuptools, not distutils, because we need to use the
# namespace_packages option for the "google" package.
from setuptools import setup, Extension, find_packages
from distuti... | c is not installed nor found in ../src. Please compile it "
"or install the binary package.\n")
sys.exit(-1)
protoc_command = [ protoc, "-I../src", "-I.", "--python_out=.", source ]
if subpro | cess.call(protoc_command) != 0:
sys.exit(-1)
def GenerateUnittestProtos():
generate_proto("../src/google/protobuf/any_test.proto", False)
generate_proto("../src/google/protobuf/map_proto2_unittest.proto", False)
generate_proto("../src/google/protobuf/map_unittest.proto", False)
generate_proto("../src/goo... |
andresailer/DIRAC | Core/Utilities/ReturnValues.py | Python | gpl-3.0 | 4,282 | 0.012144 | """
DIRAC return dictionary
Message values are converted to string
keys are converted to string
"""
import types
import traceback
from DIRAC.Core.Utilities.DErrno import strerror
def S_ERROR(*args):
""" return value on error condition
Arguments are either Errno and ErrorMessage or just ErrorMessage f... | e: value of the 'Value'
:return: dictionary { 'OK' : True, 'Value' : value }
"""
return {'OK': True, 'Value': value}
def isReturnStruct | ure(unk):
if not isinstance(unk, types.DictType):
return False
if 'OK' not in unk:
return False
if unk['OK']:
if 'Value' not in unk:
return False
else:
if 'Message' not in unk:
return False
return True
def reprReturnErrorStructure(struct, full=False):
errorNumber = struct.get(... |
damianam/easybuild-framework | easybuild/tools/repository/__init__.py | Python | gpl-2.0 | 1,270 | 0.001575 | ##
# Copyright 2011-2017 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | syBuild 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 details.
#
# You should have received a copy of the GNU General Public License
# along with Ea... | merman (Ghent University)
:author: Kenneth Hoste (Ghent University)
"""
import pkg_resources
pkg_resources.declare_namespace(__name__)
|
codeforamerica/comport | migrations/versions/2357b6b3d76_.py | Python | bsd-3-clause | 794 | 0.010076 | """empty message
Revision ID: 2357b6b3d76
Revises: fecca96b9d
Create Date: 2015-10-27 10:26:52.074526
"""
# revision identifiers, used by Alembic.
revision = '2357b6b3d76'
down_revision = 'fecca96b9d'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alemb | ic - please adjust! ###
op.add_column('citizen_complaints', sa.Column('service_type', sa.String(length=255), nullable=True))
op.add_column('citizen_complaints', sa.Column('source', sa.String(length=255), nullable=True))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alemb... | op.drop_column('citizen_complaints', 'source')
op.drop_column('citizen_complaints', 'service_type')
### end Alembic commands ###
|
gordon-elliott/glod | src/glod/db/statement_item.py | Python | mit | 944 | 0.004237 | __copyright__ = 'Copyright(c) Gordon Elliott 2017 | '
"""
"""
from a_tuin.db import RelationMap, TableMap, PagedQuery, InstanceQuery
from glod.model.statement_item import StatementItem, StatementItemDesignatedBalance
from glod.model.statement_item_collection import StatementItemCollection
from glod.model.references import statement_item__account
from glo | d.db.db_column_type_map import DB_COLUMN_TYPE_MAP
from glod.db.constants import SCHEMA_NAME
TableMap(StatementItem, SCHEMA_NAME, 'statement_item', DB_COLUMN_TYPE_MAP, RelationMap(
statement_item__account,
'account._id',
backref='statement_items',
lazy='joined'
))
class StatementItemInstanceQuery(Inst... |
mysql/mysql-utilities | mysql/utilities/command/proc.py | Python | gpl-2.0 | 8,819 | 0.00034 | #
# Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
#
# 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; version 2 of the License.
#
# This program is distributed in th... | return ' {0} {1} {2}'.format(TIME, oper, seconds)
mobj = re.match(r"([+-])?(\d+[dwhms])+", age) |
if mobj:
sign = None
if mobj.group(1):
sign = age[0]
age = age[1:]
seconds = 0
periods = [x for x in re.split(r"(\d+[dwhms])", age)]
if len(''.join(x[0::2])) > 0: # pylint: disable=W0631
raise FormatError(_INCORRECT_FORMAT_MSG.format(age)... |
DTOcean/dtocean-core | tests/test_utils_files.py | Python | gpl-3.0 | 3,004 | 0.011651 |
import os
import shutil
import zipfile
from stat import S_IREAD, S_IRGRP, S_IROTH
import pytest
from dtocean_core.utils.files import (unpack_archive,
onerror,
os_retry,
rmtree_retry,
... | move_retry,
init_dir)
def test_u | npack_archive_zip(tmpdir):
src_path = os.path.join(str(tmpdir), 'zipfile_write.zip')
dst_path = os.path.join(str(tmpdir), 'test')
readme = tmpdir.join('README.txt')
readme.write("test")
zf = zipfile.ZipFile(src_path, mode='w')
try:
zf.write(str(readme))
finally:
... |
andersx/myrpg | src/test.py | Python | bsd-2-clause | 1,605 | 0.007477 | # INTIALISATION
import pygame, math, sys
from pygame.locals import *
screen = pygame.display.set_mode((1024, 768))
car = pygame.image.load('car.jpg')
clock = pygame.time.Clock()
k_up = k_down = k_left = k_right = 0
speed = direction = 0
position = (100, 100)
TURN_SPEED = 5
ACCELERATION = 2
MAX_FORWARD_SPEED = 10
MAX_RE... | if not hasattr(event, 'key'): continue
down = event.type == KEYDOWN # key down or up?
if event.key == K_RIGHT: k_right = down * 5
elif event.key == K_LEFT: k_left = down * 5
elif event.key == K_UP: k_up = down * 2
elif event.key == K_DOWN: k_down = down * 2
el... |
screen.fill(BLACK)
# SIMULATION
# .. new speed and direction based on acceleration and turn
speed += (k_up + k_down)
if speed > MAX_FORWARD_SPEED: speed = MAX_FORWARD_SPEED
if speed < MAX_REVERSE_SPEED: speed = MAX_REVERSE_SPEED
direction += (k_right + k_left)
# .. new position based on... |
timthelion/FreeCAD | src/Mod/Path/PathScripts/PathSimpleCopy.py | Python | lgpl-2.1 | 3,675 | 0.012789 | # -*- coding: utf-8 -*-
#***************************************************************************
#* *
#* Copyright (c) 2015 Yorik van Havre <yorik@uncreated.net> *
#* ... | icense along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#*****************... | ****************************
import FreeCAD,FreeCADGui,Path,PathGui
from PySide import QtCore,QtGui
"""Path SimpleCopy command"""
# Qt tanslation handling
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def translate(context, text, disambig=None):
return QtGui.QApplication.translate(context, text, di... |
siosio/intellij-community | python/testData/completion/className/orderingLocalBeforeStdlib/orderingLocalBeforeStdlib.py | Python | apache-2.0 | 11 | 0.272727 | pa | <caret>th | |
rfosterslo/wagtailplus | wagtailplus/tests/views.py | Python | bsd-2-clause | 14,293 | 0.001819 | """
"""
from django.core.urlresolvers import reverse
from django.test import TestCase
from wagtail.tests.utils import WagtailTestUtils
class BaseTestIndexView(TestCase, WagtailTestUtils):
"""
Base test case for CRUD index view.
"""
url_namespace = None
template_dir = None
def _create_s... | method must be implemented by {0}'.format(
self.__class__.__name__
)
)
def setUp(self):
# Create the instance and login.
self.instance = self._get_instance()
| self.login()
def test_get(self):
# Generate the response.
response = self.client.get(
reverse(
'{0}:delete'.format(self.url_namespace),
args=(self.instance.pk,)
)
)
# Check assertions.
self.assertEqual(response.stat... |
drewdru/AutoTags | vk_base/models/modelsHelper.py | Python | gpl-3.0 | 984 | 0.010163 | # -*- coding: utf-8 -*-
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import as_declarative
import settings
def db_connect():
""" Performs database connection using database settings from settings.py.
:return: sqlalchemy engine instance ... | te:///images.db', echo=True)
return create_engine('{drivername}://{username}:{password}@{host}:{port}/{database}'\
.format(**settings.DATABASES['sqlalchemy'])
)
engine = db_connect()
session_maker = sessionmaker()
@as_declarative()
class Base(object):
| def __init__(self):
self.conn = engine.connect()
self.session = session_maker(bind=self.conn)
self.close()
def open(self):
self.conn = engine.connect()
self.session = session_maker(bind=self.conn)
def close(self):
self.session.close()
self.conn.close... |
innes213/TradingTools | setup.py | Python | bsd-2-clause | 624 | 0.003205 | from setuptools import setup, find_p | ackages
__version__ = '0'
with open('LICENSE.txt') as f:
license = f.read()
setup(
name='TradingTools',
version=__version__,
author='Rob Innes Hislop',
author_email='robinneshislop@gmail.com',
license=license,
packages=find_packages(),
url = 'https://github.com/innes213/TradingTools',... | ious tools that analyze and screen equities',
long_description='Various tools that analyze and screen equities',
install_requires=['numpy',
'finsymbols',
'pyhoofinance'
]
)
|
soylentdeen/Graffity | src/LoopAnalysis/mkAOTF_fig.py | Python | mit | 938 | 0.006397 | from matplotlib import pyplot
import scipy
import numpy
fig = pyplot.figure(0)
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.clear()
df = open('/home/cdeen/Data/CIAO/AOTF_output.txt', 'r')
freq = []
modes = []
theoretical = []
for i in range(60):
modes.append([])
for line in df.readlines():
l = line.split()
... | numpy.array(theoretical)
for i in range(60):
modes[i] = numpy.array(modes[i])
for i in range(45):
#ax.scatter(freq, modes[i], lw=0.5)
ax.plot(freq, modes[i], lw=0.25)
ax.plot(freq, theoretical, lw=2.0, color = 'k')
ax.loglog()
ax.set_xbound(1.0, 499.9678/2.0)
#ax.grid(True, which='both')
ax.set_title("O... | ions, gain=0.5")
ax.set_xlabel("Frequency (Hz)")
ax.set_ylabel("Rejection")
fig.show()
fig.savefig("AOTF.png")
|
zbigniewwojna/text-rcnn | core/box_list.py | Python | apache-2.0 | 6,840 | 0.005556 | # 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... | epresents a list of bounding boxes as tensorflow
tensors, where each boun | ding box is represented as a row of 4 numbers,
[y_min, x_min, y_max, x_max]. It is assumed that all bounding boxes
within a given list correspond to a single image. See also
box_list_ops.py for common box related operations (such as area, iou, etc).
Optionally, users can add additional related fields (such as weight... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.