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 |
|---|---|---|---|---|---|---|---|---|
robinedwards/django-neomodel | django_neomodel/apps.py | Python | mit | 719 | 0.006954 | from django.apps import AppConfig
from django.conf import settings
from neomodel import config
config.AUTO_INSTALL_LABELS = | False
class NeomodelConfig(AppConfig):
name = 'django_neomodel'
verbose_name = 'Django neomodel'
def read_settings(self):
config.DATABASE_URL = g | etattr(settings, 'NEOMODEL_NEO4J_BOLT_URL', config.DATABASE_URL)
config.FORCE_TIMEZONE = getattr(settings, 'NEOMODEL_FORCE_TIMEZONE', False)
config.ENCRYPTED_CONNECTION = getattr(settings, 'NEOMODEL_ENCRYPTED_CONNECTION', False)
config.MAX_CONNECTION_POOL_SIZE = getattr(settings, 'NEOMODEL_MAX_C... |
elvian/alfred | scripts/pollutionController.py | Python | mit | 1,497 | 0.038076 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
from urllib.request import urlopen
def getSoupAQHI():
html = urlopen("http://www.aqhi.gov.hk/en/aqhi/past-24-hours-aqhi45fd.html?stationid=80")
soup = BeautifulSoup(html, "lxml")
return soup
def getLatestAQHI(dataTable):
aqhiTable = data... | 376.29520771")
source = source.read().decode('utf-8')
return source
def getLatestAQICN(source):
aqi = source.split("Air Pollution.")[1]
aqi = aqi.split("title")[1]
aqi = aqi.split("</div>")[0]
aqi = aqi.split(">")[1]
aqits = source.split("Updated on ")[1].strip()
aqits = aqits.split("<")[0]
aqhiData = {}
... | able', {'id' : 'dd_stnh24_table'})
aqhi = getLatestAQHI(dataTableAQHI)
rawAQICN = getRawAQICN()
aqicn = getLatestAQICN(rawAQICN)
data = {}
data['AQHI'] = aqhi['index']
data['AQHITS'] = aqhi['dateTime']
data['AQICN'] = aqicn['index']
data['AQICNTS'] = aqicn['dateTime']
return data
def testModule():
data =... |
geier/alot | alot/addressbook/__init__.py | Python | gpl-3.0 | 1,232 | 0 | # Copyright (C) 2011-2015 Patrick Totzke <patricktotzke@gmail.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
from __future__ import absolute_import
import re
import abc
class AddressbookError(Exception):
pass
class AddressBook(object):... | for implementations.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, ignorecase=True):
self.reflags = re.IGNORECASE if ignorecase else 0
@abc.abstractmethod
def get_contacts(self): # pragma no cover
"""list all contacts tuples in this abook as (name, email) tuples"""
r... | % query, self.reflags)
for name, email in self.get_contacts():
if query.match(name) or query.match(email):
res.append((name, email))
return res
|
titilambert/home-assistant | tests/components/bayesian/test_binary_sensor.py | Python | apache-2.0 | 22,326 | 0.000851 | """The test for the bayesian sensor platform."""
import json
import unittest
from homeassistant.components.bayesian import binary_sensor as bayesian
from homeassistant.components.homeassistant import (
DOMAIN as HA_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN
f... | m tests.common import get_test_home_assistant
class TestBayesianBinarySensor(unittest.TestCase):
"""Test the threshold sensor."""
def setup_method(self, method):
"""Set up things to be run when tests are started."""
self.hass = get_test_home_assistant()
def teardown_method(self, method):... | """Stop everything that was started."""
self.hass.stop()
def test_load_values_when_added_to_hass(self):
"""Test that sensor initializes with observations of relevant entities."""
config = {
"binary_sensor": {
"name": "Test_Binary",
"platform... |
ShaneHarvey/mongo-connector | tests/test_oplog_manager_sharded.py | Python | apache-2.0 | 28,458 | 0.000738 | # Copyright 2013-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | _concern import WriteConcern
sys.path[0:0] = [""] # noqa
from mongo_connector.doc_managers.doc_manager_simulator import DocManager
from mongo_connector.locking_dict import LockingDict
from mongo_connector.namespace_config import NamespaceConfig
from mongo_connector.oplog_manager import OplogThre | ad
from mongo_connector.test_utils import (
assert_soon,
close_client,
ShardedCluster,
ShardedClusterSingle,
)
from mongo_connector.util import retry_until_ok, bson_ts_to_long
from tests import unittest, SkipTest
class ShardedClusterTestCase(unittest.TestCase):
def set_up_sharded_cluster(self, sha... |
ZUKSev/ZUKS-Controller | server/server/wsgi.py | Python | gpl-3.0 | 1,072 | 0.000933 | # This file is part of ZUKS-Controller.
#
# ZUKS-Controller 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.
#
# ZUKS-Controller is dist... | HOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public L | icense
# along with ZUKS-Controller. If not, see <http://www.gnu.org/licenses/>.
"""
WSGI config for server project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.env... |
OCA/partner-contact | partner_identification/tests/test_partner_identification.py | Python | agpl-3.0 | 4,638 | 0.001509 | # Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http:/ | /www.gnu.org/licenses/agpl.html).
from psycopg2._psycopg import IntegrityError
from odoo.exceptions import UserError, ValidationError
from odoo.te | sts import common
from odoo.tools import mute_logger
class TestPartnerIdentificationBase(common.TransactionCase):
def test_create_id_category(self):
partner_id_category = self.env["res.partner.id_category"].create(
{"code": "id_code", "name": "id_name"}
)
self.assertEqual(partn... |
corriander/python-sigfig | sigfig/sigfig.py | Python | mit | 2,902 | 0.033425 | from math import floor, log10
def round_(x, n):
"""Round a float, x, to n significant figures.
Caution should be applied when performing this operation.
Significant figures are an implication of precision; arbitrarily
truncating floats mid-calculation is probably not Good Practice in
almost all cases.
Rounding... | to a specified number of significant figures.
>>> create_string(9.80665, 3)
'9.81'
>>> create_string(0.0120076, 3)
'0.0120'
>>> create_string(100000, 5)
'100000'
Note the last representation is, without context, ambiguous. This
is a good reason to use scienti | fic notation, but it's not always
appropriate.
Note
----
Performing this operation as a set of string operations arguably
makes more sense than a mathematical operation conceptually. It's
the presentation of the number that is being changed here, not the
number itself (which is in turn only approximated by a f... |
OCA/server-tools | base_sequence_option/__init__.py | Python | agpl-3.0 | 150 | 0 | # Copyright 2021 Ecosoft Co., Ltd. (http://ecosoft.c | o.th)
# Licens | e LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from . import models
|
camlorn/clang_helper | clang_helper/extract_macros.py | Python | gpl-3.0 | 2,943 | 0.030581 | """Utilities for extracting macros and preprocessor definitions from C files. Depends on Clang's python bindings.
Note that cursors have children, which are also cursors. They are not iterators, they are nodes in a tree.
Everything here uses iterators. The general strategy is to have multiple passes over the same cu... | okens = desired_tokens[1:]
if len(desired_tokens) == 0:
#the value of this macro is none.
value = None
m = Macro | (name = name, value = value, cursor = i)
handled_macros.append(m)
currently_known_macros[m.name] = m.value
continue
#otherwise, we have to do some hacky stuff.
token_strings = [transform_token(j) for j in desired_tokens]
eval_string = "".join(token_strings)
try:
value = eval(eval_string, currently_k... |
JohnGriffiths/nipype | nipype/interfaces/freesurfer/tests/test_auto_ApplyVolTransform.py | Python | bsd-3-clause | 2,611 | 0.02298 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.freesurfer.preprocess import ApplyVolTransform
def test_ApplyVolTransform_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
fs_ta... | t_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(inputs.traits()[key], metakey), value
def test_ApplyVolTransform_outputs():
output_map = dict(transformed_file=dict(),
)
outputs = ApplyVolTransform.output_spec()
for key, metadata i | n output_map.items():
for metakey, value in metadata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
|
ClearCorp-dev/odoo-costa-rica | l10n_cr_account_banking_cr_bcr/__init__.py | Python | agpl-3.0 | 1,054 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2011 credativ Ltd (<http://www.credativ.co.uk>).
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Ge... | n the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero | General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import bcr_format
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
sburnett/seattle | repy/tests/ut_repytests_global.py | Python | mit | 47 | 0.042553 | #pragma error
#pragma repy
global foo
f | oo | = 2
|
rec/echomesh | code/python/experiments/FixColors.py | Python | mit | 762 | 0.01706 | import re
LINE_RE = re.compile(r'\s*namer.add\("(.*)", 0x(.*)\);.*')
with open('/tmp/colors.txt') as f:
data = {}
for line in f:
matches = LINE_RE.match(line)
if mat | ches:
color, number = matches.groups()
if len(number) < 8:
number = 'ff%s' % number
data[color] = number
else:
print 'ERROR: don\'t understand:', line
inverse = {}
dupes = {}
for color, nu | mber in sorted(data.iteritems()):
if number in inverse:
dupes.setdefault(number, []).append(color)
else:
inverse[number] = color
print ' namer.add("%s", 0x%s);' % (color, number)
if dupes:
print dupes
for number, colors in dupes.iteritems():
print '%s -> %s (originally %s)' % (... |
riolet/SAM | sam/models/details.py | Python | gpl-3.0 | 16,289 | 0.001719 | import web
import sam.common
import sam.models.links
class Details:
def __init__(self, db, subscription, ds, address, timestamp_range=None, port=None, page_size=50):
self.db = db
self.sub = subscription
self.table_nodes = "s{acct}_Nodes".format(acct=self.sub)
self.table_links = "s{... | d) * 1.0 / duration) AS 'max_bps'
, SUM(bytes_sent + bytes_received) AS 'sum_b'
, SUM(packets_sent) AS 'p_s'
, SUM(packets_received) AS 'p_r'
, SUM(duration * links) AS 'sum_duration'
, GROUP_CONCAT(DISTINCT protocol) AS 'protocol'
... | ON n.ipstart = l_out.s1
LEFT JOIN (
SELECT $start AS 's1'
, COUNT(DISTINCT src) AS 'unique_in_ip'
, (SELECT COUNT(1) FROM (SELECT DISTINCT src, dst, port FROM {links_table} WHERE dst BETWEEN $start AND $end) AS `temp2`) AS 'unique_in_conn'
... |
felipedau/pyaxo | examples/transfer.py | Python | gpl-3.0 | 4,487 | 0.002452 | #!/usr/bin/env python
"""
This file transfer example demonstrates a couple of things:
1) Transferring files using Axolotl to encrypt each block of the transfer
with a different ephemeral key.
2) Using a context manager with Axolotl.
The utility will prompt you for the location of the Axolotl key database
and th... | if ciphertext == '':
print 'nothing received'
exit()
cipherlist = ciphertext.split('EOP')
for item in cipherlist:
if item[-3:] == 'EOF':
item = item[:-3]
plaintext += a.decrypt(item)
filenamel... | plaintext[2:2+filenamelength]
with open(file_name, 'wb') as f:
f.write(plaintext[2+filenamelength:])
# send confirmation
reply = a.encrypt('Got It!')
client.send(reply)
print file_name + ' received'
|
nrc/rustc-perf | collector/benchmarks/cranelift-codegen/cranelift-codegen/meta-python/cdsl/formats.py | Python | mit | 10,052 | 0 | """Classes for describing instruction formats."""
from __future__ import absolute_import
from .operands import OperandKind, VALUE, VARIABLE_ARGS
from .operands import Operand # noqa
# The typing module is only required by mypy, and we don't use these imports
# outside type comments.
try:
from typing import Dict, ... | We define 'immediate' as not a value or variable arguments.
if k is VALUE:
self.num_value_operands += 1
e | lif k is VARIABLE_ARGS:
self.has_value_list = True
else:
yield FormatField(self, inum, k, member)
inum += 1
def __str__(self):
# type: () -> str
args = ', '.join(
'{}: {}'.format(f.member, f.kind) for f in self.imm_fields)
... |
jugovich/teresajugovich | config/test.py | Python | mit | 1,293 | 0.003867 | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'tjtest', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': ... | ww/example.com/media/"
MEDIA_ROOT = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = '/home/tjugovich/web... | |
genialis/resolwe | resolwe/flow/signals.py | Python | apache-2.0 | 2,030 | 0 | """.. Ignore pydocstyle D400.
============ | ===
Signal Handlers
===============
"""
from asgiref.sync import async_to_sync
from django.conf import settings
from django.db import transaction
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from resolwe.flow.managers import manager
from resolwe.flow.models import ... | the end of every Data object save event."""
if not getattr(settings, "FLOW_MANAGER_DISABLE_AUTO_CALLS", False):
immediate = getattr(settings, "FLOW_MANAGER_SYNC_AUTO_CALLS", False)
async_to_sync(manager.communicate)(data_id=data_id, run_sync=immediate)
@receiver(post_save, sender=Data)
def manage... |
fccoelho/pypln.backend | pypln/backend/workers/tokenizer.py | Python | gpl-3.0 | 1,140 | 0.000877 | # coding: utf-8
#
# Copyright 2012 NAMD-EMAP-FGV
#
# This file is part of PyPLN. You can get more information at: http://pypln.org/.
#
# PyPLN 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 o... | but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR | PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyPLN. If not, see <http://www.gnu.org/licenses/>.
from mongodict import MongoDict
from nltk import word_tokenize, sent_tokenize
from pypln.backend.celery_task import Py... |
ctalbert/mozharness | configs/partner_repacks/release_mozilla-release_android.py | Python | mpl-2.0 | 1,585 | 0.002524 | FTP_SERVER = "stage.mozilla.org"
FTP_USER = "ffxbld"
FTP_SSH_KEY = "~/.ssh/ffxbld_dsa"
FTP_UPLOAD_BASE_DIR = "/pub/mozilla.org/mobile/candidates/%(version)s-candidates/build%(buildnum)d"
DOWNLOAD_BASE_URL = "http://%s%s" % (FTP_SERVER, FTP_UPLOAD_BASE_DIR)
APK_BASE_NAME = "fennec-%(version)s.%(locale)s.android-arm.apk"... | },
"download_unsigned_base_subdir": "unsigned/%(platform)s/%(locale)s",
"download_base_url": DOWNLOAD_BASE_URL,
"release_config_file": "buildbot-configs/mozilla/release-fennec-mozilla-release.py",
"default_actions": ["clobber", "pull", "download", "repack", "upload-unsigned-bits"],
# signing ... | lias": KEY_ALIAS,
"exes": {
"jarsigner": "/tools/jdk-1.6.0_17/bin/jarsigner",
"zipalign": "/tools/android-sdk-r8/tools/zipalign",
},
}
|
EPFL-LCN/neuronaldynamics-exercises | neurodynex3/cable_equation/passive_cable.py | Python | gpl-2.0 | 6,153 | 0.004063 | """
Implements compartmental model of a passive cable. See Neuronal Dynamics
`Chapter 3 Section 2 <http://neuronaldynamics.epfl.ch/online/Ch3.S2.html>`_
"""
# This file is part of the exercise code repository accompanying
# the book: Neuronal Dynamics (see http://neuronaldynamics.epfl.ch)
# located at http://github.c... | dex]
compartment_index = int(np.floor(insert_location / (length / nr_compartm | ents)))
# next line: current_index+1 because 0 is the default current 0Amp
cable_model.location_index[compartment_index] = current_index + 1
# set initial values and run for 1 ms
cable_model.v = initial_voltage
b2.run(simulation_time)
return monitor_v, cable_model
def getting_started(... |
vejmelkam/emotiv-reader | src/signal_renderer_widget.py | Python | gpl-3.0 | 7,269 | 0.007979 |
import numpy as np
import bisect
import pygame
import scipy.signal
from albow.widget import Widget, overridable_property
from albow.theme import ThemeProperty
class SignalRendererWidget(Widget):
def __init__(self, signal_list, dev, buf, rect, **kwds):
"""
Initialize the renderer with the s... | frame.bottom))
# draw the signal onto the screen (remove mean in buffer)
zero_lev = np.mean(sig)
sig_amp = max(np.max(sig) - zero_lev, zero_lev - np.min(sig))
if sig_amp == 0:
sig_amp = 1.0
# pixel_per_lsb = self.multiplier * frame.height / sig_amp / 2.0
pixel... | lsb
draw_pts_y[draw_pts_y < frame.top] = frame.top
draw_pts_y[draw_pts_y > frame.bottom] = frame.bottom
draw_pts_x = np.linspace(0, frame.width, len(sig)) + frame.left
pygame.draw.lines(surf, color, False, zip(draw_pts_x, draw_pts_y))
# draw a bar that corresponds to 10uV
... |
twosigma/beaker-notebook | beakerx_tabledisplay/beakerx_tabledisplay/__init__.py | Python | apache-2.0 | 1,170 | 0.001709 | # Copyright 2019 TWO SIGMA OPEN SOURCE, LLC
# |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed unde... | OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .tableitems import *
from .tabledisplay import *
from ._version import version_info, __version__
from .handlers import load_jupyter_server_extension
from .c... |
opensciences/var | Import from googlecode/importAutomation.py | Python | mit | 4,045 | 0.006922 | """
Exceptions:
mccabehalsted: there are triple curly brackets ({{{) in jm1 that jekyll doesn't like
spe: is in "other" directory in terapromise
reuse: double curly brackets in reuse
dump: links end like "/ABACUS2013" without closing slash
"""
relativePath = "defect/ck/"
import os, re, datetime
from types import Non... | mary = extractSummary(fileContents)
author = extractAuthor(fileContents)
return """---
title: """ + baseName + """
excerpt: """ + summary + """
layout: repo
author: """ + author + """
---
"""
def doDeletions(fileContents):
return re.sub(r"#summary [^\n]+\n# | labels [^\n]+\n\n<wiki:toc max_depth=\"2\" />", "", fileContents)
def changeHeaders(fileContents):
return re.sub(r"\n= ([^\n]+) =\n", r"\n#\1\n", fileContents)
def reformatLinks(fileContents):
sub = re.sub(r"[^\[]http([^\s]+)", r"[http\1 http\1]", fileContents)
return re.sub(r"\[([^ ]+) ([^\]]+)\]", r"[\2... |
rsnakamura/oldape | apetools/builders/subbuilders/teardownbuilder.py | Python | apache-2.0 | 1,942 | 0.000515 |
from apetools.baseclass import BaseClass
from apetools.tools import copyfiles
from apetools.log_setter import LOGNAME
from apetools.proletarians import teardown
| class TearDownBuilder(BaseClass):
"""
A basic tear-down builder that just copies log and config files.
"""
def __init__(self, configfilename, storage, subdir="logs"):
"""
:param:
- `configfilename`: the name of the config file to copy
- `storage`: A storage object aime... | older.
"""
super(TearDownBuilder, self).__init__()
self.configfilename = configfilename
self.storage = storage
self.subdir = subdir
self._configcopier = None
self._logcopier = None
self._teardown = None
return
@property
def configcopier(se... |
belokop/indico_bare | indico/MaKaC/common/contextManager.py | Python | gpl-3.0 | 811 | 0 | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# pub | lished by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico 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 P... | t, see <http://www.gnu.org/licenses/>.
"""
Just for backwards-compatibility
"""
from indico.util.contextManager import *
|
ancho85/pylint-playero-plugin | tests/test_funcs.py | Python | gpl-2.0 | 3,850 | 0.012987 | import unittest
from libs.funcs import *
class TestFuncs(unittest.TestCase):
def test_buildPaths(self):
recPaths, repPaths, rouPaths, corePaths = buildPaths()
findTxt = lambda x, y: x.find(y) > -1
assert findTxt(recPaths["Task"][0], "base")
assert findTxt(recPaths["Department"][0... | " #From StdPy
assert recf["Department"]["DeptName"] == "string" #From standard
assert recf["Department"]["Closed"] == "Boolean" #From Master
assert recf["Department"]["internalId"] == "internalid" #From Record
assert recd["Department"]["OfficePayModes"] == "DepartmentOf... | nce", REPORT)
assert repf["Balance"]["LabelType"] == "string" #StdPy
assert repf["Balance"]["ExplodeByLabel"] == "boolean" #Standard
assert repf["Balance"]["internalId"] == "internalid" #Record
assert not repd["Balance"] #Empty dict, no detail
rouf, roud = getR... |
tdsmith/ponysay | src/balloon.py | Python | gpl-3.0 | 8,019 | 0.009993 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
ponysay - Ponysay, cowsay reimplementation for ponies
Copyright (C) 2012, 2013, 2014 Erkin Batu Altunbaş et al.
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 Softw... | al
@param ssw:list<str> See the info manual
@param sw:list<str> See the info manual
@param sww:str See the info manual
@param w:str See the info manual
@param nww:str See the info manual
'''
(self.link, self.linkmirror, self.lin... | elf.nnw, self.n, self.nne) = (nnw, n, nne)
(self.nee, self.e, self.see) = (nee, e, see)
(self.sse, self.s, self.ssw) = (sse, s, ssw)
(self.sww, self.w, self.nww) = (sww, w, nww)
_ne = max(ne, key = UCS.dispLen)
_nw = max(nw, key = UCS.dispLen)
_se = max(se, key =... |
RudolfCardinal/crate | crate_anon/preprocess/postcodes.py | Python | gpl-3.0 | 52,340 | 0 | #!/usr/bin/env python
"""
crate_anon/preprocess/postcodes.py
===============================================================================
Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of CRATE.
CRATE is free software: you can redistribute it and/or modify
it under... | n, either version 3 of the License, or
(at your option) any later version.
CRATE 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 P | ARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CRATE. If not, see <https://www.gnu.org/licenses/>.
===============================================================================
**Fetches UK postcode in... |
stlemme/python-dokuwiki-export | visitor/__init__.py | Python | mit | 301 | 0 |
from .visitor import Visitor
from .metavis | itor import MetaVisitor
from .experiments import ExperimentsVisitor
from .usedby import UsedByVisitor
from .testedscenarios import TestedScenariosVisitor
from .invalidentities import InvalidEntitiesVisitor
# from pres | enter.gesurvey import GESurveyPresenter
|
malmiron/incubator-airflow | tests/models.py | Python | apache-2.0 | 119,658 | 0.000911 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | ,
default_args={'owner': 'owner1'})
# A -> B
# A -> C -> D
# ordered: B, D, C, A | or D, B, C, A or D, C, B, A
with dag:
op1 = DummyOperator(task_id='A')
op2 = DummyOperator(task_id='B')
op3 = DummyOperator(task_id='C')
op4 = DummyOperator(task_id='D')
op1.set_upstream([op2, op3])
op3.set_upstream(op4)
topologica... |
samabhi/pstHealth | venv/lib/python2.7/site-packages/easy_thumbnails/sorl-tests/classes.py | Python | mit | 8,008 | 0 | # -*- coding: utf-8 -*-
import os
import time
from StringIO import StringIO
from PIL import Image
from django.conf import settings
from easy_thumbnails.base import Thumbnail
from easy_thumbnails.main import DjangoThumbnail, get_thumbnail_setting
from easy_thumbnails.processors import dynamic_import, get_valid_options... | ename=expected)
def tearDown(self):
super(DjangoThumbnailTest, self).tearDown()
subdir = os.p | ath.join(self.sub_dir, 'subdir')
if os.path.exists(subdir):
os.rmdir(subdir)
os.rmdir(self.sub_dir)
|
Makeystreet/makeystreet | woot/apps/catalog/migrations/0025_auto__add_topshops.py | Python | apache-2.0 | 24,810 | 0.006771 | # -*- 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 model 'TopShops'
db.create_table(u'catalog_topshops', (
(u'id', self.gf('django.db.mode... | e']"}),
u'id': ('dj | ango.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'catalog.comment': {
'Meta': {'object_name': 'Comment'},
'added_time': ('django.db.models.fields.DateTimeField', [], {}),
... |
Nihn/fuzzy_logic | fuzzy/utils/__init__.py | Python | apache-2.0 | 44 | 0 | from | functions import *
from ut | ils import *
|
jlec/coot | rcrane/coot_utils_adapter.py | Python | gpl-3.0 | 1,561 | 0.012172 | #!/usr/bin/env python
"""Allows functions from coot_utils to be imported"""
# Copyright 2011, 2012 Kevin Keating
#
# Licensed under the Educational Community 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://w... | import *
use_gui_qm = False #coot_utils requires this variable to be defined
#search the Python path for coot_utils
for curpath in sys.path:
abspath = join(curpath, "coot_utils.py")
if exists(abspath):
#when we find it, exec it
#but first exec redefine_functions.py if it's in the same... | renames func_py() to func(), which used to be done in coot_utils.py itself
#new versions of coot_utils.py requires this renaming to be done before being exec'ed
redefAbspath = join(curpath, "redefine_functions.py")
if exists(redefAbspath):
execfile(redefAbspath)
exe... |
sdpython/python3_module_template | _unittests/ut_module/test_convert_notebooks.py | Python | mit | 1,224 | 0.000817 | """
@brief test log(time=0s)
"""
import os
import unittest
from pyquickhelper.loghelper import fLOG
from pyquickhelper.filehelper import explore_folder_iterfile
from pyquickhelper.ipythonhelper import upgrade_notebook, remove_execution_number
class TestConvertNotebooks(unittest.TestCase):
"""Converts notebo... | normpath(
os.path.join(fold, "..", "..", "_doc", "notebooks"))
for nbf in explore_fold | er_iterfile(fold2, pattern=".*[.]ipynb"):
t = upgrade_notebook(nbf)
if t:
fLOG("modified", nbf)
# remove numbers
remove_execution_number(nbf, nbf)
fold2 = os.path.normpath(os.path.join(fold, "..", "..", "_unittests"))
for nbf in explore_fo... |
paour/weblate | weblate/trans/tests/test_commands.py | Python | gpl-3.0 | 8,853 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2014 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# This program is free software: you can | redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... | nse for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Tests for management commands.
"""
from django.test import TestCase
from weblate.trans.tests.test_models import RepoTestCase
from weblate.trans.mode... |
askogvold/jtk | src/demo/jython/edu/mines/jtk/awt/PerceptualColorSpaceDemo.py | Python | apache-2.0 | 5,858 | 0.022704 | #/****************************************************************************
# Copyright 2015, Colorado School of Mines and others.
# 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
#
# htt... | s graph,
# which attempts to approximate that each value change is rep | resented by a
# change in perception.
#
# Author: Chris Engelsma
# Version: 2015.09.27
##############################################################################
def main(args):
pp1 = test1()
pp2 = test2()
# pp3 = test3()
pf = PlotFrame(pp1,pp2,PlotFrame.Split.HORIZONTAL)
pf.setDefaultCloseOperation(PlotF... |
ncos/lisa | src/lisa_drive/scripts/venv/lib/python3.5/site-packages/pip-10.0.1-py3.5.egg/pip/_vendor/chardet/euctwprober.py | Python | mit | 1,793 | 0.001673 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
... | gstatemachine import CodingStateMachine
from .chardistribution import EUCTWDistributionAnalysis
from .mbcssm import EUCTW_SM_MODEL
class EUCTWProber(MultiByteCharSetProber):
def __init__(self):
super(EUCTWProber, self).__init__()
self.coding_sm = CodingStateMachine(EUCTW_SM_MODEL)
s... | t_name(self):
return "EUC-TW"
@property
def language(self):
return "Taiwan"
|
srpeiter/ChipDesignCad | testing_scripts/mario_drum.py | Python | gpl-3.0 | 674 | 0.093472 | import numpy as np
from stcad.source_dev.chip import Base_Chip
from stcad.source_ | dev.objects import Drum
import gdsCAD as cad
chipsize = 50
chip = Base_Chip('drum', chipsize, chipsize,label=False)
inductor = Drum(base_ | layer = 1,
sacrificial_layer = 2 ,
top_layer = 3,
outer_radius = 9,
head_radius = 7,
electrode_radius = 6,
cable_width = 0.5,
sacrificial_tail_width = 3,
sacrificial_tail_length = 3,
opening_width = 4,
N_holes = 3,
hole_angle = 45,
hole_distance_to_center = 4.... |
nnscr/nnscr.de | pages/admin.py | Python | mit | 430 | 0 | fr | om django.contrib import admin
from django import forms
from . import models
from nnmarkdown.form import MarkdownWidget
from nnscr.admin import site
class PageAdminForm(forms.ModelForm):
class Meta:
model = models.Page
exclude = ("slug",)
widgets = {
"text": MarkdownWidget
... | |
tstirrat15/exercism-python-responses | kindergarten-garden/python/kindergarten-garden/garden.py | Python | gpl-2.0 | 1,032 | 0.002907 | class Garden(object):
"""An object implementing a Kindergarten
Garden."""
def __init__(self, cup_string, students=None):
self.garden_rows = cup_string.split('\n')
| if students:
self.class_list = sorted(students)
else:
self.class_list = [
"Alice", "Bob", "Charlie", "David",
"Eve", "Fred", "Ginny", "Harriet",
| "Ileana", "Joseph", "Kincaid", "Larry"
]
self.plants_dict = {
"R": "Radishes",
"C": "Clover",
"G": "Grass",
"V": "Violets"
}
self.cups_per_child = 2
def plants(self, child_name):
index = self.cups_per_child ... |
andialbrecht/django-hvad | nani/tests/forms_inline.py | Python | bsd-3-clause | 1,563 | 0.008317 | # -*- coding: utf-8 -*-
from nani.admin import TranslatableModelAdminMixin
from nani.forms import translatable_inlineformset_factory
from nani.forms import TranslatableModelForm, TranslatableModelFormMetaclass
from nani.test_utils.context_managers import LanguageOverride
from nani.test_utils.testcase import NaniTestCas... | with LanguageOverride("en"):
self.object = Normal.objects.language().create(shared_field="test", translated_field="translated test")
rf = RequestFactory()
self.request = rf.post('/url/')
def test_create_fields_inline(self):
with LanguageOverride("en"):
... | AdminMixin()
formset = translatable_inlineformset_factory(translate_mixin._language(self.request),
Normal, Related)(#self.request.POST,
instance=self.object)
self.a... |
google-research/rigl | rigl/experimental/jax/datasets/cifar10_test.py | Python | apache-2.0 | 4,140 | 0.006522 | # coding=utf-8
# Copyright 2022 RigL 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 applicable law or agree... | # Normalized by stddev., expect nothing to fall outside 3 stddev.
self.assertTrue((image >= -3.).all() and (image <= 3.).all())
with self.subTest(name='LabelShape'):
| self.assertLen(label, self._batch_size_test)
with self.subTest(name='LabelType'):
self.assertTrue(np.issubdtype(label.dtype, np.int))
with self.subTest(name='LabelValues'):
self.assertTrue((label >= 0).all() and
(label <= self._dataset.num_classes).all())
def test_train_... |
WhySoGeeky/DroidPot | venv/lib/python2.7/site-packages/sphinx/util/parallel.py | Python | mit | 4,139 | 0 | # -*- coding: utf-8 -*-
"""
sphinx.util.parallel
~~~~~~~~~~~~~~~~~~~~
Parallel building utilities.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import traceback
try:
import multiprocessing
import threading
except I... | lass ParallelTasks(object):
"""Executes *nproc* tasks in parallel after forking."""
def __init__(self, nproc):
self.nproc = nproc
# list of threads to join when waiting for completion
| self._taskid = 0
self._threads = {}
self._nthreads = 0
# queue of result objects to process
self.result_queue = queue.Queue()
self._nprocessed = 0
# maps tasks to result functions
self._result_funcs = {}
# allow only "nproc" worker processes at once
... |
JuPeg/tools-artbio | unstable/local_tools/clustering4.py | Python | mit | 6,082 | 0.024005 | #!/usr/bin/python
# script find clusters of small RNA reads in the genome
# version 3 - 24-12-2013 evolution to multiprocessing
# Usage clustering.py <bowtie input> <output> <bowtie index> <clustering_distance> <minimum read number per cluster to be outputed> <collapse option> <extention value> <average_cluster_size>
#... | allback=logtask)
pool.close()
pool.join()
for lines in LOG:
for line in lines:
pr | int >> OUT, line
OUT.close()
elapsed_time = time.time() - start_time
print "number of reads: %s\nnumber of clusters: %s\ntime: %s" % (number_of_reads, number_of_clusters, elapsed_time)
|
midonet/mcp | deimos/config.py | Python | apache-2.0 | 5,937 | 0.002358 | from ConfigParser import SafeConfigParser, NoSectionError
import json
import logging
import os
import sys
import deimos.argv
import deimos.docker
from deimos.logger import log
import deimos.logger
from deimos._struct import _Struct
def load_configuration(f=None, interactive=sys.stdout.isatty()):
error = None
... | cearray(append),
ignore=coercebool(ignore))
def override(self, options=[]):
a = options if (len(options) > 0 and not self.ignore) else self.default
return a + self.append
class Containers(_Struct):
def __init__(self, image=Image(), options=Options()):
_... | def override(self, image=None, options=[]):
return self.image.override(image), self.options.override(options)
class URIs(_Struct):
def __init__(self, unpack=True):
_Struct.__init__(self, unpack=coercebool(unpack))
class Log(_Struct):
def __init__(self, console=None, syslog=None):
... |
usmansher/hangman | main.py | Python | apache-2.0 | 4,488 | 0.011809 | #!/usr/bin/python
'''
Title: Hangman
Description: A Simple Hangman Game
Author: Usman Sher (@usmansher)
Disclaimer: Its Just A Small Guessing Game made By Me (Beginning Of Coding).
'''
# Imports
import pygame, sys
from pygame.locals import *
from random import choice
# Color Variables
RED = (255, 0, 0)
GREEN = (0,... | with the Popped Bodypart
pygame.display.update() # Update the Display
guessed += guess # Add it to variable guessed
if body: # Check Whether theres a part left in variable body
text = 'You Won!'# If True
else:
text = 'You Lose! The word was '+ w... | ile True:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
# Run The Program
if __name__ == '__main__':
main()
|
vprusso/youtube_tutorials | twitter_python/part_1_streaming_tweets/tweepy_streamer.py | Python | gpl-3.0 | 1,932 | 0.006729 | # YouTube Video: https://www.youtube.com/watch?v=wlnx-7cm4Gg
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import twitter_credentials
# # # # TWITTER STREAMER # # # #
class TwitterStreamer():
"""
Class for streaming and processing live tweets.
"""
... | __init__(self, fetched_tweets_filename):
self.fetched_tweets_filename = fetched_tweets_filename
def on_data(self, data):
try:
print(data)
with open(self.fetched_tweets_filename, 'a') as tf:
tf.write(data)
return True
except BaseException a... | tus):
print(status)
if __name__ == '__main__':
# Authenticate using config.py and connect to Twitter Streaming API.
hash_tag_list = ["donal trump", "hillary clinton", "barack obama", "bernie sanders"]
fetched_tweets_filename = "tweets.txt"
twitter_streamer = TwitterStreamer()
twitter_s... |
wiliamsouza/mandriva-control-center | bin/services-mechanism.py | Python | gpl-2.0 | 169 | 0.011834 | #!/usr/bin/python
import sys
sys.path.append('/usr/share/mandriva/')
from mcc2.backends.services.service import Services
if __name__ == '__main__':
Services.main | () | |
jiobert/python | Smith_Ben/Assignments/email_validation/emai.py | Python | mit | 1,552 | 0.027706 | from flask import Flask, request, redirect, render_template, session, flash
from mysqlconnection import MySQLConnector
import re
app = Flask(__name__)
mysql = MySQLConnector(app, 'emailval')
app.secret_key = 'secret'
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
@app.route('/')
def validat... | st.form['buttonbox']):
flash('invalid emale')
return redirect('/')
else:
flash ('Great Job!');
query = "INSERT INTO email (email,updated_at,created_at) VALUES (:email,NOW(),NOW())"
data = {'email':request.form['buttonbox']}
mysql.query_db(query,data)
query = "SELECT created_at FROM email"
... | h('need a proper emale')
return render_template('email.html', email = email)
# @app.route('/emails')
# def show(email_id):
# query = "SELECT * FROM email WHERE id = :specific_id"
# data = {'specific_id': email_id}
# emails = mysql.query_db(query, data)
# return render_template('email.html', email = email)
@a... |
widdowquinn/find_differential_primers | diagnostic_primers/nucmer.py | Python | mit | 17,605 | 0.001477 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""nucmer.py
Provides helper functions to run nucmer from pdp
(c) The James Hutton Institute 2018
Author: Leighton Pritchard
Contact: leighton.pritchard@hutton.ac.uk
Leighton Pritchard,
Information and Computing Sciences,
James Hutton Institute,
Errol Road,
Invergowrie... | other.reference,
other.query,
other.referencelen,
other.querylen,
)
def __str__(self):
return ">{} {} {} {}".format(
self.reference, self.query, self.referencelen, self.queryle | n
)
class DeltaAlignment(object):
"""Represents a single alignment region and scores for a pairwise comparison"""
def __init__(self, refstart, refend, qrystart, qryend, errs, simerrs, stops):
self.refstart = int(refstart)
self.refend = int(refend)
self.querystart = int(qrystar... |
lampwins/netbox | netbox/secrets/api/urls.py | Python | apache-2.0 | 763 | 0.003932 | from rest_framework import routers
from . import views
class SecretsRootView(routers.APIRootView):
"""
Secrets API root view
"""
def get_view_name(self):
return 'Secrets'
router = routers.DefaultRouter()
router.APIRootView = SecretsRootView
# Field choices
router.register(r'_choices', view... | secret-roles', views.SecretRoleViewSet)
router.register(r'secrets', views.SecretViewSet)
# Miscellaneous
router.register(r'get-session-key', views.GetSessionKeyViewSet, basename='get-session-key')
router.register(r'generate-rsa-key-pair', views.GenerateRSAKeyPairVie | wSet, basename='generate-rsa-key-pair')
app_name = 'secrets-api'
urlpatterns = router.urls
|
cfossace/test | pyscript/pyscript2.py | Python | mit | 1,181 | 0.018628 | import requests
import hashlib
import os
import json
USERNAME = 'christine'
API_KEY = 'd0e4164c2bd99f1f888477fc25cf8c5c104a5cd | 1'
#Read in the path with user input (or navigate to the directory in the GUI)
#path = '/home/wildcat/Lockheed/laikaboss/malware/'
os.chdir("/home/wildcat/Lockheed/laikaboss")
print("Hint: /home/wildcat/Lockheed/laikaboss/malware/")
path = raw_input("Enter the path of your file: ")
for f in os.listdir(path):
os.s... | t(os.path.join(path,f), f))
os.chdir("/home/wildcat/Lockheed/crits/pyscript/mal3/")
path2 = "/home/wildcat/Lockheed/crits/pyscript/mal3/"
for f in os.listdir(path2):
read_data = open(f,'r')
md5_data = json.load(read_data)
file_data = open(f, 'r').read()
md5 = md5_data['moduleMetadata']['META_HASH']['HASHES']['... |
claytondaley/mongo-async-python-driver | examples/deferreds/insert.py | Python | apache-2.0 | 1,602 | 0.001248 | #!/usr/bin/env python
# coding: utf-8
import sys
import time
from twisted.internet import defer, reactor
from twisted.python import log
import txmongo
def getConnection():
print "getting connection..."
return txmongo.MongoConnectionPool()
def getDatabase(conn, dbName):
print "getting database..."
... | something":x*time.time()}, safe=True)
deferreds.append(d)
return defer.DeferredList(defer | reds)
def processResults(results):
print "processing results..."
failures = 0
successes = 0
for success, result in results:
if success:
successes += 1
else:
failures += 1
print "There were %s successful inserts and %s failed inserts." % (
successes, ... |
Cadair/pysac | examples/mhs_atmosphere/spruit_atmosphere.py | Python | bsd-2-clause | 12,258 | 0.007016 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 11 13:55:17 2014
@author: sm1fg
This is the main module to construct a magnetohydrostatic solar atmosphere,
given a specified magnetic network of self-similar magnetic flux tubes and
save the output to gdf format.
To select an existing configuration change the import as... | unit=u.N/u.m**3)
#============================================== | ================================
#calculate the magnetic field and pressure/density balancing expressions
#==============================================================================
for i in range(0,model_pars['nftubes']):
for j in range(i,model_pars['nftubes']):
if rank == 0:
print'calculat... |
ChrisTimperley/rostrace | rostrace/service.py | Python | mit | 5,361 | 0.002611 | #!/usr/bin/env python
#
# Limitations:
# - doesn't work if another node is using a persistent connection
# - all names MUST be fully qualified, else rosservice will fail
#
# TODO:
# - watch out for new services and tap them when they come online
# - stop broadc | asting a service when the original host dies?
#
# http://docs.ros.org/diamondback | /api/rosservice/html/index.html
import sys
import inspect
import rospy
import std_srvs.srv
import std_msgs.msg
import rosgraph
import rosservice
import rospy.core
import json
from pprint import pprint as pp
from rospy.impl.tcpros_base import TCPROSTransport
# we use the most accurate timer available to the system
f... |
DIRACGrid/DIRAC | src/DIRAC/DataManagementSystem/DB/FileCatalogComponents/FileManager/FileManagerBase.py | Python | gpl-3.0 | 54,505 | 0.001431 | """ FileManagerBase is a base class for all the specific File Managers
"""
# pylint: disable=protected-access
import six
import os
import stat
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.Utilities.List import intListToString
from DIRAC.Core.Utilities.Pfn import pfnunparse
class FileManagerBase(object):... | icas to register
"""
connection = self._getConnection(connection)
successful = {}
failed = {}
for lfn, info in list(lfns.items()):
res = self | ._checkInfo(info, ["PFN", "SE", "Size", "Checksum"])
if not res["OK"]:
failed[lfn] = res["Message"]
lfns.pop(lfn)
res = self._addFiles(lfns, credDict, connection=connection)
if not res["OK"]:
for lfn in lfns.keys():
failed[lfn] = re... |
elainenaomi/sciwonc-dataflow-examples | sbbd2016/experiments/4-mongodb-rp-3sh/9_workflow_full_10files_primary_3sh_noannot_with_proj_9s/averageratio_0/AverageRatioEvent_0.py | Python | gpl-3.0 | 1,463 | 0.002051 | #!/usr/bin/env python
"""
This activity will calculate the average of ratios between CPU request and Memory request by each event type.
These fields are optional and could be null.
"""
# It will connect to DataStoreClient
from sciwonc.dataflow.DataStoreClient import DataStoreClient
import ConfigDB_Average_0
# connect... | = 0
total_valid_tasks = 0
total_tasks = 0
event_type = i[config.COLUMN]
| while True:
doc = i['data'].next()
if doc is None:
break;
total_tasks += 1
if(doc['ratio cpu memory']):
sum_ratio = sum_ratio + float(doc['ratio cpu memory'])
total_valid_tasks += 1
newline = {}
newlin... |
paksu/django-cassandra-engine | setup.py | Python | bsd-2-clause | 1,839 | 0.000544 | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import django_cassandra_engine as meta
DESCRIPTION = 'Django Cassandra Engine - the Cassandra backend for Django'
try:
with open('README.rst', 'rb') as f:
LONG_DESCRIPTION = f.read().decode('utf-8')
except IOError:
with open('READM... | 'Environment :: Plugins',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :... | 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Database',
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
simonenkong/python_training_mantis | test/test_add_project.py | Python | gpl-2.0 | 726 | 0.004132 | __author__ = 'Nataly'
from model.project import Project
import string
import random
def random_s | tring(prefix, maxlen):
symbols = string.ascii_letters
return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
def test_add_project(app):
project = Project(random_string("name_", 10), random_string("description_", 10))
old_list = app.soap.get_project_list()
| if project in old_list:
app.project.delete_project(project)
old_list = app.soap.get_project_list()
app.project.add_project(project)
new_list = app.soap.get_project_list()
old_list.append(project)
assert sorted(old_list, key=Project.id_or_max) == sorted(new_list, key=Project.id_or_max)
|
AkioNak/bitcoin | test/functional/p2p_ibd_txrelay.py | Python | mit | 1,575 | 0.00254 | #!/usr/bin/env python3
# Copyright (c) 2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test fee filters during and after IBD."""
from decimal import Decimal
from test_framework.messages import ... | RMAL_FEE_FILTER)],
["-minrelaytxfee={}".format(NORMAL_FEE_FILTER)],
]
def run_test(self):
self.log.info("Check that nodes set minfilter to MAX_MONEY while still in IBD")
for node in self.nodes:
assert node.getblockchaininfo()['initialblockdownload']
self.... | : all(peer['minfeefilter'] == MAX_FEE_FILTER for peer in node.getpeerinfo()))
# Come out of IBD by generating a block
self.generate(self.nodes[0], 1)
self.sync_all()
self.log.info("Check that nodes reset minfilter after coming out of IBD")
for node in self.nodes:
as... |
VincentMelia/PythonBasketball | Configuration.py | Python | mit | 125 | 0 | im | port os
BasketballPlayerDatabase = 'BasketballPlayerDatabase.p'
Root_URL = 'https://' | + os.getenv('basketball_root_url')
|
jangsutsr/tower-cli | lib/tower_cli/utils/command.py | Python | apache-2.0 | 1,677 | 0 | # Copyright 2015, Ansible, Inc.
# Luke Sneeringer <lsneeringer@ansible.com>
#
# 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 requi... | the specific language governing permissions and
# limitations under the License.
import click
| class Command(click.Command):
"""A Command subclass that adds support for the concept that invocation
without arguments assumes `--help`.
This code is adapted by taking code from click.MultiCommand and placing
it here, to get just the --help functionality and nothing else.
"""
def __init__(self... |
Svolcano/python_exercise | dianhua/worker/crawler/china_telecom/heilongjiang/main.py | Python | mit | 16,977 | 0.003178 | # -*- coding: utf-8 -*-
import hashlib
from lxml import etree
from Crypto.Cipher import AES
import base64
import time
import traceback
import re
import sys
import random
reload(sys)
sys.setdefaultencoding("utf8")
if __name__ == '__main__':
import sys
sys.path.append('../..')
sys.path.appe... | if code != 0:
return code, key
if u'点击取消弹出' in resp.text:
return 0, "success"
elif u'验证码错误' in resp.text:
self.log('crawler', 'verify_error', resp)
return 2, 'verify_error'
else:
self.log("crawler", "unknown_error", resp)
... | tel_info_url = 'http://hl.189.cn/service/crm_cust_info_show.do?funcName=custSupport&canAdd2Tool=canAdd2Tool'
code, key, resp = self.get(tel_info_url)
if code != 0:
return code, key, {}
try:
selector = etree.HTML(resp.text)
full_name = selector.xpath('/... |
jrwdunham/lingsync2old | delete-empty.py | Python | apache-2.0 | 947 | 0.001056 | """Simple script to delete all forms with "PLACEHOLDER" as their transcription
and translation value.
"""
import sys
import json
from old_client import OLDClient
url = 'URL'
username = 'USERNAME'
password = 'PASSWORD'
c = OLDClient(url)
logged_in = c.login(username, password)
if not logged_in:
sys.exit('Could n | ot log in')
search = {
"query": {
"filter": ['and', [
['Form', 'transcription', '=', 'PLACEHOLDER'],
['Form', 'translations', 'transcription', '=', 'PLACEHOLDER']
]]
}
}
empty_forms = c.search | ('forms', search)
print 'Deleting %d forms.' % len(empty_forms)
deleted_count = 0
for form in empty_forms:
delete_path = 'forms/%d' % form['id']
resp = c.delete(delete_path)
if (type(resp) is not dict) or resp['id'] != form['id']:
print 'Failed to delete form %d' % form['id']
else:
dele... |
jackfirth/pyramda | pyramda/private/curry_spec/__init__.py | Python | mit | 242 | 0 | from .curry_spec import CurrySpec, ArgValues
from .arg_values_fulf | ill_curry_spec import arg_values_fulfill_curry_spec
from .make_func_curry_spec import make_func_curry_spec
from .remove_args_from_c | urry_spec import remove_args_from_curry_spec
|
unaguil/hyperion-ns2 | experiments/measures/generic/Overhead.py | Python | apache-2.0 | 1,273 | 0.01414 | import re
from measures.periodicValues.PeriodicValues import PeriodicValues
from measures.generic.GenericMeasure import GenericMeasure as GenericMeasure
import measures.generic.Units as Units
class Overhead(GenericMeasure):
def | __init__(self, period, simulationTime):
GenericMeasure.__init__(self, '', period, simulationTime, Units.MESSAGE_OVERHEAD)
self.__measures = []
self.__initializePattern = re.compile('INFO peer.BasicPeer - Peer ([0-9]+) initializing ([0-9]+\,[0-9]+).*?')
... |
def parseLine(self, line):
m = self.__initializePattern.match(line)
if m is not None:
self.__neighbors += 1
return
for measure in self.__measures:
measure.parseLine(line)
def getValues(self):
return PeriodicValues(0... |
gajim/python-nbxmpp | nbxmpp/modules/bookmarks/pep_bookmarks.py | Python | gpl-3.0 | 3,379 | 0 | # Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com>
#
# This file is part of nbxmpp.
#
# 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 your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY... | URPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; If not, see <http://www.gnu.org/licenses/>.
from nbxmpp.namespaces import Namespace
from nbxmpp.protocol import NodeProcessed
from nbxmpp.structs import Stanza... |
xenolog/fuel-utils | fuel_utils/fdb_cleaner/config.py | Python | apache-2.0 | 2,221 | 0.002251 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import eventlet
eventlet.monkey_patch()
import re
import sys
import errno
import logging
from settings i | mport LOG_NAME
class BaseAuthConfig(object):
"""
read auth config and store it.
Try be a singletone
"""
def __init__(self):
self._configs = {}
@staticmethod
def _read_config(cfg_file):
"""
Read OS auth config file
cfg_file -- the | path to config file
"""
auth_conf_errors = {
'OS_TENANT_NAME': 'Missing tenant name.',
'OS_USERNAME': 'Missing username.',
'OS_PASSWORD': 'Missing password.',
'OS_AUTH_URL': 'Missing API url.',
}
rv = {}
stripchars = " \'\""
... |
h4wkmoon/shinken | shinken/objects/timeperiod.py | Python | agpl-3.0 | 31,954 | 0.005195 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebe | l, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ... | URPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
# Calendar date
# -------------
# '(\d{4})-(\d{2})-(\d{2}) - (\d{4})-(\d{2})-(\d{2}) / (\d+) ([0-9:, -... |
kolanos/dialtone | dialtone/blueprints/message/__init__.py | Python | mit | 68 | 0 | from dialtone.blueprints.message | .views import bp as messa | ge # noqa
|
bverdu/onDemand | onDemand/plugins/iot/example/nest/base.py | Python | agpl-3.0 | 22,923 | 0.000305 | # encoding: utf-8
'''
Created on 18 août 2015
@author: Bertrand Verdu
'''
from collections import OrderedDict
from lxml import etree as et
from onDemand.plugins import Client
from onDemand.protocols.rest import Rest
from onDemand.plugins.nest.structure import Structure
from onDemand.plugins.nest.thermostat import Ther... | nce', val='/'.join((
self.path,
'SensorCollections',
str(self._structures.keys().index(p)), '')))
for p in self._structures]
if ad > 3:
| s = []
u = []
for key, structure in self._structures.iteritems():
i = 0
id_ = str(self._structures.keys().index(key))
s.append('/'.join((self.path,
'SensorCollections',
id_,
... |
patillacode/patilloid | app/patilloid.py | Python | gpl-3.0 | 565 | 0.00177 | import traceback
from f | lask import (
Blueprint,
current_app,
jsonify,
render_template,
)
bp = Blueprint('patilloid', __name__)
@bp.route('/', methods=('GET',))
def index():
try:
current_app.logger.info("Let's show them Patilloid!")
return render_template('patilloid.html')
except Exception as err:
... | ror": "Sorry, something bad happened with your request."}),
400,
)
|
the-packet-thrower/pynet | Week07/ex2_vlan.py | Python | gpl-3.0 | 3,369 | 0.002078 | #!/usr/bin/env python
'''
Using Arista's pyeapi, create a script that allows you to add a VLAN (both the
VLAN ID and the VLAN name). Your script should first check that the VLAN ID is
available and only add the VLAN if it doesn't already exist. Use VLAN IDs
between 100 and 999. You should be able to call the script ... |
'''
eapi_conn = pyeapi.connect_to("pynet-sw2")
# Argument parsing
parser = argparse.ArgumentParser(
description="Idempotent addition/removal of VLAN to Arista switch"
)
parser.add_argument("vlan_id", help="VLAN number to create or remove", action="store", type=int)
parser.add_argum... | emove the given VLAN ID", action="store_true")
cli_args = parser.parse_args()
vlan_id = cli_args.vlan_id
remove = cli_args.remove
vlan_name = cli_args.vlan_name
# Check if VLAN already exists
check_vlan = check_vlan_exists(eapi_conn, vlan_id)
# check if action is remove or add
if remo... |
z23han/Wrangling-MongoDB | Lesson_3_Problem_Set/03-Fixing_the_Area/area.py | Python | agpl-3.0 | 2,143 | 0.0056 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
In this pr | oblem set you work with cities infobox data, audit it, come up with a cleaning idea and then clean it up.
Since in the previous quiz you made a decision on which value to keep for the "areaLand" field,
you now know what has to be done.
Finish the function fix_area(). It will receive a string as an input, and | it has to return a float
representing the value of the area or None.
You have to change the function fix_area. You can use extra functions if you like, but changes to process_file
will not be taken into account.
The rest of the code is just an example on how this function can be used.
"""
import codecs
import csv
impo... |
mathLab/RBniCS | rbnics/utils/io/performance_table.py | Python | lgpl-3.0 | 12,306 | 0.003169 | # Copyright (C) 2015-2022 by the RBniCS authors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
import os
import sys
import collections
from numpy import exp, isnan, log, max, mean, min, nan, zeros as Content
from rbnics.utils.io.csv_io import CSVIO
from rbnics.utils.io.folders import F... | )])
# Then fill in with postprocessed data
for column in columns:
for operation in self._columns_operations[column]:
# Set header
if operation in ("min", "max"):
current_table_header = operation + "(" + column + ")"
... | + ")"
current_table_index = "gmean_" + column
else:
raise ValueError("Invalid operation in PerformanceTable")
table_index.append(current_table_index)
table_header[current_table_index] = current_table_header
... |
dagwieers/ansible | lib/ansible/modules/cloud/kubevirt/kubevirt_rs.py | Python | gpl-3.0 | 6,766 | 0.002513 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | gher wait_timeout value.")
if replicas and return_obj.status.readyReplicas != replicas:
self.fail_json(msg="Number of ready replicas is {0}. Failed to reach {1} ready replicas within "
"the wait_timeout period.".format(return_obj.status.ready_replicas, replicas))
... | eout')
replicas = self.params.get('replicas')
name = self.name
resource = self.find_supported_resource(KIND)
w, stream = self._create_stream(resource, namespace, wait_timeout)
return self._read_stream(resource, w, stream, name, replicas)
def execute_module(self):
# ... |
CenterForOpenScience/lookit-api | studies/migrations/0030_merge_20170827_1909.py | Python | apache-2.0 | 334 | 0 | # -*- coding: utf-8 - | *-
# Generated by Django 1.11.2 on 2017-08-27 23:09
from __future__ import unicode_literals
from django.db import migrations
class Migrat | ion(migrations.Migration):
dependencies = [
("studies", "0024_merge_20170823_1352"),
("studies", "0029_auto_20170825_1505"),
]
operations = []
|
vileopratama/vitech | src/addons/hw_escpos/escpos/printer.py | Python | mit | 6,802 | 0.007939 | #!/usr/bin/python
import usb.core
import usb.util
import serial
import socket
from escpos import *
from constants import *
from exceptions import *
from time import sleep
class Usb(Escpos):
""" Define USB printer """
def __init__(self, idVendor, idProduct, interface=0, in_ep=0x82, out_ep=0x01):
"""
... | e=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout, dsrdtr=True)
if self.device is not None:
print "Serial printer enabled"
else:
print "Unable to open serial printer on: %s" % self.devfile
def | _raw(self, msg):
""" Print any command sent in raw format """
self.device.write(msg)
def __del__(self):
""" Close Serial interface """
if self.device is not None:
self.device.close()
class Network(Escpos):
""" Define Network printer """
def __init__(self,ho... |
managedkaos/AWS-Python-Boto3 | s3/delete_contents.py | Python | mit | 599 | 0 | #!/usr/bin/env python
# a script to delete the contents of an s3 buckets
# import the sys and boto3 modules
import sys
import boto3
# create an s3 resource
s3 = boto3.resource('s3')
# iterate over the script arguments as bu | cket names
for bucket_name in sys.argv[1:]:
# use the bucket name to create a bucket object
bucket = s3.Bucket(bucket_name)
# delete the bucket's contents and print the res | ponse or error
for key in bucket.objects.all():
try:
response = key.delete()
print response
except Exception as error:
print error
|
sbelskie/symplicity | manage.py | Python | apache-2.0 | 253 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Symplicity.settings")
| from django.core.management import execute_from_command_line
execut | e_from_command_line(sys.argv)
|
jfallmann/bioconda-recipes | recipes/hops/hops.py | Python | mit | 2,649 | 0.001888 | #!/usr/bin/env python
#
# Wrapper script for Java Conda packages that ensures that the java runtime
# is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128).
#
#
# Program Parameters
#
import os
import... | f java_home and access(os.path.join(java_home, java_bin), X_OK):
return os.path.join(java_home, java_bin)
else:
return 'java'
def jvm_opts(argv):
"""Construct list of Java arguments based on our argument list.
The argument list passed in argv must not include the script name.
The retu... | of the form:
(memory_options, prop_options, passthrough_options)
"""
mem_opts = []
prop_opts = []
pass_args = []
for arg in argv:
if arg.startswith('-D'):
prop_opts.append(arg)
elif arg.startswith('-XX'):
prop_opts.append(arg)
elif arg.startswit... |
emkailu/PAT3DEM | bin/p3starscreen.py | Python | mit | 3,906 | 0.031234 | #!/usr/bin/env python
import os
import sys
import argparse
import pat3dem.star as p3s
def main():
progname = os.path.basename(sys.argv[0])
usage = progname + """ [options] <a star file>
Write two star files after screening by an item and a cutoff in the star file.
Write one star file after screening by a file con... | :
write_screen.write(''.join(header))
if | args.white == 0:
for line in lines:
skip = 0
for key in lines_sfile:
if key in line:
skip = 1
print 'Skip {}.'.format(key)
break
if skip == 0:
write_screen.write(line)
else:
for line in lines:
for key in lines_sfile:
if key in line:
print 'In... |
jtriley/gizmod | scripts/modules.d/510-LIRC-MceUSB2-MythTV.py | Python | apache-2.0 | 7,769 | 0.040674 | #***
#*********************************************************************
#*************************************************************************
#***
#*** GizmoDaemon Config Script
#*** LIRCMceUSB2 MythTV config
#***
#*****************************************
#*****************************************
... | UP)
return True
elif Event.Button == "Back":
Gizmod.Keyboards[0].createEvent(GizmoEventType | .EV_KEY, GizmoKey.KEY_ESC)
return True
elif Event.Button == "Up":
return False
elif Event.Button == "Skip":
Gizmod.Keyboards[0].createEvent(GizmoEventType.EV_KEY, GizmoKey.KEY_PAGEDOWN)
return True
elif Event.Button == "More":
Gizmod.Keyboards[0].createEvent(GizmoEventType.EV_KEY,... |
endlessm/chromium-browser | third_party/llvm/lldb/test/API/macosx/nslog/TestDarwinNSLogOutput.py | Python | bsd-3-clause | 5,655 | 0.001061 | """
Test DarwinLog "source include debug-level" functionality provided by the
StructuredDataDarwinLog plugin.
These tests are currently only supported when running against Darwin
targets.
"""
import lldb
import platform
import re
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lld... | self.skipTest("requires macOS 10. | 12 or higher")
self.do_test(
expect_regexes=[
re.compile(r"(This is a message from NSLog)"),
re.compile(r"Process \d+ exited with status")
],
settings_commands=[
"settings set target.env-vars "
"\"IDE_DISABLED_O... |
ravenbyron/phtevencoin | qa/rpc-tests/test_framework/socks5.py | Python | mit | 5,705 | 0.005784 | # Copyright (c) 2015 The Phtevencoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Dummy Socks5 server for testing.
'''
from __future__ import print_function, division, unicode_literals
import socket, threadin... | p, addr, port, username, password):
self.cmd = cmd # Command (one of Command.*)
self.atyp = atyp # Address type (one of AddressType.*)
self.addr = addr # Address
self.port = port # Port to connect to
self.username = username
self.password = password
def __repr__(self)... | d, self.atyp, self.addr, self.port, self.username, self.password)
class Socks5Connection(object):
def __init__(self, serv, conn, peer):
self.serv = serv
self.conn = conn
self.peer = peer
def handle(self):
'''
Handle socks5 request according to RFC1928
'''
... |
EDRN/PublicPortal | support/dropsies.py | Python | apache-2.0 | 703 | 0.007112 | #!/usr/bin/env py | thon
# encoding: utf-8
# Copyright 2010 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class DropHandler(BaseHTTPRequestHandler):
def dropRequest(self):
self.send_response(200)
self... | = do_TRACE = do_CONNECT = dropRequest
def main():
server = HTTPServer(('', 8989), DropHandler)
server.serve_forever()
if __name__ == '__main__':
main()
|
johngumb/danphone | junkbox/dm.py | Python | gpl-3.0 | 1,692 | 0.010047 | import sys
class DualModulusPrescaler:
def __init__(self,p):
self.m_p = p
return
def set_prescaler(self):
return
# may be internal
def set_a(self,a):
self.m_a = a
return
# may be internal
def set_n(self,n):
self.m_n = n
return
def ... | division_ratio(self):
v = (self.m_p * self.m_n) + self.m_a
return v
class Osc:
def __init__(self, ref_freq, prescaler):
self.m_ref = ref_freq
self.m_prescaler = prescaler
| return
def get_freq(self):
# print self.m_prescaler.get_division_ratio()
return (self.m_ref/self.m_prescaler.get_ref_divider()) * self.m_prescaler.get_division_ratio()
def calc_a(self):
return
def calc_n(self):
return
def get_counter_params(self,freq):
x = f... |
mail-apps/translate | translate/storage/fpo.py | Python | gpl-2.0 | 20,828 | 0.001776 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2002-2011 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# 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; e... | r):
list2[position] = item.decode("utf-8")
#Determine the newline sty | le of list2
lineend = ""
if list2 and list2[0]:
for candidate in ["\n", "\r", "\n\r"]:
if list2[0].endswith(candidate):
lineend = candidate
if not lineend:
lineend = ""
#Split if directed... |
bethgelab/foolbox | tests/test_plot.py | Python | mit | 1,086 | 0 | import pytest
import eagerpy as ep
import foolbox as fbn
def test_plot(dummy: ep.Tensor) -> None:
# just tests that the calls don't throw any errors
images = ep.zeros(dummy, (10, 3, 32, 32))
fbn.plot.images(images)
fbn.plot.images(images, n=3)
fbn.plot.images(images, n=3, data_format="channels_fir... | ols=4)
# test for single channel images
images = ep.zeros(dummy, (10, 32, 32, 1))
fbn.plot.images(images)
with pytest.raises(ValueError):
images = ep.zeros(dummy, (10, 3, 3, 3) | )
fbn.plot.images(images)
with pytest.raises(ValueError):
images = ep.zeros(dummy, (10, 1, 1, 1))
fbn.plot.images(images)
with pytest.raises(ValueError):
images = ep.zeros(dummy, (10, 32, 32))
fbn.plot.images(images)
with pytest.raises(ValueError):
images = ep... |
nagyistoce/devide | modules/vtk_basic/vtkFieldDataToAttributeDataFilter.py | Python | bsd-3-clause | 519 | 0.001927 | # class generated by DeVIDE::createDeVIDEModuleFro | mVTKObject
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk
class vtkFieldDataToAttributeDataFilter(SimpleVTKClassModuleBase):
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkFieldDataToAttributeDataFilter... | replaceDoc=True,
inputFunctions=None, outputFunctions=None)
|
zackp30/bugwarrior | bugwarrior/config.py | Python | gpl-3.0 | 5,298 | 0.000755 | import codecs
from ConfigParser import ConfigParser
import os
import subprocess
import sys
import six
import twiggy
from twiggy import log
from twiggy.levels import name2level
from xdg import BaseDirectory
def asbool(some_value):
""" Cast config values to boolean. """
return six.text_type(some_value).lower()... | = config.get(target, 'service')
if not service:
die("No 'service | ' in [%s]" % target)
if service not in SERVICES:
die("'%s' in [%s] is not a valid service." % (service, target))
# Call the service-specific validator
SERVICES[service].validate_config(config, target)
def load_config(main_section):
config = ConfigParser({'log.level': "DEBUG",... |
PythonScanClient/PyScanClient | scan/client/data.py | Python | epl-1.0 | 8,283 | 0.012435 | '''
Created on Mar 27,2015
@author: Yongxiang Qiu, Kay Kasemir
'''
try:
import xml.etree.cElementTree as ET
except:
import xml.etree.ElementTree as ET
from datetime import datetime
def getTimeSeries(data, name, convert='plain'):
'''Get values aligned by different types of time.
:param name: channel... |
:param devices: One or more devices
:param kwargs: with_id=True to add sample serial id,
with_time=True to add time (seconds since epoch)
:return: Table. result[0],result[1], .. hold the sample ID (if with_id),
the time (if wi... | id' in kwargs else False
with_time = kwargs['with_time'] if 'with_time' in kwargs else False
devsIters = [ alignSerial(data, dev) for dev in devices] # prepare devices iterators
cur_samps = [next(devIt) for devIt in devsIters] # initial devices iterators
result = [[] for dev in devices]
if... |
Telefonica/toolium-examples | android/tests/test_android.py | Python | apache-2.0 | 1,294 | 0.000774 | # -*- coding: utf-8 -*-
u"""
Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
This file is part of Toolium.
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/lic... | from nose.tools import assert_equal
from android.pageobjects.menu import MenuPageObject
from android.pageobjects.tabs import TabsPageObject
from android.test_cases import AndroidTestCase
class Tabs(AndroidTestCase):
def test_change_tab(self):
# Open tabs activity
MenuPageObject().open_option('Vie... | sert_equal('tab1', tabs_page.content1.text)
# Open second tab and check content
tabs_page.tab2.click()
assert_equal('tab2', tabs_page.content2.text)
|
mdboom/freetypy | docstrings/bitmap.py | Python | bsd-2-clause | 5,308 | 0 | # -*- 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... | y(bitmap)
"""
Bitmap_buffer = """
Get the bitmap's contents as a buffer.
In most cases, the preferred method to get the data is to cast the
`Bitmap` object to a memoryview, since that will also have size and
type information.
"""
Bitmap_convert = """
Convert a `Bitmap` to 8 bits per pixel. Given a `Bitmap` with dep... | depth 8bpp, making
the number of used bytes per line (a.k.a. the ‘pitch’) a multiple of
`alignment`.
Parameters
----------
alignment : int, optional
The pitch of the bitmap is a multiple of this parameter. Common
values are 1, 2, or 4.
Returns
-------
target : Bitmap
The bitmap, converted to 8bpp.
"""
Bi... |
Azure/azure-sdk-for-python | sdk/costmanagement/azure-mgmt-costmanagement/azure/mgmt/costmanagement/operations/_generate_reservation_details_report_operations.py | Python | mit | 15,195 | 0.005528 | # 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 ... | self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def _by_billing_account_id_initial(
self,
billing_account_id, # type: str
start_date, # type: str
end_date, # type: str
**kwargs # type: A... | ', None) # type: ClsType[Optional["_models.OperationStatus"]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2019-11-01"
accept = "application/json"
... |
skarbat/picute | piwebengine.py | Python | mit | 2,940 | 0.007143 | #!/usr/bin/env python
#
# Build QT5 webengine
#
import os
import sys
import xsysroot
if __name__ == '__main__':
# You want to be careful to enable a debug build. libQtWebengine.so takes 817MB :-)
debug_build=False
build_mode='release' if not debug_build else 'debug'
# We need a xsysroot profile wit... | oot.XSysroot(profile=xprofile)
except:
print 'You need to create a Xsysroot Picute profile'
print 'Please see the README file'
sys.exit(1)
# Locate Webengine source code directory
webengine_path=os.path.join(picute.query('tmp'), 'qt5/qtwebengine')
# | Apply temporary patch to build QT5.7 Webengine for the RPI
# https://bugreports.qt.io/browse/QTBUG-57037
if not os.path.isdir(webengine_path):
print '>>> Could not find Webengine path: {}'.format(webengine_path)
sys.exit(1)
else:
patch_file='gyp_run.pro'
print '>>> Ove... |
diamondman/proteusisc | test/test_functional.py | Python | lgpl-2.1 | 4,746 | 0.007585 | #-*- coding: utf-8 -*-
import struct
import pytest
from proteusisc.controllerManager import getDriverInstanceForDevice
from proteusisc.jtagScanChain import JTAGScanChain
from proteusisc.test_utils import FakeUSBDev, FakeDevHandle,\
MockPhysicalJTAGDevice, FakeXPCU1Handle
from proteusisc.bittypes import bitarray, N... | frame, but the frame state is not being tested
#here... just the results in the regs.
dev0 = MockPhysicalJTAGDevice(idcode=XC3S1200E_ID,
name="D0", status=bitarray('111100'))
dev1 = MockPhysicalJTAGDevice(idcode=XC3S1200E_ID,
name="D1", status=bitarray('111101'))
dev2 = MockPhys... | name="D2", status=bitarray('111110'))
usbdev = FakeUSBDev(FakeXPCU1Handle(dev0, dev1, dev2))
chain = JTAGScanChain(getDriverInstanceForDevice(usbdev))
d0, d1, d2 = get_XC3S1200E(chain), get_XC3S1200E(chain), \
get_XC3S1200E(chain)
chain._hasinit = True
chain._devices = [... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.