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 |
|---|---|---|---|---|---|---|---|---|
dmlc/tvm | python/tvm/micro/project_api/__init__.py | Python | apache-2.0 | 830 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Lice | nse"); 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 writi | ng,
# 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.
"""MicroTVM Project API Client and Server"""
|
DonBeo/scikit-learn | sklearn/covariance/tests/test_covariance.py | Python | bsd-3-clause | 10,594 | 0 | # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Gael Varoquaux <gael.varoquaux@normalesup.org>
# Virgile Fritsch <virgile.fritsch@inria.fr>
#
# License: BSD 3 clause
import numpy as np
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_alm... | (
shrunk_covariance(empirical_covariance(X)), cov.covariance_, 4)
# same test with shrinkage = 0 (<==> empirical_covariance)
cov = ShrunkC | ovariance(shrinkage=0.)
cov.fit(X)
assert_array_almost_equal(empirical_covariance(X), cov.covariance_, 4)
# test with n_features = 1
X_1d = X[:, 0].reshape((-1, 1))
cov = ShrunkCovariance(shrinkage=0.3)
cov.fit(X_1d)
assert_array_almost_equal(empirical_covariance(X_1d), cov.covariance_, 4)
... |
AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_06_01/network_management_client.py | Python | mit | 20,421 | 0.004211 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | base_url)
self.add_user_agent('azure-mgmt-network/{}'.format(VERSION))
self.add_user_agent('Azure-SDK-For-Python')
self.credentials = credentials
self.subscription_id = subscription_id
class NetworkManagementClient(object):
"""Network Client
:ivar config: Configuration for c... | plication_gateways: azure.mgmt.network.v2017_06_01.operations.ApplicationGatewaysOperations
:ivar available_endpoint_services: AvailableEndpointServices operations
:vartype available_endpoint_services: azure.mgmt.network.v2017_06_01.operations.AvailableEndpointServicesOperations
:ivar express_route_circuit_... |
marduk191/plugin.video.movie25 | resources/libs/plugins/iwatchonline.py | Python | gpl-3.0 | 22,479 | 0.029049 | import urllib,urllib2,re,string,sys,os
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
from resources.libs import main
#Mash Up - by Mash2k3 2012.
addon_id = 'plugin.video.movie25'
selfAddon = xbmcaddon.Addon(id=addon_id)
art = main.art
prettyName = 'iWatchOnline'
def AtoZiWATCHtv():
main.addDir('0-9','http://www.iw... | seahis=seahis.replace('%20',' ')
url=seahis
main.addDir(seahis,url,643,thumb)
def superSearch(encode,type):
try:
if type=='Movies': type='m'
else: type='t'
returnList=[]
search_url = 'http://www.iwatchonline.to/search'
from t0mm0.comm... | ndall('(?s)<table(.+?)</table>',search_content)
r=main.unescapes(r[0])
match=re.compile('<img.+?src=\"(.+?)\".+?<a.+?href=\"(.+?)\">(.+?)</a>').findall(r)
for thumb,url,name in match:
if type=='m':
returnList.append((name,prettyName,url,thumb,588,True))
el... |
jdemon519/cfme_tests | cfme/tests/configure/test_tag_category.py | Python | gpl-2.0 | 4,147 | 0.001447 | # -*- coding: utf-8 -*-
import fauxfactory
from cfme.configure.configuration import Category
from cfme.rest.gen_data import categories as _categories
import pytest
from utils.update import update
from utils.wait import wait_for
from utils import error
@pytest.mark.tier(2)
@pytest.mark.sauce
def test_category_crud():
... | display_name=fauxfactory.gen_alphanumeric(32))
cg.create()
with update(cg):
cg.description = fauxfactory.ge | n_alphanumeric(32)
cg.delete(cancel=False)
class TestCategoriesViaREST(object):
@pytest.fixture(scope="function")
def categories(self, request, rest_api):
response = _categories(request, rest_api, num=5)
assert rest_api.response.status_code == 200
assert len(response) == 5
... |
toastdriven/eliteracing | news/migrations/0002_add_indexes.py | Python | bsd-3-clause | 507 | 0.001972 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-28 04:23
fro | m __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('news', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='newspost',
name='creat... | ),
]
|
jeremiedecock/tictactoe-py | jdhp/tictactoe/player/greedy.py | Python | mit | 1,951 | 0.001539 | # -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# 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 right... | R 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 OR THE USE OR OTHER DEALINGS IN
# THE SOFTWAR | E.
"""
TODO...
"""
__all__ = ['GreedyPlayer']
import random
from jdhp.tictactoe.player.abstract import Player
class GreedyPlayer(Player):
"""
TODO...
"""
def play(self, game, state):
"""
TODO...
"""
action_list = game.getSetOfValidActions(state)
choosen_act... |
YosefLab/scVI | scvi/__init__.py | Python | bsd-3-clause | 791 | 0 | """scvi-tools."""
# Set default logging handler to avoid logging with logging.lastResort logger.
import logging
from logging import NullHandler
from ._constants import _CONSTANTS
from ._settings import settings
from . import data, model
# https://github.com/python-poetry/poetry/pull/2366#issuecomment-652418094
# htt... |
# this prevents double outputs
logger.propagate = False
test_var = "test"
_ | _all__ = ["settings", "_CONSTANTS", "data", "model"]
|
wolverineav/neutron | neutron/plugins/ml2/drivers/openvswitch/agent/common/constants.py | Python | apache-2.0 | 3,745 | 0.001335 | # Copyright (c) 2012 OpenStack Foundation.
#
# 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... | em'
OVS_DATAPATH_NETDEV = 'netdev'
OVS_DPDK_VHOST_USER = 'dpdkvhostuser'
# default ovs vhost-user socket location
VHOST_USER | _SOCKET_DIR = '/var/run/openvswitch'
MAX_DEVICE_RETRIES = 5
# OpenFlow version constants
OPENFLOW10 = "OpenFlow10"
OPENFLOW11 = "OpenFlow11"
OPENFLOW12 = "OpenFlow12"
OPENFLOW13 = "OpenFlow13"
OPENFLOW14 = "OpenFlow14"
# A placeholder for dead vlans.
DEAD_VLAN_TAG = p_const.MAX_VLAN_TAG + 1
|
vojtechtrefny/blivet-gui | blivetgui/dialogs/message_dialogs.py | Python | gpl-2.0 | 8,149 | 0.002209 | # -*- coding: utf-8 -*-
# message_dialogs.py
# misc Gtk.MessageDialogs
#
# Copyright (C) 2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any l... | anklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Vojtech Trefny | <vtrefny@redhat.com>
#
#------------------------------------------------------------------------------#
import os
import gettext
from gi.repository import Gtk, GdkPixbuf
#------------------------------------------------------------------------------#
_ = lambda x: gettext.ldgettext("blivet-gui", x)
#------------... |
mbedmicro/pyOCD | pyocd/target/pack/cmsis_pack.py | Python | apache-2.0 | 22,742 | 0.006464 | # pyOCD debugger
# Copyright (c) 2019 Arm Limited
# Copyright (c) 2020 Men Shiyun
# SPDX-License-Identifier: Apache-2.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.apac... | ._state_stack:
elem = state.element
if elem.tag == 'family':
families += [elem.attrib['Dvendor'], elem.attrib['Dfamily']]
elif elem.tag == 'subFamily':
families += [elem.attrib['DsubFamily']]
return families
def _extract_items(self, state_... | (state, state_info_name):
try:
filter(map, elem)
except (KeyError, ValueError) as err:
LOG.debug("error parsing CMSIS-Pack: " + str(err))
return list(map.values())
def _extract_memories(self):
def filter(map, elem):
... |
ENCODE-DCC/snovault | src/snovault/tests/test_key.py | Python | mit | 2,468 | 0.001621 | import pytest
# Test for storage.keys
pytest_plugins = [
'snovault.tests.serverfixtures',
'snovault.tests.testappfixtures',
]
items = [
{'name': 'one', 'alias': 'TEST1'},
{'name': 'two', 'alias': 'TEST2'},
]
bad_items = [
{'name': 'one', 'alias': 'BAD1'},
{'name': 'bad', 'alias': 'TEST1'},
]... | egistry.settings['local_storage_host'] = app_settings['local_storage_ | host']
config.registry.settings['local_storage_port'] = app_settings['local_storage_port']
config.registry.settings['local_storage_redis_index'] = app_settings['local_storage_redis_index']
config.registry.settings['local_storage_timeout'] = app_settings['local_storage_timeout']
config.registry.settings[... |
shish/python-clearskies | clearskies/transport.py | Python | mit | 3,430 | 0.000292 | import socket
import json
import logging
from clearskies.exc import TransportException
log = logging.getLogger(__name__)
class Transport(object):
def __init__(self, control_path):
self.control_path = control_path
def connect(self):
raise NotImplementedError()
def send(self, js):
... | NotImplementedError()
def close(self):
raise NotImplementedError()
class UnixJsonTransport(Transport):
def __init__(self, control_path):
Transport.__init__(self, control_path)
self.socket = None
def connect(self):
try:
self.socket = socket.socket(socket.AF_UNI... | raise TransportException(e)
def recv(self):
data = None
try:
data = self.socket.recv(1024)
log.debug("< %s" % data.strip())
js = json.loads(data.decode("utf8"))
return js
except ValueError as e:
raise TransportException(... |
Vaidyanath/tempest | tempest/api/identity/admin/test_users_negative.py | Python | apache-2.0 | 10,286 | 0 | # Copyright 2012 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 requ... | .client.create_user,
self.alt | _user, self.alt_password, '49ffgg99999',
self.alt_email)
@test.attr(type=['negative', 'gate'])
def test_create_user_request_without_a_token(self):
# Request to create a user without a valid token should fail
self.data.setup_test_tenant()
# Get the token of the ... |
daisychainme/daisychain | daisychain/channel_github/migrations/0001_initial.py | Python | mit | 1,029 | 0.001944 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-25 15:51
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | length=100)),
('username', models.CharField(max_length=256)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
| options={
'verbose_name': 'github account',
'verbose_name_plural': 'github accounts',
},
),
]
|
laosiaudi/tensorflow | tensorflow/contrib/learn/python/learn/utils/export.py | Python | apache-2.0 | 13,610 | 0.005952 | # Copyright 2016 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... | (predictions, dict):
default_signature = exporter.classification_signature(
examples, scores_tensor=predictions['probabilities'])
else:
default_signature = exporter.classification_signature(
examples, scores_tensor=predictions)
return default_signature, {}
def regression_signature_fn(examp... | :
examples: `Tensor`.
unused_features: `dict` of `Tensor`s.
predictions: `Tensor`.
Returns:
Tuple of default regression signature and empty named signatures.
Raises:
ValueError: If examples is `None`.
"""
if examples is None:
raise ValueError('examples cannot be None when using this si... |
PyBossa/pybossa | alembic/versions/3da51a88205a_ckan_api_key_constraint.py | Python | agpl-3.0 | 736 | 0.005435 | """ckan api key constraint
Revision ID: 3da51a88205a
Revises: 46c3f68e950a
Create Date: 2014-04-01 11:33:01.394220
"""
# revision identifiers, used by Alembic.
revision = '3da51a88205a'
down_revision = '46c3f68e950a'
from alembic import op
import sqlalchemy as sa
def upgrade():
query = '''UPDATE "user"
... | (SELECT id
FROM (SELECT id, row_number() over (par | tition BY ckan_api ORDER BY id) AS rnum
FROM "user") t
WHERE t.rnum > 1);
'''
op.execute(query)
op.create_unique_constraint('ckan_api_uq', 'user', ['ckan_api'])
def downgrade():
op.drop_constraint('ckan_api_uq', 'user')
|
Seldaiendil/meyeOS | devtools/qooxdoo-1.5-sdk/tool/pylib/ecmascript/transform/optimizer/basecalloptimizer.py | Python | agpl-3.0 | 4,225 | 0.006154 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2006-2008 1&1 Internet AG, Germany, http://www.1und1.de
#
# License:
# LGPL: http://www.gnu.org/li... | thodNode in members.items():
patch | Count += optimizeConstruct(methodNode, superClass, methodName, classDefNodes)
return patchCount
##
# Optimize calls to this.base in a tree (e.g. a method); this will skip nested
# calls to qx.*.define, as they are handled on a higher level
def optimizeConstruct(node, superClass, methodName, classDefNodes):
... |
merlin-lang/kulfi | simulate/viz/TotalThroughputVsIterations.py | Python | lgpl-3.0 | 2,403 | 0.022056 | import CommonConf
import CommonViz
import re
from collections import OrderedDict
import numpy as np
import random
import sys
import matplotlib.pyplot as pp
import pylab
EXPERIMENT_NAME = "TotalThroughputVsIterations"
X_LABEL = "TM"
Y_LABEL = "Throughput (fraction of total demand)"
random.seed()
def ... | name+"-".join(solvers)+".pdf")
pp.savefig(dirn+"/"+fname+"-".join(solvers)+".svg")
if __name__ == "__main__":
if len(sys.argv) < 2:
print "Usage: " + sys.argv[0] + " RunId" + " [optional (list_of_schemes)]"
else:
if len(sys.argv) > 2:
if sys.argv[2] == "Sink":
EXPERIMENT_NAME = "Tot... | ain("expData/"+sys.argv[1], EXPERIMENT_NAME, set(sys.argv[3:]))
else:
main("expData/"+sys.argv[1], EXPERIMENT_NAME, set(sys.argv[2:]))
else:
main("expData/"+sys.argv[1], EXPERIMENT_NAME, set(sys.argv[2:]))
|
cenx-cf/wildfly-py | setup.py | Python | apache-2.0 | 1,083 | 0 | #!/usr/bin/env python
# Setuptools install description file.
from setuptools import setup, find_packages
with open('README.md') as readme:
long_description = readme.read()
with open('requirements.txt') as f:
requirements = [line.strip() for line in f.readlines()]
setup(
name='wildfly-py',
version='... | :: Utilities'],
entry_points={
'console_scripts': ['wildfly-py = wildfly.__main__:main'],
'setuptools.installation': ['eggsecutable = wildfly.__main__:main'],
},
author='CENX',
author_email='devops@ce | nx.com',
license='Apache License 2.0',
keywords='cenx wildfly',
url='https://github.org/cenx-cf/wildfly-py')
|
rackerlabs/marconi | marconi/openstack/common/config/generator.py | Python | apache-2.0 | 10,412 | 0.000096 | # Copyright 2012 SINA Corporation
# Copyright 2014 Cisco Systems, 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/licens... | he same group?"
% opt.name
)
def _list_opts(obj):
def is_opt(o):
return (isinstance(o, cfg.Opt) and
not isinstance(o, cfg.SubCommandOpt))
opts = list()
for attr_str in dir(obj):
attr_obj = getattr(obj, attr_str)
if is_opt(attr_obj):
opts.app... | ret = {}
for opt in opts:
ret.setdefault(_guess_groups(opt, obj), []).append(opt)
return ret.items()
def print_group_opts(group, opts_by_module):
print("[%s]" % group)
print('')
for mod, opts in opts_by_module:
print('#')
print('# Options defined in %s' % mod)
print... |
mblue9/tools-iuc | tools/circos/text-from-gff3.py | Python | mit | 1,131 | 0.000884 | #!/usr/bin/env python
import logging
import sys
from BCBio import GFF
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
if __name__ == "__main__":
attr = sys.argv[2]
for record in GFF.parse(sys.argv[1]):
if len(record.features) == 0:
continue
for feature in sort... | : 0 if not feature.location.strand else feature.location.strand,
"value": feature.qualifiers.get("score", [0])[0],
}
if attr not in feature.qualifiers:
continue
name = feature.qualifiers[attr][0]
line = [
record.id,
... | name,
",".join(["%s=%s" % x for x in sorted(kv.items())]),
]
sys.stdout.write("\t".join(line))
sys.stdout.write("\n")
|
ibelikov/jimmy | jimmy/__init__.py | Python | apache-2.0 | 25 | 0 | from jimmy | ctl import | cli
|
larsbratholm/atomorder | atomorder/parse_args.py | Python | mit | 2,393 | 0.011701 | """
atomorder/parse_args.py
Parses command line arguments and overwrites setting defaults
"""
from . import settings
import argparse
import sys
description = ""
epilog = ""
parser = argparse.ArgumentParser(
description = description,
formatter_class = argparse.RawDescriptionHelpFormatter,
ep... | action='store', choices = range(0,6), default=1, type=int)
parser.add_argument('-f', '--format', help='File format', type=str, action='store', default='guess', choices=["guess","xyz","pdb"])
parser.add_argument('-m', '--method', help='Method to use.\n \
| rotate: Ignore bond order, align a single reactant and product molecule and match all atoms\n \
no-bond: Atom matching by rotation and atomic similarity\n \
full: Atom matching by rotation and bond similarity\n \
... |
soerendip42/rdkit | rdkit/VLib/Transform.py | Python | bsd-3-clause | 1,895 | 0.014248 | # $Id$
#
# Copyright (C) 2003 Rational Discovery LLC
# All Rights Reserved
#
import sys
from rdkit.VLib.Node import VLibNode
class TransformNode(VLibNode):
""" base class for nodes which filter their input
Assumptions:
- transform function takes a number of arguments equal to the
number of input... | v
[2, 4, 6, 4]
If we don't provide a function, just return the inputs:
>>> tform = TransformNode()
>>> suppl1 = SupplyNode(contents=[1,2,3,3])
>>> suppl2 = SupplyNode(contents=[1,2,3,1])
>>> tform.AddParent(suppl1)
>>> tform.AddParent(suppl2)
>>> v = [x for x in tform]
>>> v
[(... | wargs):
VLibNode.__init__(self,**kwargs)
self._func = func
def next(self):
done = 0
parent = self.GetParents()[0]
args = []
try:
for parent in self.GetParents():
args.append(parent.next())
except StopIteration:
raise StopIteration
args = tuple(args)
if self._fu... |
lbryio/lbry | lbry/tests/unit/blob_exchange/test_transfer_blob.py | Python | mit | 11,587 | 0.002675 | import asyncio
import tempfile
from io import BytesIO
import shutil
import os
from lbry.blob_exchange.serialization import BlobRequest
from torba.testcase import AsyncioTestCase
from lbry.conf import Config
from lbry.extras.daemon.storage import SQLiteStorage
from lbry.blob.blob_manager import BlobManager
from lbry.b... | self.server_from_client.tcp_port, 2, 3)
self.assertIsNotNone(transport)
self.addCleanup(transport.close)
await client_blob.verified.wait()
self.assertEqual(client_blob.get_is_verified(), True)
self.assertTrue(downloaded)
client_blob.close()
async def tes... | ": [{"blob_hash": "6f53c72de100f6f007aa1b9720632e2d049cc6049e609ad790b556dba262159f739d5a14648d5701afc84b991254206a", "blob_num": 0, "iv": "3b6110c2d8e742bff66e4314863dee7e", "length": 2097152}, {"blob_hash": "18493bc7c5164b00596153859a0faffa45765e47a6c3f12198a4f7be4658111505b7f8a15ed0162306a0672c4a9b505d", "blob_num":... |
acrosby/pyoos | pyoos/parsers/ioos_describe_sensor.py | Python | gpl-3.0 | 123 | 0.01626 | from ow | slib.swe.sensor.sml import SensorML
class IoosDescribeSensor(SensorML):
def get_true(self):
| return True |
labero/kupfer | kupfer/plugin/empathy.py | Python | gpl-3.0 | 8,669 | 0.020764 | # -*- coding: UTF-8 -*-
# vim: set noexpandtab ts=8 sw=8:
__kupfer_name__ = _("Empathy")
__kupfer_sources__ = ("ContactsSource", )
__kupfer_actions__ = ("ChangeStatus", 'OpenChat')
__description__ = _("Access to Empathy Contacts")
__version__ = "2010-10-17"
__author__ = "Jakh Daven <tuxcanfly@gmail.com>"
import dbus
i... | nnection()
_STATUSES = {
'available': _('Available'),
'away': _('Away'),
'dnd': _('Busy'),
'xa': _('Not Available'),
'hidden': _('Invisible'),
'offline': _('Offline')
}
_ATTRIBUTES = {
'alias': 'org.freedesktop.Telepathy.Connection.Interface.Aliasing/alias',
'presence': 'org.freedesktop.Tele... | caps': 'org.freedesktop.Telepathy.Connection.Interface.ContactCapabilities.DRAFT/caps',
'jid': 'org.freedesktop.Telepathy.Connection/contact-id',
'caps': 'org.freedesktop.Telepathy.Connection.Interface.Capabilities/caps',
}
ACCOUNTMANAGER_PATH = "/org/freedesktop/Telepathy/AccountManager"
ACC... |
rado0x54/project-euler | python/problem0072.py | Python | mit | 583 | 0.005146 | #!/usr/bin/env python3
"""Project Euler - Problem 72 Module"""
from problem0069 import eulers_totient
# Smallest Distance if 7 & new_d have no common devisors
# 2: 1/2
# 3: 1/3 & 2/3
# 4: 1/4 (2/4) 3/4
# 5: 1/5 2/5 3/5 4/5
# 6: 1/6 (2/6) (3/6) (4/6) 5/6
# -> Nr of values for d == phi(d)
def problem72(limit):
"""... | in eulers_totient(limit+1):
result += phi
return result
def run():
"""Def | ault Run Method"""
return problem72(1000000)
if __name__ == '__main__':
print("Result: ", run())
|
DistrictDataLabs/topicmaps | topics/serializers.py | Python | mit | 2,138 | 0.00608 | # topics.serializers
# Serializers for the topic and voting models.
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Wed Sep 09 09:34:46 2015 -0400
#
# Copyright (C) 2015 District Data Labs
# For license information, see LICENSE.txt
#
# ID: serializers.py [] benjamin@bengfort.com $
"""
Seri... | "
class Meta:
model = Topic
fields = ('url', 'title', 'vote_total',)
extra_kwargs = {
'url': {'view_name': 'api:topic-detail',},
}
class VotingSerializer(serializers.Serializer):
| """
Serializes incoming votes.
Note: There is no model associated with this serializer
"""
vote = serializers.IntegerField(validators=[InRange(-1,1)])
display = serializers.SerializerMethodField('get_vote_display')
def get_vote_display(self, obj):
displays = {
-1: "d... |
Marquand/cutorrent | uTorrent_py/uTorrent.py | Python | apache-2.0 | 11,902 | 0.031339 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# uTorrent.py version 0.1.1 ALPHA
# Copyright (C) 2006 Rob Crowther <weilawei@gmail.com>
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foun... | , but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this lib | rary; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import logging, sys, socket, simplejson
from base64 import b64encode
from httplib import *
from urllib import quote
# date/timestamp [LEVEL] error message
logging.basicConfig(datefmt='%d %b %Y ... |
dubrayn/dubrayn.github.io | examples/vtk/vtk_load_grid.py | Python | mit | 784 | 0 | #!/usr/bin/env python3
# generate 'mandel_grid.vt | r' first !
import vtk
# source
r = vtk.vtkXMLRectilinearGridReader()
r.SetFileName('mandel_grid.vtr')
# mapper
mandelMapper = vtk.vtkDataSetMapper()
mandelMapper.SetInputConnection(r.GetOutputPort())
mandelMapper.SetScalarModeToUsePointFieldData()
mandelMapper.SelectColorArray('N')
mandelMapper.SetScalarRange(0.0, 40... | nderWindow()
renWin.AddRenderer(ren)
# interactor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Initialize()
# set window size and render
renWin.SetSize(300, 300)
renWin.Render()
# start interactor loop
iren.Start()
|
SINGROUP/pycp2k | pycp2k/classes/_linres1.py | Python | lgpl-3.0 | 1,578 | 0.001901 | from pycp2k.inputsection import InputSection
from ._localize4 import _localize4
from ._current3 import _current3
from ._nmr1 import _nmr1
from ._spinspin1 import _spinspin1
from ._epr1 import _epr1
from ._polar1 import _polar1
from ._print61 import _print61
class _linres1(InputSection):
def __init__(self):
... | tart': 'RESTART', 'Wfn_restart_file_name': 'WFN_RESTART_FILE_NAME', 'Restart_every': 'RESTART_EVERY', 'Max_iter': 'MAX_ITER'}
self._subsections = {' | EPR': 'EPR', 'CURRENT': 'CURRENT', 'PRINT': 'PRINT', 'NMR': 'NMR', 'LOCALIZE': 'LOCALIZE', 'POLAR': 'POLAR', 'SPINSPIN': 'SPINSPIN'}
self._aliases = {'Restart_file_name': 'Wfn_restart_file_name'}
@property
def Restart_file_name(self):
"""
See documentation for Wfn_restart_file_name
... |
neuropoly/spinalcordtoolbox | dev/githook/pre_commit_hook.py | Python | mit | 2,812 | 0.003912 | #!/usr/bin/env python
# --------------------------------------------------------------
# Script used to write commit time for each file
# --------------------------------------------------------------
import os, sys
path_sct = os.environ.get("SCT_DIR", os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.... | for substr in target_list:
if "." in substr:
staged_files.append(substr)
# modify/add to modifs.txt
return staged_files
def save_changed_files(staged_files, sct_dir):
modif_fname = str(sct_dir)+'/scripts/modif.txt'
f = open(modif... | = date.split("-")[0]
date_without_time_zone = date_split
f.write(script_name + " = " + date_without_time_zone+"\n")
f.close()
# status, path_sct = sct.run('cp '+modif_fname+" "+path_sct+"/dev/modif_backup.txt")
# add
os.chdir("scripts")
status, output = sct.run("git add modif.txt")
... |
anhstudios/swganh | data/scripts/templates/object/static/structure/naboo/shared_bridge_stairs_s03.py | Python | mit | 453 | 0.046358 | #### NOTICE: THI | S FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/structure/naboo/shared_bridge_stairs_s03.iff"
result.attribute_template_id = -1
result... | IONS ####
return result |
SuperMass/distOS-lab3 | src/integrated/client4/client_config.py | Python | gpl-3.0 | 334 | 0.005988 | remote_server_ips = ('127.0.0.1', '127.0.0.1')
remote_server_ports = (8005, 8006)
assigned_server_index = 1 # in real system, client is distributed by a load balancing serv | er in general; here I just simulate the balancing policy.
process_id = 4
client_addr = ('127.0 | .0.1', 7004)
poisson_lambda = 5
simu_len = 60
get_score_pb = 0.8
|
xtrementl/focus | focus/environment/io.py | Python | mit | 5,099 | 0 | """ This module provides the stream encapsulation class for the runtime
environment.
"""
import os
import errno
class IOStream(object):
""" Basic abstraction interface for IO streams.
Example Usage::
>>> io = IOStream()
>>> data = io.read() # read from input stream
>>> io.w... | errors=None):
""" Initializes class.
``auto_colored``
Automatically detect if output and error streams support
colorized escape codes.
Additional keyword arguments | :
`inputs`
:Default: ``NullDevice``
Input stream (``File``-like object).
`outputs`
:Default: ``NullDevice``
Output stream (``File``-like object).
`errors`
:Default: ``... |
googleads/google-ads-python | google/ads/googleads/v9/enums/types/user_list_prepopulation_status.py | Python | apache-2.0 | 1,201 | 0.000833 | # -*- 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 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 ... | ng permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v9.enums",
marshal="google.ads.googleads.v9",
manifest={"UserListPrepopulationStatusEnum",},
)
class UserListPrepopulationStatusEnum(proto.Message):
r"""Indic... |
seomoz/SEOmozAPISamples | python/setup.py | Python | mit | 1,723 | 0 | #!/usr/bin/env python
# Copyright (c) 2011-2015 SEOmoz, Moz
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of | this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, mer | ge, publish,
# distribute, sublicense, and/or sell 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.
#
# T... |
citruspi/ReactIRC | ReactIRC/config.py | Python | mit | 643 | 0.006221 | class Config(dict):
def __init__ (self | ):
self['server'] = 'chat.freenode.com'
self['port'] = 6667
self['debug'] = False
self['verbose'] = False
self['web_host'] = '0.0.0.0'
self['web_port'] = 8080
def __getattr__(self, attr):
try:
return self.__getitem__(item)
except KeyErro... | def __setattr__ (self, attr, value):
if self.__dict__.has_key(item): # any normal attributes are handled normally
dict.__setattr__(self, attr, value)
else:
self.__setitem__(attr, value)
|
Dectinc/leetcode | python/77 - Combinations.py | Python | gpl-2.0 | 813 | 0.00246 | # -*- coding: utf-8 -*-
# @filename 77 - Combinations
# @author Dectinc
# @date 2015-03-24 21:10 PM
class Solution:
def __init__(self):
self.res = []
# @return a list | of lists of integers
def combine(self, n, k, used=None, current=None, start=1):
if k == 0:
self.res.append(current[:])
| return self.res
if used is None:
used = [False] * (n+1)
current = []
for i in xrange(start, n+1):
if used[i]:
continue
used[i] = True
current.append(i)
self.combine(n, k-1, used, current, i+1)
curre... |
kyrelos/vitelco-mobile-money-wallet | app_dir/notification_management/migrations/0002_auto_20170321_1522.py | Python | gpl-3.0 | 1,833 | 0.004364 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-21 12:22
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('notification_management', '0001_initial'),
]
operations = [
mig... | rue),
), |
migrations.AlterField(
model_name='notification',
name='state',
field=models.CharField(choices=[(b'pending', b'pending'), (b'in_progress', b'in_progress'), (b'success', b'success'), (b'failed', b'failed')], default=b'pending', max_length=20),
),
]
|
sahama/brython_autocomplete | browser.py | Python | unlicense | 7,160 | 0.000419 | if False:
class DOMNode():
Class = None
__add__ = None
__bases__ = None
__bool__ = None
__class__ = None
__contains__ = None
__del__ = None
__delattr__ = None
__delitem__ = None
__dir__ = None
__eq__ = None
__ge__ = None... | _ = None
__ne__ = None
__new__ = None
__or__ = None
__repr__ = None
__setattr__ = None
__str__ = None
ajax = None
alert = None
confirm = None
console = None
doc = None
# by this some IDE's can auto complete d | ocument objects.
document = [dom]
mouseCoords = None
prompt = None
win = None
class windiw():
InstallTrigger = None
__BRYTHON__ = None
addEventListener = None
alert = None
applicationCache = None
atob = None
blur = None
brython = None
... |
gjr80/weewx | bin/weewx/tests/gen_fake_data.py | Python | gpl-3.0 | 9,588 | 0.004693 | #
#
# Copyright (c) 2009-2019 Tom Keffer <tkeffer@gmail.com>
#
# See the file LICENSE.txt for your full rights.
#
"""Generate fake data used by the tests.
The idea is to create a deterministic database that reports
can be run against, resulting in predictable, expected results"""
from __future__ import absolute... | ment
import logging
import math
import os
import time
import weecfg.database
import weedb
import weewx.manager
log = logging.getLogger(__name__)
os.environ['TZ'] = 'America/Los_Angeles'
time.tzset()
# The start of the 'solar year' for 2009-2010
year_start_tt = (2009, 12, 21, 9, 47, 0, 0, 0, 0)
year_start = int(tim... | 0, -1) # 2010-01-01 00:00
stop_tt = (2010, 9, 3, 11, 0, 0, 0, 0, -1) # 2010-09-03 11:00
alt_start_tt = (2010, 8, 30, 0, 0, 0, 0, 0, -1)
start_ts = int(time.mktime(start_tt))
stop_ts = int(time.mktime(stop_tt))
alt_start = int(time.mktime(alt_start_tt))
# At one half-hour archive intervals:
interval = 1800
altitude... |
hasgeek/lastuser | tests/unit/lastuser_oauth/providers/fixtures.py | Python | bsd-2-clause | 234 | 0 | # -*- coding: utf-8 -*-
class Fix | tures(object):
def make_fixtures(self):
"""
Create users, attach them to organizations.
Create test client app, add te | st
resource, action and message.
"""
|
Ebag333/Pyfa | eos/effects/systemrocketemdamage.py | Python | gpl-3.0 | 473 | 0.006342 | # systemRocketEmDamage
#
# Used by:
# Celestials named like: Wolf Rayet Effect Beacon Class (6 of 6)
runTime = "early"
type = ("projected", "passive")
def handler(fit, beacon, context):
fit.modules.filteredCh | argeMultiply(lambda mod: mod.charge.requiresSkill("Rockets"),
"e | mDamage", beacon.getModifiedItemAttr("smallWeaponDamageMultiplier"),
stackingPenalties=True, penaltyGroup="postMul")
|
robotics-silver-surfer/surfer-main | lab3/Ref/src/Ref/msg/_image.py | Python | mit | 6,271 | 0.017222 | """autogenerated by genpy from Ref/image.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import Ref.msg
import std_msgs.msg
class image(genpy.Message):
_md5sum = "f5f5ba95d6a5e2a82d553cdc6692532a"
_type = "Ref/image"
_has_header = True #flag to... | write(struct.pack('<I%ss'%length, length, _x))
length = len(self.bots)
buff.write(_struct_I.pack(length))
for val1 in self.bots:
_x = val1
buff.write(_struct_3f.pack(_x.x, _x.y, _x.rot))
except struct.error as se: self._check_types(se)
except TypeError as te: self._check_types(... | nto this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
if self.header is None:
self.header = std_msgs.msg.Header()
if self.bots is None:
self.bots = None
end = 0
_x = s... |
ryfeus/lambda-packs | Keras_tensorflow_nightly/source2.7/tensorflow/tools/pip_package/setup.py | Python | mit | 8,836 | 0.005319 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | rn self.distribution.headers or []
def get_outputs(self):
return self.outfiles
de | f find_files(pattern, root):
"""Return all the files matching pattern below root dir."""
for path, _, files in os.walk(root):
for filename in fnmatch.filter(files, pattern):
yield os.path.join(path, filename)
matches = ['../' + x for x in find_files('*', 'external') if '.py' not in x]
so_lib_paths = [
... |
CauldronDevelopmentLLC/dockbot | dockbot/__init__.py | Python | gpl-3.0 | 5,070 | 0.019724 | import argparse
import sys
import dockbot
from dockbot.Error import Error
from dockbot.Dockbot import Dockbot
from dockbot.Config import Config
from dockbot.Image import Image
from dockbot.Container import Container
from dockbot.Slave import Slave
from dockbot.Master import Master
from dockbot.RemoteImage import Remo... | ype,
| help = 'Version to publish. Latest version if '
'omitted.')
parser.add_argument('--mode',
help = 'Build mode to publish. Otherwise, all modes.')
parser.add_argument('-c', '--continue', action = 'store_true',
dest='_continue',
... |
ewheeler/rapidsms-timelines | timelines/tests/test_handlers.py | Python | bsd-3-clause | 20,678 | 0.001934 | from __future__ import unicode_literals
from datetime import timedelta
from .base import (OccurrenceDataTestCase, Notification, Occurrence,
TimelineSubscription, now)
from ..handlers.base import AppointmentHandler
from ..handlers.confirm import ConfirmHandler
from ..handlers.move import MoveHandler
from ..handler... | "Matched user has no upcoming occurrence notifications."
self.notification.delete()
replies = ConfirmHandler.test('APPT CONFIRM foo bar', identity=self.connection.identity)
self.assertEqual(len(replies), 1)
reply = replies[0]
self.assertTrue('no uncompleted' in reply)
def te... | eady_confirmed(self):
"Matched user has already confirmed the upcoming occurrence."
self.notification.confirm()
replies = ConfirmHandler.test('APPT CONFIRM foo bar', identity=self.connection.identity)
self.assertEqual(len(replies), 1)
reply = replies[0]
self.assertTrue('n... |
EddyTheB/Warbler | Warbler/urls.py | Python | apache-2.0 | 174 | 0 | from django.conf.urls import include, | url
from django.contrib import admin
urlpatterns = [
url(r'^a | dmin/', admin.site.urls),
url(r'^webcam/', include('webCam.urls')),
]
|
aureooms/sak | sak/pip3.py | Python | agpl-3.0 | 100 | 0 | import subprocess
de | f release():
subprocess.call(["python3", "setup.py", "sdist", "u | pload"])
|
molly/Wikisource-to-LaTeX | core.py | Python | mit | 3,449 | 0.004352 | # -*- coding: utf-8 -*-
# Copyright (c) 2013–2015Molly White
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mod... | BUT NOT 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 ... | USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import codecs, logging, os, util
from tokenizer import Tokenizer
from tokenparser import Parser
from api import Document
def setup_logging():
logger=logging.getLogger("W2L")
logger.setLevel(logging.DEBUG)
console_formatter = logging.Formatter("%(asctime)s - %(level... |
ealegol/kolla-newton | tools/version-check.py | Python | apache-2.0 | 5,041 | 0.000397 | #!/usr/bin/env python
# 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... | .common import config as common_config
logging.basicConfig(format="%(message)s")
LOG = logging.getLogger('version-check')
# Filter list for non-projects
NOT_PROJECTS = [
'nova-novncproxy',
'nova-spicehtml5proxy',
'openstack-base',
'profiles'
]
TARBALLS_BASE_URL = 'http://tarballs.openstack.org'
VERSIO... | ef retrieve_upstream_versions():
upstream_versions = dict()
for project in VERSIONS['local']:
winner = None
series = VERSIONS['local'][project].split('.')[0]
base = '{}/{}'.format(TARBALLS_BASE_URL, project)
LOG.debug("Getting latest version for project %s from %s",
... |
vivekmumbles/git-ledger | data.py | Python | gpl-2.0 | 3,254 | 0.024585 |
import os
import re
import json
import pprint
EMPTY = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
repo = str(input('Enter clone url to git repo: '))
repo_folder = repo.split('/')[-1].split('.git')[0]
os.system('git clone ' + repo)
os.system('cd ' + repo_folder)
log = os.popen('git --git-dir ./' + repo_folder + '/.... | :
ol = o.split('\t')
changes = 1
if ol[0] != '-' and ol[1] != '-':
changes = int(ol[0])+int(ol[1])
k = '/'+repo_folder+'/'+ol[2]
if k in activity[user]:
activity[user][k] += changes
else:
activity[user][k] = changes
# print(activity)
# for l in log: print(l)
rootDir = './'+repo_folder
fileList =... | s.popen(cmd).read().split('\n')
fileList = list(map(lambda x: x[1:], fileList))
fileList = sorted(fileList, key=lambda x: x.count('/'))[1:]
# for f in fileList: print(f)
class Node:
def __init__(self, path):
self.path = path
self.contributions = {}
self.files = []
def getNode(node, path):
if node.path == pa... |
poelzi/uberclock | db/ffnet.py | Python | gpl-2.0 | 34,204 | 0.011607 | ########################################################################
## Copyright (C) 2006 by Marek Wojciechowski
## <mwojc@p.lodz.pl>
##
## Distributed under the terms of the GNU General Public License (GPL)
## http://www.gnu.org/copyleft/gpl.html
###############################################################... | aise TypeError("Length of arch[1] should be equal to arch[2].")
el | se: raise TypeError("Wrong architecture definition.")
#Merging function
def merge(conec, conec_tmp, nofi):
from scipy import array, where
try:
trans = array(conec).max() - nofi
tmp = array(conec_tmp)
tmp = where(tmp > nofi, tmp + trans, tmp)
c... |
ostree/plaso | tests/formatters/mackeeper_cache.py | Python | apache-2.0 | 1,008 | 0.00496 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the MacKeeper Cache event formatter."""
import unittest
from plaso.formatters import mackeeper_cache
from tests.formatters import test_lib
class MacKeeperCacheFormatterTest(test_lib.EventFormatterTestCase):
"""Tests for the MacKeeper Cache event formatter.""... | 'record_id',
u'room']
self._TestGetFormatStringAttributeNames(
event_formatter, expected_attribute_names)
# TODO: add test for GetMessages.
if __name__ | == '__main__':
unittest.main()
|
failys/CAIRIS | cairis/test/test_ArchitecturalPattern.py | Python | apache-2.0 | 5,840 | 0.02089 | # 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... | .iTemplateGoals = d['template_goals']
for i in self.iTemplateGoals:
self.theGoals.append(TemplateGoalParameters(i["theName"],i["theDefinition"],i["theRationale"],i["theConcerns"],i["theResponsibilities"]))
self.iComponentViews = d['architectural_patterns']
def testComponentView(self):
cvName... | psis"]
theComponents = []
for c in self.iComponentViews[0]["theComponents"]:
cName = c["theName"]
cDesc = c["theDescription"]
cInts = []
for i in c["theInterfaces"]:
cInts.append((i["theName"],i["theType"],i["theAccessRight"],i["thePrivilege"]))
cStructs = []
for cs i... |
ampasowa/factstream | webapp/run.py | Python | mit | 4,469 | 0.006489 | #!/usr/bin/env python
import threading
from threading import Thread
from flask import jsonify
from flask import render_template
from flask import Flask, redirect
from flask.ext.socketio import SocketIO, emit
from time import sleep
import json
import rethinkdb as r
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secr... | 'name']
def get_final_score(game):
return "%s %s - %s %s" % (abbrev(game['away_id']), game['away_points'], abbrev(game['home_id']), game['home_points'])
def abbrev(team_id):
return r.table('team_info').get(team_id).run(conn2)['alias']
@app.route('/')
@app.route('/index')
def index():
return render_te... | ame.html")
@app.route("/slides")
def slides():
return render_template("slides.html")
@app.route("/robots.txt")
def robots():
return render_template("robots.txt")
@app.route('/_start')
def start_pushing():
return redirect("http://ec2-54-183-107-47.us-west-1.compute.amazonaws.com:5000/_start", code=302)
@... |
SitiBanc/1061_NCTU_IOMDS | 1011/Course Material/temp.py | Python | apache-2.0 | 5,952 | 0.011415 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 12 22:25:38 2017
@author: sitibanc
"""
import math
import numpy as np
def entropy(p1, n1): # postive, negative
if p1 == 0 and n1 == 0:
return 1
value = 0
pp = p1 / (p1 + n1)
pn = n1 / (p1 + n1)
if pp > 0:
... | G1 = [] #左子樹
G2 = [] #右子樹
for t in idx:
if feature[t, j] <= threshold:
G1.append(t)
else:
G2.append(t)
# Calculate infoGain
... | e), sum(target[G2] == negative))
# Update bestIG
if thisIG > bestIG:
bestIG = thisIG
bestG1 = G1
bestG2 = G2
bestThreshold = threshold
bestf = j
if ... |
phoorichet/bbn_80211 | src/examples/bbn_80211b_test.py | Python | gpl-2.0 | 3,779 | 0.007145 | #!/usr/bin/env python
#
# Copyright 2004,2005 Free Software Foundation, Inc.
#
# Copyright (c) 2006 BBN Technologies Corp. All rights reserved.
# Effort sponsored in part by the Defense Advanced Research Projects
# Agency (DARPA) and the Department of the Interior National Business
# Center under agreement number NBC... | gr.flow_graph):
def __init__(self, rx_callback, spb, alpha, SNR):
# m is constellation size
# if diff==True we are doing DxPSK
gr.flow_graph.__init__(self)
fg = self
# transmitter
self.packet_transmitter = bbn_80211b_mod_pkts(fg, spb=spb, alpha=alpha,
... | add = gr.add_cc()
noise = gr.noise_source_c(gr.GR_GAUSSIAN, pow(10.0,-SNR/20.0))
# channel filter
rx_filt_taps = gr.firdes.low_pass(1,spb,0.8,0.1,gr.firdes.WIN_HANN)
rx_filt = gr.fir_filter_ccf(1,rx_filt_taps)
# receiver
self.bit_receiver = bbn_80211b_demod_pkts(s... |
llllllllll/lazy_python | lazy/tests/test_utils.py | Python | gpl-2.0 | 120 | 0 | from lazy.utils import isolate_namespace
def tes | t_isolate_namespace():
assert 'test' != isolate_name | space('test')
|
shellyw19-meet/meet2017y1final-proj | elias.py | Python | mit | 2,393 | 0.033013 | ######################################################################elias's code
import turtle
import random
import time
turtle.tracer(1,0)
size_x=800
size_y=500
turtle.setup(size_x,size_y)
turtle.penup()
#how far the snake moves
SQUARE_SIZE=20
pos_list=[]
plane=turtle.clone()
#the shape of the plane
turtle.regist... | if direction==RIGHT:
plane.goto(x_pos+SQUARE_SIZE,y_pos)
print('you moevd right ')
if direction==DOWN:
plane.goto(x_pos,y_pos-SQUARE_SIZE)
print('you moevd DOWN ')
if direction==LEFT:
plane | .goto(x_pos-SQUARE_SIZE,y_pos)
print('you moevd LEFT ')
if direction==UP:
plane.goto(x_pos,y_pos+SQUARE_SIZE)
print('you moevd UP ')
timer()#this is baisicly activating he timer
############################################################################################
... |
savoirfairelinux/OpenUpgrade | addons/point_of_sale/point_of_sale.py | Python | agpl-3.0 | 68,767 | 0.00714 | # -*- 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... | t Terminal integration"),
'iface_electronic_scale' : fields.boolean('Electronic Scale', h | elp="Enables Electronic Scale integration"),
'iface_vkeyboard' : fields.boolean('Virtual KeyBoard', help="Enables an integrated Virtual Keyboard"),
'iface_print_via_proxy' : fields.boolean('Print via Proxy', help="Bypass browser printing and prints via the hardware proxy"),
'iface_scan_via_proxy... |
RobinQuetin/CAIRIS-web | cairis/cairis/StepSynopsisDialog.py | Python | apache-2.0 | 2,154 | 0.012999 | # 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... | icense 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.
import wx
import armid
import WidgetFactory
import ARM
from Borg import Borg
from StepSynopsisPanel import StepSynopsisPanel
class Ste... |
FrankNagel/qlc | src/webapp/quanthistling/scripts/annotations/annotations_for_boudin1950.py | Python | gpl-3.0 | 3,903 | 0.010505 | # -*- coding: utf8 -*-
import sys, os
sys.path.append(os.path.abspath('.'))
import re
from operator import attrgetter
import difflib
# Pylons model init sequence
import pylons.test
import logging
from quanthistling.config.environment import load_environment
from quanthistling.model.meta import Sessi... | return heads
def main(argv):
bibtex_key = u"boudin1950"
if len(argv | ) < 2:
print "call: annotations_for%s.py ini_file" % bibtex_key
exit(1)
ini_file = argv[1]
conf = appconfig('config:' + ini_file, relative_to='.')
if not pylons.test.pylonsapp:
load_environment(conf.global_conf, conf.local_conf)
# Create the tables if they don'... |
iwm911/plaso | plaso/parsers/winreg_plugins/msie_zones_test.py | Python | apache-2.0 | 15,963 | 0.000814 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 L... | pt behaviors: 0 (Allow) '
u'[2001] .NET: Run components signed with Authenticode: '
u'3 (Not Allowed) '
u'[2004] .NET: Run components not signed with Authenticode: '
u'3 (Not Allowed) '
u'[2005] UNKNOWN: 0 '
u'[2007] UNKNOWN: 3 '
u'[2100] Open files based on con... | ile extension: 0 (Allow) '
u'[2101] Web sites in less privileged zone can navigate into this '
u'zone: 3 (Not Allowed) '
u'[2102] Allow script initiated windows without size/position '
u'constraints: 0 (Allow) '
u'[2103] Allow status bar updates via script: 0 '
u'[2104]... |
annapowellsmith/openpresc | openprescribing/frontend/tests/commands/test_import_ccg_boundaries.py | Python | mit | 726 | 0 | from django.core.management import call_command
from django.test import TestCase
from frontend.models import PCT
def setUpModule():
call_command('loaddata', 'frontend/tests/fixtures/ccgs.json',
verbosity=0)
def | tearDownModule():
call_command('flush', verbosity=0, interactive=False)
class CommandsTestCase(TestCase):
def test_import_ccg_boundaries(self):
args = []
opts = {
'filename': ('frontend/tests/fixtures/commands/'
'CCG_BSC_Apr2015.TAB')
}
ca... | mport_ccg_boundaries', *args, **opts)
pct = PCT.objects.get(code='03Q')
self.assertAlmostEqual(pct.boundary.centroid.x, -1.0307530606980588)
|
safwanrahman/kitsune | wsgi/config.py | Python | bsd-3-clause | 399 | 0.002506 | # see http://docs.gunicorn.org/en/latest/configure.html#configuration-file
from os import getenv
bind = '0.0.0. | 0:{}'.format(get | env('PORT', 8000))
workers = int(getenv('WSGI_NUM_WORKERS', 2))
accesslog = '-'
errorlog = '-'
loglevel = getenv('WSGI_LOG_LEVEL', 'info')
keepalive = int(getenv('WSGI_KEEP_ALIVE', 2))
worker_class = getenv('GUNICORN_WORKER_CLASS', 'meinheld.gmeinheld.MeinheldWorker')
|
generica/euler | 5.py | Python | gpl-2.0 | 329 | 0.006079 | #!/usr/bin/python
import sys
if __name__ == "__main_ | _":
i = 0
while True:
i += 20
if (i % 19 == 0) and (i % 18 == 0) and (i % 17 == 0) and (i % 16 == 0) and (i % 15 == 0) \
and (i % 14 | == 0) and (i % 13 == 0) and (i % 12 == 0) and (i % 11 == 0):
print i
sys.exit(0)
|
PyCQA/pylint | tests/functional/m/missing/missing_function_docstring.py | Python | gpl-2.0 | 413 | 0.002421 | """Tests for missing-function-docstri | ng"""
# pylint: disable=unused-argument, missing-class-docstring, too-few-public-methods, unused-variable
def func(tion): # [missing-function-docstring]
pass
def func_two(tion):
"""Documented"""
def inner(fun):
# Not documented
pass
class MyClass:
def __init__(self, my_param: int... | # [missing-function-docstring]
pass
|
lakiw/cripts | cripts/services/test/forms_test.py | Python | mit | 1,440 | 0.002778 | import unittest
from cripts.services.core import Service, Ser | viceConfigOption
from cripts.services.forms import (_get_config_fields, make_edit | _config_form,
make_run_config_form)
class ServiceWithNoDefaultConfig(Service):
name = "dummy"
version = "1.0"
class ServiceWithDefaultConfig(Service):
name = "dummy2"
version = "1.1"
default_config = [
ServiceConfigOption("some option", ServiceConfigOption.STRING),
... |
TeamSPoon/logicmoo_workspace | packs_web/butterfly/lib/python3.7/site-packages/virtualenv/seed/embed/via_app_data/via_app_data.py | Python | mit | 6,059 | 0.002311 | """Bootstrap"""
from __future__ import absolute_import, unicode_literals
import logging
import sys
import traceback
from contextlib import contextmanager
from subprocess import CalledProcessError
from threading import Lock, Thread
from virtualenv.info import fs_supports_symlink
from virtualenv.seed.embed.base_embed i... | ext
from .pip_install.copy import CopyPipInstall
from .pip_install.symlink import SymlinkPipInstall
class FromAppData(BaseEmbe | d):
def __init__(self, options):
super(FromAppData, self).__init__(options)
self.symlinks = options.symlink_app_data
@classmethod
def add_parser_arguments(cls, parser, interpreter, app_data):
super(FromAppData, cls).add_parser_arguments(parser, interpreter, app_data)
can_sym... |
jflesch/paperwork-backend | paperwork_backend/common/export.py | Python | gpl-3.0 | 885 | 0 | def dummy_export_progress_cb(*args, **kwargs):
pass
class Exporter(object):
def __init__(self, obj, export_format):
self.obj = obj
| self.export_format = str(export_format)
self.can_change_quality = False
def set_quality(quality_pourcent):
raise NotImplementedError()
def set_postprocess_func(s | elf, postprocess_func):
raise NotImplementedError()
def estimate_size():
"""
returns the size in bytes
"""
raise NotImplementedError()
def get_img(self):
"""
Returns a Pillow Image
"""
raise NotImplementedError()
def get_mime_type(se... |
benfinke/ns_python | nssrc/com/citrix/netscaler/nitro/resource/config/cs/csvserver_cspolicy_binding.py | Python | apache-2.0 | 10,784 | 0.040801 | #
# Copyright (c) 2008-2015 Citrix Systems, 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 l... | priority
except Exception as e:
raise e
@priority.setter
def priority(self, priority) :
ur"""Priority for the policy.
"""
try :
self._priority = priority
except Exception as e:
raise e
@property
def bindpoint(self) :
| ur"""The bindpoint to which the policy is bound.<br/>Possible values = REQUEST, RESPONSE.
"""
try :
return self._bindpoint
except Exception as e:
raise e
@bindpoint.setter
def bindpoint(self, bindpoint) :
ur"""The bindpoint to which the policy is bound.<br/>Possible values = REQUEST, RESPONSE
"""
t... |
cidadania/e-cidadania | tests/unit_tests/src/apps/ecidadania/debate/test_views.py | Python | apache-2.0 | 12,418 | 0.006684 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2012 Cidadania S. Coop. Galega
#
# This file is part of e-cidadania.
#
# e-cidadania 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... | l)
self.assertResponseOK(response)
self.assertTemplateNotUsed(response, 'not_allowed.html')
"""
When the admin doesn't have debate_ | delete permissions
"""
self.bar_admin.user_permissions.remove(Permission.objects.get(codename='delete_debate'))
self.bar_admin.save()
space.save()
response = self.get(url)
self.assertResponseOK(response)
self.assertTemplateUsed(response, 'not_allowed.html')
... |
yaybu/touchdown | touchdown/aws/ec2/instance.py | Python | apache-2.0 | 4,911 | 0.000814 | # Copyright 2014-2015 Isotoma Limited
#
# 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 wr... | r=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(Se | curityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Ins... |
ElektronikNode/autodrill | autodrill/ui/dialogDrills.py | Python | gpl-3.0 | 3,224 | 0.03567 | '''
autodrill 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.
autodrill is distributed in the hope that it will be useful,
but WITHOUT ANY W... | ):
try:
# try to read diameters and toolNrs from table
drills={}
for row in range(self.tableWidget_drills.rowCount()):
if self.tableWidget_drills.item(row, 0) and self.tableWidget_drills.item(row, 1):
diaStr=self.tableWidget_drills.item(row, 0).text()
toolNrStr=self.tableWidget_drill... | oolNrStr:
dia=float(diaStr)
toolNr=int(toolNrStr)
# check for positive toolNr and dia
if dia>0 and toolNr>0:
# check for double drills
if not dia in drills:
drills[dia]=toolNr
else:
raise
else:
raise
# try to read diame... |
ucarion/git-code-debt | tests/metrics/curse_test.py | Python | mit | 784 | 0 | from __future__ import absolute_import
from __future__ import unicode_literals
from git_code_debt.file_diff_stat import FileDiffStat
from git_code_debt.metric import Metric
from git_code_debt.metrics.curse import CurseWordsParser
def test_ | curse_words_parser():
parser = CurseWordsParser()
input_stats = [
FileDiffStat(
b'templates/foo.tmpl',
[b'#man seriously, fuck cheetah'],
[],
None,
),
FileDiffStat(
b'cmds/foo.py',
[b"# I'm clean I swear"],
... | alCurseWords_Template', 1) in metrics
assert Metric('TotalCurseWords_Python', 0) in metrics
|
shfengcj/pyminer | pyminer_cos_model.py | Python | gpl-2.0 | 4,382 | 0.029439 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 15:28:10 2015
@author: chaojun
"""
#===============================================================================
"""
cosmological model data struct
"""
#===============================================================================
""... | if self.isFlat:
self.Omega_k = 0.0 # spatial curvature
else:
self.Omega_k = -0.01
# romberg intergral
self.divmax = divmax
|
def __invHubble(self,z):
# Inverse of dimensionless Hubble 1/E = H_0/H
from numpy import sqrt
omega_mgz = self.Omega_M*(1.+z)**3 + self.Omega_r*(1.+z)**4 + self.Omega_k*(1.+z)**2
rhs = omega_mgz + (1. - self.Omega_M - self.Omega_r - self.Omega_k) ... |
ambitioninc/django-smart-manager | smart_manager/signal_handlers.py | Python | mit | 858 | 0.006993 | from django.db.models.signals import pre_delete
from django.dispatch import receiver
from smart_manager.models import SmartManagerObject
@receiver(pre_delete, sender=SmartManagerObject, dispatch_uid='delete_model_obj_on_smart_manager_object_delete')
def delete_model_obj_on_smart_manager_object_delete(sender, instanc... | deletions, delete all of the model objects associated with it before
the template is deleted.
"""
if instance.smart_manager.manages_deletions:
try:
instance.mo | del_obj.delete()
except:
# The model object could have been deleteed. Its ctype could have been corrupted. It could
# have also been trying to cascade delete a protected model. Ignore any deletion errors with
# model objects.
pass
|
Cartocite/osmada | osmdata/exporters.py | Python | agpl-3.0 | 1,428 | 0.0007 | import csv
import datetime
import io
from django.template.loader import render_to_string
class AbstractExporter:
pass
class CSVExporter(AbstractExporter):
def get_header_row(self):
return (
'id', 'version', 'timestamp', 'changeset',
'user', 'uid', 'action_type', 'element_type... | 'actions': actions_qs,
'import_date': datetime.datetime.now(),
}
return render_to_string(
'osmdata/adiff/di | ff_detail.xml',
{'diff': diff}
)
|
DirkHoffmann/indico | indico/web/forms/fields/datetime.py | Python | gpl-3.0 | 14,389 | 0.001251 | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import json
from datetime import time, timedelta
import dateutil.parser
import pytz
from flask import ses... | it
choices = [(unit, self.unit_names[unit]) for unit in self.units]
# Add whatever unit is necessary to represent the currenet val | ue if we have one
if best_unit and best_unit not in self.units:
choices.append((best_unit, f'({self.unit_names[best_unit]})'))
return choices
def process_formdata(self, valuelist):
if valuelist and len(valuelist) == 2:
value = int(valuelist[0])
unit = val... |
WarrenWeckesser/scipy | scipy/ndimage/tests/test_interpolation.py | Python | bsd-3-clause | 54,800 | 0.000036 | import sys
import numpy
from numpy.testing import (assert_, assert_equal, assert_array_equal,
assert_array_almost_equal, assert_allclose,
suppress_warnings)
import pytest
from pytest import raises as assert_raises
import scipy.ndimage as ndimage
from . import type... | data = numpy.array([1, 2, 3, 4.])
assert_array_equal(
expected_value,
ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
output_shape=(7,), order=1))
@pytest.mark.parametrize(
'mode, expected_value',
[('nearest', [1... | 1, 2, 3]),
('mirror', [2, 1, 2, 3]),
('reflect', [1, 1, 2, 3]),
('constant', [-1, 1, 2, 3]),
('grid-constant', [-1, 1, 2, 3])]
)
def test_boundaries2(self, mode, expected_value):
def shift(x):
return (x[0] - 0.9,)
data = numpy.array([1, 2, 3, 4])... |
madhuni/AstroBox | src/ext/makerbot_pyserial/serialcli.py | Python | agpl-3.0 | 10,048 | 0.005772 | #! python
# Python Serial Port Extension for Win32, Linux, BSD, Jython and .NET/Mono
# serial driver for .NET/Mono (IronPython), .NET >= 2
# see __init__.py
#
# (C) 2008 Chris Liechti <cliechti@gmx.net>
# this is distributed under a free software license, see license.txt
import clr
import System
import System.IO.Ports... | s" % (self.portstr, msg))
self._reconfigurePort()
self._port_handle.Open()
self._isOpen = True
if not self._rtscts:
self.setRTS(True)
| self.setDTR(True)
self.flushInput()
self.flushOutput()
def _reconfigurePort(self):
"""Set communication parameters on opened port."""
if not self._port_handle:
raise SerialException("Can only operate on a valid port handle")
#~ self._port_handle.ReceivedB... |
hmoraldo/AnimationEditor | src/AnimationEditor.py | Python | mit | 4,150 | 0.027711 | import json, glob
from PIL import Image, ImageTk
import Tkinter as tk
import Utils
canvas = None
lblImage = None
lblVertex = None
FileName = None
CurrentFrame = None # current frame number
CurrentVertex = None
FrameName = None
Images = None # the image names
ImageGlob = None
Vertices = None
Lines = None
Frames = None ... | n=4, columnspan=2)
btnSetFrameName.bind("<ButtonRelease-1>", btnSetFrameNameClick)
tk.Label(window, text="Image:").grid(row=2, column=0)
lblImage = Utils.MakeArrowButtons(window, 2, 1, btnPrev | ImageClick, btnNextImageClick)
tk.Label(window, text="Vertex:").grid(row=3, column=0)
lblVertex = Utils.MakeArrowButtons(window, 3, 1, btnPrevVertexClick, btnNextVertexClick)
btnSave = tk.Button(window, text="Save")
btnSave.grid(row=4, column=4)
btnSave.bind("<ButtonRelease-1>", btnSaveClick)
updateData()
upd... |
scalient/ebsmount | ebsmount.py | Python | gpl-2.0 | 3,196 | 0.003442 | # Copyright (c) 2010 Alon Swartz <alon@turnkeylinux.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This pro... | continue
mount(devp | ath, mountpath, mountoptions)
log(devname, "mounted %s %s (%s)" % (devpath, mountpath, mountoptions))
if exists(hookspath):
hooks = os.listdir(hookspath)
hooks.sort()
if hooks and not config.runhooks.lower() == "true":
log(devname, "skipping hooks: R... |
satanas/Turpial | turpial/ui/gtk/column.py | Python | gpl-3.0 | 18,517 | 0.003889 | # -*- coding: utf-8 -*-
# GTK3 widget to implement columns in Turpial
import pdb
import time
import urllib2
from xml.sax.saxutils import unescape
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Pango
from gi.repository import GObject
from gi.repository import GdkPixbuf
from gi.... | last_id holds
# the id for the newest status
self.last_id = statuses[0].id_
| # We need to reverse statuses because they come ordered as the newest first
statuses.reverse()
for status in statuses:
# We don't insert duplicated statuses
if status.id_ in self.status_ref:
continue
print ' Adding: %s' % status.text[:30]
... |
ray-project/ray | python/ray/autoscaler/_private/cluster_dump.py | Python | apache-2.0 | 19,917 | 0.000703 | from typing import Optional, List, Sequence, Tuple
import os
import re
import subprocess
import sys
import tarfile
import tempfile
import threading
import yaml
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
import ray # noqa: F401
from ray.autoscaler._private.cli_logger imp... | ort to avoid circular dependencies
from ray.autoscaler._private.constants import RAY_PROCESSES
processes = RAY_PROCESSES
process_infos = []
for process in psutil.process_iter(["pid", "name", "cmdline", "status"]):
try:
with process.oneshot():
cmdline = " ".j... | process_infos.append(
(
{
"executable": cmdline
if verbose
else cmdline.split("--", 1)[0][:-1],
"name": |
chosenone75/Neural-Networks | tf/PTB/reader_test.py | Python | gpl-3.0 | 2,342 | 0.008967 | """
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | n 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.
# ==============================================================================
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import tensorflow as tf
import reader
class PtbReaderTest(tf.test.TestCase):
def setUp(s... |
oschwab/dcss_stats | dcss_stats/core/dcss_data.py | Python | unlicense | 2,852 | 0.041374 | #
#crawl-ref/source/job-data.h
#
jobs={
"Abyssal Knight" : "AK",
"Air Elementalist" : "AE",
"Arcane Marksman" : "AM",
"Artificer" : "Ar",
"Assassin" : "As",
"Berserker" : "Be",
"Chaos Knight" : "CK",
"Conjurer" : "Cj",
"Earth Elementalist" : "EE",
"Enchanter" : "En",
"Fighter" : "Fi",
"Fire Elementalist" : "FE",
"Gla... | "Te",
"Troll": "Tr",
"Vampire": "Vp",
"Vine Stalker": "VS",
"Sludge Elf": "SE",
"Lava Orc": "LO",
"Djinni": "Dj"
}
#
# /crawl-ref/source/god-type.h
#
gods={
"Zin",
"Shining One",
"Kikubaaqudgha",
"Yredelemnul",
"Xom",
"Vehumet",
"Okawaru",
"Makhleb",
"Sif muna",
"Trog",
"N... | ",
"Elyvilon",
"Lugonu",
"Beogh",
"Jiyva",
"Fedhas",
"Cheibriados",
"Ashenzari",
"Dithmenos",
"Gozag",
"Qazlal",
"Ru",
"Pakellas",
"Uskayaw",
"Hepliaklqana",
"Wu Jian"
}
def is_specie(string):
return (string.lower() in list((v.lower()) for v in species.v... |
MPIB/Lagerregal | devicegroups/tests.py | Python | bsd-3-clause | 1,721 | 0.001162 | from django.test import TestCase
from django.test.client import Client
from django.urls import reverse
from model_mommy import mommy
from devicegroups.models import Devicegroup
from users.models import Lageruser
class DevicegroupTests(TestCase):
def setUp(self):
self.client = Client()
Lageruser.... | .pk)
self.assertEqual(response.status_code, 200)
def test_update_view(self):
devicegroup = mommy.make(Devicegroup)
response = self.client.get('/devicegroups/%i/edit/' % devicegroup.pk)
self.assertEqual | (response.status_code, 200)
def test_delete_view(self):
devicegroup = mommy.make(Devicegroup)
response = self.client.get('/devicegroups/%i/delete/' % devicegroup.pk)
self.assertEqual(response.status_code, 200)
|
tuturto/satin-python | satin/label.py | Python | gpl-3.0 | 2,211 | 0.000905 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2012 Tuukka Turto
#
# This file is part of satin-python.
#
# pyherc 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 ... | with label {0}'.format(self.text))
def describe_mismatch(self, item, mismatch_description):
"""
Describe this mismatch
"""
mismatch_description.append(
'QLabel with text {0} was not found'.for | mat(self.text))
def has_label(text):
"""
Check if Widget has label with given text
"""
return LabelMatcher(text)
|
IrekRybark/pyiku | pyiku/syllable_counter.py | Python | mit | 4,140 | 0.027301 | # Author: M. Emre Aydın
# Source: http://eayd.in/?p=232
import re
def SyllableCounter(word):
word = word.lower()
# exception_add are words that need extra syllables
# exception_del are words that need less syllables
exception_add = ['serious','crucial']
exception_del = ['fortunately','unfortuna... | ,'coed','coinci']
pre_one = ['preach']
syls = 0 #added syllable number
disc = 0 #discarded syllable number
#1) if letters < 3 : return 1
if len(word) <= 3 :
syls = 1
return syls
#2) if doesn't end with "ted" or "tes" or "ses" or "ied" or "ies", discard "es" and "ed" at the en... | vowel or 1 set of consecutive vowels, discard. (like "speed", "fled" etc.)
if word[-2:] == "es" or word[-2:] == "ed" :
doubleAndtripple_1 = len(re.findall(r'[eaoui][eaoui]',word))
if doubleAndtripple_1 > 1 or len(re.findall(r'[eaoui][^eaoui]',word)) > 1 :
if word[-3:] == "ted" or word[-... |
danuzclaudes/helpdesk | server.py | Python | unlicense | 6,950 | 0.001007 | import io
import json
import pdb
import random
import string
from datetime import datetime
from flask import Flask, render_template, make_response, redirect
from flask.ext.restful import Api, Resource, reqparse, abort
from twitter import Twitter
# Define our priority levels.
# These are the values that the "priority... | es(query='', sort_by='date'):
| # Returns True if the query string appears in the help request's
# title or description.
def matches_query(item):
(note_id, note) = item
text = note['title'] + note['note_content']
return query.lower() in text
# Returns the help request's value for the sort property (which by
... |
ecdavis/pantsmud | pantsmud/util/error.py | Python | apache-2.0 | 608 | 0 | """
PantsMUD | core exception classes.
"""
class BrainMissingInputHandlers(Exception):
pass
class ZoneNotFound(Exception):
pass
class NodeNotFound(Exception):
pass
class LinkNotFound(Exception):
pass
class LinkAlreadyExists(Exception):
pass
class CommandError(Exception):
pass
class CommandFail(E... | """
pass
class PatternError(Exception):
"""
Raised when an error is found in a pattern passed to a parser.
"""
pass
|
gnperumal/exscript | src/TkExscript/compat/tkCommonDialog.py | Python | gpl-2.0 | 1,394 | 0.007891 | #
# Instant Python
# tkCommonDialog.py,v 1.2 1997/08/14 14:17:26 guido Exp
#
# base class for tk common dialogues
#
# this module provides a base class for acc | essing the common
# dialogues available in Tk 4.2 and newer. use tkFileDialog,
# tkColorChooser, and tkMessageBox to access the individual
# dialogs.
#
# written by Fredrik Lundh, May 1997
#
from Tkinter import *
class Dialog:
command = None
def __init__(self, master=None, **options):
# FIXME: should ... | clError, "this module requires Tk 4.2 or newer"
self.master = master
self.options = options
def _fixoptions(self):
pass # hook
def _fixresult(self, widget, result):
return result # hook
def show(self, **options):
# update instance options
for k, v in options.... |
AloneRoad/Inforlearn | vendor/django/db/backends/mysql/creation.py | Python | apache-2.0 | 2,925 | 0.004103 | from django.conf import settings
from django.db.backends.creation import BaseDatabaseCreation
class DatabaseCreation(BaseDatabaseCreation):
# This dicti | onary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be in | terpolated against the values of Field.__dict__ before being output.
# If a column type is set to None, it won't be included in the output.
data_types = {
'AutoField': 'integer AUTO_INCREMENT',
'BooleanField': 'bool',
'CharField': 'varchar(%(max_length)s)',
'... |
jcicolani/Nomad | devel/_setup_util.py | Python | bsd-3-clause | 12,770 | 0.004229 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistrib... | MAKE_PREFIX_PATH', prefix))
for key in sorted([key for key in env_var_subfolders.keys() if key != 'CMAKE_PREFIX_PATH']):
subfolder = env_var_subfolders[key]
prefix = _prefix_env_variable(environ, key, paths, subfolder)
lines.append(prepend(environ, key, prefix))
return lines
def _pref... | iable NAME, adding any path in NEW_PATHS_STR without creating duplicate or empty items.
'''
value = environ[name] if name in environ else ''
environ_paths = [path for path in value.split(os.pathsep) if path]
checked_paths = []
for path in paths:
if not isinstance(subfolders, list):
... |
dushmis/misc | python/bulk_compile_all_java.py | Python | apache-2.0 | 1,386 | 0.050505 | #!/usr/bin/python -tt
import commands
import re
import sys
def aray__to_string(ar):
array_string=""
for item in ar:
array_string += " "+item
arra | y_string=array_string.replace(ar[0],"")
return array_string.rstrip().lstrip()
def get_class_path():
# | using find /xyz/abc/lib/ -type f \( -name "*.jar" -o -name "*.zip" \) | paste -sd: >> classpath
f=open("classpath")
lines=f.readlines()
return str(lines[0].split("\n")[0])+":."
def __file__log__(s,filename):
f=open(filename,"a")
f.write(str(s)+"\n")
f.flush()
f.close()
def main():
classpath = get_class_path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.