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 |
|---|---|---|---|---|---|---|---|---|
Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder-other-scripting-PyFoam | unittests/Basics/test_MatplotlibTimelines.py | Python | gpl-2.0 | 114 | 0.008772 | import unittest
from PyFoam.Basics.Matp | lotlibTimelines import | MatplotlibTimelines
theSuite=unittest.TestSuite()
|
pdfminer/pdfminer.six | tests/test_pdfminer_psparser.py | Python | mit | 3,405 | 0 | import logging
from pdfminer.psparser import KWD, LIT, P | SBaseParser, PSStackParser, PSEOF
logger = logging.getLogger(__name__)
class TestPSBaseParser:
"""Simplistic Test cases"""
TESTDATA = rb"""%!PS
begin end
" @ #
/a/BCD /Some_Name /foo#5f#xbaa
0 +1 -2 .5 1.234
(abc) () (abc ( def ) ghi)
(def\040\0\0404ghi) (bach\\slask) (foo\nbaa)
(this % is not a comment.)... | 6, KWD(b'"')),
(19, KWD(b"@")),
(21, KWD(b"#")),
(23, LIT("a")),
(25, LIT("BCD")),
(30, LIT("Some_Name")),
(41, LIT("foo_xbaa")),
(54, 0),
(56, 1),
(59, -2),
(62, 0.5),
(65, 1.234),
(71, b"abc"),
(77, b""),
(... |
codeyash/plugins | PyPlugins/PhpParser/py/PhpParser.py | Python | apache-2.0 | 2,782 | 0.007549 | #######################################################################
# Name: calc_peg.py
# Purpose: Simple expression evaluator example using PEG language
# Author: Igor R. Dejanovic <igor DOT dejanovic AT gmail DOT com>
# Copyright: (c) 2009-2014 Igor R. Dejanovic <igor DOT dejanovic AT gmail DOT com>
# License: MI... | g mode dot (graphviz) files for parser model
# and parse tree will be created for visualization.
# Checkout current folde | r for .dot files.
main(debug=True)
class Parser():
"""docstring for Parser"""
# connect the button's clicked signal to our python method
#ftpui.btnConnect.connect('clicked()', connectFtp)
# show the window
#ftpui.show()
|
graalvm/mx | mx_proftool.py | Python | gpl-2.0 | 55,588 | 0.002429 | #
# ----------------------------------------------------------------------------------------------------
# Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# un... | only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it wil | l 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
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU Gene... |
great-expectations/great_expectations | great_expectations/expectations/metrics/column_pair_map_metrics/__init__.py | Python | apache-2.0 | 191 | 0 | fr | om .column_pair_values_equal import ColumnPairValuesEqual
from .column_pair_values_greater import ColumnPairValuesAGreaterThanB
from | .column_pair_values_in_set import ColumnPairValuesInSet
|
googleads/google-ads-python | google/ads/googleads/v8/services/services/asset_field_type_view_service/transports/grpc.py | Python | apache-2.0 | 10,387 | 0.001155 | # -*- 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... | SSL credentials with client_cert_so | urce or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
ssl_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
s... |
edx/edx-ora | controller/management/commands/import_graded_essays.py | Python | agpl-3.0 | 5,420 | 0.008118 | from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils import timezone
#from http://jamesmckay.net/2009/03/django-custom-managepy-commands-not-committing-transactions/
#Fix issue where db data in manage.py commands is not refreshed at all once they start running
from dja... | SafeConfigParser()
parser.read(args[0])
print("Starting import...")
print("Reading config from file {0}".format(args[0]))
header_name = "importdata"
location = parser.get(header_name, 'location')
course_id = parser.get(header_name, 'course_id')
problem_id = par... | )
prompt_file = parser.get(header_name, 'prompt_file')
essay_file = parser.get(header_name, 'essay_file')
essay_limit = int(parser.get(header_name, 'essay_limit'))
state = parser.get(header_name, "state")
next_grader_type = parser.get(header_name, "next_grader")
add_grade... |
1337/yesterday-i-learned | leetcode/318m.py | Python | gpl-3.0 | 1,034 | 0.000967 | # Hashing a string into a binary representation helps compare them in linear time, and storing the max length for each
# binary representation in a hashmap is just icing on the cake
class Solution:
def maxProduct(self, words: List[str]) -> int:
def string_to_bool(string):
mask = 0b0
... | if bin_ in word_map:
word_map[bin_] = max(word_map[bin_], len(string))
else:
word_map[bin_] = len(string)
max_len = 0
for bin1, len1 in word_map.items():
for bin2, len2 in word_map.items():
if bin1 & bin2 == 0b0:
... | max(max_len, len1 * len2)
return max_len
|
giampaolo/psutil | psutil/tests/__main__.py | Python | bsd-3-clause | 293 | 0 | #!/usr/bin/ | env python3
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Run unit tests. This is invoked by:
$ python -m psutil.tests
"""
from .runner imp | ort main
main()
|
Nikita1710/ANUFifty50-Online-Mentoring-Platform | project/fifty_fifty/webcore/migrations/0017_remove_profile_emails.py | Python | apache-2.0 | 388 | 0 | # -*- coding: | utf-8 -*-
# Generated by Django 1.11 on 2017-04-30 12:24
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webcore', '0016_profile_emails'),
]
operations = [
migrations.RemoveField(
| model_name='profile',
name='emails',
),
]
|
liuzzfnst/tp-libvirt | libvirt/tests/src/virsh_cmd/nodedev/virsh_nodedev_create_destroy.py | Python | gpl-2.0 | 10,402 | 0 | import os
import re
import logging
from tempfile import mktemp
from virttest import virsh
from autotest.client.shared import error
from virttest.libvirt_xml.nodedev_xml import NodedevXML
from provider import libvirt_version
_FC_HOST_PATH = "/sys/class/fc_host"
def check_nodedev(dev_name, dev_parent=None):
"""
... | eturn value", status)
elif status_error == "no":
if status:
raise error.TestFail(result. | stderr)
else:
output = result.stdout
logging.info(output)
for scsi in output.split():
if scsi.startswith('scsi_host'):
# Check node device
if check_nodedev(scsi, scsi_host):
return scsi
... |
ResolveWang/algrithm_qa | other/q14.py | Python | mit | 2,801 | 0.00045 | """
问题描述:给定一个正数数组arr,其中所有的值都为整数,以下是最小不可组成和的概念:
1)把arr每个子集内的所有元素加起来会出现很多值,其中最小的记为min,最大的记为max.
2)在区间[min,max]上,如果有数不可以被arr某一个子集相加得到,那么其中最小的那个数是
arr的最小不可组成和.
3)在区间[min,max]上,如果所有的数 | 都可以被arr的某一个子集相加得到,那么max+1是arr
的最小不可组成和.
请写函数返回正数数组arr的最小不可组成和.
举例:
arr=[3, 2, 5],子集{2}相加产生2为min,子集{3, 2, 5}相加产生10为max.在区间[2, 10]
上,4、6和9不能被任何子集相加得到,其中4是arr的最小不可组成和.
arr=[1,2,4]。子集{1}相加产生1为min,子集{1,2,4}相加产生7为max。在区间[1,7]上,任何
数都可以被子集相加得到,所以8是arr的最小不可组成和.
进阶题目:
如果已知正数数组arr中肯定有1这个数,是否能更快地得到最小不可组成和?
"""
import sys
class... | set)
min_value = sys.maxsize
for i in arr:
min_value = min([min_value, i])
i = min_value
while True:
if i not in my_set:
return i
i += 1
@classmethod
def process(cls, arr, index, cur_sum, cur_set):
if index == len(arr... |
eduNEXT/edunext-platform | import_shims/lms/program_enrollments/api/grades.py | Python | agpl-3.0 | 413 | 0.009685 | """Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-t | oo-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_impor | t('program_enrollments.api.grades', 'lms.djangoapps.program_enrollments.api.grades')
from lms.djangoapps.program_enrollments.api.grades import *
|
chris-purcell/zerobot | modules/ping.py | Python | mit | 92 | 0 | #!/usr/bin/env | python
# Import required modules
# Function
def ping():
return "Pong!"
| |
carrete/docker-flask-starterkit-mirror | flask-app/starterkit/settings/common.py | Python | unlicense | 810 | 0 | # -*- coding: utf-8 -*-
import os
SECRET_KEY = os.environ["SECRET_KEY"]
LANGUAGES = {"en": "English", "es": "Español"}
BABEL_TRANSLATION_DIRECTORIES = "translations"
HASHEDASSETS_CATALOG = "/srv/www/hashedassets.yml"
HASHEDASSETS_SRC_DIR = "static/build"
HASHEDASSETS_OUT_DIR = "/srv/www/site/static"
HASHEDASSETS_... | //{}:{}@{}:{}/{}".format(
os.environ["STARTERKIT_DATABASE_USERNAME"],
os.environ["STARTERKIT_DATABASE_PASSWORD"],
os.environ["STARTERKIT_DATABASE_HOSTNAME"],
os.environ["STARTERKIT_DATABASE_TCP_POR | T"],
os.environ["STARTERKIT_ENVIRONMENT"],
)
SQLALCHEMY_TRACK_MODIFICATIONS = False
SENTRY_DSN = os.environ.get("SENTRY_DSN", "")
SENTRY_USER_ATTRS = ["email"]
STARTERKIT_HOMEPAGE_BLUEPRINT_URL_PREFIX = "/"
|
Beit-Hatfutsot/dbs-back | fabfile.py | Python | agpl-3.0 | 5,429 | 0.004052 | from __future__ import with_statement
import os
from datetime import datetime
import logging
from fabric.api import *
from fabric.contrib import files
env.user = 'bhs'
env.use_ssh_config = True
env.now = datetime.now().strftime('%Y%m%d-%H%M')
def dev():
env.hosts = ['bhs-dev']
def push_code(rev='HEAD', virtual... | ate))
if virtualenv:
if not files.exists('env'):
run('virtualenv env')
if requirements:
with prefix('. env/bin/activate'):
run('pip install -r requirements.txt')
run('rm -rf /tmp/api-*')
run('mv /tmp/latest-api-{} /tmp/api-{}'.format(cur_da... | nf/supervisor/ /etc/supervisor/")
sudo('cp conf/bhs_api_site /etc/nginx/sites-available/bhs_api')
def deploy(bh_env=None):
if bh_env:
if bh_env == "infra":
deploy_infra()
else:
with settings(host_string=_get_bh_env_host_string(bh_env)):
push_code()
... |
ray-project/ray | python/ray/tests/test_ray_shutdown.py | Python | apache-2.0 | 4,012 | 0.000499 | import sys
import time
import platform
import pytest
import ray
import psutil # We must import psutil after ray because we bundle it with ray.
from ray._private.test_utils import wait_for_condition, run_string_as_driver_nonblocking
def get_all_ray_worker_processes():
processes = [
p.info["cmdline"] fo... | p.poll() is None)
wait_for_condition(lambda: len(get_all_ray_worker_processes()) > 0)
cluster.re | move_node(head)
wait_for_condition(lambda: len(get_all_ray_worker_processes()) == 0)
if __name__ == "__main__":
sys.exit(pytest.main(["-v", __file__]))
|
sansna/PythonWidgets.py | lib3/web/server.py | Python | lgpl-3.0 | 3,623 | 0.008633 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Author: sansna
# Date : 2020 Aug 01 17:42:43
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))
import re
# App Config
# XXX: https://stackoverflow.com/questions/3536620/how-to-change-a-module-variable-from-another... |
ap | p.run(host="0.0.0.0", port=port)
def main():
@add_path("hello")
def func1(json):
mid = 0
if "mid" in json:
mid=json["mid"]
if mid == 1:
json["zz"] = 10
if mid == -1:
raise KeyError
return json
#AddPath("hello", func1)
"""
... |
foursquare/pants | contrib/python/src/python/pants/contrib/python/checks/tasks/checkstyle/indentation_subsystem.py | Python | apache-2.0 | 559 | 0.008945 | # coding=utf-8
# Copyright 2015 Pants proj | ect contributors (see CONTRIBUTORS.md).
# Licensed under the | Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
from pants.contrib.python.checks.tasks.checkstyle.plugin_subsystem_base import PluginSubsystemBase
class IndentationSubsystem(PluginSubsystemBase):
options_scope = 'pycheck-indentation'
... |
wavemind/mlgcb | tests/functional/tags_include.py | Python | apache-2.0 | 4,751 | 0 | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | n removing it may cause
# ETL tests to complain - they saw the file, then failed to copy
# it because it went away.
simple_content = 'Fiery the angels fell'
if not os.path.isdir(HTML_DIR):
os.mkdir(HTML_DIR)
with open(HTML_PATH, 'w') as fp:
fp.write(simple... | SON_URL)
os.unlink(HTML_PATH)
self._expect_content(simple_content, response)
def test_simple(self):
simple_content = 'Deep thunder rolled around their shores'
self._set_content(simple_content)
response = self.get(LESSON_URL)
self._expect_content(simple_content, respo... |
josepht/snapcraft | snapcraft/tests/commands/test_clean.py | Python | gpl-3.0 | 10,914 | 0 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2015-2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in ... | def test_partial_clean(self):
parts = self.make_snapcraft_yaml(n=3)
main(['clean', 'clean0', 'clean2'])
for i in [0, 2]:
self.assertFalse(
os.path.exists(parts[i]['part_dir']),
'Expected for {!r} to be wiped'. | format(parts[i]['part_dir']))
self.assertTrue(os.path.exists(parts[1]['part_dir']),
'Expected a part directory for the clean1 part')
self.assertTrue(os.path.exists(self.parts_dir))
self.assertTrue(os.path.exists(self.stage_dir))
self.assertTrue(os.path.exists(se... |
macs03/demo-cms | cms/lib/python2.7/site-packages/cms/extensions/extension_pool.py | Python | mit | 4,797 | 0.001876 | from cms.exceptions import SubClassNeededError
from .models import PageExtension, TitleExtension
class ExtensionPool(object):
def __init__(self):
self.page_extensions = set()
self.title_extensions = set()
self.signaling_activated = False
def register(self, extension):
"""
... | e from kwargs.
"""
# instance from kwargs is the draft page
draft_page = kwargs.get('instance')
language = kwargs. | get('language')
# get the new public page from the draft page
public_page = draft_page.publisher_public
if self.page_extensions:
self._copy_page_extensions(draft_page, public_page, language)
self._remove_orphaned_page_extensions()
if self.title_extensions:
... |
onshape-public/onshape-clients | python/onshape_client/oas/models/btp_function_declaration246.py | Python | mit | 13,254 | 0.000679 | # coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: [email protected]
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | method
def openapi_types():
"""
This must be a class method so a model may have prop | erties that are
of type self, this ensures that we don't create a cyclic import
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
return {
"bt_type": (str,), # noqa: E501
"atomic": (bool,), ... |
mewwts/bandpage | landingpage/urls.py | Python | mit | 146 | 0 | from django.conf.urls import patterns, url
from landingpage import views
u | rlpatterns = patterns('', url(r'^$', views.index, name='landingpag | e'))
|
DryTuna/pyramid_tutorial | authentication/tutorial/__init__.py | Python | mit | 838 | 0.001193 | from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from | .security import groupfinder
def main(global_config, **settings):
config = Configurator(settings=settings)
config.include('pyramid_chameleon')
# Security policies
authn_policy = AuthTktAuthenticationPolicy(
settings['tutorial.secret'], callback=groupfinder,
hashalg='sha512')
auth... | ACLAuthorizationPolicy()
config.set_authentication_policy(authn_policy)
config.set_authorization_policy(authz_policy)
config.add_route('home', '/')
config.add_route('hello', '/howdy')
config.add_route('login', '/login')
config.add_route('logout', '/logout')
config.scan('.views')
return... |
DaveBerkeley/iot | powermon.py | Python | gpl-2.0 | 985 | 0.011168 | #!/us | r/bin/python
import time
import json
from broker import Broker
#
#
class Handler:
def __init__(self):
self.history = []
self.size = 3
def on_power(self, msg):
data = json.loads(msg.payload)
power = data["power"]
self.process(power)
def process(self, power):
... | :
return
diff = self.history[0] - self.history[-1]
av = sum(self.history) / len(self.history)
print int(av),
print [ int(x-av) for x in self.history ],
print [ int(self.history[0]), int(self.history[-1]) ],
print int(self.history[0]) - int(self.history[-1])
... |
yunify/qingcloud-cli | qingcloud/cli/iaas_client/actions/router/describe_router_vxnets.py | Python | apache-2.0 | 1,841 | 0.003259 | # =========================================================================
# Copyright 2012-present Yunify, Inc.
# -------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the Licens... | parser.add_argument('-v', '--vxnet', dest='vxnet',
action='store', type=str, default='',
help='filter by vxnet ID. ')
@classmethod
def build_directive(cls, options):
if not options.router:
print('error: [router] should be specified')
return None
... | r': options.router,
'vxnet': options.vxnet,
'offset':options.offset,
'limit': options.limit,
}
|
chromium/chromium | third_party/tflite_support/src/tensorflow_lite_support/python/task/processor/proto/embedding_options_pb2.py | Python | bsd-3-clause | 784 | 0.001276 | # Copyright 2022 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... | HOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissi | ons and
# limitations under the License.
"""Embedding options protobuf."""
from tensorflow_lite_support.cc.task.processor.proto import embedding_options_pb2
EmbeddingOptions = embedding_options_pb2.EmbeddingOptions
|
NMTHydro/SWACodingMeeting | homework/for_meeting_3/vehicles_David.py | Python | apache-2.0 | 930 | 0.001075 | class Vehicle(object):
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def foo(self, a, b, c):
print 'does some work'
print a, b, c
class Car(Vehicle):
def __init__(self, doors, *args):
| Vehicle.__init__(self, *args)
self.doors = doors
def foo(self, *args, **kw):
print args, kw
super(Car, self).foo(*args)
class Boat(Vehicle):
def __init__(self, power, *args):
Vehicle.__init__(se | lf, *args)
if power not in ('propeller', 'sail'):
print 'warning: drive type not acceptable'
raise TypeError
self.power = power
class Airplane(Vehicle):
def __init__(self):
pass
if __name__ == '__main__':
car = Car('honda', 'civic', '2002', '2')
car.foo(1... |
GLPJJ/PL | py/g.py | Python | gpl-3.0 | 11 | 0.222222 | # | 类 pyth | on |
gangadharkadam/letzfrappe | frappe/email/bulk.py | Python | mit | 5,170 | 0.024371 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import HTMLParser
import urllib
from frappe import msgprint, throw, _
from frappe.email.smtp import SMTPServer, get_outgoing_email_account
from frappe.email.email... | rom_test
if frappe.flags.mute_emails or frappe.conf.get("mute_emails") or Fa | lse:
msgprint(_("Emails are muted"))
from_test = True
for i in xrange(500):
email = frappe.db.sql("""select * from `tabBulk Email` where
status='Not Sent' limit 1 for update""", as_dict=1)
if email:
email = email[0]
else:
break
frappe.db.sql("""update `tabBulk Email` set status='Sending' where n... |
beckastar/django | tests/migrations/test_migrations/0002_second.py | Python | bsd-3-clause | 592 | 0.001689 | from django.db import migrations, models
class Migration(migrations.Migration):
dependencie | s = [
("migrations", "0001_initial"),
]
operations = [
migrations.DeleteModel("Tribble"),
migrations.RemoveField("Author", "silly_field"),
migrations.AddField("Author", "rating", models.IntegerField(default=0)),
migrations.CreateModel(
| "Book",
[
("id", models.AutoField(primary_key=True)),
("author", models.ForeignKey("migrations.Author", null=True)),
],
)
]
|
freedesktop-unofficial-mirror/telepathy__telepathy-phoenix | src/phoenix.py | Python | lgpl-2.1 | 4,699 | 0.017876 | #!/usr/bin/env python
import os
import sys
import getopt
from util import spawnbus, setup_data_dir, setup_run_dir, scrub_env
from gi.repository import GObject, Gio
from gi.repository import TelepathyGLib as Tp
# Watch one Telepathy connection
class Connection:
def __init__ (self, connection):
self.connec... | _contact (self, contact):
# Remove from our contact list if the remote removed us
# Authorize and subscribe to the remote when asked
p = contact.get_property ("publish-state")
if p == Tp.SubscriptionState.REMOVED_R | EMOTELY:
self.connection.remove_contacts_async ([ contact ], None, None)
elif p == Tp.SubscriptionState.ASK:
self.connection.authorize_publication_async ([ contact ],
None, None )
self.connection.request_subscription_async ([ contact ],
"You su... |
buluba89/Yatcobot | yatcobot/notifier.py | Python | gpl-2.0 | 577 | 0 | import logging
from yatcobot.plugins.notifiers import NotifierABC
logger = logging.getLogger(__name__)
class NotificationService:
def __init__(self):
self.active_notifiers = NotifierABC.get_enabled()
def send_notification(self, title, message):
"""Sends a message to all enabled notifiers""... | fiers:
notifier.notify(title, | message)
def is_enabled(self):
"""Checks if any notifier is enabled"""
if len(self.active_notifiers) > 0:
return True
return False
|
MartinHjelmare/home-assistant | homeassistant/components/hydrawise/switch.py | Python | apache-2.0 | 3,451 | 0 | """Support for Hydrawise cloud switches."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_MONITORED_CONDITIONS
import homeassistant.helpers.config_validation as cv
from . import (
ALLOWED_WATERING_TIME, CONF_... | Hydrawise device."""
def __init__(self, default_watering_timer, *args):
"""Initialize a switch for Hydrawise device."""
super().__init__(*args)
self._default_watering_timer = default_watering_timer
@property
def is_on(self):
""" | Return true if device is on."""
return self._state
def turn_on(self, **kwargs):
"""Turn the device on."""
if self._sensor_type == 'manual_watering':
self.hass.data[DATA_HYDRAWISE].data.run_zone(
self._default_watering_timer, (self.data['relay']-1))
elif s... |
mahak/nova | nova/tests/unit/virt/disk/vfs/test_guestfs.py | Python | apache-2.0 | 14,130 | 0.000212 | # Copyright (C) 2012 Red Hat, 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 ... | /vda1",
vfs.handle.mounts[1][1])
self.assertEqual("/dev/mapper/guestvgf-lv_home",
vfs.handle.mounts[2][1])
self.assertEqual("/", vfs.handle.mounts[0][2])
self.assertEqual("/boot", vfs.handle.mounts[1][2])
self | .assertEqual("/home", vfs.handle.mounts[2][2])
handle = vfs.handle
vfs.teardown()
self.assertIsNone(vfs.handle)
self.assertFalse(handle.running)
self.assertTrue(handle.closed)
self.assertEqual(0, len(handle.mounts))
def test_appliance_setup_inspect_auto(self):
... |
archman/phantasy | phantasy/apps/__init__.py | Python | bsd-3-clause | 225 | 0 | # encoding: | UTF-8
#
# Copyright (c) 2015-2016 Facility for Rare Isotope Beams
#
"""
Physics Applications
"""
try:
from phantasy_apps import *
except ImportError:
| print("Package 'python-phantasy-apps' is required.")
|
JuliaSprenger/python-odmltables | setup.py | Python | bsd-3-clause | 2,563 | 0.002731 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os, glob
import warnings
from setuptools import setup, find_packages
with open("README.rst") as f:
long_description = f.read()
with open('requirements.txt') as f:
install_requires = f.read().splitlines()
with open('requirements_doc.txt') as f:
doc_... | i.main:parse_args []']},
| zip_safe=False,
keywords=['odml', 'excel', 'metadata management'],
# Extension('foo', ['foo.c'], include_dirs=['.']),
data_files=[('share/pixmaps', glob.glob(os.path.join("logo", "*"))),
('.', ['odmltables/VERSION.txt',
'requirements.txt',
'requ... |
DarthMaulware/EquationGroupLeaks | Leak #5 - Lost In Translation/windows/Resources/Dsz/PyScripts/Lib/dsz/mca/file/cmd/grep/errors.py | Python | unlicense | 1,026 | 0.008772 | # uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: errors.py
import mcl.status
ERR_SUCCESS = mcl.status.MCL_SUCCESS
ERR_INVALID_PARAM = mcl.status.framework.ERR_START
ERR_MARSHAL_FAILED = mcl.status.f... | _PATH_FAILED = mcl.status.framework.ERR_START + 2
ERR_CALLBACK_FAILED | = mcl.status.framework.ERR_START + 3
ERR_ENUM_FAILED = mcl.status.framework.ERR_START + 4
ERR_DONE_MAX_ENTRIES = mcl.status.framework.ERR_START + 5
ERR_NOT_IMPLEMENTED = mcl.status.framework.ERR_START + 6
errorStrings = {ERR_INVALID_PARAM: 'Invalid parameter(s)',
ERR_MARSHAL_FAILED: 'Marshaling data failed',
ERR_... |
MalloyDelacroix/DownloaderForReddit | DownloaderForReddit/gui/database_views/filter_widget.py | Python | gpl-3.0 | 3,726 | 0.00161 | from PyQt5.QtWidgets import QWidget, QLabel, QToolButton, QHBoxLayout, QVBoxLayout, QListWidgetItem, QFrame, QListView
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QColor
from DownloaderForReddit.guiresources.database_views.filter_widget_auto import Ui_FilterWidget
from DownloaderForReddit.utils import ... | filter_input_widget.export_filter.connect(self.add_filters)
| self.filter_box_list_widget.setSpacing(12)
self.filter_box_list_widget.setResizeMode(QListView.Adjust)
def set_default_filters(self, *filters):
self.add_filters([FilterItem(**filter_dict) for filter_dict in filters])
def filter(self, model_name):
return self.filter_download_filt... |
redhat-openstack/neutron | neutron/tests/functional/agent/test_l3_agent.py | Python | apache-2.0 | 13,694 | 0 | # Copyright (c) 2014 Red Hat, 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 require... | 10
nopreempt
advert_int 2
track_interface {
%(ha_device_name)s
}
virtual_ipaddress {
169.254.0.1/24 dev %(ha_device_name)s
}
virtual_ipaddress_excluded {
%(floating_ip_cidr)s dev %(external_device_name)s
%(external_device_cidr)s dev %(external_device_name)s
... | %(int_port_ipv6)s dev %(internal_device_name)s scope link
}
virtual_routes {
0.0.0.0/0 via %(default_gateway_ip)s dev %(external_device_name)s
}
}""" % {
'ha_confs_path': ha_confs_path,
'router_id': router_id,
'ha_device_name': ha_device_name,
'ha_devi... |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/contrib/learn/python/learn/tests/dataframe/csv_parser_test.py | Python | apache-2.0 | 2,054 | 0.002434 | # 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... | low.python.framework import dtypes
from tensorflow.python.platform import test
class CSVParserTestCase(test.TestCase):
def testParse(self):
parser = csv_parser.CSVParser(
column_names=["col0", "col1", "col2"], default_values=["", "", 1.4])
csv_lines = ["one,two,2.5", "four,five,6.0"]
csv_input ... | tring, shape=[len(csv_lines)])
csv_column = mocks.MockSeries("csv", csv_input)
expected_output = [
np.array([b"one", b"four"]), np.array([b"two", b"five"]),
np.array([2.5, 6.0])
]
output_columns = parser(csv_column)
self.assertEqual(3, len(output_columns))
cache = {}
output_t... |
root-11/outscale | tests/auction_demo_tests.py | Python | mit | 2,607 | 0.003836 | from itertools import product
from demos.auction_model import demo
def test02():
sellers = [4]
buyers = [100]
results = demo | (sellers, buyers, time_limit=False)
expected_results = {100: 4, 4: 100}
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test03():
expected_results = {101: 5, 5: 101, 6: None, 7: None}
sellers = [k for k in expected_results if k < ... | = demo(sellers, buyers)
for k, v in results.items():
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
def test04():
expected_results = {0: 101, 101: 0, 102: None,
103: None} # result: 0 enters contract with price 334.97 (the highest price)
sel... |
talbor49/Poet | web/__main__.py | Python | mit | 62 | 0 | import poet
if __name__ == '_ | _main__':
roger.tool.main( | )
|
ptphp/PyLib | src/tornado/demos/lihuashu/docs/common_bak/ty.py | Python | apache-2.0 | 668 | 0.026946 | #coding:utf8
from img import Img
i=Img()
i.open()
k=i.convert_thumbnail(input_file="/home/insion/Pictures/l.jpg",output | _file="/home/insion/Pictures/toutput.jpg")
print(k)
k=i.convert_resize(input_file="/home/insion/Pictures/l.jpg",output_file="/home/insion/Pictures/loutput2.jpg",output_size="500x")
print(k)
ki=i.composite_watermark(watermark_file="/home/insion/Pictures/lhs_log | o.png",input_file="/home/insion/Pictures/loutput2.jpg",output_file="/home/insion/Pictures/loutput.jpg")
print(ki)
ki=i.convert_watermark(watermark_file="/home/insion/Pictures/lhs_logo.png",input_file="/home/insion/Pictures/m.jpg",output_file="/home/insion/Pictures/moutput.jpg")
print(ki) |
jeremiahyan/odoo | addons/pos_sale_product_configurator/models/pos_config.py | Python | gpl-3.0 | 276 | 0.003623 | from odoo import models, fields
cl | ass PosConfig(models.Model):
_inherit = 'pos.config'
iface_open_product_info = fields.Boolean(string="Open Product I | nfo", help="Display the 'Product Info' page when a product with optional products are added in the customer cart")
|
CiscoSystems/nova-solver-scheduler | nova/tests/scheduler/solvers/constraints/test_aggregate_image_properties_isolation.py | Python | apache-2.0 | 2,908 | 0.000688 | # Copyright (c) 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/licenses/LICENSE-2.0
#
# Unless r... | cheduler.solvers.constraints import \
aggregate_image_properties_isolation
from nova import test
from nova.tests.scheduler import solver_scheduler_fakes as fakes
clas | s TestAggregateImagePropertiesIsolationConstraint(test.NoDBTestCase):
def setUp(self):
super(TestAggregateImagePropertiesIsolationConstraint, self).setUp()
self.constraint_cls = aggregate_image_properties_isolation.\
AggregateImagePropertiesIsolationConstraint
... |
kdart/pycopia | mibs/pycopia/mibs/SNMP_PROXY_MIB.py | Python | apache-2.0 | 4,800 | 0.020625 | # python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, N... | ccess = 5
s | tatus = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 7])
syntaxobject = SnmpTagValue
class snmpProxyStorageType(ColumnObject):
access = 5
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 6, 3, 14, 1, 2, 1, 8])
syntaxobject = pycopia.SMI.Basetypes.StorageType... |
CooperLuan/note-you-like | nyl.py | Python | mit | 1,840 | 0.002717 | #!python2
import logging
import os
from datetime import datetime
FORMAT = '%(asctime)-15s %(levelname)s %(message)s'
logging. | basicConfig(format=FORMAT, level=logging.INFO)
log = logging
from flask import Flask, render_template, request, jsonify
from bson.objectid import ObjectId
from models.url_model import URLModel
from models.html_model import HTMLModel
from env import MONGO, REDIS
app = Flask('nyl')
@app.route("/")
def index():
r... | methods=['POST'])
def api_url_extract():
url = request.form['url']
_doc = MONGO.url_response_cache.find_one({
'url': url,
})
if _doc:
html = _doc['body']
oid = str(_doc.pop('_id'))
log.info('load html from cache')
else:
html = URLModel(url).get_html()
... |
tropo/tropo-webapi-python | samples/gh-14.test_transfer.py | Python | mit | 778 | 0.003856 | # tests fix of gh-14 for "from" parameter in the "transfer" function.
# Proposed convention is to use "_from" as the parameter
# | so as not to conflict with "from" Python reserved word.
# _from arg works
# _from arg works with straight json
# Invoke by calling up app access number
# Sample application using the itty-bitty python web framework from:
# http://github.com/toastdriven/itty
from itty import *
from tropo import Tropo, Session
TO_N... | .body)
t = Tropo()
t.say ("One moment please.")
t.transfer(TO_NUMBER, _from="tel:+" + FROM_NUMBER)
t.say("Hi. I am a robot")
json = t.RenderJson()
print json
return json
run_itty()
|
setsulla/stir | stir/define.py | Python | mit | 267 | 0 | import os
STIR_ROOT = os.path.normpath(os.path.dirname(__file__))
STIR_APP = os.path.normpath(os.path.join(STIR_ROO | T, "application"))
STIR_LIB = os.path.normpath(os.path.join(STIR_ROOT, "library"))
# STIR_SCRI | PT = os.path.normpath(os.path.join(STIR_ROOT, "script"))
|
sivel/ansible-modules-extras | windows/win_scheduled_task.py | Python | gpl-3.0 | 2,585 | 0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
... | ndows Server 2012 or later.
options:
name:
description:
- | Name of the scheduled task
required: true
description:
description:
- The description for the scheduled task
required: false
enabled:
description:
- Enable/disable the task
choices:
- yes
- no
default: yes
state:
description:
- State that the task should ... |
sadanandb/pmt | src/pyasm/widget/tab_wdg.py | Python | epl-1.0 | 24,986 | 0.006404 | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in | any way without written permission.
#
#
#
__all__ = ['TabWdg', 'DynTabWdg','TabExtendWdg']
import types, sys, re
from pyasm.common import Common, Marshaller, Container, Environment, Xml
from pyasm.web import Widget, WebContainer, WidgetSettings, HtmlElement, | \
SpanWdg, DivWdg, AjaxLoader, MethodWdg, ClassWdg
from input_wdg import HiddenWdg, PopupMenuWdg
from pyasm.prod.biz import ProdSetting
from pyasm.biz import Project
class TabWdg(Widget):
'''The standard widget to display tabs. Most sites use this widget as
the outer container widget for navigation.... |
bvernoux/micropython | tests/multi_net/tcp_accept_recv.py | Python | mit | 672 | 0 | # Test recv on socket that just accepted a connection
import socket
PORT = 8000
# Server
def instance0():
multit | est.globals(IP=multitest.get_network_ip())
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(socket.getaddrinfo("0.0.0.0", PORT)[0][-1])
s.listen(1)
multitest.next()
s.accept()
try:
print("recv", s.recv(10)) # should raise Errno 107 ENOTCONN
exce... | 0][-1])
s.send(b"GET / HTTP/1.0\r\n\r\n")
s.close()
|
mozvip/CouchPotatoServer | couchpotato/core/settings/__init__.py | Python | gpl-3.0 | 6,744 | 0.006376 | from __future__ import with_statement
from couchpotato.api import addApiView
from couchpotato.core.event import addEvent, fireEvent
from couchpotato.core.helpers.encoding import isInt, toUnicode
from couchpotato.core.helpers.request import getParams, jsonified
from couchpotato.core.helpers.variable import mergeDicts, t... | :
from couchpotato import get_session
db = get_session()
p = db.query(Properties).filter_by(identifier = identifier).first()
if not p:
| p = Properties()
db.add(p)
p.identifier = identifier
p.value = toUnicode(value)
db.commit()
|
FabienPean/sofa | applications/plugins/Flexible/examples/patch_test/FEM.py | Python | lgpl-2.1 | 6,005 | 0.035304 | #!/usr/bin/python
import math
import Sofa
def tostr(L):
return str(L).replace('[', '').replace("]", '').replace(",", ' ')
def transform(T,p):
return [T[0][0]*p[0]+T[0][1]*p[1]+T[0][2]*p[2]+T[1][0],T[0][3]*p[0]+T[0][4]*p[1]+T[0][5]*p[2]+T[1][1],T[0][6]*p[0]+T[0][7]*p[1]+T[0][8]*p[2]+T[1][2]]
def transformF(T,F):
re... | ect('BarycentricShapeFunction', position="@parent.rest_position", nbRef="4")
childNode = simNode.createChild('childP')
childNode.createObject('MechanicalObject', template="Vec3d", name="child", position=tostr(samples) , showObject="1")
childNode.createObject('LinearMapping', template="Vec3d,Vec3d")
childNode = ... | createObject('LinearMapping', template="Vec3d,F331")
simNode.createObject('PythonScriptController',filename="FEM.py", classname="Controller")
###########################################################
simNode = rootNode.createChild('Hexa_shepard')
simNode.createObject('MeshTopology', name="mesh", position=tostr... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractThatbadtranslatorWordpressCom.py | Python | bsd-3-clause | 574 | 0.033101 |
def extract | ThatbadtranslatorWordpressCom(item):
'''
Parser for 'thatbadtranslator.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('L... | g, postfix=postfix, tl_type=tl_type)
return False
|
hanlind/nova | nova/tests/unit/api/openstack/compute/test_instance_actions.py | Python | apache-2.0 | 9,409 | 0.000106 | # Copyright 2013 Rackspace Hosting
# 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 require... | ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import mock
from oslo_policy import policy as oslo_policy
import six
from webob import exc
from nova.api.openstack.compute import in... | ce_actions_v21
from nova.api.openstack import wsgi as os_wsgi
from nova.compute import api as compute_api
from nova.db.sqlalchemy import models
from nova import exception
from nova import objects
from nova import policy
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fa... |
XiangYz/webscraper | itchat_test.py | Python | lgpl-2.1 | 157 | 0.019108 | import itchat
itchat.login()
friends = itchat.get_friends(update = True)[0:]
info = {}
for i in friends:
| info[i['NickName']] = i.Signatur | e
print(info) |
heinzehavinga/bethepresidenttoday | game/migrations/0001_initial.py | Python | cc0-1.0 | 1,827 | 0.001642 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Choice',
fields=[
('id', models.AutoField(verbo... | ields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=200)),
| ('text', models.TextField()),
],
options={
},
bases=(models.Model,),
),
migrations.AddField(
model_name='choice',
name='problem',
field=models.ForeignKey(to='game.Problem'),
preserve_default=True,
... |
atruberg/django-custom | tests/null_queries/tests.py | Python | bsd-3-clause | 2,936 | 0.000341 | from __future__ import absolute_import
from django.test import TestCase
from django.core.exceptions import FieldError
from .models import Poll, Choice, OuterA, Inner, OuterB
class NullQueriesTests(TestCase):
def test_none_as_null(self):
"""
Regression test for the use of None as a query value.
... | n't been saved.
p2 = Poll(question="How?")
self.assertEqual(repr(p2.choice_set.all()), '[]')
def test_reverse_relation | s(self):
"""
Querying across reverse relations and then another relation should
insert outer joins correctly so as not to exclude results.
"""
obj = OuterA.objects.create()
self.assertQuerysetEqual(
OuterA.objects.filter(inner__third=None),
['<Oute... |
5agado/recurrent-neural-networks-intro | src/model/servingClient.py | Python | apache-2.0 | 2,662 | 0.005259 | import os
import sys
from ast import literal_eval
import tensorflow as tf
import numpy as np
from grpc.beta import implementations
# reference local copy of Tensorflow Serving API Files
sys.path.append(os.path.join(os.getcwd(), os.pardir, os.pardir, 'ext_libs'))
import lib.predict_pb2 as predict_pb2
import lib.predi... | cur_input_tensor = tf.contrib.util.make_tensor_proto(cur_input['value'],
dtype=tf.float32 if cur_input['type']=="float32" else tf.int64,
shape=cur_input['value'].shape)
request.inputs[cur_input[... | |
SINGROUP/pycp2k | pycp2k/classes/_centroid_gyr1.py | Python | lgpl-3.0 | 712 | 0.002809 | from pycp2k.inputsection import InputSection
from ._each73 import _each73
class _centroid_gyr1(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
self.Filename = None
... | PRINT_KEY', 'Filename': 'FILENAME', 'Add_last': 'ADD_LAST', 'Common_iteration_levels': 'COMMON_ITERATION_LEVELS', 'Unit': 'UNIT'}
self._subsections = {'EACH': 'EACH'}
self._attributes | = ['Section_parameters']
|
rkashapov/buildbot | master/buildbot/reporters/gerrit.py | Python | gpl-2.0 | 15,470 | 0.00084 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | dleLegacyResult(result):
"""
make sure the re | sult is backward compatible
"""
if not isinstance(result, dict):
warnings.warn('The Gerrit status callback uses the old way to '
'communicate results. The outcome might be not what is '
'expected.')
message, verified, reviewed = result
result ... |
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2020_09_30/operations/_shared_galleries_operations.py | Python | mit | 9,946 | 0.004122 | # 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 may ... | ient, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deseri | alizer
self._config = config
@distributed_trace
def list(
self,
location: str,
shared_to: Optional[Union[str, "_models.SharedToValues"]] = None,
**kwargs: Any
) -> Iterable["_models.SharedGalleryList"]:
"""List shared galleries by subscription id or tenant id... |
IngenuityEngine/daemon | setup.py | Python | mit | 77 | 0 | from distutils.core import setup
import py2exe
setup(c | onsole | =['daemon.py'])
|
quaddra/engage | python_pkg/engage/drivers/genforma/engage_django_sdk/packager/utils.py | Python | apache-2.0 | 14,428 | 0.004713 | """Miscellaneous utility functions"""
import os
import os.path
import sys
import json
import re
import subprocess
import traceback
import logging
import copy
logger = logging.getLogger(__name__)
from parse_requirements import parse, get_local_files_matching_requirements
from engage_django_components import get_addi... | rrors import RequestedPackageError, PipError
PIP_TIMEOUT=45
def app_module_name_to_dir(app_directory_path, app_module_name, check_for_init_pys=True):
"""The application module could be a submodule, so we may need to split each level"""
dirs = app_module_name.split(".")
dirpath = app_directory_path
mo... | if module_name:
module_name = module_name + "." + dirname
else:
module_name = dirname
dirpath = os.path.join(dirpath, dirname)
init_file = os.path.join(dirpath, "__init__.py")
if check_for_init_pys and not os.path.exists(init_file):
raise Validat... |
suzp1984/web-dev-demos | data-virtualization/d3/server.py | Python | apache-2.0 | 338 | 0.005917 | import SimpleHTTPServer
import SocketServer
import os
if __name__ == "__main__":
PORT = int(os.environ.get("PORT", 8000))
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), handler | )
print("python simple http server started at port ", PORT)
httpd.serve_forever()
| |
quantumlib/OpenFermion-FQE | src/fqe/fqe_data.py | Python | apache-2.0 | 130,770 | 0.000879 | # 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 Lice | nse 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.
""" Fermionic Quantum Emulator data class for holding wavefunction data.
"""
#Expanding out simple iterator indexes is unnecessary
#pylint: disable=invalid-name
#imports are ungrou... |
biomodels/MODEL1006230003 | MODEL1006230003/model.py | Python | cc0-1.0 | 427 | 0.009368 | import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'MODEL1006230003.xml')
with open(sbmlFilePath,'r') as f:
| sbmlString = f.read() |
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString) |
CLVsol/odoo_addons | clv_insured/seq/clv_insured_seq.py | Python | agpl-3.0 | 3,732 | 0.007771 | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | Use "/" to get an automatic new Insured Code.')
@api.model
def create(self, vals):
if not 'code' in vals or ('code' in vals and vals['code'] == '/'):
code_seq = self.pool.get('ir.s | equence').get(self._cr, self._uid, 'clv_insured.code')
vals['code'] = format_code(code_seq)
return super(clv_insured, self).create(vals)
@api.multi
def write(self, vals):
if 'code' in vals and vals['code'] == '/':
code_seq = self.pool.get('ir.sequence').get(self._cr, sel... |
lcpt/xc | verif/tests/materials/prestressing/test_short_term_loss_prestress_01.py | Python | gpl-3.0 | 3,985 | 0.032209 | # -*- coding: utf-8 -*-
from __future__ import division
'''Test for checking variation of initial prestress force along a
post-tensioned member.
Data and rough calculation are taken from
Example 4.3 of the topic 4 of course "Prestressed Concrete Design
(SAB 4323) by Baderul Hisham Ahmad
ocw.utm.my
Problem stateme... |
P_re=3214.8 #prestress force at right end [kN]
# XC model
#Tendon [m] definition, layout and friction losses
a,b,c=geom_utils.fit_parabola(x=np.array([0,lBeam/ | 2.0,lBeam]), y=np.array([eEnds,eMidspan,eEnds]))
x_parab_rough,y_parab_rough,z_parab_rough=geom_utils.eq_points_parabola(0,lBeam,n_points_rough,a,b,c,angl_Parab_XZ)
tendon=presconc.PrestressTendon([])
tendon.roughCoordMtr=np.array([x_parab_rough,y_parab_rough,z_parab_rough])
#Interpolated 3D spline
tendon.pntsInterpT... |
Pinyto/cloud | manage.py | Python | gpl-3.0 | 254 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__m | ain__":
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pinytoCloud.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
tswast/google-cloud-python | vision/setup.py | Python | apache-2.0 | 2,379 | 0.00042 | # 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 or agreed to in writing, ... | ssifiers=[
release_status,
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming | Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Operating System :: OS Independent",
"Topic :: Internet",
],
platforms="Posix; MacOS X; Windows",
packages=packages,
... |
ngageoint/voxel-globe | voxel_globe/image_view/apps.py | Python | mit | 125 | 0.032 | from django.apps import AppConfig
class ImageViewConfig(AppConfig):
name = 'v | oxe | l_globe.image_view'
label = 'image_view' |
qalit/DAMS | DAMS/apps/generic_views/forms.py | Python | gpl-2.0 | 4,640 | 0.004741 | from django import forms
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.db import models
import types
from DAMS import settings
def return_attrib(obj, attrib, arguments=None):
try:
result = reduce(getattr, attrib.split("."), obj)
if isi... | DetailSelectMultiple(
choices=field.widget.choices,
attrs=field.widget.attrs,
queryset=getattr(field, 'queryset', None),
)
| self.fields[field_name].help_text=''
elif isinstance(field.widget, forms.widgets.Select):
self.fields[field_name].widget = DetailSelectMultiple(
choices=field.widget.choices,
attrs=field.widget.attrs,
queryset=getattr(f... |
senthil10/NouGAT | nougat/evaluete.py | Python | mit | 18,678 | 0.004711 | from __future__ import absolute_import
from __future__ import print_function
import sys, os, yaml, glob
import subprocess
import pandas as pd
import re
import shutil
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from nougat import common, align
from itertools import groupby
from collections im... | obal_config, sample_config):
sorted | _libraries_by_insert = \
common._sort_libraries_by_insert(sample_config)
_check_libraries(sorted_libraries_by_insert)
computeAssemblyStats(sample_config)
# filter out short contigs
sample_config = _build_new_reference(sample_config)
if "tools" in sample_config:
"""If so, execute... |
sdickreuter/python-pistage | build/lib/PIStage/_defines.py | Python | mit | 77 | 0 | __auth | or__ = 'sei'
DEFAULT | _SERIAL = '/dev/ttyUSB0'
DEFAULT_BAUDRATE = 57600
|
chrisndodge/edx-platform | common/djangoapps/student/views.py | Python | agpl-3.0 | 105,293 | 0.002678 | """
Student Views
"""
import datetime
import logging
import uuid
import json
import warnings
from collections import defaultdict
from urlparse import urljoin, urlsplit, parse_qs, urlunsplit
from django.views.generic import TemplateView
from pytz import UTC
from requests import HTTPError
from ipware.ip import get_ip
i... | cations
from openedx.core.djangoapps.credit.email_utils import get_credit_provider_display_names, make_providers_strings
from openedx.core.djangoapps | .user_api.preferences import api as preferences_api
from openedx.core.djangoapps.programs.models import ProgramsApiConfig
from openedx.core.djangoapps.programs import utils as programs_utils
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from openedx.core.djangoapps.theming impo... |
drodri/python-cpp-accu2016 | 5pybind11_zlib/test_compress.py | Python | mit | 2,059 | 0.01117 | import myzlib
st=z_stream()
ZLIB_VERSION = "1.2.8"
Z_NULL = 0x00
Z_OK = 0x00
Z_STREAM_END = 0x01
Z_NEED_DICT = 0x02
Z_NO_FLUSH = 0x00
Z_FINISH = 0x04
CHUNK = 1024 * 32
def compress(input, level=6):
out = []
st = z_stream()
st.avail_in = len(input)
st.next_in = input
st.avail_out = Z_NULL
s... | r = _zlib.inflate(ctypes.byref(st), Z_NO_FLUSH)
if err in [Z_OK, Z_STREAM_END]:
out.append(outbuf[:CHUNK-st.avail_out])
else:
raise AssertionError, err
if err == Z_STREAM_E | ND:
break
err = _zlib.inflateEnd(ctypes.byref(st))
assert err == Z_OK, err
return "".join(out)
def _test():
input = "Hello world, hello world" * 100000
ct_archive = compress(input, 6)
print "Compression ", len(input), "=>", len(ct_archive)
ct_orig = decompress(ct_archive)
... |
astrofle/CRRLpy | crrlpy/imtools.py | Python | mit | 21,537 | 0.006454 | #!/usr/bin/env python
import logging
import inspect
import numpy as np
#from matplotlib import _cntr as cntr
#from contours.core import shapely_formatter as shapely_fmt
#from contours.quad import QuadContourGenerator
from astropy.coordinates import Angle
from astropy import constants as c
from astropy import wcs
fro... |
Generic polygon class.
Note: code based on:
http://code.activestate.com/recipes/578381-a-point-in-polygon-program-sw-sloan-algorithm/
Parameters
----------
x : array
A sequence of nodal x-coords.
y : array
A sequence | of nodal y-coords.
"""
def __init__(self, x, y):
self.logger = logging.getLogger(__name__)
self.logger.info("Creating Polygon")
if len(x) != len(y):
raise IndexError('x and y must be equally sized.')
self.x = np.asfarray(x)
self.y = np.asfa... |
chrisortman/CIS-121 | projects/LCD.py | Python | mit | 1,100 | 0.012727 | def zero():
print " __ "
print "| |"
print "|__|"
def one():
print " "
print " |"
print " |"
def two():
print " __"
print " __|"
print "|__ "
def three():
print " __ "
print " __|"
print " __|"
def four():
print "|_|"
print " |"
def f... | " |"
while True:
x = raw_input("Type the number you would like printed: ")
if x == '1':
one()
elif x == '2':
two()
elif x == '3':
three()
elif x == '4':
four()
elif x == '5':
five()
elif x == '6':
six()
elif x == '7':
seven()
... | ne()
elif x == '0':
zero()
else:
print "Number not entered"
|
joksnet/youtube-dl | youtube_dl/extractor/sohu.py | Python | unlicense | 3,221 | 0.000622 | # encoding: utf-8
import json
import re
from .common import InfoExtractor
from ..utils import ExtractorError
class SohuIE(InfoExtractor):
_VALID_URL = r'https?://(?P<mytv>my\.)?tv\.sohu\.com/.+?/(?(mytv)|n)(?P<id>\d+)\.shtml.*?'
_TEST = {
u'url': u'http://tv.sohu.com/20130724/n382479172.shtml#super... | efec7',
u'info_dict': {
u'title': u'MV:Far East Movement《The Illest》',
| },
}
def _real_extract(self, url):
def _fetch_data(vid_id, mytv=False):
if mytv:
base_data_url = 'http://my.tv.sohu.com/play/videonew.do?vid='
else:
base_data_url = u'http://hot.vrs.sohu.com/vrs_flash.action?vid='
data_url = base_... |
facebookexperimental/eden | eden/hg-server/edenscm/hgext/infinitepush/bundlestore.py | Python | gpl-2.0 | 6,167 | 0.001135 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# Infinitepush Bundle Store
"""store for infinitepush bundles"""
import hashlib
import os
import subprocess
from tempfile import NamedTemporaryFile
fr... | from edenscm.mercurial.i18n import _
class bundlestore(object):
def __init__(self, repo):
storetype = repo.ui.config("infinitepush", "storetype", "")
if storetype == "disk":
self.store = filebundlestore(repo)
elif storetype == "external":
self.store = externalbundle... | d %s") % storetype
)
indextype = repo.ui.config("infinitepush", "indextype", "")
if indextype == "disk":
from . import fileindex
self.index = fileindex.fileindex(repo)
elif indextype == "sql":
# Delayed import of sqlindex to avoid including unnec... |
Lorquas/subscription-manager | src/rhsmlib/dbus/facts/client.py | Python | gpl-2.0 | 2,191 | 0.001826 | from __future__ import print_function, division, absolute_import
# Copyright (c) 2010-2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or F... | = None
| log.debug("Disconnected from FactsService")
|
mountainpenguin/pyrt | modules/config.py | Python | gpl-3.0 | 5,462 | 0.001098 | #!/usr/bin/env python
""" Copyright (C) 2012 mountainpenguin ([email protected])
<http://github.com/mountainpenguin/pyrt>
This file is part of pyRT.
pyRT is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
t... | tore(
sockpath=configfile["rtorrent_socket"],
serverhost=configfile["host"],
serverport=configfile["port"],
password=configfile["password"],
ssl_certificate=cert,
ssl_private_key=pkey,
ca_certs=ca_certs,
... | refresh=refresh,
scgi_username=scgi_username,
scgi_password=scgi_password,
scgi_method=scgi_method,
)
self._flush()
except KeyError:
raise ConfigError("Config File is malformed")
def get(self, conf):
if conf in sel... |
damianam/easybuild-framework | easybuild/tools/package/utilities.py | Python | gpl-2.0 | 7,628 | 0.002622 | ##
# Copyright 2015-2017 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | dtemp(prefix='eb-pkgs-')
pkgtype = build_option('package_type')
_log.info("Will be creating %s package(s) in %s", pkgtype, workdir)
try:
origdir = os.getcwd()
os.chdir(workdir)
except OSError, err:
raise EasyBuildError("Failed to chdir into workdir %s: %s", workdir, err)
pa... | e.name(easyblock.cfg)
pkgver = package_naming_scheme.version(easyblock.cfg)
pkgrel = package_naming_scheme.release(easyblock.cfg)
_log.debug("Got the PNS values name: %s version: %s release: %s", pkgname, pkgver, pkgrel)
deps = []
if easyblock.toolchain.name != DUMMY_TOOLCHAIN_NAME:
toolcha... |
opendatatrentino/ckan-api-client | ckan_api_client/tests/functional/client_sync/test_real_harvesting_scenario.py | Python | bsd-2-clause | 1,266 | 0 | # """
# Test some "real life" harvesting scenario.
# We have "data dumps" of an imaginary catalog for a set of days.
# The testing procedure should be run as follows:
# 1- Get current state of the database
# 2- Update data from the "harvest source"
# 3- Make sure the database state matches the expected one:
# - u... | sets should still be there
# - only datasets from this souce should have been changed,
# and should match the desired state.
# 4- Loop for all the days
# """
# import os
# import pytest
# from ckan_api_client.syncing import CkanDataImportClient
# from .utils import ckan_client # noqa (fixture)
# # from .uti... | name(__file__))
# DATA_DIR = os.path.join(os.path.dirname(HERE), 'data', 'random')
# HARVEST_SOURCE_NAME = 'dummy-harvest-source'
# @pytest.fixture(params=['day-{0:02d}'.format(x) for x in xrange(4)])
# def harvest_source(request):
# return HarvestSource(DATA_DIR, request.param)
# @pytest.mark.skipif(True, rea... |
awemulya/fieldsight-kobocat | onadata/apps/logger/south_migrations/0031_auto__add_field_xform_last_submission_time.py | Python | bsd-2-clause | 10,336 | 0.007933 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'XForm.last_submission_time'
db.add_column(u'odk | _logger_xform', 'last_submission_time',
self.gf('django.db.models.fields.DateTimeField')(null=True, blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'XForm.last_submission_time'
db.delete_column(u'odk_logger_xform', 'last_submi... | models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
... |
Danisan/dvit-odoo8 | invoice_discount/__init__.py | Python | agpl-3.0 | 26 | 0 | #
imp | ort invoice_discount | |
OEASLAN/LetsEat | web/manage.py | Python | gpl-2.0 | 249 | 0.004016 | #!/usr/bin/env python
import os
import sys
i | f __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "letseat.settings")
from django.core.management import execute_from_command_line
| execute_from_command_line(sys.argv) |
ibm-messaging/message-hub-samples | kafka-python-console-sample/producertask.py | Python | apache-2.0 | 1,944 | 0.003603 | """
Copyright 2015-2018 IBM
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... | 018
"""
import asyncio
from confluent_kafka import Producer
class ProducerTask(object):
def __init__(self, conf, topic_name):
self.topic_name = topic_name
self.producer = Producer(conf)
self.counter = 0
self.running = True
def stop(self):
self.running = False
def ... |
spulec/moto | moto/mediastoredata/models.py | Python | apache-2.0 | 2,506 | 0.001197 | import hashlib
from collections import OrderedDict
from moto.core import BaseBackend, BaseModel
from moto.core.utils import BackendDict
from .exceptions import ClientError
class Object(BaseModel):
def __init__(self, path, body, etag, storage_class="TEMPORAL"):
self.path = path
self.body = body
... | elf.storage_class,
"Path": self.path,
"ContentSHA256": self.content_sha256,
}
return data
class MediaStoreDataBackend(BaseBackend):
def __init__(self, region_name=None):
super().__init__()
self.region_name = region_name
self._objects = OrderedDict()... | _name = self.region_name
self.__dict__ = {}
self.__init__(region_name)
def put_object(
self,
body,
path,
content_type=None,
cache_control=None,
storage_class="TEMPORAL",
upload_availability="STANDARD",
):
new_object = Object(
... |
vitorio/ocropodium | ocradmin/presets/tests/test_scripts.py | Python | apache-2.0 | 4,800 | 0.002708 | """
Test plugin views.
"""
import os
import glob
from django.test import TestCase
from django.utils import simplejson as json
from django.conf import settings
from django.test.client import Client
from django.contrib.auth.models import User
from ocradmin.core.tests import testutils
from nodetree import script, node
i... | .load(f)
for fname in os.listdir(INVALID_SCRIPTDIR):
if fname.endswith("json"):
| with open(os.path.join(INVALID_SCRIPTDIR, fname), "r") as f:
self.scripts[fname] = json.load(f)
self.testuser = User.objects.create_user("test_user", "[email protected]", "testpass")
self.client = Client()
self.client.login(username="test_user", password="testpass")
def ... |
PacificBiosciences/rDnaTools | src/pbrdna/__init__.py | Python | bsd-3-clause | 1,847 | 0.002166 | #################################################################################
# Copyright (c) 2013, Pacific Biosciences of California, 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:
# ... | ocumentation and/or other materials provided with the distribution.
# * Neither the name of Pacific Biosciences nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PAT... | HIS SOFTWARE IS PROVIDED BY PACIFIC BIOSCIENCES AND ITS
# CONTRIBUTORS "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 PACIFIC BIOSCIENCES OR
# ITS CONTRIBUTORS BE LIABLE FO... |
lukas-ke/faint-graphics-editor | py/faint/formatsvgz.py | Python | apache-2.0 | 1,026 | 0.001949 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2014 Lukas Kemmer
#
# 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 require... | name, imageprops, "en")
def save(filename, canvas):
"""Save the image to the specified file as zipped svg."""
write_svg.write_svgz(filenam | e, canvas)
|
TheAlgorithms/Python | sorts/comb_sort.py | Python | mit | 1,851 | 0.001621 | """
This is pure Python implementation of comb sort algorithm.
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz
Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991.
Comb sort improves on bubble sort algorithm.
In bubble sort, distance (or gap) between ... | to prevent slowing
down by small values
at the end of a list.
More info on: https://en.wikipedia.org/wiki/Comb_sort
For doctests run following command:
python -m doctest -v comb_sort.py
or
python3 -m doctest -v comb_sort.py
For manual testing run:
python comb_sort.py
"""
def comb_sort(data: list) -> list:
"""... | s
:return: the same collection in ascending order
Examples:
>>> comb_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> comb_sort([])
[]
>>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3])
[-15, -7, 0, 2, 3, 8, 45, 99]
"""
shrink_factor = 1.3
gap = len(data)
completed = False
while ... |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_4_0_0/models/group.py | Python | bsd-3-clause | 7,973 | 0.007651 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Group) on 2019-05-07.
# 2019, SMART Health IT.
from . import domainresource
class Group(domainresource.DomainResource):
""" Group of multiple entities.
Represents a defined c... | up members.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.identifier = None
""" Unique id.
List of `Identifier` items (represented as `dict` in JSON). """
self.managingEntity = None
"" | " Entity that is the custodian of the Group's definition.
Type `FHIRReference` (represented as `dict` in JSON). """
self.member = None
""" Who or what is in group.
List of `GroupMember` items (represented as `dict` in JSON). """
self.name = None
""" Labe... |
SamHames/scikit-image | skimage/feature/util.py | Python | bsd-3-clause | 4,764 | 0 | import numpy as np
from skimage.util import img_as_float
class FeatureDetector(object):
def __init__(self):
self.keypoints_ = np.array([])
def detect(self, image):
"""Detect keypoints in image.
Parameters
----------
image : 2D array
Input image.
... | ((0, 2 * offset[1], offset[0], 0))
for i in range(matches.shape[0]):
idx1 = matches[i, 0]
idx2 = matches[i, 1]
if matches_color is None:
color = np.random.rand(3, 1)
else:
color = matches_color
ax.plot((keypoints1[idx1, 1], keypoints2[idx2, 1] + off... | _prepare_grayscale_input_2D(image):
image = np.squeeze(image)
if image.ndim != 2:
raise ValueError("Only 2-D gray-scale images supported.")
return img_as_float(image)
def _mask_border_keypoints(image_shape, keypoints, distance):
"""Mask coordinates that are within certain distance from the i... |
mulkieran/pyudev | pyudev/pyqt4.py | Python | lgpl-2.1 | 3,930 | 0.001018 | # -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <[email protected]>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, ... | op by turning device events into Qt signals.
:mod:`PyQt4.QtCore` from PyQt4\_ must be available | when importing this
module.
.. _PyQt4: http://riverbankcomputing.co.uk/software/pyqt/intro
.. moduleauthor:: Sebastian Wiesner <[email protected]>
"""
from __future__ import (print_function, division, unicode_literals,
absolute_import)
from PyQt4.QtCore import QSocketNotifie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.