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 |
|---|---|---|---|---|---|---|---|---|
quantmind/lux | tests/odm/utils.py | Python | bsd-3-clause | 2,440 | 0 |
class SqliteMixin:
config_params = {'DATASTORE': 'sqlite://'}
class OdmUtils:
config_file = 'tests.odm'
async def _create_task(self, token, subject='This is a task', person=None,
**data):
data['subject'] = subject
if person:
data['assigned'] = pers... | in data)
self.assertEqual(len(request.cache.new_items), 1)
self.assertEqual(request.cache.new_items[0]['id'], data['id'])
self.assertFalse(requ | est.cache.new_items_before_commit)
return data
async def _get_task(self, token, id):
request = await self.client.get(
'/tasks/{}'.format(id),
token=token)
response = request.response
self.assertEqual(response.status_code, 200)
data = self.json(respons... |
eustislab/horton | horton/correlatedwfn/test/test_lagrange.py | Python | gpl-3.0 | 5,097 | 0.003924 | # -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2015 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | rnal)
scf_solver = PlainSCFSolver()
scf_solver(ham, lf, olp, occ_model, exp_alpha)
one = lf.create_two_index(obasis.nbasis)
one.iadd(kin)
one.iadd(na)
# Do AP1roG optimization:
geminal_solver = RAp1rog(lf, occ_model)
| energy, g = geminal_solver(one, er, external['nn'], exp_alpha, olp, False)
geminal_solver.lagrange.assign(np.random.rand(3,25))
x = geminal_solver.geminal._array.ravel(order='C')
dxs = np.random.rand(200, 3*25)*(0.001)
check_delta(x, dxs, geminal_solver)
def fun(x, ham):
iiaa = ham.get_auxmatrix... |
jbedorf/tensorflow | tensorflow/contrib/nn/python/ops/alpha_dropout.py | Python | apache-2.0 | 3,426 | 0.002335 | # 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... | print_function
import numbers
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import gen_math_ops
fro... | prob, noise_shape=None, seed=None, name=None): # pylint: disable=invalid-name
"""Computes alpha dropout.
Alpha Dropout is a dropout that maintains the self-normalizing property. For
an input with zero mean and unit standard deviation, the output of
Alpha Dropout maintains the original mean and standard deviati... |
endeepak/pungi | tests/test_string.py | Python | mit | 846 | 0 | import unittest
from pungi import string
from pungi import expect
class StringTest(unittest.TestCase):
def test_pp_with_no_args(self):
expect(string.pp()).toBe("")
def test_pp_of_single_arg(self):
expect(string.pp('1')).toBe("'1'")
expect(string.pp(1)).toBe("1")
def test_pp_of_m... |
def test_humanize_camelcase_word(self):
| expect(string.humanize("SomeOne")).toBe("some one")
expect(string.humanize("SomeOneElse")).toBe("some one else")
if __name__ == '__main__':
unittest.main()
|
probablytom/tomwallis.net | core/admin.py | Python | artistic-2.0 | 146 | 0.006849 | __author__ = 'tom'
from django.contrib import admin
from core.model | s import Post, Project
admin.site.register(Post)
admin.site.re | gister(Project) |
antoinecarme/sklearn2sql_heroku | tests/regression/diabetes/ws_diabetes_SVR_poly_hive_code_gen.py | Python | bsd-3-clause | 122 | 0.016393 | from sklearn2sql_heroku.tests.regression import generic a | s reg_gen |
reg_gen.test_model("SVR_poly" , "diabetes" , "hive")
|
JordiCarreraVentura/spellchecker | lib/__init__.py | Python | gpl-3.0 | 127 | 0 |
fro | m TextStreamer import TextStreamer
from parser import (
LinguistListParser
)
from FeatureEngine import Feature | Engine
|
swtp1v07/Savu | savu/test/plugin_test_sart.py | Python | apache-2.0 | 1,105 | 0.000905 | # Copyright 2014 Diamond Light Source Ltd.
#
# 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 t... | S OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the spec | ific language governing permissions and
# limitations under the License.
"""
.. module:: plugins_test
:platform: Unix
:synopsis: unittest test classes for plugins
.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>
"""
import unittest
from savu.test.plugin_test import PluginTest
class SimpleR... |
bjschafer/showdown-sync | cookie_reader.py | Python | apache-2.0 | 2,178 | 0.005051 | ########################################################################################################################
#
# cookie_reader.py
#
| # Purpose: read cookies from the web browser (currently only Chrome supported) and make them into Python objects
#
# Author: Braxton J. Schafer (bjschafer) [bjs]
#
# Creation date: 10/10/2014
#
# Copyright (c) 2014 Braxton J. Schafer
#
# Changelog:
#
############################# | ###########################################################################################
import sqlite3 as sqlite
import sys
import os.path
import json
from pokemon import pokemon
class cookie_reader():
def __init__(self, cookie_location, browser_type):
self.cookie_location = cookie_location
s... |
abdoosh00/edraak | lms/djangoapps/courseware/views.py | Python | agpl-3.0 | 36,829 | 0.002525 | """
Courseware views functions
"""
import logging
import urllib
import json
from collections import defaultdict
from django.utils.translation import ugettext as _
from django.conf import settings
from django.core.context_processors import csrf
from django.core.exceptions import PermissionDenied
from django.core.urlr... | ort StudentModule, StudentModuleHistory
from course_modes.models import CourseMode
from open_ended_grading import open_ended_notifications
from student.models import UserTestGroup, CourseEnrollment
from student.views import single_course_reverification_info
from util.cache import cache, cache_if_anonymous
from xblock.... | oundError, NoPathToItem
from xmodule.modulestore.search import path_to_location
from xmodule.tabs import CourseTabList, StaffGradingTab, PeerGradingTab, OpenEndedGradingTab
from xmodule.x_module import STUDENT_VIEW
import shoppingcart
from opaque_keys import InvalidKeyError
from microsite_configuration import microsit... |
HardLight/denyhosts | tests/test_counter.py | Python | gpl-2.0 | 4,362 | 0.00321 | from __future__ import print_function, unicode_literals
from datetime import datetime, timedelta
import time
import unittest
from DenyHosts.counter import Counter, CounterRecord
class CounterRecordTest(unittest.TestCase):
def test_init(self):
c = CounterRecord()
self.assertEqual(c.get_count(), 0)... | ric, but any object can be used.
Verify that what we pass to the constructor is accessible.
"""
count = object()
c = CounterRecord(count= | count)
self.assertTrue(c.get_count() is count)
def test_str(self):
"""
CounterRecord.__str__ is actually used in PurgeCounter.write_data, so it's
worth testing
"""
count = 1
date = object()
c = CounterRecord(count=count, date=date)
string = '%... |
cortext/crawtextV2 | ~/venvs/crawler/lib/python2.7/site-packages/pymongo/cursor_manager.py | Python | mit | 2,846 | 0 | # Copyright 2009-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | s = []
self.__max_dying_cursors = 20
self.__connection = weakref.ref(connection)
CursorManager.__init__(self, connection)
def __del__(self):
"""Cleanup - be sure to kill any outstanding cursors.
"""
self.__connection().kill_cursors(self.__dying_cursors)
def clo... | s:
- `cursor_id`: cursor id to close
"""
if not isinstance(cursor_id, (int, long)):
raise TypeError("cursor_id must be an instance of (int, long)")
self.__dying_cursors.append(cursor_id)
if len(self.__dying_cursors) > self.__max_dying_cursors:
self.__c... |
jim-minter/ose3-demos | bin/etcd-client.py | Python | apache-2.0 | 2,017 | 0.000496 | #!/usr/bin/python
import argparse
import fcntl
import os
import requests
import socket
| import struct
import textwrap
def parse_args():
ap = argparse.ArgumentParser()
ap.add_argument("--host", nargs="?", default=socket.gethostname())
ap.add_argument("--port", nargs="?", default="4001")
ap.add_argument("cmd", choices=["ls", "watch"])
ap.add_argument("key", nargs="?", default="/ | ")
return ap.parse_args()
def get_winsize(fd=2):
TIOCGWINSZ = 21523
try:
return struct.unpack("hh", fcntl.ioctl(fd, TIOCGWINSZ, "xxxx"))
except:
return (os.environ.get("LINES", 25), os.environ.get("COLUMNS", 80))
def ls(url, key, level=""):
j = s.get(url + key, cert=cert, verify... |
2ndy/RaspIM | usr/lib/python2.6/lib2to3/pytree.py | Python | gpl-2.0 | 28,107 | 0.000391 | # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""
Python parse tree definitions.
This is a very concrete parse tree; we need to keep every token and
even the comments and whitespace between tokens.
There's also a pattern matching implementation here.
"""
__autho... | """
assert type >= 256, type
self.type = type
self.children = list(children)
for ch in self.children:
assert ch.parent is None, repr(ch)
ch.parent = self
if prefix is not None:
self.prefix = prefix
def __repr__(self):
"""Return... | e_repr(self.type),
self.children)
def __unicode__(self):
"""
Return a pretty string representation.
This reproduces the input source exactly.
"""
return u"".join(map(unicode, self.children))
if sys.version_info > (3, 0):
__str__ =... |
crslab/Inverse-Reinforcement-Learning | irl/value_iteration.py | Python | mit | 4,821 | 0.001659 | """
Find the value function associated with a policy. Based on Sutton & Barto, 1998.
Matthew Alger, 2015
matthew.alger@anu.edu.au
"""
import numpy as np
def value(policy, n_states, transition_probabilities, reward, discount,
threshold=1e-2):
"""
Find the value function associa... | ptimal_value(n_states, n_actions, transition_probabilities, reward,
discount, threshold=1e-2):
"""
Find the optimal value function.
n_states: Number of states. int.
n_actions: Number of acti | ons. int.
transition_probabilities: Function taking (state, action, state) to
transition probabilities.
reward: Vector of rewards for each state.
discount: MDP discount factor. float.
threshold: Convergence threshold, default 1e-2. float.
-> Array of values for each state
"""
... |
googleapis/python-aiplatform | google/cloud/aiplatform_v1/services/index_service/transports/grpc_asyncio.py | Python | apache-2.0 | 17,093 | 0.001404 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
... | The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attemp... |
kennedyshead/home-assistant | homeassistant/components/lcn/config_flow.py | Python | apache-2.0 | 3,022 | 0.000662 | """Config flow to configure the LCN integration."""
import logging
import pypck
from homeassistant import config_entries
from homeassistant.const import (
CONF_HOST,
CONF_IP_ADDRESS,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
)
from .const import CONF_DIM_MODE, CONF_SK_NUM_TRIES, DOMAIN
_LOGGER = ... | icense key is required",
host_name,
)
return self.async_abort(reason="license_error")
except TimeoutError:
_LOGGER.warning('Connection to PCHK "%s" failed', host_name)
return self.async_abort(reason="connection_timeout")
# check if we alre... | s configured
entry = get_config_entry(self.hass, data)
if entry:
entry.source = config_entries.SOURCE_IMPORT
self.hass.config_entries.async_update_entry(entry, data=data)
return self.async_abort(reason="existing_configuration_updated")
return self.async_creat... |
LukasMosser/MontePetro | montepetro/models.py | Python | gpl-2.0 | 2,237 | 0.001341 | import logging
from copy import deepcopy
from mont | epetro.seed_generators import SeedGenerator
class Model(object):
def __i | nit__(self, name, seed):
self.name = name
self.seed = seed
self.seed_generator = SeedGenerator(self.seed)
self.properties = {}
self.regions = {}
def add_region(self, region):
if region.name in self.regions.keys():
logging.log(logging.ERROR,
... |
poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/Bio/KEGG/Enzyme/__init__.py | Python | apache-2.0 | 10,978 | 0.002824 | # Copyright 2001 by Tarjei Mikkelsen. All rights reserved.
# Copyright 2007 by Michiel de Hoon. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Code to work with the KEGG En... | work if enzyme entries
# | have more than one link id per db id. For now, that's not
# the case - storing links ids in a list is only to make
# this class similar to the Compound.Record class.
s = []
for entry in self.dblinks:
s.append(entry[0] + ": " + " ".join(entry[1]))
return _write_kegg(... |
antoinecarme/pyaf | tests/artificial/transf_Anscombe/trend_Lag1Trend/cycle_0/ar_12/test_artificial_32_Anscombe_Lag1Trend_0_12_20.py | Python | bsd-3-clause | 263 | 0.087452 | imp | ort pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 0, transform = "Anscombe", sigma = 0.0, exog_count = 2 | 0, ar_order = 12); |
joker-ace/internships-reviews | src/utils/__init__.py | Python | mit | 21 | 0 | __author__ = ' | joker' | |
jdowner/qtile | libqtile/widget/keyboardlayout.py | Python | mit | 4,269 | 0.000937 | # Copyright (c) 2013 Jacob Mourelos
# Copyright (c) 2014 Shepilov Vladislav
# Copyright (c) 2014-2015 Sean Vig
# Copyright (c) 2014 Tycho Andersen
#
# 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 Sof... | copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ... | LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE... |
kxgames/seacow_economy_minigame | src/gui.py | Python | gpl-3.0 | 2,254 | 0.005768 | #!/usr/bin/env python3
import kxg
import pyglet
from .world import Player
from .messages import SetupPlayer, MakeInvestment
class Gui:
def __init__(self):
self.window = pyglet.window.Window()
self.window.set_visible(True)
self.batch = pyglet.graphics.Batch()
self.texts = []
... | tial_message,
font_name='Arial',
font_size=40,
x = x_coor, y = y_coor,
anchor_x='left', anchor_y='bottom',
batch= self.batch, group= self.text_group
))
return self.texts[-1]
c | lass GuiActor(kxg.Actor):
def __init__(self):
super().__init__()
self.player = Player()
def on_setup_gui(self, gui):
self.gui = gui
self.gui.window.set_handlers(self)
self.supply_label = self.gui.create_text('', 20, 280)
self.demand_label = self.gui.create_text... |
bernard357/smart-video-counter | source/updater_mysql.py | Python | apache-2.0 | 2,420 | 0.000413 | # -*- coding: utf-8 -*-
"""Mysql module"""
import datetime
import logging
import MySQLdb as msql
class MysqlUpdater(object):
"""
Updates a database
"""
def __init__(self, settings=None):
"""
Sets updater settings
:param settings: the parameters for this updater
:type ... | cursor.execute(sql_insert,
(items[0],
datetime.datetime.utcnow(),
int(items[1]),
int(items[2]),
int(items[3])))
db.commit()
cursor.close()
... | .error(str(feedback))
|
DataONEorg/d1_python | test_utilities/src/d1_test/instance_generator/tests/test_person.py | Python | apache-2.0 | 1,335 | 0 | #!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... | ://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions ... | ==========================================
@d1_test.d1_test_case.reproducible_random_decorator("TestPerson")
class TestPerson(d1_test.d1_test_case.D1TestCase):
def test_1000(self):
"""generate()"""
person_list = [
d1_test.instance_generator.person.generate().toxml("utf-8")
... |
nicholasserra/sentry | src/sentry/utils/runner.py | Python | bsd-3-clause | 438 | 0 | #!/usr/bin/env python
"""
sentry.utils.runner
~~~~~~~~~~~~~~~~~~~
| :copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
# Backwards compatibility
from sentry.runner import configure, main # NOQA
import warnings
warnings.warn("'sentry.utils.runn | er' has moved to 'sentry.runner'",
DeprecationWarning)
|
abesto/fig | compose/cli/main.py | Python | apache-2.0 | 16,398 | 0.002012 | from __future__ import print_function
from __future__ import unicode_literals
import logging
import sys
import re
import signal
from operator import attrgetter
from inspect import getdoc
import dockerpty
from .. import __version__
from ..project import NoSuchService, ConfigurationError
from ..service import BuildErro... | ault: directory name)
Commands:
build Build or rebuild services
help Get help on a command
kill Kill containers
logs View output from containers
port Print the public port for a port binding
ps List containers
pull Pulls service images
... | rvices
restart Restart services
up Create and start containers
"""
def docopt_options(self):
options = super(TopLevelCommand, self).docopt_options()
options['version'] = "docker-compose %s" % __version__
return options
def build(self, project, options):
... |
shacknetisp/fourthevaz | modules/core/api/__init__.py | Python | mit | 3,378 | 0.00148 | # -*- coding: utf-8 -*-
import configs.module
import wsgiref.simple_server
import select
import json
import bot
from urllib import parse
import irc.fullparse
import irc.splitparse
import os.path
def init(options):
m = configs.module.Module(__name__)
if 'wserver' in options['server'].state:
del options... | e_hook('api.path.%s' % path,
ret, self.server, q, environ)
else:
ret['message'] = 'invalid action'
ret['status'] = 'error'
self.server.do_base_hook('api.action.%s' % action,
ret, self.server, q, | environ)
if '_html' in ret:
return [ret['_html'].encode('utf-8')]
except KeyError:
pass
return [json.dumps(ret).encode('utf-8')]
def apiactioncommand(ret, server, q, environ):
del ret['message']
ip = environ['REMOTE_ADDR']
if 'command' not in q:
... |
jledbetter/openhatch | mysite/profile/migrations/0088_add_field_portfolioentry_receive_maintainer_updates.py | Python | agpl-3.0 | 17,027 | 0.008398 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'PortfolioEntry.receive_maintainer_updates'
db.add_column('profile_portfolioentry', 're... | ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'customs.webresponse': {
'Meta': {'object_name': 'WebResponse'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'response_headers': ('django.db.models.fields.TextField', []... | TextField', [], {})
},
'profile.citation': {
'Meta': {'object_name': 'Citation'},
'contributor_role': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}),
'data_import_attempt': ('django.db.models.fields.related.ForeignKey', [], {'to': "or... |
tchellomello/home-assistant | homeassistant/components/songpal/__init__.py | Python | apache-2.0 | 1,582 | 0.002528 | """The songpal component."""
from collections import OrderedDict
import logging
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import Home... | istantType, config: OrderedDict) -> bool:
"""Set up songpal environment."""
conf = config.get(DOMAIN)
if conf is None:
return True
for config_entry in conf:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source":... | PORT},
data=config_entry,
),
)
return True
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
"""Set up songpal media player."""
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, "media_player")
)
... |
Rohit4198/Calendargui | main.py | Python | mit | 4,749 | 0.003159 |
import Tkinter
import calendar
import time
import tkFont
import ttk
def sequence(*functions): # to run 2 or more functions on button click
for function in functions:
function()
def update(y, m, tx, curdate): # generate calendar with right colors
calstr = calendar.month(y, m)
tx.configure(state=T... | inter.CENTER)
tx.configure(state=Tkinter.DISABLED) # make text view not editable
top = Tkinter.Tk()
top.title("Calendar")
top.minsize(200, 250)
top.maxsize(200, 200)
logo = Tkinter.PhotoImage(file="r.gif")
top.tk.call('wm', 'iconphoto', top._w, logo)
segoe = t | kFont.Font(family='Segoe UI')
curtime = time.localtime()
year = Tkinter.StringVar()
month = Tkinter.StringVar()
yearInt = curtime[0]
monthInt = curtime[1]
dateInt = curtime[2]
HLayout = ttk.PanedWindow(top, orient=Tkinter.HORIZONTAL)
ctx = Tkinter.Text(top, padx=10, pady=10, bg="#E6E6FA", relief=Tkinter.FLAT, height=9,... |
maxive/erp | addons/website_hr_recruitment/tests/test_website_hr_recruitment.py | Python | agpl-3.0 | 830 | 0.003614 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.api import Environment
import odoo.tests
@odoo.tests.tagged('post_install', '-at | _install')
class TestWebsiteHrRecruitmentForm(odoo.tests.HttpCase):
def test_tour(self):
self.phantom_js("/", "odoo.__DEBUG__.services['web_tour.tour'].run('website_hr_recruitment_tour')", "odoo.__DEBUG__.services['web_tour.tour'].tours.website_hr_recruitment_tour.ready")
# check result
rec... | '=', '### HR RECRUITMENT TEST DATA ###')])
self.assertEqual(len(record), 1)
self.assertEqual(record.partner_name, "John Smith")
self.assertEqual(record.email_from, "john@smith.com")
self.assertEqual(record.partner_phone, '118.218')
|
ygol/odoo | addons/website_blog/models/website.py | Python | agpl-3.0 | 2,036 | 0.002456 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, _
from odoo.addons.http_routing.models.ir_http import url_for
class Website(models.Model):
_inherit = "website"
@api.model
def page_search_dependencies(self, page_id=False):
... | ndencies(page_id=page_id)
page = self.env['website.page'].browse(int(page_id))
path = page.url
dom = [
('content', 'ilike', path)
]
posts = self.env['blog.post'].search(dom)
if posts:
page_key = _('Blog Post')
if len(posts) > 1:
... | key = _('Blog Posts')
dep[page_key] = []
for p in posts:
dep[page_key].append({
'text': _('Blog Post <b>%s</b> seems to have a link to this page !') % p.name,
'item': p.name,
'link': p.website_url,
})
return dep
@a... |
elbeardmorez/quodlibet | quodlibet/tests/test_po.py | Python | gpl-2.0 | 11,377 | 0.000176 | # -*- coding: utf-8 -*-
# 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.
from tests import TestCase, skipUnless
from tes... | cks strings starting and ending with a tag.
# TODO: fix for all cases by adding a translator comment
# and insert
if re.match("<.*?>.*</.*?>", entry.msgid):
fails.append(entry)
self.conclude(fails, "contains markup, remove it!")
def test_terms_letter_cas... | ays written with a specific
combination of lower and upper case letters.
Examples:
MusicBrainz - ok
musicbrainz - lower case letters
musicbrainz_track_id - ok
musicbrainz.org - ok
"""
terms = (
'AcoustID', 'D-Bus', 'Ex ... |
inuitwallet/plunge | client/client.py | Python | mit | 21,310 | 0.004927 | #! /usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2015 creon (creon.nu@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... | yright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN ... | RISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
"""
import os
import sys
import time
import json
import tempfile
import signal
import subprocess
import threading
import logging
import logging.handlers
import socket
from math import ceil
from thread import start_new_... |
edisonlz/fruit | web_project/base/site-packages/grappelli/dashboard/dashboards.py | Python | apache-2.0 | 6,499 | 0.004462 | """
Module where admin tools dashboard classes are defined.
"""
from django.template.defaultfilters import slugify
from django.utils.importlib import import_module
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.contrib.contenttypes.models import Content... | LinkList(
_('Support'),
children=[
{
'title': _('Django documentation'),
'url': 'http://docs.djangoproject.com/',
'exter | nal': True,
},
{
'title': _('Django "django-users" mailing list'),
'url': 'http://groups.google.com/group/django-users',
'external': True,
},
{
'title': _('Django irc channel')... |
sighalt/pyhooker | examples/example_classes/wheel.py | Python | gpl-3.0 | 95 | 0 | from .interfaces import I | Wheel
_ | _author__ = 'sighalt'
class MichelinWheel(IWheel):
pass
|
dougnd/matplotlib2tikz | test/testfunctions/image_plot.py | Python | mit | 753 | 0 | # -*- coding: utf-8 -*-
#
desc = 'An \\texttt{imshow} plot'
phash = '7558d3b30f634b06'
def plot():
from matplotlib import rcParam | s
from matplotlib import pyplot as pp
import os
try:
from PIL import Image
except ImportError:
raise RuntimeError('PIL must be installed to run this example')
this_dir = os.path.dirname(os.path.realpath(__file__))
lena = Image.open(os.path.join(this_dir, 'lena.png'))
dpi = r... | pp.imshow(lena, origin='lower')
# Set the current color map to HSV.
pp.hsv()
pp.colorbar()
return fig
|
tmeits/pybrain | pybrain/tests/unittests/structure/networks/custom/test_capturegame_network.py | Python | bsd-3-clause | 1,368 | 0.001462 | """
Build a CaptureGameNetwork with LSTM cells
>>> from pybrain.structure.networks.custom import CaptureGameNetwork
>>> from pybrain import MDLSTMLayer
>>> size = 2
>>> n = CaptureGameNetwork(size = size, componentclass = MDLSTMLayer, hsize = 1, peepholes = False)
Check it's string representation
>... | <MDLSTMLayer 'hidden(0, 0, 3)'>, <SigmoidLayer 'output'>]
Connections:
[<IdentityConnection ...
Check some of the connections dimensionalities
>>> c1 = n.connections[n['hidden(1, 0, 3)']][0]
>>> c2 = n.connections[n['hidden(0, 1, 2)']][-1]
>>> print((c1.indim, c1.outdim))
(1, 1)
>>>... | >>> from pybrain.tests import xmlInvariance
>>> xmlInvariance(n)
Same representation
Same function
Same class
Check its gradient:
>>> from pybrain.tests import gradientCheck
>>> gradientCheck(n)
Perfect gradient
True
"""
__author__ = 'Tom Schaul, tom@idsia.ch'
from pybrain.tests im... |
washimimizuku/frozen-flower | frozenflower2/frontend/admin.py | Python | mit | 218 | 0 | from django.contrib import admin
from frozenflower.frontend.models import *
admin.site.register(Tag)
admin.site.register(Article)
admin.site.register(Comment)
admin.site.register(Feed)
admin.site.register(Repository | )
| |
technologiescollege/Blockly-rduino-communication | scripts_XP/Lib/site-packages/idlexlib/idlexMain.py | Python | gpl-3.0 | 12,959 | 0.005093 | #! /usr/bin/env python
## """
## Copyright(C) 2011 The Board of Trustees of the University of Illinois.
## All rights reserved.
##
## Developed by: Roger D. Serwy
## University of Illinois
##
## Permission is hereby granted, free of charge, to any person obtaining
## a copy of th... | h.split(fullfile)
if filename.startswith('idlex-'):
new_filename = filename
else:
new_filename = 'idlex-' + filename
new_fullfile = os.path.join(dir | ectory, new_filename)
value.file = new_fullfile
value.Load()
mod = extensionManager.load_extension('idlexManager')
mod.extensionManager = extensionManager
mod.version = version
mod.update_globals()
# add idlex to the extension list
e = idleConf.userCfg['extensions']
if not... |
google/google-ctf | third_party/edk2/ArmPlatformPkg/Scripts/Ds5/profile.py | Python | apache-2.0 | 11,068 | 0.02331 | #!/usr/bin/python
#
# Copyright (c) 2014, ARM Limited. All rights reserved.
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.o... | module_value['cycles'] += cycles
add_cycles_to_function.prev_func_name = func_name
add_cycles_to_function.prev_module_name = module_name
add_cycles_to_function.prev_entry = module_value
return (func_name, module_name)
elif (module_value['end'] == 0):
module_value['cycles'] += cyc... | dule_name
add_cycles_to_function.prev_entry = module_value
return (func_name, module_name)
# Workaround to fix the 'info func' limitation that does not expose the 'static' function
module_name = get_module_from_addr(modules, addr)
functions[func_name] = {}
functions[func_name][module_name] = {}... |
bahattincinic/arguman.org | web/premises/migrations/0031_premise_weight.py | Python | mit | 431 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrat | ions.Migration):
dependencies = [
('premises', '0030_report_reason'),
]
operations = [
migrations.AddField(
model_name='premise',
| name='weight',
field=models.IntegerField(default=0),
preserve_default=True,
),
]
|
Lilykos/invenio | invenio/ext/sqlalchemy/__init__.py | Python | gpl-2.0 | 7,906 | 0.000379 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2011, 2012, 2013, 2014, 2015 CERN.
#
# Invenio 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 (a... | ractice should never be called.
It is only provided to satisfy pylint that it is okay not to
raise E1101 errors in the client code.
:see http://stack | overflow.com/a/3515234/780928
"""
raise AttributeError("%r instance has no attribute %r" % (self, name))
def schemadiff(self, excludeTables=None):
"""Generate a schema diff."""
from migrate.versioning import schemadiff
return schemadiff \
.getDiffOfModelAgainstDa... |
anthimeschrefheere/openClassM | openClassM/forum/urls.py | Python | gpl-2.0 | 274 | 0.043796 | # from django.conf.urls import patterns, url
# urlpatterns = patterns('',
# url | (r'^forum/$', 'forum.views.forum_dir'),
# url(r'^forum/(?P<forum_id>\d+)/$', 'forum.views.thread_dir'),
# url(r'^thread/(?P<thread_id>\d+)/$', 'forum.views.post_d | ir'),
# )
|
seeARMS/Computer-Network-Queue-Simulation | rando.py | Python | mit | 774 | 0.00646 | import numpy as np
'''
pps = packets per second
rand = the randomly generated number
'''
def exponential(pps, rand):
X = (-1 / pps) * np.log(1 - rand)
return X
def generate_random():
# this needs to incl | ude 1 though?
# currently its [0, 1)
s = np.random.uniform
return s
'''
ticks * tick_duration is the time duration
for which we want to simulate the system
'''
def tick(ticks):
for i in ticks:
'''todo: call the data packet generator to try to generate
a new data packet
... | will end in this tick, thereby pushing the packet out of queue
'''
|
jirikuncar/invenio-utils | invenio_utils/datacite.py | Python | gpl-2.0 | 4,248 | 0.000471 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2015 CERN.
#
# Invenio 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... | ze object."""
self.url = "http://data.datacite.org/application | /x-datacite+xml/"
self.error = False
try:
data = urllib2.urlopen(self.url + doi).read()
except urllib2.HTTPError:
self.error = True
if not self.error:
# Clean the xml for parsing
data = re.sub('<\?xml.*\?>', '', data, count=1)
... |
JohnPapps/django-oracle-drcp | django-oracle-drcp/compiler.py | Python | bsd-2-clause | 73 | 0 | # pylint: di | sable=W0401
from django.db.backends.oracle.compiler im | port *
|
thomec/tango | lists/models.py | Python | gpl-2.0 | 850 | 0 | # lists/models.py
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
class List(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
def get_absolute_url(self):
return reverse('view_list', args=[self.id])
... | = ('id',)
unique_toge | ther = ('list', 'text')
def __str__(self):
return self.text
|
riccardodg/lodstuff | lremap/it.cnr.ilc.lremapowl/src/lremapobj/paper.py | Python | gpl-3.0 | 3,059 | 0.014711 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on May 12, 2014
Model Paper
fields:
conf
year
passcode
paper id
status
title
category1
category1
keywords
@author: riccardo
'''
class Paper(object):
__conf=""
__year=""
__passcode=""
__pid=""
__status=""
__title=""
... |
self.__year = value
def del_conf(self):
del self.__conf
def del_year(self):
del | self.__year
conf = property(get_conf, set_conf, del_conf, "conf's docstring")
year = property(get_year, set_year, del_year, "year's docstring")
|
beeftornado/sentry | src/sentry/runner/commands/createuser.py | Python | bsd-3-clause | 3,480 | 0.002011 | from __future__ import absolute_import, print_function
import click
import sys
from sentry.runner.decorators import configuration
def _get_field(field_name):
from sentry.models import User
return User._meta.get_field(field_name)
def _get_email():
from django.core.exceptions import ValidationError
... | .save(force_update=force_update)
| click.echo("User updated: %s" % (email,))
else:
click.echo("User: %s exists, use --force-update to force" % (email,))
sys.exit(3)
else:
user.save()
click.echo("User created: %s" % (email,))
# TODO(dcramer): kill this when we improve flows
if se... |
robwarm/gpaw-symm | gpaw/test/pw/davidson_pw.py | Python | gpl-3.0 | 1,034 | 0.000967 | from ase import Atom, Atoms
from gpaw import GPAW
from g | paw.test import equal
a = 4.05
d = a / 2**0.5
bulk = Atoms([Atom('Al', (0, 0, 0)),
Atom('Al', (0.5, 0.5, 0.5))], pb | c=True)
bulk.set_cell((d, d, a), scale_atoms=True)
h = 0.25
calc = GPAW(mode='pw',
nbands=2*8,
kpts=(2, 2, 2),
convergence={'eigenstates': 7.2e-9, 'energy': 1e-5})
bulk.set_calculator(calc)
e0 = bulk.get_potential_energy()
niter0 = calc.get_number_of_iterations()
calc = GPAW(mode='pw... |
cernanalysispreservation/analysis-preservation.cern.ch | cap/modules/deposit/minters.py | Python | gpl-2.0 | 1,769 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of CERN Analysis Preservation Framework.
# Copyright (C) 2018 CERN.
#
# CERN Analysis Preservation Framework 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... | to it by virtue of its status
# as an Intergovernmental Or | ganization or submit itself to any jurisdiction.
# or submit itself to any jurisdiction.
"""PID minters for drafts."""
from __future__ import absolute_import, print_function
import uuid
from invenio_pidstore.models import PersistentIdentifier, PIDStatus
def cap_deposit_minter(record_uuid, data):
"""Mint deposi... |
leppa/home-assistant | homeassistant/components/hue/sensor.py | Python | apache-2.0 | 3,075 | 0.000325 | """Hue sensor entities."""
from aiohue.sensors import TYPE_ZLL_LIGHTLEVEL, TYPE_ZLL_TEMPERATURE
from homeassistant.components.hue.sensor_base import (
GenericZLLSensor,
SensorManager,
async_setup_entry as shared_async_setup_entry,
)
from homeassistant.const import (
DEVICE_CLASS_ILLUMINANCE,
DEVICE... | if self.sensor.lightlevel is None:
return None
# https://developers.meethue.com/develop/hue-api/supported-devices/#clip_zll_lightlevel
# Light level in 10000 log10 (lux) +1 measured by sensor. Logarithm
# scale used because the human eye adjusts to light levels and small
... | und(float(10 ** ((self.sensor.lightlevel - 1) / 10000)), 2)
@property
def device_state_attributes(self):
"""Return the device state attributes."""
attributes = super().device_state_attributes
attributes.update(
{
"lightlevel": self.sensor.lightlevel,
... |
sibirrer/astrofunc | astrofunc/LightProfiles/hernquist.py | Python | mit | 2,501 | 0.001999 | import numpy as np
class Hernquist(object):
"""
class for pseudo Jaffe lens light (2d projected light/mass distribution
"""
def __init__(self):
from astrofunc.LensingProfiles.hernquist import Hernquist as Hernquist_lens
self.lens = Hernquist_lens()
def function(self, x, y, sigma0,... | )
def light_3d(self, r, sigma0, Rs):
"""
:param y:
:param sigma0:
:param Rs:
:param center_x:
:param center_y:
:return:
"""
rho0 = self.lens.sigma2rho(sigma0, Rs)
return self.lens.density(r, rho0, Rs)
class Hernquist_Ellipse(object)... | projected light/mass distribution
"""
def __init__(self):
from astrofunc.LensingProfiles.hernquist import Hernquist as Hernquist_lens
self.lens = Hernquist_lens()
self.spherical = Hernquist()
def function(self, x, y, sigma0, Rs, q, phi_G, center_x=0, center_y=0):
"""
... |
NewGlobalStrategy/NetDecisionMaking | models/0.py | Python | mit | 1,624 | 0.009236 | # - Coding UTF8 -
#
# Networked Decision Making
# Site: http://code.google.com/p/global-decision-making-system/
#
# License Code: GPL, General Public License v. 2.0
# License Content: Creative Commons Attribution 3.0
#
# Also visit: www.web2py.com
# or Groups: http://groups.google.com/group/web2py
# For d... | ython social auth will hopefully be added I don't think dual login worked with google but
#lets setup again and see
#Plan for this for now is that netdecisionmaking will use web2py and Janrain while
#globaldecisionmaking will use google - for some reason Janrain doesn't seem
#to come up with google as a login and goog... | n does not support dual methods
#reason for which has not been investigated
#settings.logon_methods = 'web2py'
#settings.logon_methods = 'google'
#settings.logon_methods = 'janrain'
settings.logon_methods = 'web2pyandjanrain'
settings.verification = False
settings.approval = False
|
rdo-management/neutron | neutron/db/l3_dvr_db.py | Python | apache-2.0 | 31,991 | 0.000344 | # Copyright (c) 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 ... | "listed"), router_db['id'])
def check_router_has_no_firewall(self, context, router_db):
"""Check if FWaaS is associated with the legacy router."""
fwaas_service = manager.NeutronManager.get_service_plugins().get(
constants.FIREWALL)
if fwaas_service:
... | _service.get_firewalls(
context,
filters={'tenant_id': [router_db['tenant_id']]})
if tenant_firewalls:
raise l3.RouterInUse(router_id=router_db['id'])
return True
def check_router_has_no_vpnaas(self, context, router_db):
"""Check if VPNaaS... |
coreos/mockldap | setup.py | Python | bsd-2-clause | 1,346 | 0.000743 | #!/usr/bin/env python
from setuptools import setup
try:
import unittest2 # noqa
except ImportError:
test_loader = 'unittest:TestLoader'
else:
test_loader = 'unittest2:TestLoader'
setup(
na | me='mockldap',
version='0.1.8',
description=u"A simple mock implementation of python-ldap.",
long_description=open('README').read(),
url='http://bitbucket.org/psagers/mockldap/' | ,
author='Peter Sagerson',
author_email='psagers.pypi@ignorare.net',
license='BSD',
packages=['mockldap'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Programming Language :: Python',
'Intended Audience :: Developers',
'I... |
crits/mcrits | transforms/relatedemails.py | Python | bsd-2-clause | 859 | 0 | from MaltegoTransform import *
from mcrits_utils import *
crits = mcrits()
me = MaltegoTransform()
me.parseArguments(sys.argv)
id_ = me.getVar('id')
crits_type = me.getVar('crits_type')
for result in crits.get_related(crits_type, id_, 'Email'):
# For each related object, get the details.
obj = crits.get_sing... | spla | yName='subject',
value=obj.get('subject', ''))
me.returnOutput()
|
remotesyssupport/koan | koan/imagecreate.py | Python | gpl-2.0 | 5,995 | 0.015013 | """
Virtualization installation functions for image based deployment
Copyright 2008 Red Hat, Inc.
Bryan Kearney <bkearney@redhat.com>
Original version based on virt-image
David Lutterkort <dlutter@redhat.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General P... | bridge = bridge, conn=guest.conn)
else:
default_network = virtinst.util.default_network()
#dev api
#default_network = | virtinst.util.default_network(guest.conn)
nic = VirtualNetworkInterface(random_mac(), type=default_network[0], network=default_network[1])
guest.nics.append(nic)
def start_install(name=None, ram=None, disks=None,
uuid=None,
extra=None,
... |
MTG/essentia | test/src/unittests/tonal/test_tristimulus.py | Python | agpl-3.0 | 2,180 | 0.011927 | #!/usr/bin/env python
# Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 (FSF), e... | [0.1666666667, 0, 0])
def test4Freqs(self):
mags = [1,2,3,4]
freqs = [100, 435, 6547, 24324]
self.assertAlmostEqualVector(
Tristimulus()(freqs, mags),
[.1, .9, 0])
def test5Freqs(self):
mags = [1,2,3,4,5]
freqs = [100, 324, 5678, 589... | elf):
freqs = [1,2,1.1]
mags = [0,0,0]
self.assertComputeFails(Tristimulus(), freqs, mags)
def testFreqMagDiffSize(self):
freqs = [1]
mags = []
self.assertComputeFails(Tristimulus(), freqs, mags)
def testEmpty(self):
freqs = []
mags = []
... |
misuzu/torpedomsg | examples/client.py | Python | mit | 1,270 | 0 | import logging
import signal
import tornado.ioloop
import tornado.log
import torpedomsg
tornado.log.enable_pretty_logging()
class LineReader(object):
def __init__(self, host, port):
self.client = torpedomsg.TorpedoClient(host, port)
self.client.set_connect_callback(self.connect_callback)
... | allback(self, address, msg):
cmd = msg.get('cmd')
data = msg.get('data')
if cmd == 'updates' or cmd == 'snapshot':
logging.info('%s: %s', cmd, len(data))
if __name__ == '__main__':
ioloop = tornado.ioloop.IOL | oop.instance()
reader = LineReader('127.0.0.1', 8888)
def handle_signal(sig, frame):
logging.warning('received signal: %r', sig)
ioloop.add_callback_from_signal(ioloop.stop)
signal.signal(signal.SIGINT, handle_signal)
signal.signal(signal.SIGTERM, handle_signal)
ioloop.start()
|
mzdaniel/oh-mainline | vendor/packages/amqplib/amqplib/client_0_8/transport.py | Python | agpl-3.0 | 7,349 | 0.002721 | """
Read/Write AMQP frames over network transports.
2009-01-14 Barry Pederson <bp@barryp.org>
"""
# Copyright (C) 2009 Barry Pederson <bp@barryp.org>
#
# 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 Softwa... | s):
"""
Write a string out to the SSL | socket fully.
"""
while s:
n = self.sslobj.write(s)
if not n:
raise IOError('Socket closed')
s = s[n:]
class TCPTransport(_AbstractTransport):
"""
Transport that deals directly with TCP socket.
"""
def _setup_transport(self):
... |
ltilve/chromium | tools/chrome_proxy/integration_tests/chrome_proxy_benchmark.py | Python | bsd-3-clause | 6,442 | 0.017075 | # Copyright 2014 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.
from integration_tests import chrome_proxy_measurements as measurements
from integration_tests import chrome_proxy_pagesets as pagesets
from telemetry import... | .top_20'
class ChromeProxyDataSavingDirect(benchmark.Benchmark):
tag = 'data_saving_direct'
test = measurements.ChromeProxyDataSaving
page_set = pagesets.Top20PageSet
@classmethod
def Name(cls):
return 'chrome_proxy_benchmark.data_saving_direct.top_20'
class ChromeProxyDataSavingSynthetic(ChromeProxy... | d
def Name(cls):
return 'chrome_proxy_benchmark.data_saving.synthetic'
class ChromeProxyDataSavingSyntheticDirect(ChromeProxyDataSavingDirect):
page_set = pagesets.SyntheticPageSet
@classmethod
def Name(cls):
return 'chrome_proxy_benchmark.data_saving_direct.synthetic'
class ChromeProxyHeaderValida... |
limscoder/amfast | examples/streaming/python/cp_server.py | Python | mit | 1,741 | 0.004021 | """An example server using the CherryPy web framework.
To run the example execute the command:
python cp_server.py
"""
import os
import optparse
import logging
i | mport sys
import cherrypy
import amfas | t
from amfast.remoting.cherrypy_channel import CherryPyChannelSet, StreamingCherryPyChannel
class App(CherryPyChannelSet):
"""Base web app."""
@cherrypy.expose
def index(self):
raise cherrypy.HTTPRedirect('/streaming.html')
if __name__ == '__main__':
usage = """usage: %s [options]""" % __file... |
dstockwell/catapult | dashboard/dashboard/alerts.py | Python | bsd-3-clause | 6,457 | 0.006659 | # Copyright 2015 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.
"""Provides the web interface for displaying an overview of alerts."""
__author__ = 'sullivan@google.com (Annie Sullivan)'
import datetime
import json
impo... | entities."""
return [_GetStoppageAlertDict(a) for a in stoppage_alerts]
def GetAnomalyDict(anomaly_entity, bisect_status=None):
"""Returns a dictionary for an Anomaly which can be encoded as JSON.
Args:
anomaly_entity: An Anomaly entity.
bisect_status: String status of bisect run.
Returns:
A dic... | 'median_after_anomaly': anomaly_entity.median_after_anomaly,
'median_before_anomaly': anomaly_entity.median_before_anomaly,
'percent_changed': '%s' % anomaly_entity.GetDisplayPercentChanged(),
'improvement': anomaly_entity.is_improvement,
'bisect_status': bisect_status,
'recovered': ... |
Nate28/mayaxes | mayaxes.py | Python | gpl-2.0 | 6,007 | 0.013651 | # -*- coding: utf-8 -*-
"""
Created on Tue May 28 12:20:59 2013
=== MAYAXES (v1.1) ===
Generates a set of MayaVI axes using the mayavi.mlab.axes() object with a
white background, small black text and a centred title. Designed to better
mimic MATLAB style plots.
Unspecified arguments will be set to default values... | er).
=== Inputs ===
'title' Figure title text (default = 'VOID')
'xlabel' X axis label text (default = 'X')
'ylabel' Y axis label text (default = 'Y')
'z | label' Z axis label text (default = 'Z')
'handle' Graphics handle of object (if bounding box is to be plotted)
'title_size' Font size of the title text (default = 25)
'ticks' Number of divisions on each axis (default = 7)
'font_scaling' Font scaling factor for axis text (default = 0.7)
'backgr... |
ContinuumIO/dask | dask/utils.py | Python | bsd-3-clause | 34,443 | 0.000436 | from datetime import timedelta
import functools
import inspect
import os
import shutil
import sys
import tempfile
import re
from errno import ENOENT
from collections.abc import Iterator
fr | om contextlib import contextmanager
from importlib import import_module
from numbers import Integral, Number
from threading import Lock
import uuid
from weakref import WeakValueDictionary
from functools import lru_cache
from .core import get_deps
from .optimization import key_split # noqa: F401
system_encoding = s... | else:
return func(*args)
def deepmap(func, *seqs):
""" Apply function inside nested lists
>>> inc = lambda x: x + 1
>>> deepmap(inc, [[1, 2], [3, 4]])
[[2, 3], [4, 5]]
>>> add = lambda x, y: x + y
>>> deepmap(add, [[1, 2], [3, 4]], [[10, 20], [30, 40]])
[[11, 22], [33, 44]]
... |
stfp/memopol2 | apps/meps/models.py | Python | agpl-3.0 | 1,081 | 0.002775 | from django.db import models
from couchdbkit.ext.django.schema import Document, StringProperty, ListProperty
class MEP(Document):
id = StringProperty()
trophies_ids = ListProperty()
@property
def trophies(self):
"""
Retrieves trophies Dj | ango's objects from trophies_ids.
"""
from trophies.models import ManualTr | ophy
return [ManualTrophy.objects.get(id=trophy_id) for trophy_id in self.trophies_ids]
class Position(models.Model):
mep_id = models.CharField(max_length=128)
subject = models.CharField(max_length=128)
content = models.CharField(max_length=512)
submitter_username = models.CharField(max_length... |
nioinnovation/python-xbee | xbee/tests/test_fake.py | Python | mit | 1,321 | 0.003028 | #! /usr/bin/python
"""
test_fake.py
By Paul Malmsten, 2010
pmalmsten@gmail.com
Tests fake device objects for proper | functionality.
"""
import unittest
from xbee.tests.Fake import Serial
class TestFakeSerialRead(unittest.TestCase):
"""
Fake Serial class should work as intended to emluate reading from a serial port.
"""
def setUp(self):
"""
Create a fake read device for each test.
... | """
self.device = Serial()
self.device.set_read_data("test")
def test_read_single_byte(self):
"""
Reading one byte at a time should work as expected.
"""
self.assertEqual(self.device.read(), 't')
self.assertEqual(self.device.read(), 'e')
sel... |
kura/kura.io | plugins/pelican_gist/test_plugin.py | Python | mit | 2,786 | 0.000359 | # -*- coding: utf-8 -*-
"""
Test pelican-gist
=================
Test stuff in pelican_gist.
"""
from __future__ import unicode_literals
import os
from pelican_gist import plugin as gistplugin
from mock import patch
import requests.models
def test_gist_url():
gist_id = str(3254906)
filename = 'brew-update-n... | dy = """Some gist body"""
# Make sure there is no cache
for f in (gistplugin.cache_filename(path_base, gist_id),
gistplugin.cache_filename(path_base, gist_id, filename)):
if os.path.exists(f):
os.remove(f)
# Get an empty cache
cache_file = gistplugin.get_cache(path_ba... | che file
gistplugin.set_cache(path_base, gist_id, body)
# Fetch the same file
cached = gistplugin.get_cache(path_base, gist_id)
assert cached == body
# Set a cache file
gistplugin.set_cache(path_base, gist_id, body, filename)
# Fetch the same file
cached = gistplugin.get_cache(path_ba... |
kalpana-org/kalpana | kalpana/chapters.py | Python | gpl-3.0 | 19,512 | 0.001025 | # Copyright nycz 2011-2020
# This file is part of Kalpana.
# Kalpana 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.
# Kalpana is di... | commands = [
make_command(
'word-count-chapter',
self.count_chapter_words,
help_text='Print the word count of a chapter',
short_name='c',
arg_help={
'': 'Print the word count of the chapter your cursor is in.... | self.go_to_chapter,
help_text='Jump to a specified chapter.',
short_name='.',
category='movement',
arg_help={
'0': 'Jump to the start of the file.',
'1': 'Jump to the first chapter.',
'n': '... |
kedder/soaring-coupons | coupons/migrations/0004_auto_20191107_2124.py | Python | agpl-3.0 | 580 | 0.001724 | # Generated by Django 2.2.7 on 2019-11-07 21:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("coupons", "0003_auto_20191027_0939"),
]
operations = [
migrations.AlterField(
model_name="coupon",
name="id",
... | ),
),
migrations.AlterField(
model_name="order",
name="notes",
field=models.CharField(max_length=255, null=True | ),
),
]
|
schelleg/PYNQ | pynq/lib/pmod/pmod_led8.py | Python | bsd-3-clause | 5,931 | 0.007587 | # Copyright (c) 2016, Xilinx, 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:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of ... | a LED object.
|
Parameters
----------
mb_info : dict
A dictionary storing Microblaze information, such as the
IP name and the reset name.
index: int
The index of the pin in a Pmod, starting from 0.
"""
if index not in range(PMOD_NUM_DI... |
RudolfCardinal/crate | crate_anon/crateweb/config/urls.py | Python | gpl-3.0 | 18,507 | 0 | #!/usr/bin/env python
"""
crate_anon/crateweb/config/urls.py
===============================================================================
Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of CRATE.
CRATE is free software: you can redistribute it and/or modify
it under... | dmin sites
# -------------------------------------------------------------------------
# ... obfuscate: p351 of Greenfeld_2015.
url(r'^mgr_admin/', mgr_admin_site.urls),
url(r'^dev_admin/', dev_admin_site.urls),
url(r'^res_admin/', res_admin_site.urls),
# ... namespace is defined in call to Admi... | y views
# -------------------------------------------------------------------------
url(r'^build_query/$',
research_views.query_build, name=UrlNames.BUILD_QUERY),
url(r'^query/$',
research_views.query_edit_select, name=UrlNames.QUERY),
url(r'^activate_query/(?P<query_id>[0-9]+)/$',
... |
eabdullin/nlp_mthesis | wordvectormix.py | Python | mit | 2,152 | 0.005112 | import numpy as np
import numpy.core.multiarray as ma
encoding = 'utf8'
unicode_errors = 'strict'
import scipy.spatial.distance as dist
totalcount = 0
alignedcount = 0
from math import *
def square_rooted(x):
return round(sqrt(sum([a * a for a in x])), 3)
def cosine_similarity(x, y):
numerator = sum(a * b ... | nt += 1
if wordvec is not None:
alignedcount += 1
for wordi in xrange(len(vkk_words)):
vec = vkk_vecs[wordi]
# dotres = np.linalg.norm(wordvec - vec)
dotres = cosi | ne_similarity(wordvec,vec)
matrix_rukk[i, j] = dotres
j += 1
j = 0
i += 1
i = 0
j = 0
for word in vkk_words:
wordvec = finvec(word,vru_words,vru_vecs)
if wordvec is not None:
for wordi in range(len(vru_words)):
vec = vru_vecs[wordi]
dotres = cosin... |
ashh87/caffeine | setup.py | Python | gpl-3.0 | 1,042 | 0.013436 | #!/usr/bin/env python
from distutils.core import setup
import os
import sys
def main():
SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
| "share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, dirs, files in os.walk(SHARE_PATH):
data_files.append(tuple((path.replace(SHARE_PATH,"share", 1),
[os.path.join(path, file) for file in files if file n... | name="caffeine",
version="2.4.1",
description="""A status bar application able to temporarily prevent
the activation of both the screensaver and the "sleep" powersaving
mode.""",
author="The Caffeine Developers",
author_email="bnsmith@gmail.com",
url="https://laun... |
operepo/ope | laptop_credential/winsys/misc.py | Python | mit | 1,023 | 0.004888 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys
import time
import uuid
import win32api
import win32con
import win32gui
import win32console
import win32gui
from winsys import core, registry
def set_console_title(text):
title = win32console.GetConsoleTitle()
| win32console.SetConsoleTitle(text)
return title
def console_hwnd():
title = uuid.uuid1().hex
old_title = set_console_title(title)
try:
time.sleep(0.05)
return win32gui.FindW | indow(None, title)
finally:
set_console_title(old_title)
def set_environment(**kwargs):
root = registry.registry("HKC")
env = root.Environment
for label, value in kwargs.iteritems():
env.set_value(label, value)
win32gui.SendMessageTimeout(
win32con.HWND_BROADCAST, win32con.W... |
rwl/openpowersystem | dynamics/dynamics/generators/gen_sync.py | Python | agpl-3.0 | 1,631 | 0.003679 | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# 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; version 2 dated June... | ronous model is | defined for the CIM, with several variations indicated by the 'model type' attribute. This model can be used for all types of synchronous machines (salient pole, solid iron rotor, etc.).
"""
# <<< gen_sync.attributes
# @generated
# >>> gen_sync.attributes
# <<< gen_sync.references
# @generat... |
wackerl91/luna | resources/lib/di/lazyproxy.py | Python | gpl-3.0 | 1,231 | 0.001625 | class LazyProxy(object):
def __init__(self, original_module, original_class, init_args):
self._original_module = original_module
self._original_class = original_class
self._original_init_args = init_args
self._instance = None
def __getattr__(self, name):
if self._instanc... | f):
import importlib
module = importlib.import_module(self._original_module)
class_ = getattr(module, self._original_class)
if self._original_init_args is not None:
for index, arg in enumerate(self._original_init_args):
| if arg[:1] == '@':
from resources.lib.di.requiredfeature import RequiredFeature
self._original_init_args[index] = RequiredFeature(arg[1:]).request()
import inspect
args = inspect.getargspec(class_.__init__)[0]
if args[0] == 'self':
... |
GentlemanBrewing/ADCLibraries-MCP3424 | IOPi/tutorial1.py | Python | mit | 697 | 0 | #!/usr/bin/python3
"""
================================================
ABElectronics IO Pi 32-Channel Port Expander - Tutorial 1
Version 1.0 Created 29/02/2015
Requires python 3 smbus to be installed
run with: python3 tutorial1.py
================================================
This example uses the write_pin and w... | ods to switch pin 1 on
and off on the IO Pi.
"""
from ABE_helpers import ABEHelpers
from ABE_IoPi import IoPi
import time |
i2c_helper = ABEHelpers()
i2c_bus = i2c_helper.get_smbus()
bus = IoPi(i2c_bus, 0x21)
bus.set_port_direction(0, 0x00)
bus.write_port(0, 0x00)
while True:
bus.write_pin(1, 1)
time.sleep(1)
bus.write_pin(1, 0)
time.sleep(1)
|
tatwell/hiring-curve | config/distributions.py | Python | gpl-3.0 | 1,031 | 0.009699 | identity = {
# https://www.census.gov/prod/cen2010/briefs/c2010br-03.pdf
'sex': [('M',49.2),('F',50.8)],
# https://en.wikipedia.org/wiki/Race_and_ethnicity_in_the_United_States
'race': [('O',72.4),('U',12.6)]
}
iq = {
# Class: (mu, sigma)
# http://www.iq | comparisonsite.com/sexdifferences.aspx
'M': (103.08, 14.54), |
'F': (101.41, 13.55),
# https://commons.wikimedia.org/wiki/File:WAIS-IV_FSIQ_Scores_by_Race_and_Ethnicity.png
'O': (103.21, 13.77),
'U': (88.67, 13.68),
# http://isteve.blogspot.com/2005/12/do-black-women-have-higher-iqs-than.html
# See the URL above for the provenance of the figures. As heri... |
championswimmer/minor-1-piBot-videostream | control-codes/python/ultrasonic.py | Python | gpl-2.0 | 1,305 | 0.006897 | #!/usr/bin/python
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#|R|a|s|p|b|e|r|r|y|P|i|-|S|p|y|.|c|o|.|u|k|
#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# ultrasonic_1.py
# Measure distance using an ultrasonic module
#
# Author : Matt Hawkins
# Date : 09/01/2013
# Import required Python libraries
import time
impor... |
while | GPIO.input(GPIO_ECHO)==0:
start = time.time()
while GPIO.input(GPIO_ECHO)==1:
stop = time.time()
# Calculate pulse length
elapsed = stop-start
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = elapsed * 34000
# That was the distance there and back so halve the ... |
starbops/OpenADM | core/src/pox_modules/uipusher.py | Python | gpl-2.0 | 6,837 | 0.041685 | import logging
from pymongo import MongoClient
import json
from bson import json_util
import time
import datetime
logger = logging.getLogger(__name__)
class UIPusher:
def __init__(self,core,parm):
# register event handler
core.registerEventHandler("controlleradapter", self.controllerHandler)
# register webso... | [hashkey][0]
key['counterPacket'] = self.tmpcache[hashkey][1]
key['duration'] = self.tmpcache[hashkey][3]
self.db[self.intervalList[0]].save(key) |
def statisticHandler(self,data):
if self.enable == False:
return "Time\t1\n"
#declare variable
multiGroup = {}
output = "Time"
count = 1
# for hourly query
if int(data['interval']) ==0:
fromTime = datetime.datetime.strptime(data['from'],"%Y-%m-%d")
toTime = datetime.datetime.strptime(data['... |
aurarad/auroracoin | qa/rpc-tests/listsinceblock.py | Python | mit | 2,579 | 0.002714 | #!/usr/bin/env python3
# Copyright (c) 2017 The DigiByte Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import AuroracoinTestFramework
from test_framework.util import assert_equa... | p of the chain (bb4). It would then return
results restricted to bb3-bb4.
Now: listsinceblock finds the fork at ab0 and returns results in the
range bb1-bb4.
This test only checks that [tx0] is present.
'''
assert_equal(self.is_network_split, False)
self.nodes[... | f.nodes[2].getbalance(), 50)
assert_equal(self.nodes[3].getbalance(), 0)
# Split network into two
self.split_network()
assert_equal(self.is_network_split, True)
# send to nodes[0] from nodes[2]
senttx = self.nodes[2].sendtoaddress(self.nodes[0].getnewaddress(), 1)
... |
rr-/dotfiles | cfg/alacritty/__main__.py | Python | mit | 231 | 0 | from libdotfiles.packages import try_install
from libdotfiles.util import HOME_DIR, PKG_DIR, copy_ | file
try_install("alacritty")
copy_file(
PKG_DIR / "alacritty.yml",
HOME_DIR / ".config" / "alacri | tty" / "alacritty.yml",
)
|
plotly/python-api | packages/python/plotly/plotly/validators/parcoords/line/colorbar/_showticklabels.py | Python | mit | 523 | 0 | import _pl | otly_utils.basevalidators
class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self,
plotly_name="showticklabels",
parent_name="parcoords.line.colorbar",
**kwargs
):
super(ShowticklabelsValidator, self).__init__(
plotly... | )
|
tschalch/pyTray | src/lib/reportlab/graphics/testdrawings.py | Python | bsd-3-clause | 9,682 | 0.025098 | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/graphics/testdrawings.py
__version__=''' $Id $ '''
"""This contains a number of routines to generate test drawings
for reportla... | popular demand, the mayor gets a big one at the end
## D.add(NamedReference('MyHouse',
## House,
## transform=mmult(translate(x,110), scale(1.2,1.2)),
## fill = color,
## )
## )
##
##... | steps back out of a drawing node. All the circles are part of a
## group setting the line color to blue; the second circle explicitly
## sets it to red. Ideally, the third circle should go back to blue."""
## D = Drawing(400, 200)
##
##
## G = Group(
## Circle(100,100,20),
## ... |
tsunam/dotd_parser | routes.production-mode.py | Python | mit | 339 | 0.014749 | #
# Currently we don't | do multi-lingual support
#
# See router.example.py for language customization hints
#
# To INSTALL: copy this file to youe base web2py installation:
# ./web2py/routes.py
# Then restart your server deployment ( web2py, apache w/mod_wsgi )
#
routers = dict(
BASE = dict(default_applicatio | n='dotd_parser'),
)
|
davidbarkhuizen/dart | OHLCVAnalysis.py | Python | mit | 1,209 | 0.07196 | from histogram import Histogram
class OHLCVAnalysis:
def __init__(self, dates, open, high, low, close, vol, start, end):
if start > end:
(start, end) = (end, start)
self.report_log = []
max = None
max_date = None
min = None
min_date = None
seq_start = dates[0]
seq_end = dates[0]
... | port_log.append('Min = %s - %s' % (str(min), min_date))
h = Hist | ogram(series)
for l in h.report():
self.report_log.append(l)
def report(self):
return self.report_log
|
lock8/django-rest-framework-jwt-refresh-token | tests/urls.py | Python | mit | 248 | 0 | from django.con | f.urls import url
from refreshtoken.routers import router
from refreshtoken.views import Del | egateJSONWebToken
urlpatterns = router.urls + [
url(r'^delegate/$', DelegateJSONWebToken.as_view(),
name='delegate-tokens'),
]
|
tejesh95/Zubio.in | zubio/allauth/socialaccount/providers/github/tests.py | Python | mit | 1,978 | 0.000506 | from allauth.socialaccount.tests import create_oauth2_tests
from allauth.tests import MockedResponse
from allauth.socialaccount.providers import registry
from .provider import GitHubProvider
class GitHubTests(create_oauth2_tests(registry.by_id(GitHubProvider.id))):
def get_mocked_response(self):
return Mo... | sr/subscriptions",
"public_repos":14,
"hireable":false,
"url":"https://api.github.com/users/pennersr",
"public_gists":0,
"starred_url":"https://api.github.com/users/pennersr/starred{/owner}{/repo}",
| "html_url":"https://github.com/pennersr",
"location":"The Netherlands",
"bio":null,
"name":"Raymond Penners",
"repos_url":"https://api.github.com/users/pennersr/repos",
"followers_url":"https://api.github.com/users/pennersr/followers",
"id":2010... |
catchchaos/Movie-Recommender-GA- | Modular_UI.py | Python | mit | 7,347 | 0.008575 | from movielens import *
import numpy as np
import pickle
import random
import os.path
NO_OF_RECOMMENDATIONS = 10
def load_from_dataset(utility_matrix):
user = []
item = []
ratings = []
d = Dataset()
d.load_users("data/u.user", user)
d.load_items("data/u.item", item)
d.load_ratings("data/u... | if i != 943:
pcs_matrix[i] = pcs(944, i + 1, utility_new, user)
user_index = []
for i in user:
user_index.append(i.id - 1)
user_index = user_index[:943]
user_index = np.array(user_index)
top_similar = [x for (y, x) in sorted(zip(pcs_matrix, user_index), key=lambda pair: pai... | xe < utility_matrix[top_5[i]][j]:
maxe = utility_matrix[top_5[i]][j]
maxi = j
top_5_cluster.append(maxi)
#print top_5_cluster
res = {}
for i in range(len(top_5_cluster)):
if top_5_cluster[i] not in res.keys():
res[top_5_cluster[i]] = len(top_5_clu... |
priscillaboyd/SPaT_Prediction | src/neural_network/RNN_LSTM.py | Python | apache-2.0 | 4,376 | 0.0016 | # Copyright 2017 Priscilla Boyd. 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 ... | l.add(Activation("linear"))
# compile using MSE as loss function for regressio | n, RMSPROP as optimiser
model.compile(loss="mse", optimizer="RMSProp", metrics=['accuracy'])
# return the model
return model
def run_rnn(file):
# define model params
"""
Run the process to train/test a recurrent neural network using LSTM using a given dataset file.
:param string file: Lo... |
alberts/check_mk | web/plugins/icons/inventory.py | Python | gpl-2.0 | 1,927 | 0.007265 | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | e as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU G | eneral Public License for more de-
# ails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
def paint_icon_inventory(what, row, tags, ... |
eunchong/build | third_party/buildbot_8_4p1/buildbot/db/migrate/versions/007_add_object_tables.py | Python | bsd-3-clause | 1,552 | 0.002577 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import sqlalchemy as sa
def upgrade(migrate_engine):
metadata = sa.MetaData()
metadata.bind = migrate_engine
objects = sa.Table("objects", metadata,
sa.Column("id", sa.Integer, primary_key=True... | ss_name', name='object_identity'),
)
objects.create()
object_state = sa.Table("object_state", metadata,
sa.Column("objectid", sa.Integer, sa.ForeignKey('objects.id'),
nullable=False),
sa.Column("name", sa.String(length=256), nullable=False),
sa.Column("... |
the-dalee/gnome-2048 | core/model/commands/engine.py | Python | mit | 1,148 | 0.002613 | import i18n
class EngineCommand(object):
type = "Engine"
description = "Do nothing with engine"
def execute(self):
pass
def undo(self):
pass
class AddScore(EngineCommand):
def __init__(self, engine, score):
self.engine = engine
self.last_score = engine.score
... | engine.state = self.new_state
| def undo(self):
self.engine.state = self.last_state
|
DaveTCode/CreatureRogue | battle_test.py | Python | mit | 2,852 | 0.004558 | """
Script used to test the battle state functionality. Allows the user to pick
a pair of creatures and then uses the game loop to fight them.
Will probably crash when the battle concludes because the rest of the game
will not be set up at that point.
"""
import argparse
import CreatureRogue.creature_... | ("You've selected a: Lv.{0} {1}".format(args.defending_creature_level, defending_species))
attacking_moves = [Move(move_data) for move_data | in attacking_species.move_data_at_level(args.attacking_creature_level)]
wild_creature = BattleCreature(creature_creator.create_wild_creature(game.static_game_data, defending_species, args.defending_creature_level), game.static_game_data)
game_data.battle_data = BattleData(game_data,
... |
DeanSherwin/django-dynamic-scraper | tests/basic/scheduler_test.py | Python | bsd-3-clause | 2,244 | 0.006684 | #Stage 2 Update (Python 3)
import datetime
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from dynamic_scraper.utils.scheduler import Scheduler
class SchedulerTest(TestCase):
def test_config_wrong_def(self):
conf_dict_str = '\
"MIN_TIME" ---- 15,\n\
"MAX... | conf_dict_str = '\
"MIN_TIME": 15,\n\
"MAX_TIME": 10080,\n\
"INITIAL_NEXT_ACTION_FACTOR": 10,\n\
"ZERO_ACTIONS_FACTOR_CHANGE": 20,\n\
"FACTOR_CHANGE_FACTOR": 1.3,\n'
sched = Scheduler(conf_dict_str)
# Successful action, not-initialized next action factor
result = sched.calc_next_... | .calc_next_action_time(True, 13, 9)
self.assertEqual(result, (datetime.timedelta(minutes=150), 10, 0))
# Successful action, new time delta under min time
result = sched.calc_next_action_time(True, 1, 9)
self.assertEqual(result, (datetime.timedelta(minutes=15), 0.769, 0))
... |
coderanger/stratosphere | test/test_template.py | Python | apache-2.0 | 8,830 | 0.001133 | #
# Author:: Noah Kantrowitz <noah@coderanger.net>
#
# Copyright 2014, Balanced, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | /16'}
assert self.d(MyTemplate) == {
'Resources': {
'Subnet': {
'Properties': {
'CidrBlock': '10.0.0.0/16',
'VpcId': {'Ref': 'vpc-teapot'},
'Tags': [{'Key': 'Description' | , 'Value': 'I am a teapot.'}],
},
'Type': 'AWS::EC2::Subnet',
},
},
}
def test_subnet_tags(self):
class MyTemplate(stratosphere.Template):
def subnet(self):
"""I am a teapot."""
return {
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.