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 |
|---|---|---|---|---|---|---|---|---|
GraRi135/letsmeet | src/letsmeet-rrrr.py | Python | mit | 832 | 0.028846 | #!/usr/bin/env python2
import rrrr
import sys
import os.path
import time
if len(sys.argv) < 2 or not os.path.isfile(sys.argv[1]):
print ("Create a timetable from GTFS using rrtimetable.")
sys.exit(-1)
router = rrrr.Raptor(timetable = sys.argv[1])
now = int(time.time())
# print router.stops()[0:10]
best_tim... | r.meet(from_idx = 10, to_idx = 100, depart = now)
calc = []
for sp_index in range(0, len(best_times_a['best_time'])):
a = best_times_a['best_time'][sp_index]
b = best_times_b['best_time'][sp_index]
if a == 65535 or b | == 65535:
continue
d = abs(a - b)
calc.append((sp_index, (a - d) + (b - d),))
s = sorted(calc, key=lambda x: x[1])
print s[0:10]
for x in s[0:10]:
print best_times_a['stop_name'][x[0]]
|
ofek/hatch | tests/backend/builders/test_wheel.py | Python | mit | 40,565 | 0.002169 | import platform
import sys
import zipfile
import pytest
from packaging.tags import sys_tags
from hatchling.builders.plugin.interface import BuilderInterface
from hatchling.builders.utils import get_known_python_major_versions
from hatchling.builders.wheel import WheelBuilder
from hatchling.metadata.utils import DEFAU... | {'name': 'my__app', 'dynamic': ['version']},
'tool': {
'hatch': {
'version': {'path': 'my_app/__about__.py'},
'build': {'targets': {'wheel': {'versions': ['standard']}}},
},
},
}
builder = WheelBuilder(str(pr... | project_path.as_cwd(env_vars={'SOURCE_DATE_EPOCH': '1580601700'}):
artifacts = list(builder.build(str(build_path)))
assert len(artifacts) == 1
expected_artifact = artifacts[0]
build_artifacts = list(build_path.iterdir())
assert len(build_artifacts) == 1
assert expe... |
nyrocron/eve-wspace | evewspace/evewspace/settings.py | Python | apache-2.0 | 8,416 | 0.003446 |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MULTI_TENANT = True
AUTH_USER_MODEL = 'account.EWSUser'
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
# import Celery config
import djcelery
djcelery.setup_loader()
BROKER_URL = 'amqp://guest:guest@localhost:5672/'
ALLOWED_HOSTS = ['*',]
from datetime import time... | pdate':{
'task': 'core.tasks.update_all_alliances',
'schedule': crontab(mi | nute=30, hour=10, day_of_week="tue"),
'args': ()
},
'stale_locations':{
'task': 'Map.tasks.clear_stale_records',
'schedule': timedelta(minutes=5),
'args': ()
},
'cache_reddit':{
'task': 'core.tasks.ca... |
animekita/selvbetjening | sdemo/settings.py | Python | mit | 738 | 0.00271 | from selvbetjening.settings_base import *
ROOT_URLCONF = 'sdemo.urls'
# installed applications
INSTALLED_APPS.extend([
'selvbetjening.frontend.base',
'selvbetjening.front | end.auth',
'selvbetjening.frontend.userportal',
'selvbetjening.frontend.eventportal',
'selvbetjening.frontend.eventsingle',
'selvbetjening.api.re | st',
'sdemo'
])
# Fix, the sdemo fixtures dir is missing from the fixtures list? lets add it manually
import os
FIXTURE_DIRS = (
os.path.join(os.path.abspath(os.path.dirname(__file__)), 'fixtures'),
)
LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/auth/log-in/'
# import localsettings, a per deployment configurati... |
google/empirical_calibration | empirical_calibration/core_test.py | Python | apache-2.0 | 12,713 | 0.003146 | # Copyright 2019 The Empirical Calibration 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ))
@parameterized.parameters((ec.Objective.ENTROPY), (ec.Objective | .QUADRATIC))
def test_autoscale(self, objective):
weights_raw = ec.calibrate(
covariates=self.covariates,
target_covariates=self.target_covariates,
autoscale=False,
objective=objective)[0]
weights_scaled = ec.calibrate(
covariates=self.covariates,
target_covari... |
mdworks2016/work_development | Python/20_Third_Certification/venv/lib/python3.7/site-packages/redis/__init__.py | Python | apache-2.0 | 1,209 | 0 | from redis.client import Redis, StrictRedis
from redis.connection import (
BlockingConnectionPool,
ConnectionPool,
Connection,
SSLConnection,
UnixDomainSocketConnection
)
from redis.utils import from_url
from redis.exceptions import (
AuthenticationError,
AuthenticationWrongNumberOfArgsError... | alue)
except ValueError:
return value
__version__ = '3.5.1'
VERSION = tuple(map(int_or_str, __version__.split('.')))
__all__ = [
'AuthenticationError',
'AuthenticationWrongNumberOfArgsError',
'BlockingConnectionPool',
'BusyLoadingError',
'ChildDeadlockedError',
'Connection',
'... | 'SSLConnection',
'StrictRedis',
'TimeoutError',
'UnixDomainSocketConnection',
'WatchError',
]
|
davidvillaciscalderon/PythonLab | Session 4/bucles.py | Python | mit | 211 | 0.07109 | a = [1 | ,2,3,4,5]
b = [2,3,4,5,6]
to_100=list(range(1,100))
print ("Printing B")
for i in a:
print i
print ("Printing A")
for i in b:
print i
print | ("Print 100 elements")
for i in to_100:
print i |
toast38coza/FlashGiving | campaign/migrations/0010_auto_20160717_1410.py | Python | mit | 892 | 0.002242 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-17 14:10
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Mig | ration(migrations.Migration):
dependencies = [
('campaign', '0009_transaction_status'),
]
operations = [
migrations.AddField(
model_name='campaign',
name='start_date',
field=models.DateTimeField(auto_now | =True, default=datetime.datetime(2016, 7, 17, 14, 10, 41, 17239, tzinfo=utc)),
preserve_default=False,
),
migrations.AlterField(
model_name='campaign',
name='expiry_date',
field=models.DateTimeField(auto_now=True, default=datetime.datetime(2016, 7, 17, 14,... |
cophey/fabric | bddtests/orderer/configuration_pb2.py | Python | apache-2.0 | 7,996 | 0.006253 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: orderer/configuration.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflec... | one),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[] | ,
oneofs=[
],
serialized_start=40,
serialized_end=69,
)
_BATCHSIZE = _descriptor.Descriptor(
name='BatchSize',
full_name='orderer.BatchSize',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='maxMessageCount', full_name='orderer.BatchSize.m... |
usingsky/korean_lunar_calendar_py | korean_lunar_calendar/__init__.py | Python | mit | 115 | 0.017391 | from .korean_lu | nar_calendar import KoreanLunarCalendar
_ | _version__ = '0.2.1'
__all__ = [ 'KoreanLunarCalendar' ]
|
ksmaheshkumar/grr | gui/plugins/fileview.py | Python | apache-2.0 | 51,028 | 0.007722 | #!/usr/bin/env python
# -*- mode: python; encoding: utf-8 -*-
#
"""This plugin renders the filesystem in a tree and a table."""
import cgi
import os
import random
import socket
from django import http
from M2Crypto import X509
from grr.gui import renderers
from grr.gui.plugins import fileview_widgets
from grr.gui.p... | self.results = []
for row in self.proxy:
self.results.append([row.offset, repr(row)])
return renderers.TemplateRenderer.Layout(self, request, response)
class UsersRenderer(semantic.RDFValueArrayRenderer): |
classname = "Users"
name = "Users"
class NetworkAddressRenderer(semantic.RDFValueRenderer):
classname = "NetworkAddress"
name = "Network Address"
layout_template = renderers.Template("{{result|escape}}")
def Layout(self, request, response):
_ = request, response
return self.RenderFromTemplate(se... |
ganga-devs/ganga | ganga/GangaCore/GPIDev/Adapters/ICredentialInfo.py | Python | gpl-3.0 | 9,520 | 0.003046 |
import copy
import os
from abc import ABCMeta, abstractmethod
from datetime import datetime, timedelta
from functools import wraps
import time
import threading
import GangaCore.Utility.logging
from GangaCore.Core.exceptions import CredentialsError
from GangaCore.GPIDev.Credentials.CredentialStore import credential_... | turn self.cache[method.__name__]
| return cache_function
def retry_command(method):
"""
This method attempts to run the same function which can exit due to a CredetialsError
Any other exceptions are raised as appropriate. If a command fails it's assumed to have failed due to an invalid user input and is retried upto crednential_store.retry_... |
leogregianin/pychess | lib/pychess/perspectives/learn/EndgamesPanel.py | Python | gpl-3.0 | 6,976 | 0.000717 | import random
from io import StringIO
from gi.repository import Gtk
from pychess.compat import create_task
from pychess.System.prefix import addDataPrefix
from pychess.Utils.const import WHITE, BLACK, LOCAL, NORMALCHESS, ARTIFICIAL, chr2Sign, chrU2Sign, FAN_PIECES, HINT, ENDGAME
from pychess.Utils.LearnModel import L... |
bfan = []
for piece in black_pieces:
bfan.append(FAN_PIECES[1][chr2Sign[piece]])
self.store.append(["".join(wfan), "".join(bfan), title])
self.tv.set_model(self.store)
self.tv.get_selection().set_mode(Gtk.SelectionMode.BROWSE)
... | learncombo%s" % ENDGAME))
scrollwin = Gtk.ScrolledWindow()
scrollwin.add(self.tv)
scrollwin.show_all()
self.box.pack_start(scrollwin, True, True, 0)
self.box.show_all()
return self.box
def row_activated(self, widget, path, col):
if path is None:
... |
solbirn/pyActiveSync | pyActiveSync/utils/wbxml.py | Python | gpl-2.0 | 12,682 | 0.008437 | ########################################################################
# Copyright (C) 2013 Sol Birnbaum
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the Licen... | ytes.append(possibly_new_code_page.index)
self.current_code_page = possibly_new_code_page
token_tag = self.current_code_page.get_token(split_xmlns_tag[1])
else:
if self.current_code_page.index != self.default_code_page.index:
wbxml_bytes.append(self.Global... | ode_page.index)
self.current_code_page = self.code_pages[self.default_code_page.index]
token_tag = self.current_code_page.get_token(current_node.tag)
token_tag |= 0x40
wbxml_bytes.append(token_tag)
#text, cdata = None, None
if current_node.text:
wb... |
adamcandy/qgis-plugins-meshing-initial | release/rastercalc/rastercalcdialog.py | Python | lgpl-2.1 | 16,388 | 0.038628 | # -*- coding: utf-8 -*-
##########################################################################
#
# QGIS-meshing plugins.
#
# Copyright (C) 2012-2013 Imperial College London and others.
#
# Please see the AUTHORS file in the main source directory for a
# full list of copyright holders.
#
# Dr Adam S. C... | icense for more
# details.
#
# A copy of the GNU General Public License is available on the World Wide Web
# at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
# to the Free S | oftware Foundation, Inc., 59 Temple Place - Suite 330, Boston,
# MA 02111-1307, USA.
#
#******************************************************************************
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
import os.path
import osgeo.gdal as gdal
import os... |
pombredanne/python-ptrace | ptrace/debugger/process_event.py | Python | gpl-2.0 | 1,864 | 0.003219 | from ptrace.signames import signalName
class ProcessEvent(Exception):
"""
A process event: program exit, program killed by a signal, program
received a signal, etc.
The attribute "process" contains the related process.
"""
def __init__(self, process, message):
Exception.__init__(self, ... | rmally (otherwise | )
"""
def __init__(self, process, signum=None, exitcode=None):
pid = process.pid
if signum:
message = "Process %s killed by signal %s" % (
pid, signalName(signum))
elif exitcode is not None:
if not exitcode:
message = "Process %s ex... |
samastur/Impostor | impostor/__init__.py | Python | mit | 229 | 0 | """Impostor."""
__version__ = "2.0.5"
__author__ | = "Marko Samastur"
__email__ = "markos@gaivo.net"
__mantaine | r__ = "Andreu Vallbona"
__mantainer_email__ = "avallbona@gmail.com"
default_app_config = "impostor.apps.ImpostorConfig"
|
googleads/google-ads-python | google/ads/googleads/v9/errors/types/campaign_budget_error.py | Python | apache-2.0 | 2,016 | 0.000992 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ing possible campaign budget
errors.
"""
class CampaignBudgetError(proto.Enum):
r"""Enum describing possible campaign budget errors."""
UNSPECIFIED = 0
UNKNOWN = 1
CAMP | AIGN_BUDGET_CANNOT_BE_SHARED = 17
CAMPAIGN_BUDGET_REMOVED = 2
CAMPAIGN_BUDGET_IN_USE = 3
CAMPAIGN_BUDGET_PERIOD_NOT_AVAILABLE = 4
CANNOT_MODIFY_FIELD_OF_IMPLICITLY_SHARED_CAMPAIGN_BUDGET = 6
CANNOT_UPDATE_CAMPAIGN_BUDGET_TO_IMPLICITLY_SHARED = 7
CANNOT_UPDATE_CAMPAIGN_BUD... |
reider-roque/crypto-challenges | cryptopals/set-1-basics/chal-4/single_byte_xor_cipher.py | Python | mit | 5,192 | 0.003659 | from binascii import unhexlify
from pprint import pprint
from | xor import xor
def get_possible_keys(ciphertext):
key_len = len(ciphertext) // 2
# Generate list of potential keys
possible_keys = []
for i in | range(256):
hex_num = hex(i).split('x')[1].zfill(2)
possible_keys.append(hex_num * key_len)
return possible_keys
def get_possible_plaintexts(ciphertext, keys):
plaintexts = []
for key in keys:
plaintext = unhexlify(xor(ciphertext, key))
plaintexts.append(plaintext)
r... |
nirmitgoyal/longclaw | config.py | Python | mit | 427 | 0 | from redis i | mport Redis
from runserver import host
# rethink config
RDB_HOST = 'localhost'
RDB_PORT = 28015
TODO_DB = 'knuth'
rds = Redis()
DEFAULT_PIC = 'https://github.com/identicons/'
FB_APP_ID = 122742198082740
FB_APP_SECRET = "8474009531f56532cf1e194df6afd53d"
CAPTCHA_SECRET = '6LesFgwTAAAAAIy1YjMlYaWJ27QbqXP4Sm3tcDpI'
A... | redis = Redis()
|
lhupfeldt/multiconf | test/utils/check_containment.py | Python | bsd-3-clause | 2,613 | 0.00421 | # Copyright (c) 2012 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from collections import OrderedDict
from multiconf import AbstractConfigItem
from multiconf.multiconf import _RootEnvProxy, _ItemParentProxy
def _id_name_type(item):
return repr(id(i... | m.contained_in (compared): {ci}
start_item (compared): {start_item}
item.contained_in (actual): {real_ci}
start_item (actual): {real_start_item}
"""
def _mk_ex_msg(item, compared_ci, real_ci, compared_start_item, real_start_item):
if re | al_ci or real_start_item:
return _ex_msg_complex.format(
item=_id_name_type(item), ci=_id_name_type(compared_ci), start_item=_id_name_type(compared_start_item),
real_ci=_id_name_type(real_ci), real_start_item=_id_name_type(real_start_item))
return _ex_msg_simple.format(item=_id_name_... |
jlcarmic/producthunt_simulator | venv/lib/python2.7/site-packages/scipy/spatial/tests/test__plotutils.py | Python | mit | 1,567 | 0.003191 | from __future__ import division, print_function, absolute_import
from numpy.testing import dec, assert_, assert_array_equal
try:
import matplotlib
matplotlib.rcParams['backend'] = 'Agg'
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollectio | n
has_matplotlib = True
except:
has_matplotlib = False
from scipy.spatial import \
delaunay_plot_2d, voronoi_plot_2d, convex_hull_plot_2d, \
Delaunay, Voronoi, ConvexHull
class TestPlotting:
points = [(0,0), (0,1), (1,0), (1,1)]
@dec.skipif(not has_matplotlib, "Matplotlib not available")
... | r = delaunay_plot_2d(obj, ax=fig.gca())
assert_array_equal(obj.simplices, s_before) # shouldn't modify
assert_(r is fig)
delaunay_plot_2d(obj, ax=fig.gca())
@dec.skipif(not has_matplotlib, "Matplotlib not available")
def test_voronoi(self):
# Smoke test
fig = pl... |
jenshnielsen/hemelb | Tools/setuptool/InletProcessing/SurfaceIntersectionFinder.py | Python | lgpl-3.0 | 2,707 | 0.010344 | #
# Copyright (C) University College London, 2007-2012, all rights reserved.
#
# This file is part of HemeLB and is provided to you under the terms of
# the GNU LGPL. Please see LICENSE in the top level directory for full
# details.
#
from vtk import vtkSTLReader, vtkCutter, vtkPlane, \
vtkPolyDataConnectivityF... | utter = vtkCutter()
self.cutter.SetInputConnection(self.reader.GetOutputPort())
self.regionPicker = vtkPolyDataConnectivityFilter()
self.regionPicker.SetInputConnecti | on(self.cutter.GetOutputPort())
self.regionPicker.SetExtractionModeToClosestPointRegion()
self.scaler = vtkTransformPolyDataFilter()
self.scaler.SetInputConnection(self.regionPicker.GetOutputPort())
self.GetFileName = self.reader.GetFileName
self.SetFileName = s... |
marinkaz/orange3 | Orange/widgets/utils/plot/owpoint.py | Python | bsd-2-clause | 2,028 | 0.001972 | """
#####################
Point (``owpoint``)
#####################
.. class:: OWPoint
Represents a point on the plot, usually a part of a curve, or in a legend item.
The point is identified with its symbol, color, size, label, and state, where the state can be ether unselected (default),
marker, or sele... | ed, ``False`` otherwise.
.. method:: set_marked(marked)
Sets the point's marked state to ``marked``
.. method:: is_marked()
:returns: ``True`` if the point is marked, ``False`` otherwise.
.. method:: set_label(label)
Sets the point's label to ``label``.
The label is dis... | r the symbol.
.. method:: label()
:returns: The point`s label, set with :meth:`set_label`
:rtype: str
"""
from PyQt4.QtGui import QGraphicsPathItem, QPen, QBrush
from PyQt4.QtCore import Qt, QPointF
import orangeqt
OWPoint = orangeqt.Point
|
zejacobi/DeltaGreen | LetsEncryptConfig.py | Python | gpl-3.0 | 196 | 0.005102 | ROOT = '/.well-known/acme-challenge'
ENDPOINT = '/k9s7WeOPg3HdSjwlAqEVRxnezsGGe-CFOwPfOcU3VgU'
RESPONSE = 'k9s7WeOPg3 | HdSjwlAqEVRxnezsGGe-CFOwPfOc | U3VgU.QBkCfzPq0mKXIJSktgl4_b7psKazh3MSZ8juWnZbJbg'
|
bytedance/fedlearner | fedlearner/common/metrics.py | Python | apache-2.0 | 8,599 | 0.000349 | # Copyright 2020 The FedLearner 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... | ,
# 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.
# coding: utf-8
import atexit
import datetime
import json
import os
import threading
import time
import logging
from functools import wrap... | s es7
import elasticsearch6 as es6
import pytz
from elasticsearch import helpers as helpers7
from elasticsearch6 import helpers as helpers6
from .common import Config, INDEX_NAME, INDEX_TYPE, get_es_template
from . import fl_logging
class Handler(object):
def __init__(self, name):
self._name = name
... |
TylerMoeller/fail2ban | fail2ban/helpers.py | Python | gpl-2.0 | 3,914 | 0.019417 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*-
# vi: set ft=python sts=4 ts=4 sw=4 noet :
# This file is part of Fail2Ban.
#
# Fail2Ban 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;... | mmon_prefix2 != "":
sftb = '...' + sftb[len(common_prefix2):]
self.__prev = prev_next
return sftb
class FormatterWithTraceBack(logging.Formatter):
"""Custom formatter which expands %(tb) an | d %(tbc) with tracebacks
TODO: might need locking in case of compressed tracebacks
"""
def __init__(self, fmt, *args, **kwargs):
logging.Formatter.__init__(self, fmt=fmt, *args, **kwargs)
compress = '%(tbc)s' in fmt
self._tb = TraceBack(compress=compress)
def format(self, record):
record.tbc = record.tb =... |
unintended/Cohen | coherence/upnp/devices/basics.py | Python | mit | 13,455 | 0.003567 | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008 Frank Scholz <coherence@beebits.net>
import os.path
from twisted.python import util
from twisted.web import resource, static
from twisted.internet import reactor
import coherence.extern.louie ... | icon['url'][7:]
# elif icon['url'] == '.face':
# icon_path = os.path.join(os. | path.expanduser('~'), ".face")
# else:
# from pkg_resources import resource_filename
# icon_path = os.path.abspath(resource_filename(__name__, os.path.join('..', '..', '..', 'misc', 'device-icons', icon['url'])))
#
# if os.path.exists(i... |
ella/django-event-tracker | eventtracker/models.py | Python | bsd-3-clause | 1,073 | 0.005592 | from datetime import datetime
from pymongo.connection import Connection
from django.db import models
from eventtracker.conf import settings
def get_mongo_collection():
"Open a connection to MongoDB and return the collection to use."
if settings.RIGHT_MONGODB_HOST:
connection = Connection.paired(
... | NGODB_HOST, port=settings.MONGODB_PORT)
return connection[settings.MONGODB_DB][settings.MONGODB_COLLECTION]
def save_event(collection, event, timestamp, params):
"Save the event in MongoDB collection"
collection.insert({
'event': event,
'timestamp': datetime.fromtimestamp(timestamp),
... | ):
"Dummy model for development."
timestamp = models.DateTimeField(auto_now_add=True)
event = models.SlugField()
params = models.TextField()
|
myhearter/dianping | ddp/app/manage.py | Python | mit | 246 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ | == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ddp.settings | ")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
liampauling/flumine | tests/test_order.py | Python | mit | 23,869 | 0.000922 | import string
import unittest
import datetime
import collections
from unittest import mock
from flumine.order.order import (
BaseOrder,
BetfairOrder,
ExchangeType,
OrderTypes,
OrderStatus,
VALID_BETFAIR_CUSTOMER_ORDER_REF_CHARACTERS,
LIVE_STATUS,
COMPLETE_STATUS,
)
from flumine.exceptio... | et_notes)
self.assertIsNone(self.order.bet_id)
self.assertIsNone(self.order.EXCHANGE)
self.assertEqual(self.order.update_data, {})
| self.assertIsNone(self.order.publish_time)
self.assertIsNone(self.order.market_version)
self.assertIsNone(self.order.async_)
self.assertIsNotNone(self.order.date_time_created)
self.assertIsNone(self.order.date_time_execution_complete)
self.assertFalse(self.order.simulated)
... |
uditsaxena/CS689_final_project | train.py | Python | bsd-2-clause | 27 | 0.037037 | imp | ort model
model.train() | |
lamby/pkg-python-redis | redis/connection.py | Python | mit | 40,079 | 0.000075 | from __future__ import with_statement
from distutils.version import StrictVersion
from itertools import chain
import os
import socket
import sys
import threading
import warnings
try:
import ssl
ssl_available = True
except ImportError:
ssl_available = False
from redis._compat import (b, xrange, imap, byte_... | or:
e = sys.exc_info()[1]
raise ConnectionError("Error while reading from socket: %s" %
(e.args,))
def read(self, length):
length = length + 2 # make sure to read the \r\n terminator
# make sure we've read enough data from the socket
... | es_read += len(data)
# purge the buffer when we've consumed it all so it doesn't
# grow forever
if self.bytes_read == self.bytes_written:
self.purge()
return data[:-2]
def readline(self):
buf = self._buffer
buf.seek(self.bytes_read)
data = buf.r... |
avikivity/scylla | test/alternator/test_streams.py | Python | agpl-3.0 | 62,504 | 0.006416 | # Copyright 2020 ScyllaDB
#
# This file is part of Scylla.
#
# Scylla 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 lat | er version.
#
# Scylla 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 Affero General Public License
# along with Scylla. If not, see <http://www.gnu.org/licenses/>.
# Tests for s... |
hodgestar/laghuis | laghuis/speaker.py | Python | mit | 1,222 | 0 | """ Box for outputing to a pair of speakers.
"""
from .box import Box
class Speakers(Box):
| SINK_TEMPLATE = None
def __init__(self, pipeline, name, device):
super(Speakers, self).__init__(name, pipeline)
se | lf.add_sequence([
'audiomixer name=mixer',
'audiopanorama name=pan',
self.SINK_TEMPLATE % {
"name": "sink",
"device": device,
},
])
@classmethod
def _create_many(cls, pipeline, srcs):
return [
cls(pipeli... |
damomeen/pox-datapath | pox/lib/ioworker/__init__.py | Python | apache-2.0 | 12,928 | 0.016321 | # Copyright 2012 Colin Scott
# Copyright 2012 Andreas Wundsam
# Copyright 2012 James McCauley
#
# This file is part of POX.
#
# POX 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 Licen... | end and len(self.send_buf) == 0:
self.socket.shutdown(socket.SHUT_WR)
except socket.error as (s_errno, strerror):
if s_errno != errno.EAGAIN:
log.error("Socket %s error %i during send: %s", str(self),
s_errno, strerror)
self.close()
loop._workers.discard(self)
... | :
"""
Number of available bytes to read()
"""
return len(self.receive_buf)
@property
def connect_handler (self):
if self._custom_connect_handler is _dummy_handler:
return None
return self._custom_connect_handler
@connect_handler.setter
def connect_handler (self, callback):
""... |
flh/odoo | openerp/addons/base/ir/ir_qweb.py | Python | agpl-3.0 | 59,920 | 0.003571 | # -*- coding: utf-8 -*-
import collections
import cStringIO
import datetime
import hashlib
import json
import itertools
import logging
import math
import os
import re
import sys
import textwrap
import uuid
from subprocess import Popen, PIPE
from urlparse import urlparse
import babel
import babel.dates
import werkzeug
... | self._render_tag[tag] = func
def add_template(self, qwebcontext, name, node):
"""Add a parsed template in the context. Used to preprocess templates."""
qwebcontext.templates[n | ame] = node
def load_document(self, document, res_id, qwebcontext):
"""
Loads an XML document and installs any contained template in the engine
"""
if hasattr(document, 'documentElement'):
dom = document
elif document.startswith("<?xml"):
dom = etree.... |
airbnb/superset | superset/db_engine_specs/bigquery.py | Python | apache-2.0 | 8,436 | 0.001897 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | account
except ImportError:
raise Exception(
"Could not import libraries `pandas_gbq` or `google.oauth2`, which are "
"required to be installed in your environment in order "
"to upload data to BigQuery"
)
if not ("name" in kwargs ... | ma and con need to be defined in kwargs")
gbq_kwargs = {}
gbq_kwargs["project_id"] = kwargs["con"].engine.url.host
gbq_kwargs["destination_table"] = f"{kwargs.pop('schema')}.{kwargs.pop('name')}"
# add credentials if they are set on the SQLAlchemy Dialect:
creds = kwargs["con"]... |
raultron/ivs_sim | python/old_experiments/screen_calibration_3cam_views.py | Python | mit | 3,386 | 0.021855 | # -*- coding: utf-8 -*-
"""
Created on Wed May 10 11:15:22 2017
@author: lracuna
"""
from vision.camera import Camera
from vision.plane import Plane
from vision.screen import Screen
import numpy as np
import matplotlib.pyplot as plt
from mayavi import mlab
import cv2
#%% Create a camera
cam = Camera()
#Set camera ... | 60)
plt.gca().invert_yaxis()
plt.show()
#%% Opencv camera calibration
objp1 = transpose(s1.get_points_basis()[:3,:])
imgp1 = transpose(cam_points1[:2,:])
objp2 = transpose(s1.get_points_basis()[:3,:])
imgp2 = transpose(cam_points2[:2,:])
objp3 = transpose(s1.get_points_basis()[:3,:])
imgp3 = transpose(cam_points... |
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
objpoints.append(objp1.astype(np.float32))
objpoints.append(objp2.astype(np.float32))
objpoints.append(objp3.astype(np.float32))
#With round we introduce qua... |
SteerSuite/steersuite-rutgers | steerstats/tools/plotting/errorRibbonPlotMulti.py | Python | gpl-3.0 | 1,412 | 0.043909 |
import sys
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
sys.path.append('../../')
from util import readCSVToMatrix
file_path = sys.argv[1]
file = open(file_path)
def plotErrorRibbon(x, mu, std, metric, pp):
fig, ax = plt.subplots(1)
ax.fill_between(x, mu... | )
ax.tick_params(axis='both', which='major', labelsize=16)
ax.tick_params(axis='both', which='minor', labelsize=14)
plt.axis("tight")
plt.savefig('convergence_plot_' + metric + '.svg', format='svg', dpi= | 1000, bbox_inches='tight')
pp.savefig(fig, bbox_inches='tight')
# plt.show()
if __name__ == '__main__':
print file
data = readCSVToMatrix(file, delimiter=',')
print data
pp = PdfPages("convergence" + '_plots.pdf')
plotErrorRibbon(data[:,0], data[:,1], data[:,5], 'coverage', pp)
plotErrorRibbon(data... |
tiposaurio/venton | apps/sad/urls.py | Python | bsd-3-clause | 4,159 | 0.000721 | # _*_ coding: ut | f-8 _*_
from django.conf.urls import patterns, url # , include
# views
from .views import UserListView, UserCreateView, UserUpdateView, \
UserDeleteView, UserActiveUpdateView, PersonListView
from .views import MenuListView, MenuCreateView, MenuUpdateView, \
MenuDeleteView, MenuUpdateActiveView, UserDetailVie... | om .views import ModuleListView, ModuleCreateView, \
ModuleUpdateView, ModuleDeleteView, ModuleUpdateActiveView, \
ModuleSolutionsUpdateView
from .views import GroupListView, GroupCreateView, GroupUpdateView,\
GroupDeleteView, GroupPermissionsUpdateView
from .views import PermissionListView, PermissionCre... |
TerryRen/TrPython | TrLib/SuperBank.py | Python | apache-2.0 | 2,931 | 0.01641 | #python 2.7
#coding=utf-8
__author__ = "Terry.Ren"
import logging
import logging.handlers
class Bank(object):
M3 = 3
M6 = 6
Y1 = 1 * 12
Y3 = 3 * 12
Y5 = 5 * 12
"""Supper class of bank"""
def __init__(self):
self.__init_logging()
pass
def __init_logging(self):
... | totalAmount = 0.0
if type == Bank.Y1:
for i in range(year):
totalAmount += self.Deposit(amount, i + 1, interest)
return totalAmount
'''
Deposit money via Compounding
'''
def Deposit(self, amount, year, interest):
self._logger.info(u"测试") ... | oney per 3 month via Compounding
'''
def Deposit3Month(self, amount, year, interestPerYear):
interest = interestPerYear / 4
cycle = (year * 12) / 3
return amount * ((1 + interest) ** cycle)
def Deposit6Month(self, amount, year, interestPerYear):
interest = interestPerYea... |
aimas/TuniErp-8.0 | addons/website_blog/tests/test_website_blog_flow.py | Python | agpl-3.0 | 2,863 | 0.002794 | # -*- coding: utf-8 -*-
from openerp.addons.website_blog.tests.common import TestWebsiteBlogCommon
class TestWebsiteBlogFlow(TestWebsiteBlogCommon):
def test_website_blog_followers(self):
""" Test the flow of followers and notifications for blogs. Intended
flow :
- people subscribe to ... | a published post')
# Armand posts a message -> becomes follower
test_blog_post.sudo().message_post(
body='Armande BlogUser Commented',
| type='comment',
author_id=self.user_employee.partner_id.id,
subtype='mt_comment',
)
self.assertIn(
self.user_employee.partner_id, test_blog_post.message_follower_ids,
'website_blog: people commenting a post should follow it afterwards')
|
t-amerssonis/okami | src/Okami/third-parts/gitpy/exceptions.py | Python | mit | 2,527 | 0.003166 | # Copyright (c) 2009, Rotem Yaari <vmalloc@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code mu | st retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distrib... | derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY Rotem Yaari ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL... |
nicholsn/ncanda-data-integration | scripts/crond/post_github_issues.py | Python | bsd-3-clause | 7,944 | 0.000504 | #!/usr/bin/env python
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
##
"""
Post GitHub Issues
------------------
Take the stdout and stderr passed to the catch_output_email and create an issue
on GitHub that uses a tag corresponding to the s... | s on verbose.
Returns:
object: A github.Label.
"""
if verbose:
print "Checking for label..."
label = None
| label_text = None
try:
label_start = 1 + title.index('(')
label_end = title.index(')')
label_text = title[label_start:label_end]
except ValueError, e:
print "Warning: This tile has no embeded label. {0}".format(e)
if label_text:
try:
label = [repo.get_l... |
savoirfairelinux/account-fiscal-rule | __unported__/account_fiscal_position_rule_sale/__openerp__.py | Python | agpl-3.0 | 1,681 | 0 | # -*- encoding: utf-8 -*-
###############################################################################
#
# account_fiscal_position_rule_sale for OpenERP
# Copyright (C) 2009-TODAY Akretion <http://www.akretion.com>
# @author Renato Lima <renato.lima@akretion.com>
# Copyright 2012 Camptocamp SA
# @autho... | 'sale_view.xml',
'security/account_fiscal_position_ | rule_sale_security.xml',
'security/ir.model.access.csv',
],
'demo': [],
'installable': False,
}
|
wcmckee/nikola | nikola/plugins/compile/rest/listing.py | Python | mit | 7,496 | 0.001067 | # -*- coding: utf-8 -*-
# Copyright © 2012-2016 Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights t... | class CodeBlock(Directive):
"""Parse and mark up content of a code block."""
optional_arguments = 1
option_spec = {'class': directives.class_option,
'name': directives.unchanged,
'number-lines': directives.unchanged, # integer or None
'linenos': dir... |
def run(self):
"""Run code block directive."""
self.assert_has_content()
if 'linenos' in self.options:
self.options['number-lines'] = self.options['linenos']
if 'tab-width' in self.options:
self.content = [x.replace('\t', ' ' * self.options['tab-width']) fo... |
ocefpaf/pycsw | setup.py | Python | mit | 5,698 | 0.000176 | # -*- coding: iso-8859-15 -*-
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
#
# Copyright (c) 2015 Tom Kralidis
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files... | find_packages_xsd('pycsw')
# Because package 'pycsw' contains all other packages,
# process it last, so that it doesn't set it's package_data
# files to one already set in other packages
ROOT_PACKAGE = PAC | KAGE_DATA_XSD.pop(0)
# set package_data
PACKAGE_DATA = get_package_data(PACKAGE_DATA_XSD)
# update package_data for pycsw package
PACKAGE_DATA.update(get_package_data([ROOT_PACKAGE], 'schemas'))
# set the dependencies
# GeoNode and OpenDataCatalog do not require SQLAlchemy
with open('requirements.txt') as f:
INS... |
tbenthompson/quadracheer | tests/test_rl_quad.py | Python | mit | 4,531 | 0.00309 | import numpy as np
from quadracheer.recursion import recursive_quad,\
gll_nodes, modified_vandermonde, modified_moments
from quadracheer.rl135 import rl1
from quadracheer.map import map_pts_wts, map_singular_pt,\
map_distance_to_interval, map_weights_by_inv_power
def test_small_order_recursive_... | equal(exact[i], est, 10)
def test_mapped_recursi | ve_quad2():
mapped_ay = map_singular_pt(0.2, 0.0, 1.0)
mapped_by = map_distance_to_interval(0.3, 0.0, 1.0)
moments = modified_moments(rl1, 10, mapped_ay, mapped_by)
x, w = recursive_quad(moments)
x, w = map_pts_wts(x, w, 0.0, 1.0)
w = map_weights_by_inv_power(w, 1.0, 0.0, 1.0)
exact = [2.33... |
kevswanberg/mnl_elo_bot | tests/test_elo_bot.py | Python | mit | 519 | 0.001927 | import unittest
import sys
sys.path.append(".")
from mnl_elo_bot import elo_bot # noqa
class IntegrationTest(unittest.TestCase):
# Just see if it initializes and runs...
def test_process(self):
| teams = elo_bot.main(False, None, '')
for team in teams.values():
self.assertIsNotNone(team.name)
self.assertIsNotNone(team.color)
self.assertIsNotNone(team.emoji)
self. | assertIsNotNone(team.history)
if __name__ == '__main__':
unittest.main()
|
SanaMobile/sana.protocol_builder | src-django/authentication/tests/test_logout.py | Python | bsd-3-clause | 1,015 | 0.003941 | from django.test import TestCase, Client
from django.contrib.auth.models im | port User
from rest_framework.authtoken.models import Token
from rest_framework import status
from nose.tools import assert_equals
class LogoutTest(TestCase):
def setUp(self):
self.cli | ent = Client()
def test_unauthenticated_user_cannot_logout(self):
response = self.client.get('/auth/logout')
assert_equals(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_authenticated_user_can_logout(self):
user = User.objects.create_user('username', 'test@test.com', 'pas... |
maxamillion/anaconda | pyanaconda/exception.py | Python | gpl-2.0 | 14,461 | 0.002904 | #
# exception.py - general exception formatting and saving
#
# Copyright (C) 2000-2013 Red Hat, Inc.
# 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; either version 2 of ... | port re
import errno
import glob
import tracebac | k
import blivet.errors
from pyanaconda.errors import CmdlineError
from pyanaconda.ui.communication import hubQ
from pyanaconda.constants import THREAD_EXCEPTION_HANDLING_TEST, IPMI_FAILED
from pyanaconda.threads import threadMgr
from pyanaconda.i18n import _
from pyanaconda import flags
from pyanaconda import startup_u... |
tseaver/google-cloud-python | container/noxfile.py | Python | apache-2.0 | 5,050 | 0.000792 | # -*- coding: utf-8 -*-
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | e docs for this | library."""
session.install("-e", ".")
session.install("sphinx", "alabaster", "recommonmark")
shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
session.run(
"sphinx-build",
"-W", # warnings as errors
"-T", # show full traceback on exception
"-N", # no... |
clairetang6/bokeh | examples/plotting/file/elements.py | Python | bsd-3-clause | 1,464 | 0.006148 | import pandas as pd
from bokeh.plotting import figure, show, output_file
from bokeh.sampledata.periodic_table import elements
elements = elements[elements["atomic number"] <= 82]
elements = elements[~pd.isnull(elements["melting point"])]
mass = [float(x.strip("[]")) for x in elements["atomic mass"]]
elements["atomic ... | "#d6604d", "#b2182b", "#67001f"]
melting_points = elements["melting point"]
low = min(melting_points)
high= max(melting_points)
melting_point_inds = [int(10*(x-low)/(high-low)) for x in meltin | g_points] #gives items in colors a value from 0-10
melting_colors = [palette[i] for i in melting_point_inds]
TOOLS = "pan,wheel_zoom,box_zoom,reset,resize,save"
p = figure(tools=TOOLS, toolbar_location="left", logo="grey", plot_width=1200)
p.title = "Density vs Atomic Weight of Elements (colored by melting point)"
p... |
acekiller/pencil | util/osx-app-packager.py | Python | gpl-2.0 | 3,189 | 0.022264 | #!/usr/bin/env python
import os
import os.path
import shutil
import sys
if len(sys.argv) < 2:
sys.stderr.write('No binary to package specified.');
sys.stderr.flush()
#print '#!/bin/sh\n'
binary = sys.argv[1]
if binary[0] != '/':
binary = os.path.join(os.getcwd(), binary)
frameworkDir = os.path.normpath(os.path.jo... | binary = framework.split('.', 1)[0].strip()
target = os.path.join(frameworkDir, framework, binary) if binary else os.path.join(frameworkDir, framework)
output = os.popen('otool -L "%s"' % target).readlines()
for line in output:
line = line.split('(', 1)[0].strip()
if line.startswith('/System | ') or line.startswith('/usr/lib') or line.startswith('/usr/X11') or line.endswith(':'):
pass
else:
name = os.path.basename(line)
if name in frameworks:
pass
elif name + '.framework' in frameworks:
name = name + '.framework/' + name
else:
print 'Could not resolve the framework or dynamic lib... |
dietrichc/streamline-ppc-reports | examples/dfp/v201405/team_service/create_teams.py | Python | apache-2.0 | 1,855 | 0.007547 | #!/usr/bin/python
#
# 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 b... | ion of our README.
Tags: TeamService.createTeams
"""
__author__ = ('Nicholas Chen',
'Joseph DiLallo')
import uuid
# Import appropriate modules from the client library.
from googleads import dfp
def main(client):
# Initialize appropriate service.
team_service = client.GetService('TeamService', ve... | teams = []
for i in xrange(5):
team = {
'name': 'Team %s' % uuid.uuid4(),
'hasAllCompanies': 'false',
'hasAllInventory': 'false',
'teamAccessType': 'READ_WRITE'
}
teams.append(team)
# Add Teams.
teams = team_service.createTeams(teams)
# Display results.
for team i... |
rwl/openpowersystem | ucte/control_area/control_area.py | Python | agpl-3.0 | 2,764 | 0.005789 | #------------------------------------------------------------------------------
# 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... | ven the implied | warranty of MERCHANDABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA... |
ttfseiko/openerp-trunk | openerp/addons/mrp_byproduct/mrp_byproduct.py | Python | agpl-3.0 | 8,796 | 0.006025 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | 'Byproducts'),
}
class mrp_production(osv.osv):
_description = 'Production'
_inherit= 'mrp.production'
def action_confirm(self, cr, uid, ids, context=None):
""" Confirms production order and calculates quantity based on subproduct_type.
@return: Newly generated picking Id.
"... | picking_id = super(mrp_production,self).action_confirm(cr, uid, ids, context=context)
product_uom_obj = self.pool.get('product.uom')
for production in self.browse(cr, uid, ids):
source = production.product_id.property_stock_production.id
if not production.bom_id:
... |
akintolga/superdesk-core | superdesk/factory/manager.py | Python | agpl-3.0 | 540 | 0 |
import superdesk
from fla | sk.ext.script import Manager
class SuperdeskManager():
"""Superdesk scripts manager."""
def __init__(self, app, commands):
self.manager = Manager(app)
self.commands = commands
def run(self):
"""Run manager with predefined set of commands."""
self.manager.run(self.commands... | superdesk.COMMANDS)
|
ryumei/softlayer-utility | sl-ls.py | Python | mit | 3,178 | 0.007443 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# sl-ls.py: get information utility
# Created by NAKAJIMA Takaaki
# Last modified: Apr 16, 2014.
#
# Require: Python v3
#
# See also https://softlayer-api-python-client.readthedocs.org
#
# You should set env variables
# SL_USER... | e']))
# Virtual guest OSes
# for vg in client['Account'].getVirtualGuests(limit=10, offset=0):
print("## Virtual guests ##");
for vg in VirtualGuests(client):
print("AccountId=%s, ID=%d, hostname=%s"
% (vg['accountId'], vg['id'], vg['hostname']))
print("## Instance... | s():
print("FQDN=%s, IP_addrs=%s, %s"
% (cci['fullyQualifiedDomainName'], cci['primaryIpAddress'], cci['primaryBackendIpAddress']))
print("## Billing items ##")
billing_mask = "id, parentId, description, currentHourlyCharge"
print(master_account.getAllBillingItems(mask=billing... |
onnudilol/vetcalc | functional_tests/test_home.py | Python | mit | 1,691 | 0.00414 | from .base import FunctionalTest
from selenium.webdriver.common.keys import Keys
class HomePageTest(FunctionalTest):
def test_home_page_displays_menu(self):
# Marfalo the vet tech is sick of calculating dosages by hand and is too lazy to use a spreadsheet,
# so he decides to use a web app.
... | _link_text('Rx Info')
self.browser.find_element_by_link_text('Create A Treatment Sheet')
def test_navbar_updates_active_class(self):
# Marfalo clicks on a link and sees that the navigation bar updates to show what page he is on
self.browser.get(self.server_url)
self.browser.f | ind_element_by_link_text('Calc').send_keys(Keys.RETURN)
active = self.browser.find_element_by_xpath("//li[@class='active']/a[1]")
self.assertIn('Calc', active.text)
# Marfalo is done calculating dosages and returns to the home page
# When he does, the navbar updates to show that he is b... |
galak/zephyr | boards/xtensa/intel_adsp_cavs15/tools/lib/stream_desc.py | Python | apache-2.0 | 8,094 | 0.000371 | #!/usr/bin/env python3
#
# Copyright (c) 2019 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
import math
import logging
from time import sleep
from ctypes import c_uint16, POINTER, cast, c_uint8, c_uint64
from lib.driver import Register
import lib.registers as regs_def
import lib.platforms as plat_def
cla... | lue = sdfmt
logging.debug("SD#%02d: SD_FMT=%s" % (self.idx, self.fmt))
def set_stream_id(self, stream_id):
logging.de | bug("SD#%02d: Set Stream ID: 0x%04X" % (self.idx, stream_id))
sd_ctl = self.ctl_sts.value
sd_ctl &= ~(0xF << 20)
sd_ctl |= (stream_id << 20)
self.ctl_sts.value = sd_ctl
logging.debug("SD#%02d: SD_CTL_STS=%s" % (self.idx, self.ctl_sts))
def set_traffic_priority(self, value):
... |
creighton/ADL_LRS | lrs/utils/__init__.py | Python | apache-2.0 | 3,345 | 0.002392 | import ast
import json
import urllib
import urlparse
from isodate.isodatetime import parse_datetime
from django.conf import settings
from ..exceptions import ParamError
agent_ifps_can_only_be_one = ['mbox', 'mbox_sha1sum', 'openid', 'account']
def get_agent_ifp(data):
ifp_sent = [
a for a in agent_ifps_... | return {la: langdict[la]}
except KeyError:
# if th | e language header does match any exactly, then if it is only a 2 character
# header, try matching it against the keys again ('en' would match 'en-US')
if not '-' in la:
# get all keys from langdict...get all first parts of them..if la is in it, return it
... |
ojengwa/grr | lib/aff4_objects/stats_store.py | Python | apache-2.0 | 26,581 | 0.007411 | #!/usr/bin/env python
"""Storage implementation for gathered statistics.
Statistics collected by StatsCollector (see lib/stats.py) is stored in AFF4
space. Statistics data for different parts of the system is separated by
process ids. For example, for the frontend, process id may be "frontend",
for worker - "worker", ... | and timestamp != self.ALL_TIMESTAMPS:
start, end = timestamp
data_store | .DB.DeleteAttributes(self.urn, predicates, start=start,
end=end, token=self.token, sync=sync)
class StatsStore(aff4.AFF4Volume):
"""Implementation of the long-term storage of collected stats data.
This class allows to write current stats data to the data store, read
and delet... |
bskari/park-stamper | parks/tests/views/test_profile.py | Python | mit | 1,042 | 0 | from mock import patch
from pyramid import testing
from parks.models import User
from parks.tests.test_base import IntegrationTestBase
from parks.views.profile import profile_user
class ProfileUnitTest(IntegrationTestBase):
@patch('parks.logic.user.get_user_by_username_or_email')
@patch('parks.logic.stamp_co... | :
mock_get_user_by_username_or_email.return_value = User(
username='guest',
password='123',
signup_ip=1,
)
request = testing.DummyRequest()
request.matchdict['username'] = 'guest'
page = profile_user(request)
expected_keys = set((
... |
def test_profile_personal_view(self):
# TODO (bskari|2013-07-04) Implement this
pass
|
openstack/horizon | openstack_dashboard/dashboards/identity/identity_providers/protocols/tables.py | Python | apache-2.0 | 2,469 | 0 | # Copyright (C) 2015 Yahoo! 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... | ASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the s | pecific language governing permissions and limitations
# under the License.
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext_lazy
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard import policy
... |
daydayuplo/gee | earth_enterprise/src/server/wsgi/serve/kh_constants.py | Python | apache-2.0 | 1,227 | 0 | #!/usr/bin/python
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# | Unless required by | applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""kh_constants module.
... |
cloudpassage/cloudpassage-halo-python-sdk | cloudpassage/agent_upgrade.py | Python | bsd-3-clause | 3,326 | 0 | """AgentUpgrade Class"""
from .http_helper import HttpHelper
from .halo_endpoint import HaloEndpoint
class AgentUpgrade(HaloEndpoint):
"""Initializing the AgentUpgrade class:
Args:
session (:class:`cloudpassage.HaloSession`): This will define how you
interact with the Halo API, including... | gent version specified
agent_version_gt (str): An agent version that is greater than
the agent version specified
agent_version_lte (str): An agent version that is less than,
or equal to, the agent version specified
agent_version_lt (str): An agent vers... | Returns:
string: agent upgrade request ID.
"""
endpoint = "/v1/agent_upgrades"
request = HttpHelper(self.session)
body = {"upgrade": kwargs}
response = request.post(endpoint, body)
return response["upgrade"]["id"]
def delete(self, upgrade_id):
... |
dstlmrk/catcher | catcher/api/middleware.py | Python | mit | 3,340 | 0.004192 | #!/usr/bin/python
# coding=utf-8
import falcon
import ujson
import json
from catcher import models
import datetime
from playhouse.shortcuts import model_to_dict
import logging
from catcher.models import User, NullUser
import peewee
class PeeweeConnection(object):
def process_request(self, req, resp):
mo | dels.db.connect()
def process_response(self, req, resp, resource):
if not models.db.is_closed():
models.db.close()
class Crossdomain(object):
def process_request(self, req, resp):
resp.append_header(
"Access-Control-Allow-Origin", "*"
)
resp.a | ppend_header(
"Access-Control-Allow-Headers",
"Content-Type,Authorization,X-Name"
)
resp.append_header(
"Access-Control-Allow-Methods",
"PUT,POST,DELETE,GET"
)
class Authorization(object):
def process_request(self, req, resp):
user = ... |
afrolov1/nova | nova/virt/driver.py | Python | apache-2.0 | 53,033 | 0.000057 | # Copyright 2011 Justin Santa Barbara
# 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 requ... | .LibvirtDriver, xenapi.XenAPIDriver, '
'fake.FakeDriver, baremetal.BareMetalDriver, '
'vmwareapi.VMwareESXDriver, vmwareapi.VMwareVCDriver'),
cfg.StrOpt('default_ephemeral_format',
help='The default format an ephemeral_volume will be '
'format... |
'"none" => no storage provisioning is done up front, '
'"space" => storage is fully allocated at instance start'),
cfg.BoolOpt('use_cow_images',
default=True,
help='Whether to use cow images'),
cfg.BoolOpt('vif_plugging_is_fatal',
... |
thcipriani/rdio-shit | bin/rdio-history-csv.py | Python | gpl-2.0 | 1,498 | 0.003338 | #!/usr/bin/env python2
"""
rdio-history-csv.py
~~~~~~~~~~~~~~~~~~~
Simple script for parsing the output of
https://www.rdio.com/api/1/getHistoryForUser
The way I made this happen was:
#. login to rdio.com in chrome,
#. visit https://www.rdio.com/people/tylercipriani/history/ with devtools
open
#.... | e output to "rdio-history.json"
#. Run this script, redirect output to "rdio-history.csv"
#. ???
#. Profit.
"""
import os
import json
def p | rocess(string):
return string.encode('ascii', 'ignore').replace(',', '').replace('"','').replace("'",'')
print "Date Played,Artist,Title,Album"
history_fmt = '{time},{artist},{title},{album}'
NA = 'N/A'
history_path = os.path.abspath(
os.path.join(
os.path.dirname(__file__), '..', 'raw', 'rdio-history... |
HBEE/odoo-addons | product_bookstore/__openerp__.py | Python | agpl-3.0 | 1,376 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | ILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
######################################################... | ############
{
'name': 'Product Bookstore',
'version': '8.0.1.0.0',
'category': 'Gestión de ventas',
'description': """
""",
'author': 'ADHOC SA',
'website': 'www.adhoc.com.ar',
'depends': [
'product'],
'data': [
'product_view.xml',
],
'test': [],
'install... |
williballenthin/python-registry | samples/forensicating.py | Python | apache-2.0 | 11,552 | 0.007271 | #!/usr/bin/env python
# created by Glenn P. Edwards Jr.
# http://hiddenillusion.blogspot.com
# @hiddenillusion
# Version 0.1
# Date: 07-23-2013
# (while at FireEye)
from __future__ import print_function
from __future__ import unicode_literals
import os
import re
import sys
import time
try:
from Registry ... |
print(("=" * 51) + "\n[+] Operating System Information\n" + ("=" * 51))
print("[-] Product Name.....: %s" % os_dict['ProductName'])
pr | int("[-] Product ID.......: %s" % os_dict['ProductId'])
print("[-] CSDVersion.......: %s" % os_dict['CSDVersion'])
print("[-] Path Name........: %s" % os_dict['PathName'] )
print("[-] Install Date.....: %s" % os_dict['InstallDate'] )
print("[-] Registered Org...: %s" % os_dict['RegisteredOrgani... |
sekiskylink/dispatcher-2.1 | web/app/controllers/users_handler.py | Python | gpl-3.0 | 4,860 | 0.003909 | import web
from . import csrf_protected, db, get_session, require_login, render, userRolesByName
from app.tools.pagination2 import doquery, countquery, getPaginationString
from app.tools.utils import default, lit
from settings import PAGE_LIMIT
class Users:
@require_login
def GET(self):
params = web.i... | if session.role == 'Administrator':
db.query("DELETE FROM users WHERE id=$id", {'id': params.d_id})
roles = db.query("SELECT id, name FROM user_roles ORDER by name")
current_role_id = userRolesByName[session.role]
criteria = ""
if session.role == 'Administrator':... | elds="a.id, a.firstname, a.lastname, a.username, a.email, a.telephone, b.name as role ",
criteia="a.user_role = b.id",
order="a.firstname, a.lastname",
limit=limit, offset=start)
else:
dic = lit(
relations='users a, user_roles b',
... |
dknlght/dkodi | src/plugin.video.animehere/servers/rapidgator.py | Python | gpl-2.0 | 1,401 | 0.022143 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para rapidgator
# http://bl | og.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
from core import scrapertools
from core import logger
from core import config
def test_video_exi | sts( page_url ):
return True,""
def get_video_url( page_url , premium = False , user="" , password="", video_password="" ):
logger.info("[rapidgator.py] get_video_url(page_url='%s')" % page_url)
video_urls = []
return video_urls
# Encuentra vídeos del servidor en el texto pasado
def find_videos(data):... |
leapcode/bitmask_client | pkg/install_venv.py | Python | gpl-3.0 | 7,504 | 0.001199 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2010 OpenStack, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# ... | derr, message % args
sys.exit(1)
def check_python_version():
if sys.version_info < (2, 6):
die("Need Python Version >= 2.6")
def run_command_with_code(cmd, redirect_output=True, check_exit_code=True):
"""
Runs a command in an out-of-p | rocess shell, returning the
output of that command. Working directory is ROOT.
"""
if redirect_output:
stdout = subprocess.PIPE
else:
stdout = None
print 'executing command: %s', cmd
proc = subprocess.Popen(cmd, cwd=ROOT, stdout=stdout)
output = proc.communicate()[0]
if... |
cedric222/pycarwings2 | tests/test_pycarwings2.py | Python | apache-2.0 | 368 | 0.021739 | #!/usr/bin/env python
import time
import logging
import sys
import pycarwings2
import pytest
logging.basicConfig(st | ream=sys.stdout, level=logging.ERROR)
def test_bad_password():
with pytest.raises(pycarwings2.Carwin | gsError) as excinfo:
s = pycarwings2.Session("user@domain.com", "password", "NE")
l = s.get_leaf()
assert 'INVALID' in str(excinfo.value)
|
prinsmike/nltk_book | ch01/13-cumulative_frequency_plot.py | Python | apache-2.0 | 109 | 0.009174 | #!/usr/bin/env python2. | 7
from nltk.book import *
fdist1 = FreqDist(text1)
fdist1. | plot(50, cumulative=True) |
syurkevi/arrayfire-python | arrayfire/base.py | Python | bsd-3-clause | 570 | 0.001754 | ########################## | #############################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
########################################################
"""
Implementation of ... | :
self.arr = ct.c_void_p(0)
|
OpenPhilology/nidaba | nidaba/storage.py | Python | gpl-2.0 | 8,081 | 0.000495 | # -*- coding: utf-8 -*-
"""
nidaba.storage
~~~~~~~~~~~~~~
This module contains all file handling/storage management/ID mapping methods.
"""
from __future__ import unicode_literals, print_function, absolute_import
from nidaba.lock import lock
from nidaba.config import nidaba_cfg
from nidaba.nidabaexceptions import (... | bs_path(jobID, *path):
"""
Returns the absolute path of a file.
Takes a job ID and a sequence of path components and checks if their
absolute path is in the directory of that particular job ID.
Args:
jobID (unicode): A unique job ID
*path (unicode): A list of path components that a... | abaStorageViolationException: The resulting absolute path is
either not in the storage_path of the
nidaba configuration or not in its job
directory.
"""
if len(path) < 1:
raise Nida... |
Juniper/nova | nova/api/openstack/placement/microversion.py | Python | apache-2.0 | 9,893 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | sion is None:
min_version = self.min_version
if max_version is None:
max_version = self.max_version
return min_version <= self <= max_version
def extract_version(headers):
| """Extract the microversion from Version.HEADER
There may be multiple headers and some which don't match our
service.
"""
found_version = microversion_parse.get_version(headers,
service_type=SERVICE_TYPE)
version_string = found_version or min_v... |
numericube/twistranet | twistranet/sharing/urls.py | Python | agpl-3.0 | 351 | 0.019943 | from django.conf.urls.defaults import *
from twistranet.core.views import AsView
from views import *
urlpatterns = patterns('sharing',
url(r'^like_toggle_by_id/(\d+)$', AsVi | ew(LikeToggleView, lookup = 'id'), name=LikeToggleView.name),
url(r'^like_toggle_by_slug/(\d+)$', AsView(LikeToggleView, lookup = 'slug') | , name=LikeToggleView.name),
)
|
binarybin/MPS_Proba | src/radiatingboys.py | Python | gpl-2.0 | 5,035 | 0.020258 | """
Program name: MPS-Proba
Program purpose: The Alpha version of the APC 524 project.
File name: radiatingboys.py
File purpose: the radiating boys model
Responsible person: Bin Xu
"""
from numpy import ndarray, zeros
import numpy as np
from model import Model
class RadiatingBoys(Model):
"""
A probablistic mo... | .p2 * self.sigma_x
mpo_left[:, :, 0, 3] = self.I
# mpo_middle = [I, 0, 0, 0]
# [Sx, 0, 0, 0]
# [0, I, 0, 0]
# [0, | p1 Sx, p2 Sx, I]
mpo_middle[:, :, 0, 0] = self.I
mpo_middle[:, :, 1, 0] = self.sigma_x
mpo_middle[:, :, 2, 1] = self.I
mpo_middle[:, :, 3, 1] = self.p1 * self.sigma_x
mpo_middle[:, :, 3, 2] = self.p2 * self.sigma_x
mpo_middle[:, :, 3, 3] = self.I
# m... |
Frojd/Frojd-Fabric | examples/wordpress/fabfile.py | Python | mit | 76 | 0.013158 | fro | m stages import *
from fabrik.api import setup, deploy, rol | lback, debug
|
SelvorWhim/competitive | Codewars/AlternatingSort.py | Python | unlicense | 385 | 0.012987 | def alternate_sort(l):
neg = sorted([x for x in l if x < 0], reverse = True)
pos = sor | ted([x for x in l if x >= 0])
combo = [None]*(len(l))
alter_len = min(len(neg),len(pos))
combo[:2*alter_len | :2] = neg[:alter_len]
combo[1:2*alter_len+1:2] = pos[:alter_len]
combo[2*alter_len:] = neg[alter_len:] if len(neg) > len(pos) else pos[alter_len:]
return combo
|
kpanic/lymph | iris/cli/request.py | Python | apache-2.0 | 4,222 | 0.002373 | # -*- coding: utf-8 -*-
import json
import textwrap
import sys
import logging
import iris
from iris.client import Client
from iris.exceptions import LookupFailure
from iris.cli.base import Command
logger = logging.getLogger(__name__)
class RequestCommand(Command):
"""
Usage: iris request [options] [--ip=<a... | result = client.request(address, 'iris.inspect', {}).body
except LookupFailure:
logger.error("cannot resolve %s", address)
sys.exit(1)
print
for method in result['methods']:
print("rpc {name}({params})\n {help}\n".format(
name=self... | mand(Command):
"""
Usage: iris discover [--instances] [--ip=<address> | --guess-external-ip | -g] [options]
Show available services
Options:
--instances Show service instances.
--ip=<address> Use this IP for all sockets.
--guess-external-ip, -g Gu... |
gregdetre/abracadjabra | abracadjabra/wsgi.py | Python | mit | 1,437 | 0.000696 | """
WSGI config for abracadjabra project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATI... | the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mo... | _SETTINGS_MODULE", "abracadjabra.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI ... |
googleapis/python-analytics-data | samples/generated_samples/analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py | Python | apache-2.0 | 1,518 | 0.001976 | # -*- 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... | _async]
from google.analytics import data_v1beta
async def sample_batch_run_pivot_reports():
# Create a client
client = data_v1beta.BetaAnalyticsDataAsyncClient()
# Initialize request argument(s)
request = data_v1beta.BatchRunPivotReportsRequest(
)
# Make the request
response = await cli... | 1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async]
|
AlexanderBrevig/Espruino | boards/MINISTM32_STRIVE.py | Python | mpl-2.0 | 4,266 | 0.028833 | #!/bin/false
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at h... |
}
#left {
top: 430px;
right: 800px;
}
#top {
top: 20px;
left: 230px;
}
#top2 {
top: 80px;
left: 230px;
}
#bottom {
top: 680px;
left: 230px;
}
#bottom2 {
top: 610px;
l | eft: 230px;
}
""";
def get_pins():
pins = pinutils.scan_pin_file([], 'stm32f103xe.csv', 6, 10, 11)
return pinutils.only_from_package(pinutils.fill_gaps_in_pin_list(pins), chip["package"])
|
strin/yaotalk | main.py | Python | gpl-3.0 | 1,714 | 0.023337 | # coding: utf-8
from gui import *
import thread
import color
import time
import os
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import YaoSpeech
from dialogue import *
class dialogue_thread(QThread):
def __init__(self):
QThread.__init__(self)
self.voi... | alk
self.dialogue = DialogueManager(self.voiceface, DialogueModelTagging())
def run(self):
self.dialogue.run()
return None
def listen(self):
YaoSpeech.listen()
print "YaoSpeech: listening..."
def recognize(self):
result = YaoSpeech.recognize()
if res | ult == None or result == '':
return
result = result.decode('utf-8')
print "speech recognized: ", result
self.emit(QtCore.SIGNAL('display(QString, QString)'), u'Human: '+result, '#bb2244')
self.voiceface.addMessage(result)
print "YaoSpeech: recognizing..."
def display(self, msg):
self.emit(QtCore.SIGNAL... |
yezune/kicomav | Engine/plugins/dummy.py | Python | gpl-2.0 | 5,530 | 0.014286 | # -*- coding:utf-8 -*-
# Made by Kei Choi(hanul93@gmail.com)
import os # ÆÄÀÏ »èÁ¦¸¦ À§ÇØ import
import kernel
#---------------------------------------------------------------------
# KavMain Ŭ·¡½º
# ŰÄÞ¹é½Å ¿£Áø ¸ðµâÀÓÀ» ³ªÅ¸³»´Â Ŭ·¡½ºÀÌ´Ù.
# ÀÌ Å¬·¡½º°¡ ¾øÀ¸¸é ¹é½Å ¿£Áø Ä¿³Î ¸ðµâ¿¡¼ ·ÎµùÇÏÁö ¾Ê´Â´Ù.
#----------... | le, filename) :
try :
fformat = {} # Æ÷¸Ë Á¤º¸¸¦ ´ãÀ» °ø°£
mm = mmhandle
if mm[0:5] == 'Dummy' : # Çì´õ üũ
fformat['size'] = len(mm) # Æ÷¸Ë ÁÖ¿ä Á¤º¸ ÀúÀå
ret = {}
ret['ff_dummy'] = fformat
re | turn ret
except :
pass
return None |
kichkasch/ioids | ioids/policyengine.py | Python | gpl-3.0 | 11,565 | 0.007955 | """
Responsible for parsing IOIDS data engine policies and providing interfaces for checking against them.
Inter-Organisational Intrusion Detection System (IOIDS)
Check README in the IOIDS folder for more information.
@author: Michael Pilgermann
@contact: mailto:mpilgerm@glam.ac.uk
@license: GPL (General Public Lice... | lobal _policyEngine
if not _policyEngine:
_policyEngine = PolicyEngine()
return _policyEngine
| class PolicyEngine:
def __init__(self):
"""
Yet empty constructor.
"""
self._rules = {}
def startup(self):
"""
Loads the policy XML files into memory.
"""
tmpRules = []
parser = PolicyParser()
locations = config.LOCATION_P... |
IEMLdev/propositions-restful-server | ieml/test/test_path.py | Python | gpl-3.0 | 8,291 | 0.022072 | import unittest
import tqdm
from ieml.dictionary.script import Script
from ieml.ieml_database import IEMLDatabase, GitInterface
from ieml.usl import PolyMorpheme, Lexeme, Word
from ieml.usl.decoration.parser.parser import PathParser
from ieml.usl.decoration.path import PolymorphemePath, GroupIndex, FlexionPath, Lexem... | ript)
self.check(">role>E:A:.", RolePath, w, Lexeme)
self.check(">role>E:A:.>content", RolePath, w, PolyMorpheme)
self.check(">", RolePath, w, Word)
def test_paths_values_to_usl(self):
pm = [(">constant>S:", "S:"), (">constant>B:" | , "B:"), (">group_0 2>T:", "T:"), (">group_0 2>A:", "A:")]
res = usl_from_path_values(pm)
self.assertIsInstance(res, PolyMorpheme)
self.assertEqual(str(res), "S: B: m2(A: T:)")
pm = [(">content>constant>S:", "S:"), (">content>constant>B:", "B:"), (">content>group_0 1>T:", "T:")]
res = usl_from_path_values(pm... |
pducks32/intergrala | python/sympy/doc/src/modules/mpmath/plots/hermite.py | Python | mit | 240 | 0.079167 | # Her | mite polynomials H_n(x) on the real line for n=0,1,2,3,4
f0 = lambda x: hermite(0,x)
f1 = lambda x: hermite(1,x)
f2 = lambda x: hermite(2,x)
f3 = lambda x: hermite(3,x)
f4 = lambda x: hermite(4,x)
plot([f0,f1,f2,f3,f4],[-2,2],[-25,25]) | |
chrcoe/suds_requests | tests/test_transport.py | Python | bsd-3-clause | 1,143 | 0 | import mock
import suds.transport
import suds_requests
def test_open(): |
session = mock.Mock()
session.get.return_value.content = 'abc123'
transport = suds_requests.RequestsTransport(session)
request = suds.transport.Request('http://url')
response | = transport.open(request)
assert response.read() == 'abc123'
def test_send():
session = mock.Mock()
session.post.return_value.content = 'abc123'
session.post.return_value.headers = {
1: 'A',
2: 'B',
}
session.post.return_value.status_code = 200
transport = suds_requests.Re... |
akx/shoop | shoop_tests/front/test_customer_information.py | Python | agpl-3.0 | 2,322 | 0.000431 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# 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 __future__ import unicode_literals
import | pytest
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.shortcuts import resolve_url
from shoop.testing.factories import get_default_shop
from shoop.testing.soup_utils import extract_form_fields
from shoop_tests.utils import Smart... | user = get_user_model().objects.create_user(
username="Niilo_Nyyppa",
email="niilo@example.shoop.io",
password=user_password,
first_name="Niilo",
last_name="Nyyppä",
)
client.login(username=user.username, password=user_password)
# make sure all information matches ... |
ptphp/PyLib | src/sqlalchemy/main.py | Python | apache-2.0 | 696 | 0.014368 | # | !/usr/bin/env python
# -*- coding=utf-8 -*-
'''
Cr | eated on 2013-2-2
@author: Joseph
'''
from sqlalchemy.orm import sessionmaker #@UnresolvedImport
from sqlalchemy import create_engine #@UnresolvedImport
from User import User
from sqlalchemy.ext.declarative import declarative_base #@UnresolvedImport
Base = declarative_base()
engine = create_engine('sqlite:///:memory:',... |
comfortablynumb/shopeet | docs/tutorial/es/conf.py | Python | mit | 6,377 | 0.006743 | # -*- coding: utf-8 -*-
#
# Shopeet documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 27 16:35:50 2010.
#
# Th | is 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 configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules ... | ute, like shown here.
#sys.path.append(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.auto... |
bdarnell/tornado | tornado/iostream.py | Python | apache-2.0 | 65,697 | 0.000502 | #
# Copyright 2009 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | first_pos
buffers = self._buffers
while buffers and size > 0:
is_large, b = | buffers[0]
b_remain = len(b) - size - pos
if b_remain <= 0:
buffers.popleft()
size -= len(b) - pos
pos = 0
elif is_large:
pos += size
size = 0
else:
# Amortized O(1) shrink for... |
technige/py2neo | test/unit/test_storage.py | Python | apache-2.0 | 15,510 | 0.002321 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2021, Nigel Small
#
# 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
#
# Unle... | b})
de | f test_should_fail_on_bad_node_sequence(self):
store = FrozenGraphStore(self.store)
self.assertEqual(list(store.relationships(n_ids=(self.a, self.b, self.c))), [])
def test_should_fail_on_bad_node_set(self):
store = FrozenGraphStore(self.store)
_ = store.relationships(n_ids={self.a,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.