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 |
|---|---|---|---|---|---|---|---|---|
kajgan/e2 | lib/python/Components/config.py | Python | gpl-2.0 | 55,036 | 0.035159 | from enigma import getPrevAsciiCode
from Tools.NumericalTextInput import NumericalTextInput
from Tools.Directories import resolveFilename, SCOPE_CONFIG, fileExists
from Components.Harddisk import harddiskmanager
from copy import copy as copy_copy
from os import path as os_path
from time import localtime, strftime
# Co... | args[x]:
x(self, self.extra_args[x])
else:
x(self)
except:
x(self)
def changedFinal(self):
if self.__notifiers_final:
for x in self.notifiers_final:
try:
| if self.extra_args and self.extra_args[x]:
x(self, self.extra_args[x])
else:
x(self)
except:
x(self)
# immediate_feedback = True means call notifier on every value CHANGE
# immediate_feedback = False means call notifier on leave the config element (up/down) when value have CHANGED
# cal... |
kallimachos/BottleOS | wsgi/mybottleapp.py | Python | gpl-3.0 | 823 | 0.001215 | from bottle import route, default_app, template
# -----------------------------------------------------------------------------
# This must be added in order to do correct path lookups for templates in
# wsgi/views/
import os
from bottle import TEMPLATE_PATH
TEMPLATE_PATH.append(os.path.join(os.environ['OPENSHIFT_REP... | ex(): # route for printing debug information
return template('<b>TEMPLATE_PATH = {{info}}', info=T | EMPLATE_PATH)
application = default_app()
|
mikehulluk/morphforge | src/morphforgecontrib/simulation/channels/neuroml_via_neurounits/neuroml_via_neurounits_neuron.py | Python | bsd-2-clause | 2,634 | 0.004935 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are m... | LAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CO | NSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF TH... |
WebSpider/SickRage | sickbeard/providers/torrentleech.py | Python | gpl-3.0 | 8,079 | 0.004827 | # Author: Idan Gutman
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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 o... | results.append(classes.Proper(title, url, datetime.datetime.today(), self.show))
return results
def | seedRatio(self):
return self.ratio
class TorrentLeechCache(tvcache.TVCache):
def __init__(self, provider):
tvcache.TVCache.__init__(self, provider)
# only poll TorrentLeech every 20 minutes max
self.minTime = 20
def _getRSSData(self):
search_params = {'RSS': ['']}
... |
shanew/electrum | gui/gtk.py | Python | gpl-3.0 | 49,880 | 0.008721 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | on(nz, "Number of zeros displayed after the decimal point.\nFor example, if this number is 2, then '5.' is displayed as '5.00'")
nz.show()
vbox.pack_start(nz, False,False, 5)
dialog.show()
r = dialog.run()
fee = fee_entry.get_text()
nz = nz_entry.get_text()
dialog.destr... | L:
return
try:
fee = int(COIN * Decimal(fee))
except Exception:
show_message("error")
return
self.config.set_key('fee_per_kb', fee)
try:
nz = int( nz )
if nz>8: nz = 8
except Exception:
show_message("error")
return
if self.num_ze... |
Learning-from-our-past/Kaira | names/location_name_white_list.py | Python | gpl-2.0 | 260 | 0.003922 | import re
WHI | TE_LIST = {
'names': {
'eno': {},
'evo': {},
'ii': {},
'li': {'alias': 'Ii'},
'utö': {},
'usa': {}
},
'p | atterns': [
{
'find': re.compile('([A-ZÄÖa-zäö-]*)(mlk)'),
'replace': r'\1 mlk'
}
]
} |
zulip/zulip | zerver/tests/test_widgets.py | Python | apache-2.0 | 14,342 | 0.001743 | import re
from typing import Any, Dict
import orjson
from django.core.exceptions import ValidationError
from django.http import HttpResponse
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.validator import check_widget_content
from zerver.lib.widget import get_widget_data, get_widget_type
from zerve... | "poll",
extra_data=dict(
options=["Red", "Green", "Blue", "Yellow"],
question="What is your favorite color?",
),
)
submessage = SubMessage.objects.get(message_id=message.id)
self.assertEqual(submessage.msg_type, "widget")
self.asse... | supply a question.
content = "/poll"
payload["content"] = content
result = self.api_post(sender, "/api/v1/messages", payload)
self.assert_json_success(result)
expected_submessage_content = dict(
widget_type="poll",
extra_data=dict(
option... |
ricardoyorky/emailqueue | emailqueue/mongodb.py | Python | mit | 2,778 | 0.00072 | """
The MIT License (MIT)
Copyright (c) 2015 Ricardo Yorky
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, merge... | tions of the Software.
T | HE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN A... |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/django/core/management/commands/runserver.py | Python | agpl-3.0 | 7,307 | 0.001916 | from __future__ import unicode_literals
import errno
import os
import re
import socket
import sys
from datetime import datetime
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError
from django.core.servers.basehttp import get_internal_wsgi_applicati... | ise_last_exception()
threading = options.get('use_threading')
shutdown_message = options. | get('shutdown_message', '')
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
self.stdout.write("Performing system checks...\n\n")
self.validate(display_num_errors=True)
try:
self.check_migrations()
except ImproperlyConfigured:
pass
... |
opentracing/opentracing-python | testbed/test_nested_callbacks/test_threads.py | Python | apache-2.0 | 1,887 | 0 | from __future__ import print_function
from concurrent.futures import ThreadPoolExecutor
from opentracing.mocktracer import MockTracer
from ..testcase import OpenTracingTestCase
from ..utils import await_until
class TestThreads(OpenTracingTestCase):
def setUp(self):
self.tracer = MockTracer()
sel... | # to be run, as in such case only the first will be executed,
# and the rest will get canceled.
await_until(lambda: len(self.tracer.finished_spans()) == 1, 5)
spans = self.tracer.finished_spans()
self.assertEqual(len(spans), 1)
self.assertEqual(spans[0].operation_name, 'one')
... | self.assertEqual(spans[0].tags.get('key%s' % i, None), str(i))
def submit(self):
span = self.tracer.scope_manager.active.span
def task1():
with self.tracer.scope_manager.activate(span, False):
span.set_tag('key1', '1')
def task2():
... |
saltstack/salt | tests/integration/files/returners/noop_returner.py | Python | apache-2.0 | 704 | 0.004261 | """
noop_returner
~~~~~~~~~~~~~
A returner that does nothing which is used to test the salt-master `event_return` functionality
"""
import logging
import salt.utils.jid
log = logging.getLogger(__name__)
__virtualname__ = "runtests_noop"
def __virtual__():
return True
def event_return(events):
log.debu... | , events)
def returner(ret):
log.debug("NOOP_RETURN.returner - Ret: %s", ret)
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
"""
Do any wo | rk necessary to prepare a JID, including sending a custom id
"""
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
|
hlzz/dotfiles | graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/news/test/__init__.py | Python | bsd-3-clause | 18 | 0 | "" | "News Tests"""
| |
mfojtik/openshift-docker-registry | docker_registry/lib/rlock.py | Python | apache-2.0 | 1,366 | 0 | # -*- coding: utf-8 -*-
# https://gist.github.com/adewes/6103220
import redis
import time
class Lo | ckTimeout(BaseException):
pass
class Lock(object):
'''Implements a distributed lock using Redis.'''
def __init__(self, redis, lock_type, key, expires=60):
self.key = key
self.lock_type = lock_type
self.redis | = redis
self.expires = expires
self.owns_lock = False
def lock_key(self):
return "%s:locks:%s" % (self.lock_type, self.key)
def __enter__(self):
expires = time.time() + self.expires + 1
pipe = self.redis.pipeline()
lock_key = self.lock_key()
pipe.watch(l... |
dudarev/reddoid | reddoid/sources/backends/twitter.py | Python | bsd-2-clause | 1,028 | 0 | from twython import Twython
from django.conf import settings
from .base import BaseSource
class TwitterSource(BaseSource):
def __init__(self, uid=None, screen_name=None):
if uid is None and screen_name is None:
raise ValueError
self.uid = uid
self.screen_name = screen_name
... | tweets = twitter.get_user_timeline(user_id=self.uid)
| else:
tweets = twitter.get_user_timeline(screen_name=self.screen_name)
for tweet in tweets:
yield {
'id': tweet['id'],
'content': tweet['text'],
'created_at': tweet['created_at'],
'entities': tweet['entities']
... |
aglitke/vdsm | vdsm/storage/storage_exception.py | Python | gpl-2.0 | 44,109 | 0.000136 | #
# Copyright 2009-2011 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | dst=%s: %s" % (src, dst, msg)
code = 218
message = "Cannot share volume"
class SharedVolumeNonWritable(VolumeGeneralException):
code = 219
message = "Shared volume is read only"
class InternalVolumeNonWritable(VolumeGeneralException):
code = 220
message = "Volume cannot be access to writes,... | 21
message = "Cannot change volume's modify time"
class CannotDeleteVolume(StorageException):
code = 222
message = "Volume deletion error"
class CannotDeleteSharedVolume(StorageException):
code = 223
message = "Shared Volume cannot be deleted"
class NonLeafVolumeNotWritable(VolumeGeneralExcept... |
AtmaHou/atma | sampler.py | Python | mit | 888 | 0.001126 | # coding: utf-8
import random
import json
def full_sample(tar_f=None, res_f=None, res_size=50, start_pos=0, end_pos=100):
buff = []
if tar_f:
with open(tar_f, 'r') as reader:
cnt = 0
for line in reader:
buff.append(json.dumps({'text': line, 'id': cnt}))
... | start_pos, end_pos)
with open(res_f, 'w') as writer:
writer.write('\n'.join(result_set))
else:
print 'ERROR: no target file'
if __name__ == '__main__':
test_f | = './template/title_template'
full_sample(test_f, res_size=50, start_pos=0, end_pos=2000)
|
jotathebest/ubi-tools | src/connect.py | Python | gpl-3.0 | 1,710 | 0.039181 | import requests
import os
def post_var(token, ubi_source, ubi_var, value, timestamp=None, context=None):
'''
This function posts data to ubidots
Input parameters:
token: The Ubidots token
ubi_source: The name of the user's Ubidots datasource
ubi_var: The name of the user's Ubidots variable
value: Value to b... | Returns in this order the next parameters: value, timestamp, context
'''
try:
url = os.getenv("UBIDOTS_URL") if os.getenv("UBIDOTS_URL") is not None else "http://things.ubidots.com/"
url = url + "api/v1.6/devices/" + ubi_source + "/" + ubi_var + "/values?page_size=1"
headers = {"X-Auth-Token": token,
"Co... | }
r = requests.get(url=url, headers=headers)
return r.json()[0]['value'], r.json()[0]['timestamp'], r.json()[0]['context']
except Exception as e:
return e
|
akimovmike/model_sweeper | common_funcs.py | Python | gpl-3.0 | 1,794 | 0.024526 | import numpy as np
import pandas as pd
import sklearn as sk
import sklearn.linear_model
import sklearn.metrics
import scipy.stats as sc
def calibrate(res):
'''Calibrates probabilities'''
f1=np.log(1+res)
f2=np.sin(res)
f3=f1*f1
f4=f2*f2
f5=f1*f2
return (res+f1+f2+f3+f4+f5)/4.025
def make_e... | del.fit(df[df.columns.difference([target_name,feature])], df[feature])
pos = np.in1d(model.coef_, np.sort(model.coef_)[-5:])
r2s = r2s.append(pd.DataFrame({'r2':sk.metrics.r2_score(df[feature],\
model.predict(df[df.columns.difference([target_name, feature])])),\
| 'predictors' : str(df.columns.difference([target_name, feature])[np.ravel(np.argwhere(pos == True))].tolist())}, index = [feature]))
print('Testing', feature)
print('-----------------')
if len(r2s[r2s['r2'] >= r2_threshold]) > 0:
print('Multicollinearity detected')
print(r2s[r2s['r2'] ... |
fanglinfang/myuw | myuw/test/dao/notice_categorization.py | Python | apache-2.0 | 829 | 0 | from django.test import Test | Case
from myuw.dao.notice_categorization import NOTICE_CATEGORIES
class TestNoticeCategories(TestCase):
def test_categories(self):
c | ategorization = NOTICE_CATEGORIES.get(
"StudentALR_IntlStuCheckin", None)
self.assertIsNotNone(categorization)
self.assertEqual(categorization["myuw_category"], "Holds")
self.assertTrue(categorization["critical"])
self.assertEqual(len(categorization["location_tags"]), 2)
... |
manashmndl/thefuck | thefuck/rules/tmux.py | Python | mit | 482 | 0 | import re
from thefuck.utils import replace_command, for_app
@for_app('tmux')
def match(command):
return ('ambiguous | command:' in command.stderr
and 'could be:' in command.stderr)
def get_new_command(command):
cmd = re.match(r"ambiguous comma | nd: (.*), could be: (.*)",
command.stderr)
old_cmd = cmd.group(1)
suggestions = [cmd.strip() for cmd in cmd.group(2).split(',')]
return replace_command(command, old_cmd, suggestions)
|
chrisfilo/NeuroVault | scripts/detect_parcellations_and_rois.py | Python | mit | 804 | 0.003731 | import os
from gzip import GzipFile
import django
import nibabel as nb
import neurovault.apps.statmaps.utils as nvutils
from neurovault.apps.statmaps.models import StatisticMap, BaseStatisticMap
os.environ.setdefau | lt("DJANGO_SETTINGS_MODULE", "neurovault.settings")
django.setup()
for image in StatisticMap.objects.filter(map_type=BaseStatisticMap.OTHER):
image.file | .open()
gzfileobj = GzipFile(filename=image.file.name, mode='rb', fileobj=image.file.file)
nii = nb.Nifti1Image.from_file_map({'image': nb.FileHolder(image.file.name, gzfileobj)})
map_type = nvutils.infer_map_type(nii)
if map_type != BaseStatisticMap.OTHER:
print "changed type of %s to %s"%(imag... |
pkimber/compose | example_compose/views.py | Python | apache-2.0 | 665 | 0 | # -*- encoding: utf-8 -*-
from django.views.generic import TemplateView
from base.view_utils import BaseMixin
from compose.models import CodeSnippet
class DashView(BaseMixin, Temp | lateView):
template_name = 'example/dash.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
try:
obj = CodeSnippet.objects.get(slug=CodeSnippet.CSS)
snippet = obj.code
except CodeSnippet.DoesNotExist:
snippet = '... | dict(snippet=snippet))
return context
class SettingsView(BaseMixin, TemplateView):
template_name = 'example/settings.html'
|
fluentstream/asterisk-p2p | res/pjproject/tests/pjsua/scripts-sendto/126_sdp_with_port_0_and_no_rtpmap_for_dynamic_pt.py | Python | gpl-2.0 | 659 | 0.027314 | # $Id: 126_sdp_with_port_0_and_no_rtpmap_for_dynamic_pt.py 369517 2012-07-01 17:28:57Z file $
import inc_sip as sip
import inc_sdp as sdp
sdp = \
"""
v=0
o=- 0 0 IN IP4 127.0. | 0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=video 0 RTP/AVP 100
m=audio 5000 RTP/AVP 0
"""
pjsua_args = "--null-audio --auto-answer 200"
extra_headers = ""
include = ["Content-Type: application/sdp", # response must include SDP
"m=video 0 RTP/AVP[\\s\\S]+m=audio [1-9]+[0-9]* RTP/AVP"
]
exclude = []
sendto_cfg = sip.Se... | ude)
|
syscoin/syscoin | test/functional/test_framework/address.py | Python | mit | 6,052 | 0.004627 | #!/usr/bin/env python3
# Copyright (c) 2016-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Encode and decode Bitcoin addresses.
- base58 P2PKH and P2SH addresses.
- bech32 segwit v0 P2WPKH and ... | (bytes.fromhex('00000041c1eaf111802559bad61b60d62b1f897c63928a'), 111)
check_base58(bytes.fromhex('1f8ea1702a7bd4941bca0941b852c4bbfedb2e05'), 0)
check_base58(bytes.fromhex('3a0b05f4d7f66c3ba7009 | f453530296c845cc9cf'), 0)
check_base58(bytes.fromhex('41c1eaf111802559bad61b60d62b1f897c63928a'), 0)
check_base58(bytes.fromhex('0041c1eaf111802559bad61b60d62b1f897c63928a'), 0)
check_base58(bytes.fromhex('000041c1eaf111802559bad61b60d62b1f897c63928a'), 0)
check_base58(bytes.fromhex('000... |
globalspin/haemapod | haemapod/handlers/people/bounding_box.py | Python | mit | 365 | 0.024658 | from model import User
from geo.geomodel import geotypes
def get(handler, response):
lat1 = handler.request | .get('lat1')
lon1 = handler.request.get('lng1')
lat2 = handler.request.get('lat2')
lon2 = handler.request.get('lng2')
response.users = User.bounding_box_fetch(
User.all(),
geotypes.Box(float(lat1),float(lon2),float(lat2),float(lon1 | )),
)
|
bamos/python-scripts | python2.7/music-organizer.py | Python | mit | 7,790 | 0.001284 | #!/usr/bin/env python2.7
__author__ = ['[Brandon Amos](http://bamos.github.io)']
__date__ = '2014.04.19'
"""
This script (music-organizer.py) organizes my music collection for
iTunes and [mpv](http://mpv.io) using tag information.
The directory structure is `<artist>/<track>`, where `<artist>` and `<track>`
are lower... | ('--artist', action='store_true',
help='''Operate in 'artist' mode and copy all songs to the
root of the directory and cleanly format the names to
be easily typed and navigated in a shell.''')
parser.add_argument('--delete-unrecognized-extensions', action='sto... | '.")
sys.exit(-1)
elif not (args.collection or args.artist):
print("Error: Mode '--collection' or '--artist' not provided.")
sys.exit(-1)
# Maps a string such as 'The Beatles' to 'the-beatles'.
def toNeat(s):
s = s.lower().replace("&", "and")
# Put spaces between and remove blank characters.
... |
Ahed91/SPS | wsgi/util.py | Python | gpl-2.0 | 729 | 0.009602 | #!/usr/bin/env python
# encoding: utf-8
import random
def color_variant(brightness_offset=1):
hex_color = "#%06x" % random.randint(0,0xFFFFFF)
""" takes a color like #87c95f and produc | es a lighter or darker variant """
if len(hex_color) != 7:
raise Exception("Passed %s into color_variant(), needs to be in #87c95f format." % hex_color)
rgb_hex = [hex_color[x:x+2] for x in [1, 3, 5]]
new_rgb_int = [int(hex_value, 16) + brightness_offset for hex_value in rgb_hex]
new_rgb_int... |
return [hex_color, "#" + "".join([hex(i)[2:] for i in new_rgb_int])]
|
CARocha/plataforma_fadcanic | manage.py | Python | mit | 262 | 0.003817 | #!/usr/bin/env python
import os
import sys
if __name__ | == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "plataforma_fadcanic.sett | ings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
wmarshall484/streamsx.topology | com.ibm.streamsx.topology/opt/python/packages/streamsx/topology/__init__.py | Python | apache-2.0 | 5,465 | 0.003111 | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
"""
Python application support for IBM Streams.
Overview
########
IBM® Streams is an advanced analytic platform that allows user-developed applications to quickly ingest,
analyze and correlate information as it arrives from thousands of... | plications where the topic and stream type matches.
An application only receives tuples that are published while
it is connected, thus tuples are lost during a connection failure.
A Python application publishes streams using :py:meth:`~topology.Stream.publish`
and subscribes using :py:meth:`~topology.Topology.subscri... | her
types (schemas) can be subscribed to by any Streams application.
"""
import logging
_debug = logging.getLogger('streamsx.topology.internal')
_debug.addHandler(logging.NullHandler())
_debug.setLevel(logging.CRITICAL)
|
Turgon37/SMSShell | tests/test_smsshell_commands.py | Python | gpl-3.0 | 2,388 | 0.001256 | # -*- coding: utf8 -*-
import argparse
import logging
import pytest
import SMSShell
import SMSShell.commands
def test_abstract_init():
"""Test abstract init methods
"""
abs = SMSShell.commands.AbstractCommand(logging.getLogger(),
object(),
... | t())
with pytest.raises(SMSShell.commands.CommandBadI | mplemented):
com._argsParser()
|
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_4_0_0/models/researchelementdefinition_tests.py | Python | bsd-3-clause | 1,910 | 0.004712 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b on 2019-05-07.
# 2019, SMART Health IT.
import os
import io
import unittest
import json
from . import researchelementdefinition
from .fhirdate import FHIRDate
class ResearchElementDefinitionTests(unittest.TestCase):
def ins... | oncept.text, "Diabetic patients over 65")
self.assertEqual(inst.id, "example")
self.assertEqual(inst.meta.tag[0].code, "HTEST")
self.assertEqual(inst.meta.tag[0].display, "test health data" | )
self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
self.assertEqual(inst.status, "draft")
self.assertEqual(inst.text.div, "<div xmlns=\"http://www.w3.org/1999/xhtml\">[Put rendering here]</div>")
self.assertEqual(inst.text.status, "generated... |
nzlosh/st2 | st2tests/st2tests/mocks/liveaction.py | Python | apache-2.0 | 4,369 | 0.001602 | # Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... | ad, LiveActionDB):
if state == action_constants.LIVEACTION_STATUS_REQUESTED:
cls.process(payload)
else:
worker.get_worker().process(payload)
except Exception:
traceback.print_exc()
print(payload)
class MockLiveActi... | ayload)
if ex_req is not None:
scheduling_queue.get_handler()._handle_execution(ex_req)
@classmethod
def publish_create(cls, payload):
# The scheduling entry point is only listening for status change and not on create.
# Therefore, no additional processing is required here ... |
samalba/image-spider | spider/validate_url.py | Python | mit | 987 | 0.002026 | # -*- coding: ascii -*-
from urllib.request import urlparse
from urllib.parse import urljoin, urldefrag
def validate_url(url, parent_url='http:'):
"""
Val | idate a URL to be a string having an explicit recognized scheme.
Arguments:
url: string URL
parent_url: optional string URL from which | to inherit an implicit
scheme.
Returns: dict having:
valid: boolean truth value.
url: string modified URL.
"""
if bytes == type(url):
url = url.decode()
parsed_url = urlparse(url)
if 0 < len(parsed_url.path) and '/' == parsed_url.path[0]:
url ... |
lolotux/cabot-docker | cabot/settings.py | Python | mit | 7,851 | 0.000637 | import os
import dj_database_url
import re
from django.conf import settings
from cabot.celeryconfig import *
from cabot.cabot_config import *
settings_dir = os.path.dirname(__file__)
PROJECT_ROOT = os.path.abspath(settings_dir)
TEMPLATE_DEBUG = DEBUG = os.environ.get("DEBUG", False)
ADMINS = (
('Admin', os.envir... | s': ['console', 'log_file', 'mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'django.db.backends': {
'handlers': ['console', 'log_file', 'mail_admins'],
'level': 'INFO',
'propagate': False,
},
# Catch All Logger -- Captu... | ole', 'log_file', 'mail_admins'],
'level': 'INFO',
'propagate': True,
}
}
}
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERM... |
memento7/KINCluster | KINCluster/KINCluster.py | Python | mit | 1,586 | 0.001892 | from types import ModuleType
import logging
from KINCluster.core.cluster import Cluster
from KINCluster.core.extractor import Extractor
from KINCluster i | mport settings as sets
class KINCluster:
__log = logging
__log.basicConfig(level=logging.INFO)
def __init__(self, pipeline, cluster=Cluster, extractor=Extractor, settings={}):
def getattrs(module):
keys = [key for key in dir(module) if not key.startswith('__')]
return {key:... | (settings, ModuleType):
settings = getattrs(settings)
if isinstance(settings, dict):
for key, value in settings.items():
self.settings[key] = value
self.pipeline = pipeline
self.cluster = cluster(settings=self.settings)
self.extractor = extractor
... |
s20121035/rk3288_android5.1_repo | external/lldb/test/expression_command/issue_11588/s11588.py | Python | gpl-3.0 | 671 | 0.035768 | class Issue11581SyntheticProvider(object):
def __init__(self, valobj, dict):
self.valobj = valo | bj
self.addrOf = valobj.AddressOf()
self.addr = valobj.GetAddress()
self.load_address = valobj.GetLoadAddress()
def num_children(self):
return 3;
def get_child_at_index(self, index):
if index == 0:
return self.addrOf
if index == 1:
return self.valobj.CreateValueFromExpression("addr", str(self.addr... | (self.load_address))
def get_child_index(self, name):
if name == "addrOf":
return 0
if name == "addr":
return 1
if name == "load_address":
return 2
|
GeosoftInc/gxapi | spec/core/DATALINKD.py | Python | bsd-2-clause | 5,063 | 0.008295 | from .. import Availability, Class, Constant, Define, Method, Parameter, Type
gx_class = Class('DATALINKD',
doc="DATALINK Display object.")
gx_methods = {
'Miscellaneous': [
Method('CreateArcLYR_DATALINKD', module='geoengine.map', version='6.4.0',
availability=Availabi... | lass:`DATALINKD` objec | t for a BING dataset",
return_type="DATALINKD",
return_doc=":class:`DATALINKD` handle, terminates if creation fails",
parameters = [
Parameter('layer', type=Type.INT32_T,
doc="0 = Aerial, 1 = Road")
]),
... |
kingjr/natmeg_arhus | get_events.py | Python | bsd-3-clause | 383 | 0.015666 | import mne
import scipy.io as sio
import sys as sys
file_events = str(sys.argv[2])
file_data = str(sys.argv[1])
events = mne.read_events(file_events)
raw = | mne.fiff.Raw(file_data)
start = raw.first_samp
print "start:"+str(start)
print "events[0]:"+str(events[0,0])+"->"+str(events[0,0]-start)
events[:,0] = events[:,0]-s | tart
sio.savemat(file_events[0:-3] + "mat", {'events':events}) |
SaptakS/open-event-orga-server | app/models/track.py | Python | gpl-3.0 | 1,616 | 0.001238 | from app.models import db
class Track(db.Model):
"""Track model class"""
__tablename__ = 'tracks'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
description = db.Column(db.Text)
track_image_url = db.Column(db.Text)
color = db.Column(db.String, null... | ion_id = session
self.track_image_url = track_image_url
self.color = color
self.location = location
@staticmethod
def get_service_name():
return 't | rack'
def __repr__(self):
return '<Track %r>' % self.name
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return self.name
@property
def font_color(self):
h = self.color.lstrip('#')
a = 1 - (0.299 * int(h[0:2], 16) + 0.587 * ... |
MHendricks/Motionbuilder-Remote | arduinoremote.py | Python | mit | 14 | 0 | impo | rt Rem | ote
|
laubed/gcon | gconlib/commands.py | Python | mit | 1,967 | 0.011693 | #!/usr/bin/env python3
import json
import os
SERIAL_DIRECTORY = "/dev/serial/by-id/"
class BaseCommand(object):
def execute(self, gcon, data):
return {"error" : "Not yet implemented"}
class CommandListSerial(BaseCommand):
def execute(self, gcon, data):
if os.path.exists(SERIAL_DIRECTORY):
... | {"result" : "SUCCESS"}
class CommandRequestStatus(BaseCommand):
def execute(self, gcon, data):
if not gcon.serialrunner.isConnected():
return {"status" : "N | OT_CONNECTED"}
if gcon.serialrunner.isHalted():
return {"status" : "HALTED"}
if gcon.serialrunner.isConnected() and len(gcon.serialrunner.queue) == 0: # TODO: No File Print Running
return {"status" : "IDLE"}
return {"status" : "UNKNOWN"}
# TODO: File Printing
... |
tyagian/Infrastructure-Automation-Ansible-Nginx | POST.py | Python | apache-2.0 | 542 | 0.00369 | import requests
import json
paylo | ad = {}
#create an empty dictionary
url = "http://10.102.62.236:3000/users/adduser"
#Insert the data in dictionary
payload['username'] = str(raw_input("Enter username : "))
payload['email'] = str(raw_input("Enter email : "))
payload['fullname'] = str(raw_input("Enter fullname : "))
payload['age'] = str(raw_input("Ente... | cation'] = str(raw_input("Enter location : "))
payload['gender'] = str(raw_input("Enter gender: "))
r = requests.post(url, data=json.dumps(payload))
print(r.text)
|
Inndy/LINE | line/api.py | Python | bsd-3-clause | 7,999 | 0.0035 | # -*- coding: utf-8 -*-
"""
line.client
~~~~~~~~~~~
LineClient for sending and receiving message from LINE server.
:copyright: (c) 2014 by Taehoon Kim.
:license: BSD, see LICENSE for more details.
"""
import rsa
import requests
try:
import simplejson as json
except ImportError:
import json... | ESSION_LINE_URL = LINE_DOMAIN + "/authct/v1/keys/line"
LINE_SESSION_NAVER_URL = LINE_DOMAIN + "/authct/v1/keys/naver"
ip = "127.0.0.1"
version = "3.7.0"
com_name = ""
revision = 0
_session = requests.session()
_headers = {}
def ready(self):
"""
Afte... | to communicate with LINE server
"""
raise Exception("Code is removed because of the request of LINE corporation")
def tokenLogin(self):
self.transport = THttpClient.THttpClient(self.LINE_HTTP_URL)
self.transport.setCustomHeaders(self._headers)
self.protocol = TCompactPro... |
ashleyrback/echidna | echidna/scripts/dump_smeared_energy.py | Python | mit | 4,198 | 0 | """ Example smearing script
This script:
* Reads in mc spectra from hdf5
* Smears spectra, default is to use weighted Gaussian method, but can
also use specify random Gaussian method via command line
* Smeared spectrum is saved to the same directory with ``_#value#ly`` or
``_#value#rs`` added to the file... | include:
* "weight", default
* "random"
"""
import echidna.output.store as store
import echidna.core.smear as smear
import echidna.utilities as utilities
import os
_logger = utilities.start_logging()
def main(args):
"""Smears | energy and dumps spectra.
Args:
args (Namespace): Container for arguments. See
>>> python dump_smeared_energy.py -h
"""
if args.dest:
if os.path.isdir(args.dest):
directory = args.dest
if directory[-1] != "/":
directory += "/"
else:
... |
mo-g/iris | lib/iris/tests/unit/analysis/maths/test_add.py | Python | gpl-3.0 | 1,656 | 0 | # (C) British Crown Copyright 2014 - 2015, Met Office
#
# This file is part of Iris.
#
# Iris 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 3 of the License, or
# (at your option) any l... | ith Iris. If not, see <http://www.gnu.org/licenses/>.
"""Unit tests for the :func:`iris.analysis.maths.add` function."""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# Import iris.tests first so that some things can be initialised b... | import operator
from iris.analysis.maths import add
from iris.tests.unit.analysis.maths import \
CubeArithmeticBroadcastingTestMixin, CubeArithmeticMaskingTestMixin
class TestBroadcasting(tests.IrisTest, CubeArithmeticBroadcastingTestMixin):
@property
def data_op(self):
return operator.add
@... |
strogo/turbion | turbion/bits/antispam/urls.py | Python | bsd-3-clause | 209 | 0.004785 | import operator
fr | om turbion.bits.antispam import Filter
urlpatterns = reduce(
operator.add,
[filter.urlpatterns for name, | filter in Filter.manager.all() if hasattr(filter, 'urlpatterns')],
[]
)
|
ari-zah/gaiasky | core/scripts/radec-conv.py | Python | lgpl-3.0 | 472 | 0.006356 | #!/usr/bin/env python
import sys, math
if len(sys.argv) != 3:
print("Usage:")
print("%s [RA HH:MM:SS] [DEC Deg:Arcmin:Arcsec] " % sys.argv[0])
exit( | 0)
ra = sys.argv[1]
dec = sys.argv[2]
rai = ra.split(":")
deci = dec.split(":")
radeg = float(rai[0]) * 15.0 + float(rai[1]) * (1.0 / 60.0) + float(rai[2]) * (1.0 / 3600)
decdeg = float(deci[0]) + float(deci[1]) * (1.0 / 60.0) + float(deci[2]) * (1.0 / 3600.0)
print("RA,DEC: %f,%f deg" | % (radeg, decdeg))
|
johnsliao/bostonservicemap | config.py | Python | mit | 98 | 0.05102 | # boston
MIN_LAT=42
MAX_LAT=43
MIN_LON | =-72
MAX_LON=-70
# i | mage size
CANVAS_X = 500
CANVAS_Y = 500 |
fkeles/sports | lib/utils/scrapingUtils.py | Python | gpl-2.0 | 7,381 | 0.017613 | # -*- coding: utf-8 -*-
import regexUtils
import re
import urllib
import urlparse
def findJS(data):
idName = '(?:f*id|ch)'
jsName = '([^\"\']+?\.js[^\"\']*?)'
regex = "(?:java)?scr(?:'\+')?ipt.*?" + idName + "\s*=\s*[\"']([^\"']+)[\"'][^<]*</scr(?:'\+')?ipt\s*>[^<]*<scr(?:'\+')?ipt[^<]*src=[\"']" + jsNa... | l = regexUtils.findall(area, 'SWFObject\([\'"]([^\'"]+)[\'"]')
if not swfUrl:
swfUrl = regexUtils.findall(area, sep1 + '([^\'"& ]+\.swf)')
if not swfUrl:
swfUrl = regexUtils.findall(data, sep1 + '([^\'"& ]+\.swf)')
if swfUr... | in(url, finalSwfUrl)
regex = '://(.*?)/'
server = regexUtils.findall(tmpRtmp, regex)
if server:
if server[0].find(':') == -1:
tmpRtmp = tmpRtmp.replace(server[0], server[0] + ':1935')
... |
Pablo126/SSBW | Tarea4/tarea4/lib/python3.5/site-packages/mongoengine/base/document.py | Python | gpl-3.0 | 41,762 | 0.000383 | import copy
import numbers
from collections import Hashable
from functools import partial
from bson import ObjectId, json_util
from bson.dbref import DBRef
from bson.son import SON
import pymongo
import six
from mongoengine import signals
from mongoengine.base.common import get_document
from mongoengine.base.datastru... | set default values only to fields loaded from DB
__only_fields = set(values.pop('__only_fields', values))
_created = values.pop | ('_created', True)
signals.pre_init.send(self.__class__, document=self, values=values)
# Check if there are undefined fields supplied to the constructor,
# if so raise an Exception.
if not self._dynamic and (self._meta.get('strict', True) or _created):
_undefined_fields = s... |
gieseke/bufferkdtree | bufferkdtree/neighbors/brute/base.py | Python | gpl-2.0 | 14,008 | 0.01078 | #
# Copyright (C) 2013-2016 Fabian Gieseke <fabian.gieseke@di.ku.dk>
# License: GPL v2
#
import os
import math
import threading
import warnings
import numpy as np
import bufferkdtree.neighbors.brute.wrapper_cpu_float as wrapper_cpu_float
import bufferkdtree.neighbors.brute.wrapper_cpu_double as wrapper_cpu_double
tr... | + unicode(e))
def get | _params(self):
""" Get parameters for this estimator.
Parameters
----------
deep : boolean, optional
If True: Will return the parameters for this
estimator and its contained estimator subobjects.
Returns
-------
params : ... |
agustinhenze/natsort.debian | test_natsort/slow_splitters.py | Python | mit | 5,511 | 0 | # -*- coding: utf-8 -*-
"""Alternate versions of the splitting functions for testing."""
from __future__ import unicode_literals
import unicodedata
from natsort.compat.py23 import PY_VERSION
if PY_VERSION >= 3.0:
long = int
def int_splitter(x, signed, safe, sep):
"""Alternate (slow) method to split a string... | nums.append(char)
# Reset any string.
if strings:
full_list.append(''.join(strings))
strings = []
# If this is a unicode digit, append directly to the full list.
elif char.isdigit():
# Reset any string or number.
if strings:... | .append(''.join(strings))
if nums:
full_list.append(int(''.join(nums)))
strings = []
nums = []
full_list.append(unicodedata.digit(char))
# Otherwise add to the string.
else:
strings.append(char)
# Reset any number.
... |
JensAstrup/pyEchosign | pyEchosign/classes/library_document.py | Python | mit | 4,570 | 0.003282 | from typing import TYPE_CHECKING
import arrow
import requests
from io import BytesIO
from pyEchosign.utils.request_parameters import get_headers
from pyEchosign.utils.handle_response import check_error
if TYPE_CHECKING:
from .account import EchosignAccount
class LibraryDocument(object):
"""
Represents ... | ls, account, json_data):
echosign_id = json_data.get('libraryDocumentId')
template_type = json_data.get('libraryTemplateTypes')
modified_date = json_data.get('modifiedDate')
name = json_data.get('name')
scope = json_data.get('scope')
return LibraryDocument(account, echosi... | son_data.get('libraryDocumentList')
return [cls.json_to_agreement(account, doc_data) for doc_data in response_data]
@property
def locale(self):
if not self.fully_retrieved:
self.retrieve_complete_document()
return self._locale
@property
def audit_trail_file(self):
... |
aronsky/home-assistant | homeassistant/components/switchbot/switch.py | Python | apache-2.0 | 5,033 | 0.000397 | """Support for Switchbot bot."""
from __future__ import annotations
import logging
from typing import Any
from switchbot import Switchbot # pylint: disable=import-error
import voluptuous as vol
from homeassistant.components.switch import (
DEVICE_CLASS_SWITCH,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homea... | e is on."""
return self.data["data"]["isOn"]
@property
def extra_state_attributes(self) -> dict:
"""Return the state attributes."""
| return {
**super().extra_state_attributes,
"switch_mode": self.data["data"]["switchMode"],
}
|
SciTools/nc-time-axis | nc_time_axis/__init__.py | Python | bsd-3-clause | 16,851 | 0.000178 | """
Support for cftime axis in matplotlib.
"""
import warnings
import cftime
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
import matplotlib.units as munits
import numpy as np
from ._version import version as __version__ # noqa: F401
_DEFAULT_RESO... | alendar={self.calendar}>"
)
_RESOLUTION_TO_FORMAT = {
"SECONDLY": "%H:%M:%S",
"MINUTELY": "%H:%M",
"HOURLY": "%Y-%m-%d %H:%M",
"DA | ILY": "%Y-%m-%d",
"MONTHLY": "%Y-%m",
"YEARLY": "%Y",
}
class AutoCFTimeFormatter(mticker.Formatter):
"""
Automatic formatter for :py:class:`cftime.datetime` data.
Automatically chooses a date format based on the resolution set by the
:py:class:`NetCDFDateTimeLocator`. If no resolution is se... |
ercas/route_distances | setup.py | Python | mit | 372 | 0.032258 | #!/usr/bin/env python3
import setuptools
setuptools.setup(
name = "rout | e_distances",
version = "1.10.0",
license = "MIT",
description = "Classes for getting the distance of a route between two"
| "places using various different services",
packages = ["route_distances"],
install_requires = ["googlemaps", "requests", "shapely"]
)
|
expobrain/python-unotifier | unotifier/notifiers/toaster.py | Python | mit | 935 | 0 | from __future__ import unicode_literals
import os
from .. import VENDOR_PATH
from .abstract import AbstractNotifier
class ToasterNotifier(AbstractNotifier):
notifier_cmd = os.path.join(VENDOR_PATH, 'toaster', 'toast.exe')
def get_cmd_options(self, options):
options = self._map_app_icon(options)
... | ptions)
options['p'] = options.pop('icon', None)
options['t'] = options.pop('title', None)
options['w'] = options.pop('wait', None)
# Remove escape char to debug "HRESULT : 0xC00CE508" exception
options['m'] = (options.get('message') or '').replace('\x1b', '')
if (not ... | None)
options.pop('silent', None)
options.pop('sound', None)
return options
|
teeple/pns_server | work/install/Python-2.7.4/Lib/test/test_long_future.py | Python | gpl-2.0 | 9,026 | 0.000776 | from __future__ import division
# When true division is the default, get rid of this and add it to
# test_long.py instead. In the meantime, it's too obscure to try to
# trick just part of test_long into using future division.
import sys
import random
import math
import unittest
from test.test_support import run_unitt... | less(
float.__getformat__("double").startswith("IEEE"),
"test requires IEEE 754 doubles")
DBL_MAX = sys.float_info.max
DBL_MAX_EXP = sys.floa | t_info.max_exp
DBL_MIN_EXP = sys.float_info.min_exp
DBL_MANT_DIG = sys.float_info.mant_dig
DBL_MIN_OVERFLOW = 2**DBL_MAX_EXP - 2**(DBL_MAX_EXP - DBL_MANT_DIG - 1)
# pure Python version of correctly-rounded true division
def truediv(a, b):
"""Correctly-rounded true division for integers."""
negative = a^b < 0
... |
votervoice/openstates | openstates/hi/committees.py | Python | gpl-3.0 | 2,141 | 0.00327 | from pupa.scrape import Scraper, Organization
import lxml.html
HI_URL_BASE = "http://capitol.hawaii.gov"
def get_chamber_url(chamber):
chamber_code = {'upper': 'S', 'lower': 'H'}[chamber]
URL = "%s/committees/committees.aspx?chamber=%s" % (HI_URL_BASE, chamber_code)
return URL
class HICommitteeScrap... | name=ctty_name)
org.add_source( | HI_URL_BASE + ctty_url)
self.get_committee_data(ctty_url, org)
yield org
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractDlscanlationsCom.py | Python | bsd-3-clause | 547 | 0.034735 |
def extractDlscanlationsCom(i | tem):
'''
Parser for 'dlscanlations.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'),
('Loiterous', 'Loiterous', 'oel')... | in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
kgao/MediaDrop | mediadrop/lib/tests/xhtml_normalization_test.py | Python | gpl-3.0 | 2,947 | 0.004411 | # -*- coding: utf-8 -*-
# This file is a part of MediaDrop (http://www.mediadrop.net),
# Copyright 2009-2014 MediaDrop contributors
# For the exact contribution history, see the git revision log.
# The source code contained in this file is licensed under the GPLv3 or
# (at your option) any later version.
# See LICENSE.... | break_xhtml(htmlified_text)
assert_equals('<p>first line</p>\n<p>second line</p>', display_text)
assert_equals(expected_html, clean_xhtml(display_text))
def test_adds_nofollow_attribute_to_links(self):
original = '<a href="http://example.com">link</a>'
cleaned = clean_xhtml(original... | om" rel="nofollow">link</a>')
def _test_removes_follow_attribute_from_links(self):
original = '<a href="http://example.com" rel="follow">link</a>'
cleaned = clean_xhtml(original)
assert_equals(cleaned, '<a href="http://example.com" rel="nofollow">link</a>')
def test_makes_automatic_lin... |
aweinstock314/aweinstock-programming-competition-solutions | upe_competition_2015_11_01/railforest/railforest_weinsa.py | Python | agpl-3.0 | 1,246 | 0.008828 | #!/usr/bin/env python
# UPE Programming competiton 2015-11-1 "railforest" solution by Avi Weinstock
import re
import sys
INFINITY = float('inf')
line_to_ints = lambda line: [int(x, 10) for x in re.split(' *', line)]
def solver(width, height, grid):
prevs = [[0, list()] for _ in range(width)]
for (y, line) in... | rents = []
for (x,cost) in enumerate(line):
if cost < 0:
cost = INFINITY
cur = [INFINITY, []]
for dx in [-1,0,1]:
if x+dx < 0 or x+dx >= width:
continue
#print(x,x+dx)
tmp = prevs[x+dx]
... | cur[0] = tmp[0] + cost
cur[1] = tmp[1] + [x]
currents.append(cur)
prevs = currents
solution = min([x for (x,_) in prevs])
if solution == INFINITY:
solution = -1
return solution
def main():
lines = sys.stdin.read().split('\n')
(height, width... |
fpsw/Servo | servo/views/note.py | Python | bsd-2-clause | 13,001 | 0.000385 | # -*- coding: utf-8 -*-
import json
from io import StringIO
from gsxws import escalations
from django import template
from django.contrib import messages
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from django.forms.models import modelformset_factory
from django.views.decor... | escalation_form = EscalationForm(request.POST,
prefix='escalation',
instance=note.escalation)
if escalation_form.is_valid():
note.escalation = escal | ation_form.save()
form = NoteForm(request.POST, instance=note)
if form.is_valid():
note = form.save()
formset = AttachmentFormset(request.POST, request.FILES)
if formset.is_valid():
files = formset.save(commit=False)
for f in file... |
SRabbelier/Melange | app/soc/models/seed_db.py | Python | apache-2.0 | 28,823 | 0.009957 | #!/usr/bin/env python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | ser
# pylint: disable=W0221
def seed(self, i, entities=None):
user_properties = {
'key_name': 'user_%04d' % i,
'link_id': 'user_%04d' % i,
'account': users.User(email='user_%04d@example.com' % i),
'name': 'User %04d' % i,
}
entity = User(**user_properties)
if e... |
class GSoCOrganizationSeeder(Seeder):
"""A Seeder for Melange Organization model.
"""
def type(self):
return GSoCOrganization
# pylint: disable=W0221
def seed(self, i, entities=None, current_user=None, gsoc2009=None):
properties = {
'key_name': 'google/gsoc2009/org_%04d' % i,
'lin... |
lenonr/dev_xfce | Auto_Config/base/.gimp-2.8/plug-ins/gimp_instagram_XproII.py | Python | gpl-3.0 | 3,841 | 0.035938 | #!/usr/bin/env python
# -*- coding: utf8 -*-
# *************************************************************************** #
# #
# Version 0.1 - 2013-08-01 #
# Copyright (C) 2013 Marco Cr... | #
# 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 #
#... | #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License ... |
marktiu7/demo | csvt/manage.py | Python | apache-2.0 | 802 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "csvt.settings")
try:
from django.core.management import execute_from_c | ommand_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
| "Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
jurgnjn/biokludge | scripts/cap/txn_starts2tics.py | Python | gpl-2.0 | 4,939 | 0.006074 | #!/usr/bin/env python
import argparse
import sys
import HTSeq as hts
def inv_dist(i, j):
"""
Distance between too GenomicInterval-s.
0 if adjacent or overlapping
inf if on different chromosomes or strands
"""
if i.overlaps(j): return(0)
if (i.chrom == j.chrom) and (i.strand == j.st... | (l_tic[i-1][0].end, l_tic[i][0].end)
l_tic[i-1] = (l_tic[i-1][0], l_tic[i-1][1] + l_tic[i][1])
del l_tic[i]
i -= 1
else:
i += 1
# Straightforward unit tests for cap_cluster:
l_tic_test = [
(hts.GenomicInterval("chr1", 1, 2, "+"), 1),
(hts.GenomicInterval(... | val("chr1", 52, 52, "+"), 1),
(hts.GenomicInterval("chr1", 74, 75, "+"), 8),
(hts.GenomicInterval("chr1", 156, 157, "+"), 1),
(hts.GenomicInterval("chr1", 1, 2, "-"), 1),
(hts.GenomicInterval("chr1", 27, 27, "-"), 1),
(hts.GenomicInterval("chr1", 52, 52, "-"), 1),
(hts.GenomicInterval("chr1", 74... |
kingsamchen/Eureka | crack-data-structures-and-algorithms/leetcode/count_negative_numbers_in_a_sorted_matrix_q5340.py | Python | mit | 488 | 0 | class Solution(object):
def countN | egatives(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
| if len(grid) == 0 or len(grid[0]) == 0:
return 0
cnt = 0
rows = len(grid)
cols = len(grid[0])
for i in range(rows):
for j in range(cols):
if grid[i][j] < 0:
# prune
cnt += cols - j
... |
atvcaptain/enigma2 | lib/python/Components/Converter/ConfigEntryTest.py | Python | gpl-2.0 | 1,749 | 0.028016 | from __future__ import print_function
from __future__ import absolute_import
from Components.Converter.Converter import Converter
from Components.Element import cached
from Components.config import configfile
class ConfigEntryTest(Converter, object):
def __init__(self, argstr):
Converter.__init__(self, argstr)
a... | !!\narg[0] must start with 'config.',\narg[1] is the compare string,\narg[2],arg[3] are optional arguments and must be 'Invert' or 'CheckSourceBoolean'")
@cached
def getBoolean(self):
if self.argerror:
print("ConfigEntryTest got invalid arguments", self.converter_arguments, "force True!!")
return True
if s... | source.boolean:
return False
if self.checkInvertSourceBoolean and self.source.boolean:
return False
val = configfile.getResolvedKey(self.configKey)
ret = val == self.configValue
return ret ^ self.invert
boolean = property(getBoolean)
|
madcowfred/evething | thing/tasks/contracts.py | Python | bsd-2-clause | 13,495 | 0.003186 | # ------------------------------------------------------------------------------
# Copyright (c) 2010-2013, EVEthing team
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of... | ------------------------------------------------------------------------------
import datetime
from decimal import Decimal
from .apitask import APITask
from thing.models import Alliance, Character, Contract, Corporation, Event, Station, APIKey
class Contracts(APITask):
name = 'thing.contracts'
def run(s... | return
# Make sure the character exists
try:
character = Character.objects.select_related('details').get(pk=character_id)
except Character.DoesNotExist:
self.log_warn('Character %s does not exist!', character_id)
return
now = datetime.dat... |
skalavala/smarthome | custom_components/image_processing/tensorflow.py | Python | mit | 13,028 | 0.000384 | """
Component that performs TensorFlow classification on images.
For a quick start, pick a pre-trained COCO model from:
https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md
For more details about this platform, please refer to the documentation at
https://home-assist... | ATTR_MATCHES = 'matches'
ATTR_SUMMARY = 'summary'
ATTR_TOTAL_MATCHES = 'total_matches'
CONF_FILE_OUT = 'file_out'
CONF_MODEL = 'model'
CONF_GRAPH = 'graph'
CONF_LABELS = 'labels'
CONF_MODEL_DIR = 'model_dir'
CONF_CATEGORIES = 'categories'
CONF_CATEGORY = 'category'
CONF_AREA = 'area'
CONF_TOP = 'top'
CONF_LEFT = 'left... | nal(CONF_LEFT, default=0): cv.small_float,
vol.Optional(CONF_BOTTOM, default=1): cv.small_float,
vol.Optional(CONF_RIGHT, default=1): cv.small_float
})
CATEGORY_SCHEMA = vol.Schema({
vol.Required(CONF_CATEGORY): cv.string,
vol.Optional(CONF_AREA): AREA_SCHEMA
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.exten... |
nodesign/weioMinima | things/input/distance/sharp_proximity.py | Python | bsd-3-clause | 2,595 | 0.008092 | ###
#
# WEIO Web Of Things Platform
# Copyright (C) 2013 Nodesign.net, Uros PETREVSKI, Dras | ko DRASKOVIC
# All rights reserved
#
# ## ## ######## #### #######
# ## ## ## ## ## ## ##
# ## ## ## ## ## ## ##
# ## ## ## ###### ## ## ##
# ## ## ## ## ## ## ##
# ## ## ... | ## ## ##
# ### ### ######## #### #######
#
# Web Of Things Platform
#
# This file is part of WEIO and is published under BSD license.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions... |
idjaw/redlock-py | redlock/__init__.py | Python | mit | 3,073 | 0.000651 | import string
import random
import time
from collections import namedtuple
import redis
# Python 3 compatibility
string_type = getattr(__builtins__, 'basestring', str)
try:
basestring
except NameError:
basestring = str
Lock = namedtuple("Lock", ("validity", "resource", "key"))
class CannotObtainLock(Exce... |
retry = 0
val = self.get_unique_id()
# Add 2 milliseconds to the drift to account for Redis expires
# prec | ision, which is 1 millisecond, plus 1 millisecond min
# drift for small TTLs.
drift = int(ttl * self.clock_drift_factor) + 2
while retry < self.retry_count:
n = 0
start_time = int(time.time() * 1000)
for server in self.servers:
if self.lock_in... |
mdboom/freetypy | lib/freetypy/tests/test_truetype.py | Python | bsd-2-clause | 4,807 | 0.000208 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Michael Droettboom All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, t... | tion == 614
assert x.y_strikeout_size == 143
assert x.y_subscript_x_offset == 0
assert x.y_subscript_x_size == 1351
assert x.y_subscript_y_offset == -446
assert x.y_subscript_y_size == 1228
assert x.y_superscript_x_offset == 0
assert x.y_superscript_x_size == 1351
assert x.y_superscript_... | et == 595
assert x.y_superscript_y_size == 1228
# def test_pclt():
# face = ft.Face(vera_path())
# # TODO: There seems to be some weird offset in the PCLT table
# x = face.get_tt_pclt()
# make_assert(x)
# assert False
def test_postscript():
face = ft.Face(vera_path())
x = face.tt_... |
tempbottle/concoord | concoord/proxy/queue.py | Python | bsd-3-clause | 770 | 0.001299 | """
@author: Deniz Altinbuken, Emin Gun Sirer
@note: Queue proxy
@copyright: See LICENSE
"""
from concoord.clientproxy import ClientProxy
class Queue:
def __init__(self, bootst | rap, timeout=60, debug=False, token=None):
self.proxy = ClientProxy(bootstra | p, timeout, debug, token)
def __concoordinit__(self):
return self.proxy.invoke_command('__init__')
def append(self, item):
return self.proxy.invoke_command('append', item)
def remove(self):
return self.proxy.invoke_command('remove')
def get_size(self):
return self.pro... |
brendangregg/bcc | tools/zfsdist.py | Python | apache-2.0 | 5,394 | 0.001112 | #!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# zfsdist Summarize ZFS operation latency.
# For Linux, uses BCC, eBPF.
#
# USAGE: zfsdist [-h] [-T] [-m] [-p PID] [interval] [count]
#
# Copyright 2016 Netflix, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
#
# 14-Feb-20... | e_return")
b.attach_kretprobe(event="zpl_open", fn_name="trace_open_return")
b.attach_kretprobe(event="zpl_fsync", fn_name="trace_fsync_return")
print("Tracing ZFS operation latency... Hit Ctrl-C to end.")
# output
exiting = 0
dist = b.get_table("dist")
while (1):
tr | y:
if args.interval:
sleep(int(args.interval))
else:
sleep(99999999)
except KeyboardInterrupt:
exiting = 1
print()
if args.interval and (not args.notimestamp):
print(strftime("%H:%M:%S:"))
dist.print_log2_hist(label, "operation")
dist.clear()... |
RedFantom/GSF-Parser | settings/eval.py | Python | gpl-3.0 | 597 | 0 | """
Author: RedFantom
Contributors: Daethyra (Naiii) and Sprigellania (Zarainia)
License: GNU GPLv3 as in LICENSE
Copyright (C) 201 | 6-2018 RedFantom
"""
from ast import literal_eval
def config_eval(value):
"""
Safely evaluate a string that can be a in a configuration file to a
valid Python value. Performs error handling and checks special
cases.
"""
try:
literal = literal_eval(value)
except (ValueError, SyntaxE... |
return False
else:
return literal
|
fkie-cad/iva | tests/test_local_repositories/test_iva_formatter.py | Python | lgpl-3.0 | 3,606 | 0.005824 | import unittest
from tests.dict_tester import DictTester
from local_repositories import iva_formatter
CVE_ID = "CVE-1999-0004"
SUMMARY = "MIME buffer overflow in email clients, e.g. Solaris mailtool and Outlook."
VUL_CONFIG = ["cpe:2.3:a:hp:dtmail", "cpe:2.3:a:university_of_washington:pine:4.02", "cpe:2.3:o:sco:unixw... | E_ID, "summary": SUMMARY, "Modified": "2008-09-09T08:33:31.007Z",
"Published": "1997-12-16T00:00:00Z", "cvss": 5, "cvss-time": "2004-01-01T00:00:00Z",
"access": {"complexity": "LOW", "vector": "NETWORK", "authentication": "NONE"},
"references": ["http://www.microsof... | configuration": VUL_CONFIG, "vulnerable_configuration_cpe_2_2": VUL_CONFIG_CPE_2_2}
CVE_KEYS = {'cve_id': '', 'cve_summary': '', 'cpe_entries': ''}
CVE_SEARCH_CPE = {"id": "cpe:2.3:a:%240.99_kindle_books_project:%240.99_kindle_books:6:-:-:-:-:android",
"references": ["https://play.google.com/store/app... |
jonparrott/google-cloud-python | speech/google/cloud/speech_v1/types.py | Python | apache-2.0 | 1,722 | 0 | # -*- coding: utf-8 -*-
#
# Copyri | ght 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, softwar | e
# 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
import sys
from google.api_core... |
abztrakt/labtracker | Machine/tests.py | Python | apache-2.0 | 765 | 0.002614 | from django.test import TestCase
from django.http import HttpRequest, QueryDict
import forms
import model | s
class MachineIssue(TestCase):
fixtures = ['dev',]
def setUp(self):
pass
def testSingleUpdateForm(self):
"""
Test the itemStatusForm to see if it updates the machine correctly
| """
qdict = QueryDict("", mutable=True)
qdict.setlist('status', ['2'])
form = forms.itemStatusForm(qdict)
self.assertTrue(form.is_valid())
# get machine
machine = models.Item.objects.get(pk=1)
num_status = machine.status.all().count()
self.assertEqu... |
kuke/models | fluid/PaddleRec/tagspace/infer.py | Python | apache-2.0 | 3,355 | 0.000298 | import sys
import argparse
import time
import math
import unittest
import contextlib
import numpy as np
import six
import paddle.fluid as fluid
import paddle
import utils
def parse_args():
parser = argparse.ArgumentParser("tagspace benchmark.")
parser.add_argument(
'--test_dir', type=str, default='tes... | return_numpy=False)
value.append(para[0]._get_float_element(0))
if step_id % size == 0 and step_id > 1:
all_num += 1 |
true_pos = [dat[2] for dat in data][0][0]
if value.index(max(value)) == int(true_pos):
true_num += 1
value = []
print("epoch:" + str(epoch) + "\tacc:" + str(1.0 * true_num / all_num))
t1 = time.time()
if __name__ == "__main__":
a... |
dennybaa/st2 | st2common/st2common/bootstrap/policiesregistrar.py | Python | apache-2.0 | 7,460 | 0.002145 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | se_dirs):
"""
Discover all the packs in the provided directory and register policies from all of the
discovered packs.
:return: Number of policies registered.
:rtype: ``int``
"""
# Register packs first
se | lf.register_packs(base_dirs=base_dirs)
registered_count = 0
content = self._pack_loader.get_content(base_dirs=base_dirs,
content_type='policies')
for pack, policies_dir in six.iteritems(content):
if not policies_dir:
L... |
elbeardmorez/quodlibet | quodlibet/quodlibet/mmkeys/osx.py | Python | gpl-2.0 | 5,611 | 0.000713 | # -*- coding: utf-8 -*-
# Copyright 2012 Martijn Pieters <mj@zopatista.com>
# Copyright 2014 Eric Le Lay elelay.fr:dev
#
# 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 L... | e(self._tap, True)
return event
# Convert the Quartz CGEvent into something | more useful
keyEvent = NSEvent.eventWithCGEvent_(event)
if keyEvent.subtype() is 8: # subtype 8 is media keys
data = keyEvent.data1()
keyCode = (data & 0xFFFF0000) >> 16
keyState = (data & 0xFF00) >> 8
if keyCode in self._EVENTS:
if keyStat... |
acdh-oeaw/totetiroler | places/views.py | Python | mit | 4,026 | 0.000994 | import requests
import json
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import render, redirect, get_object_or_404
from django.views import generic
from django.views.generic.edit import DeleteView
from django.core.urlresolvers impo... | est, 'places/edit_alternativenames.html', {'form': form, 'instance': instance}
)
else:
form = AlternativeNameForm(instance=instance)
return render(
request, 'places/edit_alternativenames.html', {'form': form, 'instance': instance})
class AlternativeNameDelete(DeleteView):
... | lazy('places:alternativename_list')
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(AlternativeNameDelete, self).dispatch(*args, **kwargs)
class PlaceListView(generic.ListView):
template_name = "places/list_places.html"
context_object_name = 'object_list'
... |
alien4cloud/alien4cloud-cloudify3-provider | alien4cloud-cloudify3-provider/src/test/resources/outputs/blueprints/openstack/lamp/wrapper/Wordpress_Mysql/wordpressConnectToMysqlMysql/tosca.interfaces.relationship.Configure/pre_configure_source/_a4c_pre_configure_source.py | Python | apache-2.0 | 17,718 | 0.004572 |
from cloudify import ctx
from cloudify.exceptions import NonRecoverableError
from cloudify.state import ctx_parameters as inputs
import subprocess
import os
import re
import sys
import time
import threading
import platform
from StringIO import StringIO
from cloudify_rest_client import CloudifyClient
from cloudify im... | e in all_node_instances:
if len(result) > 0:
result += ','
result += node_instance.id
return result
def get_host_node_name(instance):
for relationship in instance.relationships:
if 'clou | dify.relationships.contained_in' in relationship.type_hierarchy:
return relationship.target.node.id
return None
def __get_relationship(node, target_name, relationship_type):
for relationship in node.relationships:
if relationship.get('target_id') == target_name and relationship_type in rela... |
Dioptas/Dioptas | dioptas/model/Configuration.py | Python | gpl-3.0 | 34,175 | 0.003921 | # -*- coding: utf-8 -*-
# Dioptas - GUI program for fast processing of 2D X-ray diffraction data
# Principal author: Clemens Prescher (clemens.prescher@gmail.com)
# Copyright (C) 2014-2019 GSECARS, University of Chicago, USA
# Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany
... | The management of multiple Configurations is done by the DioptasModel.
"""
def __init__(self, working_directories=None):
super(Configuration, self).__init__()
self.img_model = ImgModel()
self.mask_model = MaskModel()
self.calibration_model = CalibrationModel(self.img_model)
... | h_model = BatchModel(self.calibration_model, self.mask_model)
self.pattern_model = PatternModel()
if working_directories is None:
self.working_directories = {'calibration': '', 'mask': '', 'image': os.path.expanduser("~"), 'pattern': '',
'overlay': ''... |
CLVsol/clvsol_odoo_addons | clv_event_history/wizard/__init__.py | Python | agpl-3.0 | 205 | 0 | # -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import event_mass_e | dit
| |
santi-pdp/segan | model.py | Python | mit | 36,546 | 0.002162 | from __future__ import print_function
import tensorflow as tf
from tensorflow.contrib.layers import batch_norm, fully_connected, flatten
from tensorflow.contrib.layers import xavier_initializer
from scipy.io import wavfile
from generator import *
from discriminator import *
import numpy as np
from data_loader import re... | le_wavs')
ref_Gs = self.generator(noisybatch, is_ref=True,
| spk=None,
do_prelu=do_prelu)
print('num of G returned: ', len(ref_Gs))
self.reference_G = ref_Gs[0]
self.ref_z = ref_Gs[1]
if do_prelu:
self.ref_alpha = ref_Gs[2:]
self.alpha_summ = []
... |
deepjets/deepjets | etc/plotting_NR.py | Python | bsd-3-clause | 6,730 | 0.004012 | def plot_kinematics(signal, background, nbins=100,
mass_range=(50., 110.), pt_range=(200., 500.),
mass_pad=10, pt_pad=50,
linewidth=1, title=None):
import numpy as np
from matplotlib import pyplot as plt
import h5py
pt_min, pt_max = pt_range
... | (signal_aux['mass_trimmed'] < mass_max) &
(signal_aux['pt_trimmed'] > pt_min) &
(signal_aux['pt_trimmed'] < pt_max))
background_selection = (( | background_aux['mass_trimmed'] > mass_min) &
(background_aux['mass_trimmed'] < mass_max) &
(background_aux['pt_trimmed'] > pt_min) &
(background_aux['pt_trimmed'] < pt_max))
#signal_selection = slice(0, None)
#background_select... |
zlorb/mitmproxy | mitmproxy/addons/__init__.py | Python | mit | 1,495 | 0 | from mitmproxy.addons import anticache
from mitmproxy.addons import anticomp
from mitmproxy.addons import block
from mitmproxy.addons import browser
from mitmproxy.addons import check_ca
from mitmproxy.addons import clientplayback
from mitmproxy.addons import core
from mitmproxy.addons import cut
from mitmproxy.addons ... | ons import setheaders
from mitmproxy.addons import stickyauth
from mitmproxy.addons import stickycookie
from mitmproxy.addons import streambodies
from mitmproxy.addons import save
from mitmproxy.addons import upstream_auth
def defa | ult_addons():
return [
core.Core(),
browser.Browser(),
block.Block(),
anticache.AntiCache(),
anticomp.AntiComp(),
check_ca.CheckCA(),
clientplayback.ClientPlayback(),
cut.Cut(),
disable_h2c.DisableH2C(),
export.Export(),
onboard... |
Kiddo3D/SmartControl | smartcontrol/printer/PrinterConnectionManager.py | Python | agpl-3.0 | 2,779 | 0.004318 | from multiprocessing.dummy import Pool
import sys
from threading import Thread
import time
from PyQt5.QtCore import QObject, pyqtSignal
import serial
from serial.tools import list_ports
from .Port import Port
from .PrinterConnection import PrinterConnection
class PrinterConnectionManager(QObject, Thread):
INTER... | for i in range(self.INTERVAL):
if not self._running:
break
time.sleep(1)
finally:
# Close | all connections on stop
for connection in self._connections:
connection.close()
self._connections = []
def start(self):
self._running = True
Thread.start(self)
def stop(self):
self._running = False
def get(self, id):
for connection i... |
Morisset/PyNeb_devel | pyneb/sample_scripts/Choroni_School/ex6_2.py | Python | gpl-3.0 | 7,588 | 0.022272 | import numpy as np
import pyCloudy as pc
import matplotlib.pyplot as plt
from pyneb.utils.physics import IP
# TODO: Add comments
"""
Pregunta 1
"""
def alpha_B(Te):
"""
Recomb. coefficient, case B
"""
T4 = Te/1e4
return 2.6e-13/T4
def U_mean_def(QH0, Ne, Rstr):
"""
\int_0^{Rstr}{U.dV} / \... | ot(2, 1, 1)
for M in Ms:
plt.plot(M.get_cont_x(unit = 'eV'), np.log10(M.get_cont_y(unit = 'esHz')), label=M.model_name_s)
plt.xlim((10., 60))
plt.ylim((18, 24))
plt.ylabel('log [erg.s-1.Hz-1]')
plt.legend(loc=3)
plt.s | ubplot(2, 1, 2)
for M in Ms:
plt.plot(M.get_cont_x(unit = 'eV'), np.log10(M.get_cont_y(unit = 'Q')), label=M.model_name_s)
plt.xlim((10., 60))
plt.ylim((42., 50))
plt.xlabel('E [eV]')
plt.ylabel('QH0(E)')
# TODO: avoid overlap
for ip in IP:
plt.plot([IP[ip], IP[ip]], [49, 50]... |
agry/NGECore2 | scripts/mobiles/naboo/capper_spineflap.py | Python | lgpl-3.0 | 1,610 | 0.027329 | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate | = MobileTemplate()
mobileTemplate.setCreatureName('capper_spineflap')
mobileTemplate.setLevel(2)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(False)
mobileTemplate.setScale(1)
mobileTemplate.setMeatType... | late.setHideAmount(10)
mobileTemplate.setBoneType("Avian Bones")
mobileTemplate.setBoneAmount(6)
mobileTemplate.setSocialGroup("self")
mobileTemplate.setAssistRange(8)
mobileTemplate.setStalker(False)
mobileTemplate.setOptionsBitmask(Options.ATTACKABLE)
templates = Vector()
templates.add('object/mobile/shared... |
swn1/pyzmq | zmq/backend/cli/constants.py | Python | bsd-3-clause | 6,712 | 0.028308 | #-----------------------------------------------------------------------------
# Python module level constants
#-----------------------------------------------------------------------------
import ZeroMQ
_Version = ZeroMQ.lib.zmq.version()
VERSION = _Version.ToString()
VERSION_MAJOR = _Version[0]
VERSION_MINOR = _Versi... | IBE
#UNSUBSCRIBE = ZMQ_UNSUBSCRIBE
#LAST_ENDPOINT = ZMQ_LAST_ENDPOINT
#TCP_ACCEP | T_FILTER = ZMQ_TCP_ACCEPT_FILTER
#PLAIN_USERNAME = ZMQ_PLAIN_USERNAME
#PLAIN_PASSWORD = ZMQ_PLAIN_PASSWORD
#CURVE_PUBLICKEY = ZMQ_CURVE_PUBLICKEY
#CURVE_SECRETKEY = ZMQ_CURVE_SECRETKEY
#CURVE_SERVERKEY = ZMQ_CURVE_SERVERKEY
#ZAP_DOMAIN = ZMQ_ZAP_DOMAIN
#CONNECT_RID = ZMQ_CONNECT_RID
#GSSAPI_PRINCIPAL = ZMQ_GSSAPI_PRINC... |
geometalab/osmaxx | tests/clipping_area/conftest.py | Python | mit | 499 | 0.002004 | import pytest
@pytest.fixture
def clipping_area_hsr_data():
return {
"name": "HSR Polygon",
"clipping_multi_polygon": {
"type": "MultiPolygon",
"coordinates": [
[[[47.223954659939984, 8.814822435379028], [47.22422061004465, 8.8171184062 | 95776], [47.22350654921145, 8.818931579589844], [47.222388077452706, 8.818915486335754], [47.22243179666168, 8.816501498222351], [47.22395465993 | 9984, 8.814822435379028]]]
]
}
}
|
digitalbitbox/electrum | setup.py | Python | mit | 2,673 | 0.000374 | #!/usr/bin/env python3
# python setup.py sdist --format=zip,gztar
from setuptools import setup
import os
import sys
import platform
import imp
import argparse
version = imp.load_source('version', 'lib/version.py')
if sys.version_info[:3] < (3, 4, 0):
sys.exit("Error: Electrum requires Python version >= 3.4.0...... | 'electrum_plugins': 'plugins',
},
package_data={
'electrum': [
'servers.json',
'servers_testnet.json',
'currencies.json',
'checkpoints.json',
'www/index.html',
'wordlist/*.txt',
'locale/*/LC_MESSAGES/electrum.mo',
... | ,
description="Lightweight Bitcoin Wallet",
author="Thomas Voegtlin",
author_email="thomasv@electrum.org",
license="MIT Licence",
url="https://electrum.org",
long_description="""Lightweight Bitcoin Wallet"""
)
|
jeremiah-c-leary/vhdl-style-guide | vsg/vhdlFile/classify/sequential_statement.py | Python | gpl-3.0 | 3,197 | 0.000313 |
#from vsg.vhdlFile import utils
from vsg.vhdlFile.classify import assertion_statement
from vsg.vhdlFile.classify import case_statement
from vsg.vhdlFile.classify import exit_statement
from vsg.vhdlFile.classify import if_statement
from vsg.vhdlFile.classify import loop_statement
from vsg.vhdlFile.classify import next... | iReturn != iToken:
return iReturn
# print('--> checking case_statement')
iReturn = case_statement.detect(iToken, lObjects)
if iReturn != iToken:
return iReturn
# print('--> checking if_statement')
iReturn = if_statement.detect(iToken, lObjects)
if iReturn != iToken:
retu... | = loop_statement.detect(iToken, lObjects)
if iReturn != iToken:
return iReturn
# print('--> checking variable_assignment')
iReturn = variable_assignment_statement.detect(iToken, lObjects)
if iReturn != iToken:
return iReturn
# print('--> checking exit_statement')
iReturn = exit_... |
EduJGURJC/elastest-service-manager | src/esm/controllers/service_instances_controller.py | Python | apache-2.0 | 14,612 | 0.003559 | # Copyright © 2017-2019 Zuercher Hochschule fuer Angewandte Wissenschaften.
# 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/l... | else:
return "Supplied body content is not or is mal-formed JSON", 400
svc_type = STORE.get_service_instance(service.service_id)
if len(svc_type) == 1:
return 'Service instance with id {id} already exists'.format(id=service.service_id), 409
# look up manifest based on pl... | ifest for creation to the target system
# store the ID along with refs to service, plan and manifest
# get the manifest for the service/plan
# TODO some validation required here to ensure it's the right svc/plan
svc_type = STORE.get_service(service.service_id)[0]
if svc_type is ... |
hbradlow/autograde | autograde/migrations/0004_auto__chg_field_testresult_test_case.py | Python | gpl-3.0 | 7,406 | 0.007291 | # -*- 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):
# Changing field 'TestResult.test_case'
db.alter_column('autograde_testresult', 'test_case_id', self.gf('dj... | },
'autograde.kvpair': {
'Meta': {'object_name': 'KVPair'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'value': ('django.db.models. | fields.CharField', [], {'max_length': '100'})
},
'autograde.project': {
'Meta': {'object_name': 'Project'},
'framework_files': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'framework_files'", 'symmetrical': 'False', 'to': "orm['autograde.ProjectFile']... |
stggh/PyAbel | examples/example_all_O2.py | Python | mit | 4,428 | 0.002033 | # -*- coding: utf-8 -*-
# This example compares the available inverse Abel transform methods
# currently - direct, hansenlaw, and basex
# processing the O2- photoelectron velocity-map image
#
# Note it transforms only the Q0 (top-right) quadrant
# using the fundamental transform code
from __future__ import absolute_i... | /O2-ANU1024.txt.bz2')
IM = np.loadtxt(imagefile)
# recenter the image to mid-pixel (odd image width)
IModd = abel.tools.center.center_image(IM, center="slice", odd_size=True)
h, w = IModd.shape
print("centered image 'data/O2-ANU | 2048.txt' shape = {:d}x{:d}".format(h, w))
# split image into quadrants
Q = abel.tools.symmetry.get_image_quadrants(IModd, reorient=True)
Q0 = Q[0]
Q0fresh = Q0.copy() # keep clean copy
print ("quadrant shape {}".format(Q0.shape))
# Intensity mask used for intensity normalization
# quadrant image region of brig... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.