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 |
|---|---|---|---|---|---|---|---|---|
bjuvensjo/scripts | vang/bitbucket/has_branch.py | Python | apache-2.0 | 1,977 | 0 | #!/usr/bin/env python3
import argparse
from sys import argv
from vang.bitbucket.get_branches import get_branches
from vang.bitbucket.utils import get_repo_specs
def has_br | anch(repo_specs, branch):
for spec in repo_specs:
branches = [
b['displayId'] for spec, bs in get_branches((spec, ), branch)
for b in bs
]
yield spec, branch in branches
def main(branch,
only_has=True,
only_not_has=False,
dirs=None,
| repos=None,
projects=None):
specs = get_repo_specs(dirs, repos, projects)
for spec, has in has_branch(specs, branch):
if only_has:
if has:
print(f'{spec[0]}/{spec[1]}')
elif only_not_has:
if not has:
print(f'{spec[0]}/{spec[1]... |
madflow/qnap-radicale | shared/lib/daemon/pidfile.py | Python | gpl-2.0 | 2,139 | 0 | # -*- coding: utf-8 -*-
# daemon/pidfile.py
# Part of ‘python-daemon’, an implementation of PEP 3143.
#
# Copyright © 2008–2015 Ben Finney <[email protected]>
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Apache License, version 2.0 as published by the
#... | values.
:return: ``None``.
The `timeout` defaults to the value set during
initialisation with the `acquire_timeout` parameter. It is
passed to `PIDLockFile.acquire`; see that method for
| details.
"""
if timeout is None:
timeout = self.acquire_timeout
super(TimeoutPIDLockFile, self).acquire(timeout, *args, **kwargs)
# Local variables:
# coding: utf-8
# mode: python
# End:
# vim: fileencoding=utf-8 filetype=python :
|
SinnerSchraderMobileMirrors/django-cms | cms/test_utils/util/context_managers.py | Python | bsd-3-clause | 6,028 | 0.004147 | # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
from django.core.signals import request_started
from django.db import reset_queries
from django.template import context
from django.utils.translation import get_language, activate
from shutil import rmtree as _rmtree
from tem... | de, self).__init__('out', buffer)
class LanguageOverride(object):
def __init__(self, language):
self.newlang = language
def __enter__(self):
self.oldlang = get_language()
activate(self.newlang)
def __exit__(self, type, value, traceback):
act | ivate(self.oldlang)
class TemporaryDirectory:
"""Create and return a temporary directory. This has the same
behavior as mkdtemp but can be used as a context manager. For
example:
with TemporaryDirectory() as tmpdir:
...
Upon exiting the context, the directory and everthing cont... |
maxwelld90/searcher_simulations | configs/publications/cikm2015/scripts/user_summary_generator_cg.py | Python | gpl-2.0 | 13,051 | 0.009961 | import os
import sys
import fnmatch
serp_directory = '/Users/david/Dropbox/Shares/Vu-David/data/iiix_serp_results/'
serp_directory_files = [z for z in os.listdir(serp_directory) if os.path.isfile(os.path.join(serp_directory, z))]
def get_user_topic_queries(queries):
"""
Taking the queries data structure (gene... | the CG the searcher obtained (by marking).
"""
serp_filename = get_serp_file(queryid)
serp_fo = open(serp_filename, 'r')
cg_count = 0
for line in serp_fo:
if line.startswith('rank | '):
continue
line = line.strip().split(',')
marked = int(line[6])
trec_judgement = int(line[7])
if marked > 0:
cg_count += trec_judgement
serp_fo.close()
return cg_count
def generate_summary_file(query_details_file, per_query_stats_... |
tylerprete/evaluate-math | postfix.py | Python | mit | 792 | 0.001263 | import sys
from stack import Stack
def parse_expression_into_parts(expression):
"""
Parse expression into list of parts
:rtype : list
:param expression: str # i.e. "2 * 3 + ( 2 - 3 )"
"""
raise NotImplementedError("complete me!")
def evaluate_expression(a, b, op):
raise NotImplementedErr... | ts):
raise NotImplementedError("complete me!")
if __name__ == "__main__":
expr = None
if len(sys.argv) > 1:
expr = sys.argv[1]
parts = parse_expression_into_parts(expr)
print "Evaluating %s == %s" % (expr, evaluate_postfix(parts))
else:
print 'Usage: python postfix.py "... | stfix.py "9 1 3 + 2 * -"'
print "Spaces are required between every term."
|
pidydx/grr | grr/lib/builders/tests.py | Python | apache-2.0 | 196 | 0 | #!/u | sr/bin/env python
"""Test registry for builders."""
# These need to register plugins so, pylint: disable=unused-import
from grr.lib.builders import signing_test
# pylint: enab | le=unused-import
|
pygeo/geoval | geoval/polygon/__init__.py | Python | apache-2.0 | 23 | 0 | from . | polygon impo | rt *
|
DailyActie/Surrogate-Model | 01-codes/scikit-learn-master/sklearn/linear_model/tests/test_sgd.py | Python | mit | 44,262 | 0.000226 | import pickle
import unittest
import numpy as np
import scipy.sparse as sp
from sklearn import linear_model, datasets, metrics
from sklearn.base import clone
from sklearn.linear_model import SGDClassifier, SGDRegressor
from sklearn.preprocessing import LabelEncoder, scale, MinMaxScaler
from sklearn.utils.testing impor... | sification problem
X5 = np.array([[-2, -1], [-1, | -1], [-1, -2], [1, 1], [1, 2], [2, 1]])
Y5 = [1, 1, 1, 2, 2, 2]
true_result5 = [0, 1, 1]
# Classification Test Case
class CommonTest(object):
def factory(self, **kwargs):
if "random_state" not in kwargs:
kwargs["random_state"] = 42
return self.factory_class(**kwargs)
# a simple i... |
CenterForOpenScience/scinet | scinet/views.py | Python | mit | 4,696 | 0.005537 | import json
import os
from flask import request, g, render_template, make_response, jsonify, Response
from helpers.raw_endpoint import get_id, store_json_to_file
from helpers.groups import get_groups
from json_controller import JSONController
from main import app
from pymongo import MongoClient, errors
HERE = os.pat... | make_response(jsonify( { 'error': 'Page Not Found' } ), 404)
@app.errorhandler(405)
def method_not_allowed(error):
return make_resp | onse(jsonify( { 'error': 'Method Not Allowed' } ), 405) |
nuagenetworks/vspk-python | vspk/v6/nutestsuite.py | Python | bsd-3-clause | 12,813 | 0.009444 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyrigh... | """ Set last_updated_date value.
Notes:
Time stamp when this object was last updated.
| This attribute is named `lastUpdatedDate` in VSD API.
"""
self._last_updated_date = value
@property
def description(self):
""" Get description value.
Notes:
An operator given description of the Test Suite.
"""... |
planetarypy/pdsspect | pdsspect/pdsspect_image_set.py | Python | bsd-3-clause | 26,738 | 0.000037 | """The main model for all the views in pdsspect"""
import os
import warnings
import numpy as np
from astropy import units as astro_units
from ginga.util.dp import masktorgb
from planetaryimage import PDS3Image
from ginga.BaseImage import BaseImage
from ginga import colors as ginga_colors
from ginga.canvas.types.image ... | return self._wavelength.unit
@unit.setter
def unit(self, new_unit):
self._check_acceptable_unit(new_unit)
new_unit = astro_units.Unit(new_unit)
self._wavelength = self._wavelength.to(new_unit)
def _check_acceptable_unit(self, unit):
if unit not in self.accepted_units:
... | 'Unit mus be one of the following %s' % (
', '.join(self.accepted_units)
)
)
def get_wavelength(self):
""":class:`astropy.units.quantity.Quantity` Copy of the wavelength"""
return self._wavelength.copy()
class PDSSpectImageSet(object):
"""... |
valdergallo/raidmanager | manager/admin.py | Python | mit | 81 | 0 | # encoding: utf-8
fr | om django.contri | b import admin
# Register your models here.
|
molmod/tamkin | tamkin/pftools.py | Python | gpl-3.0 | 21,612 | 0.004164 | # -*- coding: utf-8 -*-
# TAMkin is a post-processing toolkit for normal mode analysis, thermochemistry
# and reaction kinetics.
# Copyright (C) 2008-2012 Toon Verstraelen <[email protected]>, An Ghysels
# <[email protected]> and Matthias Vandichel <[email protected]>
# Center for Molecular Modeling... | , temps):
"""
Arguments:
| ``pf`` -- A partition function
| ``temps`` -- An array with temperatures to consider.
The tables with energy, free energy, heat capacity, entropy, |
logarithm of the partition function and the first and second order
derivative of the logarithm of the partition functions are computed
and stored in self.tables. The latter attribute is a list of
ThermoTable objects.
The results can be written to a csv file with ... |
salivatears/ansible | lib/ansible/plugins/action/service.py | Python | gpl-3.0 | 2,322 | 0.003876 | # (c) 2015, Ansible Inc,
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is di... | TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=dict()):
''' handler for package operations '''
| name = self._task.args.get('name', None)
state = self._task.args.get('state', None)
module = self._task.args.get('use', 'auto')
if module == 'auto':
try:
module = self._templar.template('{{ansible_service_mgr}}')
except:
pass # co... |
respawner/peering-manager | peering/__init__.py | Python | apache-2.0 | 2,416 | 0.001656 | import json
import re
import subprocess
from django.conf import settings
default_app_config = "peering.apps.PeeringConfig"
def call_irr_as_set_resolver(irr_as_set, address_family=6):
"""
Call a subprocess to expand the given AS-SET for an IP version.
"""
prefixes = []
if not irr_as_set:
... | code is {}".format(process.returncode)
if err and err.strip():
error_log += ", stderr: {}".format(err)
raise ValueError(error_log)
prefixes. | extend([p for p in json.loads(out.decode())["prefix_list"]])
return prefixes
def parse_irr_as_set(asn, irr_as_set):
"""
Validate that an AS-SET is usable and split it into smaller part if it is actually
composed of several AS-SETs.
"""
as_sets = []
# Can't work with empty or whitespace o... |
BehavioralInsightsTeam/edx-platform | openedx/core/djangoapps/theming/checks.py | Python | agpl-3.0 | 2,784 | 0.001796 | """
Settings validations for the theming app
"""
import os
import six
from django.conf import settings
from django.core.checks import Error, Tags, register
@register(Tags.compatibility)
def check_comprehensive_theme_settings(app_configs, **kwargs):
"""
Checks the comprehensive theming theme directory settings... | Error(
"COMPREHENSIVE_THEME_DIRS must contain only strings.",
obj=theme_dirs,
id='openedx.core.djangoapps.theming.E005',
)
)
if not all([theme_dir.startswith("/") for theme_dir in theme_dirs]):
errors.appen... | dirs,
id='openedx.core.djangoapps.theming.E006',
)
)
if not all([os.path.isdir(theme_dir) for theme_dir in theme_dirs]):
errors.append(
Error(
"COMPREHENSIVE_THEME_DIRS must contain valid paths.",
... |
arrayfire/arrayfire-python | arrayfire/features.py | Python | bsd-3-clause | 2,480 | 0.002823 | #######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
######################################################... | .feat))
return out
def get_ypos(self):
"""
Returns the y-positions of the f | eatures detected.
"""
out = Array()
safe_call(backend.get().af_get_features_ypos(c_pointer(out.arr), self.feat))
return out
def get_score(self):
"""
Returns the scores of the features detected.
"""
out = Array()
safe_call(backend.get().af_get_... |
oblique-labs/pyVM | rpython/flowspace/test/test_checkgraph.py | Python | mit | 2,837 | 0.003525 | from rpython.flowspace.model import *
import py
def test_mingraph():
g = FunctionGraph("g", Block([]))
g.startblock.closeblock(Link([Constant(1)], g.returnblock))
checkgraph(g)
def template():
g = FunctionGraph("g", Block([]))
g.startblock.closeblock(Link([Constant(1)], g.returnblock))
checkgr... | v], g.returnblock))
py.test.raises(AssertionError, checkgraph, g)
def test_useundefinedvar():
v = Variable()
g = FunctionGraph("g", Block([]))
g.startblock.closeblock(Link([v], g.returnblock))
py.test.raises(AssertionError, checkgraph | , g)
v = Variable()
g = FunctionGraph("g", Block([]))
g.startblock.exitswitch = v
g.startblock.closeblock(Link([Constant(1)], g.returnblock))
py.test.raises(AssertionError, checkgraph, g)
def test_invalid_arg():
v = Variable()
g = FunctionGraph("g", Block([]))
g.startblock.operations.a... |
WeftWiki/phetools | hocr/hocr_cgi.py | Python | gpl-3.0 | 10,682 | 0.008706 | # -*- coding: utf-8 -*-
#
# @file hocr.py
#
# @remark Copyright 2014 Philippe Elie
# @remark Read the file COPYING
#
# @author Philippe Elie
import os
import sys
import json
sys.path.append(os.path.expanduser('~/phe/common'))
import serialize
sys.path.append(os.path.expanduser('~/phe/jobs'))
import sge_jobs
import co... | def span_anchor(anchor, table):
return '<span id="' + table + '_' + str(anchor) + '"></span>'
def a_anchor(anchor, table):
return '<a href="#' + table + '_' + str(anchor) + '">' + str(anchor) + '</a>'
def format_job_table_anchor(ancho | r):
return span_anchor(anchor, 'job') + a_anchor(anchor, 'acct')
def format_accounting_table_anchor(anchor):
return span_anchor(anchor, 'acct') + a_anchor(anchor, 'job')
def format_timestamp(timestamp, fields):
return time.strftime("%d/%m/%Y %H:%M:%S", time.gmtime(timestamp))
def format_sge_jobnumber_job... |
chrmoritz/zoxel | src/plugins/tool_extrude.py | Python | gpl-3.0 | 6,660 | 0.000601 | # tool_extrude.py
# Extrusion tool.
# Copyright (c) 2015, Lennart Riecken
#
# 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 versi... | AXIS:
tdx = dx
| if dx > 0:
tx = 1
elif dx < 0:
tx = -1
elif ax == self.api.mainwindow.display.Y_AXIS:
tdy = dx
if dx > 0:
ty = 1
elif dx < 0:
ty = -1
elif ax == self.api.mainwindow.display.Z_AXIS:
... |
almc/speed_reader | pyperclip.py | Python | gpl-2.0 | 5,763 | 0.004164 | # Pyperclip v1.4
# A cross-platform clipboard module for Python. (only handles plain text for now)
# By Al Sweigart [email protected]
# Usage:
# import pyperclip
# pyperclip.copy('The text to be copied to the clipboard.')
# spam = pyperclip.paste()
# On Mac, this module makes use of the pbcopy and pbpaste com... | th the os.
# On Linux, this module makes use of the xclip command, which should come with the os. | Otherwise run "sudo apt-get install xclip"
# Copyright (c) 2010, Albert Sweigart
# All rights reserved.
#
# BSD-style license:
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code mu... |
clone2727/mhkutil | stream.py | Python | gpl-3.0 | 3,692 | 0.026273 | # mhkutil - A utility for dealing with Mohawk archives
#
# mhkutil is the legal property of its developers, whose names
# can be found in the AUTHORS file distributed with this source
# distribution.
#
# mhkutil is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public Licen... | t your option) any later version.
#
# mhkutil is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITN | ESS 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 mhkutil. If not, see <http://www.gnu.org/licenses/>.
import os
import struct
# TODO: Find a better place for this
def makeTag(text):
if len(text) != ... |
agaldona/odoo-addons | stock_information_mrp_procurement_plan/models/stock_information.py | Python | agpl-3.0 | 8,497 | 0 | # -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api, _
import openerp.addons.decimal_precision as dp
class StockInformation(models.Model):
_inherit = 'stock.information'
@api.multi
def ... | self.ensure_one()
return {'name': _('Incoming procurements from plan'),
'view_type': 'form',
"view_mode": 'tree,form',
'res_model': 'procurement.order',
'type': 'ir.actions.act_window',
'domain': [('id', 'in',
... | ng_pending_procurements_pla |
WilliamQLiu/job-waffle | employer/admin.py | Python | apache-2.0 | 113 | 0 | f | rom django.contrib import admin
from .models import Job
# Register your models here.
admin.site.register(Job)
| |
fnp/wolnelektury | src/redirects/admin.py | Python | agpl-3.0 | 595 | 0 | from django.contrib import admin
from django.contrib.sites. | models import Site
from . import models
class RedirectAdmin(admin.ModelAdmin):
list_display = ['slug', 'url', 'counter', 'created_at', 'full_url']
readonly_fields = ['counter', 'created_at', 'full_url']
fields = ['slug', 'url', 'counter', 'created_at', 'full_url']
def full_url(self, obj):
if ... |
admin.site.register(models.Redirect, RedirectAdmin)
|
KECB/learn | computer_vision/01_inspecting_images.py | Python | mit | 412 | 0 | import numpy as np
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('images/dolphin.png', 0)
cv2.imshow("Dolphin Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print('The intensity value at row 50 & column 100 is : {}'.format(img[49, 99]))
|
print('Row 50 column values:')
print(img[49, :])
p | rint('Rows 101-103 & columns 201-203')
print(img[100:103, 200:203])
plt.plot(img[49, :])
plt.show()
|
DevCouch/coderbyte_python | medium/letter_count.py | Python | gpl-2.0 | 614 | 0.004886 | def LetterCount(str):
words = str.split(" ")
result_word = ""
letter_count = 0
for word in words:
word_map = {}
for ch in w | ord:
| if ch in word_map:
word_map[ch] += 1
else:
word_map[ch] = 1
max_key = max(word_map.iterkeys(), key=lambda k: word_map[k])
if letter_count < word_map[max_key] and word_map[max_key] > 1:
letter_count = word_map[max_key]
result_wor... |
vipmike007/avocado-vt | virttest/asset.py | Python | gpl-2.0 | 21,905 | 0.000228 | import urllib2
import logging
import os
import re
import string
import types
import glob
import ConfigParser
import StringIO
import commands
import shutil
from distutils import dir_util # virtualenv problem pylint: disable=E0611
from avocado.utils import process
from avocado.utils import genio
from avocado.utils impo... | dir = data_dir.get_test_providers_dir()
| for provider in glob.glob(os.path.join(provider_dir, '*.ini')):
provider_name = os.path.basename(provider).split('.')[0]
provider_info = get_test_provider_info(provider_name)
if backend is not None:
if backend in provider_info['backends']:
provider_name_list.appen... |
xgfone/snippet | snippet/example/python/circuit_breaker.py | Python | mit | 8,647 | 0.000347 | # -*- coding: utf8 -*-
from time import time
from threading import Lock
from functools import wraps
STATE_CLOSED = "closed"
STATE_OPEN = "open"
STATE_HALF_OPEN = "half-open"
def get_now():
return int(time())
class CircuitBreakerError(Exception):
pass
class TooManyRequestsError(CircuitBreakerError):
... | __
@wraps(wrapped)
def wrapper(*args, **kwargs):
return self.call(wrapped, *args, **kwargs)
CircuitBreakerMonitor.register(self)
return wrapper
def allow(self):
"""Checks if a new request can proceed.
It returns a callback that should be used to regist... | ()
return lambda ok: self._after_request(generation, ok)
def call(self, func, *args, **kwargs):
"""Run the given request if the CircuitBreaker accepts it.
It raises an error if the CircuitBreaker rejects the request.
Otherwise, it will return the result of the request.
If ... |
ifnull/hello-tracking | project/urls.py | Python | apache-2.0 | 482 | 0 | """URLs."""
from django.conf.urls import include, url
from django.contrib import admin
import apps.status.views
admin.autodiscover()
# Examples:
# url(r'^$', 'getting | started.views.home', name='home'),
# url(r'^blog/ | ', include('blog.urls')),
urlpatterns = [
url(r'^$', apps.status.views.index, name='index'),
url(r'^trackings/(?P<carrier_slug>[\w-]+)/(?P<tracking_number>[\w-]+)/$',
apps.status.views.trackings),
url(r'^admin/', include(admin.site.urls)),
]
|
tstenner/bleachbit | tests/TestCommon.py | Python | gpl-3.0 | 2,298 | 0.00087 | # vim: ts=4:sw=4:expandtab
# BleachBit
# Copyright (C) 2008-2020 Andrew Ziem
# https://www.bleachbit.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
# ... | abs_dir = os.path.expandvars(abs_dirs[os.name])
self.assertExists(abs_dir)
self.assertEqual(os.path.expanduser(abs_dir), abs_dir)
# A relative path (without a reference to the home directory)
# should not be expanded.
| self.assertEqual(os.path.expanduser('common'), 'common')
|
davidwilson-85/easymap | graphic_output/Pillow-4.2.1/Tests/test_file_cur.py | Python | gpl-3.0 | 1,063 | 0 | from helper import unittest, PillowTestCase
from PIL import Image, CurImagePlugin
TEST_FILE = "Tests/images/deerstalker.cur"
class TestFileCur(PillowTestCase):
def test_sanity(self):
im = Image.open(TEST_FILE)
self.assertEqual(im.size, (32, 32))
self.assertIsInstance(im, CurImagePlugi | n.CurImageFile)
# Check some pixel colors to ensure image is loaded properly
self.assertEqual(im.getpixel((10, 1)), (0, 0, 0, 0 | ))
self.assertEqual(im.getpixel((11, 1)), (253, 254, 254, 1))
self.assertEqual(im.getpixel((16, 16)), (84, 87, 86, 255))
def test_invalid_file(self):
invalid_file = "Tests/images/flower.jpg"
self.assertRaises(SyntaxError,
lambda: CurImagePlugin.CurImageFil... |
aheck/reflectrpc | tests/rpcsh-tests.py | Python | mit | 16,724 | 0.011182 | #!/usr/bin/env python3
from __future__ import unicode_literals
from builtins import bytes, dict, list, int, float, str
import os
import sys
import unittest
import pexpect
sys.path.append('..')
from reflectrpc.rpcsh import print_functions
from reflectrpc.rpcsh import split_exec_line
from reflectrpc.rpcsh import Ref... | }]}, 5, ['str1', 'str2', 5, 'str3']])
def test_rpcsh_compiles_and_runs(self):
python = sys.executable
exit_status = os.system("cd .. && %s rpcsh --help > /dev/null" % (python))
self.assertEqual(exit_status, 0)
def test_rpcsh_complete_function_names(self):
rpcsh = ReflectRpcShel... | t_anotherthing'},
{'name': 'echo'},
{'name': 'echoEcho'},
{'name': 'add'},
]
result = rpcsh.function_completion('', 'exec ')
self.assertEqual(result, ['get_something', 'get_anotherthing', 'echo', 'echoEcho', 'add'])
result = rpcsh.functio... |
GoogleCloudPlatform/gcpdiag | gcpdiag/lint/gke/err_2021_001_logging_perm.py | Python | apache-2.0 | 1,986 | 0.007049 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | led():
report.add_skipped(c, 'logging disabled')
else:
# Verify service-account permissions for every nodepool.
| for np in c.nodepools:
sa = np.service_account
if not iam.is_service_account_enabled(sa, context.project_id):
report.add_failed(np, f'service account disabled or deleted: {sa}')
elif not iam_policy.has_role_permissions(f'serviceAccount:{sa}', ROLE):
report.add_failed(np, f... |
kickstandproject/ripcord | ripcord/openstack/common/config/generator.py | Python | apache-2.0 | 8,281 | 0.000121 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 SINA Corporation
# 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.or... | is a list of (module, options) tuples
opts_by_group = {'DEFAULT': []}
for module_name in os.getenv(
"OSLO_CONFIG_GENERATOR_EXTRA_MODULES", "").split(','):
module = _import_module(module_name)
if module:
for group, opts in _list_ | opts(module):
opts_by_group.setdefault(group, []).append((module_name, opts))
for pkg_name in pkg_names:
mods = mods_by_pkg.get(pkg_name)
mods.sort()
for mod_str in mods:
if mod_str.endswith('.__init__'):
mod_str = mod_str[:mod_str.rfind(".")]
... |
vadimtk/chrome4sdp | build/android/pylib/remote/device/remote_device_gtest_run.py | Python | bsd-3-clause | 2,746 | 0.008012 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this sour | ce code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Run specific test on specific environment."""
import logging
import os
import tempfile
from pylib import constants
from pylib.base import base_test_result
from pylib.remote.device import remote_device_test_run
from pylib.remote.de... | s RemoteDeviceGtestTestRun(remote_device_test_run.RemoteDeviceTestRun):
"""Run gtests and uirobot tests on a remote device."""
DEFAULT_RUNNER_PACKAGE = (
'org.chromium.native_test.NativeTestInstrumentationTestRunner')
#override
def TestPackage(self):
return self._test_instance.suite
#override
d... |
abelectronicsuk/ABElectronics_Python_Libraries | IOPi/demos/demo_iopireadwrite.py | Python | gpl-2.0 | 2,479 | 0.000403 | #!/usr/bin/env python
"""
================================================
ABElectronics IO Pi | Digital I/O Read and Write Demo
Requires python smbus to be installed
For Python 2 install with: sudo apt-get install python-smbus
For Python 3 install with: sudo apt-get install python3-smbus
run with: python demo_iopire... | of bus 1 on the IO Pi board and sets
pin 1 of bus 2 to match.
The internal pull-up resistors are enabled so the input pin
will read as 1 unless the pin is connected to ground.
Initialise the IOPi device using the default addresses, you will need to
change the addresses if you have changed the jumpers on the IO Pi
"""
... | erals
import time
try:
from IOPi import IOPi
except ImportError:
print("Failed to import IOPi from python system path")
print("Importing from parent folder instead")
try:
import sys
sys.path.append("..")
from IOPi import IOPi
except ImportError:
raise ImportError(
... |
goldhand/product-purchase | config/settings/local.py | Python | bsd-3-clause | 2,534 | 0.001184 | # -*- coding: utf-8 -*-
'''
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
'''
import os
from .common import * # noqa
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool('DJANGO_DEB... | onthly": {
"stripe_plan_id": "pro-monthly",
"name": "Web App Pro ($24.99/month)",
"description": "The monthly subscription plan to WebApp",
"price": 2499, # $24.99
"currency": "usd",
"interval": "month"
},
"yearly": {
"stripe_plan_id": "pro-yearly",
... | Web App Pro ($199/year)",
"description": "The annual subscription plan to WebApp",
"price": 19900, # $199.00
"currency": "usd",
"interval": "year"
}
}
|
harshilasu/LinkurApp | y/google-cloud-sdk/platform/gcutil/lib/google_compute_engine/gcutil_lib/mock_api_types.py | Python | gpl-3.0 | 13,909 | 0.008412 | # Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | '{name} doesn\'t support validation'.format(
name=self.__class__.__nam | e__))
# pylint: disable=unused-argument
def ValidateString(self, method, path, value):
raise ValidationError(
'{name} doesn\'t support validation of a string value'.format(
name=self.__class__.__name__))
class AnyType(_ApiType):
"""Represents discovery type 'any'."""
__slots__ = tuple... |
sameerparekh/pants | tests/python/pants_test/backend/jvm/tasks/jvm_compile/java/test_apt_compile_integration.py | Python | apache-2.0 | 4,227 | 0.009936 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.util.cont... | """
# Demonstrate that the annotation processor is working
with self.do_test_compile(
'testprojects/src/java/org/pantsbuild/testproject/annotation/processorwithdep/main',
expected_files=['Main.class | ', 'Main_HelloWorld.class', 'Main_HelloWorld.java']) as found:
gen_file = self.get_only(found, 'Main_HelloWorld.java')
self.assertTrue(gen_file.endswith(
'org/pantsbuild/testproject/annotation/processorwithdep/main/Main_HelloWorld.java'),
msg='{} does not match'.format(gen_file))
# Try... |
rickyHong/Tensorflow_modi | tensorflow/python/kernel_tests/gather_op_test.py | Python | apache-2.0 | 2,641 | 0.012874 | """Tests for tensorflow.ops.tf.gather."""
import tensorflow.python.platform
import numpy as np
import tensorflow as tf
class GatherTest(tf.test.TestCase):
def testScalar1D(self):
with self.test_session():
params = tf.constant([0, 1, 2, 3, 7, 5])
indices = tf.constant(4)
gather_t = tf.gather(... | al([4, 3], gather_t.get_shape())
def testHigherRank(self):
np.random.seed(1)
shape = (4, 3, 2)
params = np.random.randn(*shape)
indices = np.random.randint(shape[0], size=15).reshape(3, 5)
with self.test_session():
tf_params = tf.constant(params)
| tf_indices = tf.constant(indices)
gather = tf.gather(tf_params, tf_indices)
self.assertAllEqual(params[indices], gather.eval())
self.assertEqual(indices.shape + params.shape[1:], gather.get_shape())
# Test gradients
gather_grad = np.random.randn(*gather.get_shape().as_list())
pa... |
achedeuzot/django-envconf | envconf/__init__.py | Python | mit | 131 | 0 | # -*- coding: utf-8 | -*-
from __future__ import unicode_literals
from .envconf import *
from .path import *
__version__ = '0.3.5' | |
psachin/swift | swift/common/manager.py | Python | apache-2.0 | 26,766 | 0.000037 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | * disks, can get high
def setup_env():
"""Try to increase resource limits of the OS. Mov | e PYTHON_EGG_CACHE to /tmp
"""
try:
resource.setrlimit(resource.RLIMIT_NOFILE,
(MAX_DESCRIPTORS, MAX_DESCRIPTORS))
except ValueError:
print(_("WARNING: Unable to modify file descriptor limit. "
"Running as non-root?"))
try:
resource.se... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/eggs/docutils-0.7-py2.7.egg/docutils/statemachine.py | Python | gpl-3.0 | 56,989 | 0.000544 | # $Id: statemachine.py 6314 2010-04-26 10:04:17Z milde $
# Author: David Goodger <[email protected]>
# Copyright: This module has been placed in the public domain.
"""
A finite state machine specialized for regular-expression-based text filters,
this module defines the following classes:
- `StateMachine`, a state ma... | n
`State.initial_transitions`::
initial_transitions = ['atransition', ...]
c) Define a method for each transition, with the same name as the
transition pattern::
def atransition(self, match, context, next_state):
# do something
result = [...] # a list
... | cut processing short.
d) You may wish to override the `State.bof()` and/or `State.eof()` implicit
transition methods, which handle the beginning- and end-of-file.
e) In order to handle nested processing, you may wish to override the
attributes `State.nested_sm` and/or `State.nested_sm_kwargs`.
... |
jokerdino/unity-tweak-tool | UnityTweakTool/section/appearance.py | Python | gpl-3.0 | 5,247 | 0.019821 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Team:
# J Phani Mahesh <[email protected]>
# Barneedhar (jokerdino) <[email protected]>
# Amith KK <[email protected]>
# Georgi Karavasilev <[email protected]>
# Sam Tran <[email protected]>
# Sam Hewitt <[email protected]>
# Angel Ar... | radio_right])
# Pass in the id of restore defaults button to enable it.
Fonts.enable_restore('b_theme_font_reset')
WindowControls.enable_restore('b_window_control_reset')
# Each page must be added using add_page
Appearance.add_page(Fonts)
# XXX : Disabled since the implementation is inadequate
# Appearance. | add_page(WindowControls)
themesettings=HandlerObject(SpaghettiThemeSettings(Appearance.builder))
Appearance.add_page(themesettings)
# After all pages are added, the section needs to be registered to start listening for events
Appearance.register()
|
Yegorov/http-prompt | http_prompt/execution.py | Python | mit | 11,589 | 0 | import re
import click
import six
from httpie.context import Environment
from httpie.core import main as httpie_main
from parsimonious.exceptions import ParseError, VisitationError
from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor
from six import BytesIO
from six.moves.urllib.parse i... | , children):
path = node.text
self.context_override.url = urljoin2(self.context_override.url, path)
return node
def visit_cd(self, node, children):
_, _, _, path, _ = chi | ldren
self.context_override.url = urljoin2(self.context_override.url, path)
return node
def visit_rm(self, node, children):
children = children[0]
kind = children[3].text
if kind == '*':
# Clear context
for target in [self.context.headers,
... |
BernardFW/bernard | src/bernard/misc/start_project/files/src/__project_name_snake__/states.py | Python | agpl-3.0 | 1,539 | 0 | # coding: utf-8
from bernard import (
layers as lyr,
)
from bernard.analytics import (
page_view,
)
from bernard.engine import (
BaseState,
)
from bernard.i18n import (
translate as t,
)
class __project_name_camel__State(BaseState):
"""
Root class for __project_name_readable__.
Here you m... | this page using | the analytics provider set in the configuration. If there
is no analytics provider, nothing special will happen and the handler
will be called as usual.
"""
@page_view('/bot/hello')
async def handle(self):
self.send(lyr.Text(t.HELLO))
|
andrasmaroy/pconf | tests/test_env.py | Python | mit | 9,384 | 0.000639 | from mock import MagicMock, mock_open, patch
from unittest import TestCase
from warnings import simplefilter
import pconf
from pconf.store.env import Env
TEST_ENV_BASE_VARS = {
"env__var": "result",
"env__var_2": "second_result",
}
TEST_ENV_MATCHED_VARS = {"matched_var": "match"}
TEST_ENV_WHITELIST_VARS = {"... | r=TEST_SEPARATOR, parse_values=TEST_PARSE_VALUES)
except AttributeError:
self.fail("Parsing environment variables raised AttributeError")
result = env_store.get()
self.assertEqual(result, TEST_SEPARATED_VARS)
self.assertIsInstance(result, dict)
@patch("pconf.store.env.o... | ew=MagicMock())
@patch(MOCK_OPEN_FUNCTION, mock_open(read_data=TEST_DOCKER_SECRE |
rolandwz/pymisc | utrader/strategy/bollingTrader.py | Python | mit | 2,348 | 0.032794 | # -* | - coding: utf-8 -*-
import datetime, time, csv, os
from utils.db import SqliteDB
from utils.rwlogging import log
from utils.rwlogging import strategyLogger as logs
from trader import Trader
from indicator import ma, macd, bolling, rsi, kdj
from strategy.pool import StrategyPool
highest = 0
def runStrategy(prices):
l... | ollingTrade(pool, prices, ps, 12, 2.4)
#pool.showStrategies()
#return
for i in range(2, 40):
j = 0
log.debug(i)
while j <= 5:
doBollingTrade(pool, prices, ps, i, j)
j += 0.1
pool.showStrategies()
def doBollingTrade(pool, prices, ps, period, deviate):
global highest
sname = 'BOLLING_' + str(per... |
JoeGermuska/agate | agate/data_types/__init__.py | Python | mit | 3,646 | 0.000274 | #!/usr/bin/env python
"""
This module contains the :class:`.DataType` class and its subclasses. These
types define how data should be converted during the creation of a
:class:`.Table`.
A :class:`TypeTester` class is also included which be used to infer data
types from column data.
"""
from copy import copy
from ag... | ray of
column types.
:param rows:
The data as a sequence of any seque | nces: tuples, lists, etc.
"""
num_columns = len(column_names)
hypotheses = [set(self._possible_types) for i in range(num_columns)]
force_indices = [column_names.index(name) for name in self._force.keys()]
if self._limit:
sample_rows = rows[:self._limit]
elif... |
rhyolight/nupic.research | projects/thing_classification/l2l4l6_experiment.py | Python | gpl-3.0 | 8,785 | 0.006716 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2018, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | s()[iteration]
# Select sensations to infer
np.random.shuffle(sensations[0])
sensations = [sensations[0][:self.numOfSensations]]
self.network.sendReset()
# Collect all statistics for every inference.
# See L246aNetwork._updateInfer | enceStats
stats = defaultdict(list)
self.network.infer(sensations=sensations, stats=stats, objname=objname)
stats.update({"name": objname})
return stats
def plotAccuracy(suite, name):
"""
Plots classification accuracy
"""
path = suite.cfgparser.get(name, "path")
path = os.path.join(path, na... |
SohKai/ChronoLogger | web/flask/lib/python2.7/site-packages/sqlalchemy/util/_collections.py | Python | mit | 25,079 | 0.001156 | # util/_collections.py
# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Collection classes and helpers."""
import sys
import itertools
import weakref... | try:
self._list.append(key)
| except AttributeError:
# work around Python pickle loads() with
# dict subclass (seems to ignore __setstate__?)
self._list = [key]
dict.__setitem__(self, key, object)
def __delitem__(self, key):
dict.__delitem__(self, key)
self._list.... |
pankajp/pysmoke | pysmoke/tests/test_marshal.py | Python | mit | 987 | 0.005066 | from __future__ import print_function, absolute_import
import random
import unittest
from pysmoke impor | t marshal
from pysmoke.smoke import ffi, Type, TypedValue, pystring, smokec, not_implemented, charp, dbg
from pysmoke import QtCore, QtGui
qtcore = QtCore.__binding__
qtgui | = QtGui.__binding__
class MarshalTestCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_qstring(self):
qstr = marshal.QString.from_py('aqstring')
print(qstr)
pstr = marshal.QString.to_py(qstr)
#dbg()
self.assertEqual(... |
btbuxton/python-pomodoro | research/multi_recv.py | Python | mit | 864 | 0.002315 | #http://pymotw.com/2/socket/multicast.html
import socket
import struct
import sys
multicast_group = '224.3.29.71'
server_address = ('', 10000)
# Create the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind to the server address
sock.bind(server_address)
# Tell the operating system to add the soc... | /respond loop
while True:
print >>sys.stderr, '\nwaiting to receive message'
data, address = sock.recvfrom(1024)
print >>sys.stderr, 'received %s bytes from %s' % (len(data), a | ddress)
print >>sys.stderr, data
print >>sys.stderr, 'sending acknowledgement to', address
sock.sendto('ack', address)
|
verityrise/Canine_Analysis | integrate_genome.py | Python | epl-1.0 | 753 | 0.01992 | #!/usr/bin/python
'''
This programs is to integrate dog reference genome from chr to a single one.
Author: Hongzhi Luo
'''
import gzip
import glob
import shutil
path='/vlsci/LSC0007/shared/canine_alport_syndrome/ref_files/'
#path=''
prefix='cfa_ref_CanFam3.1'
def integrate_genome():
'''
@param: num: chr1...ch... | s:
#cat_together.append(f)
#for files in cat_together:
outfile=gzip.open(path+prefix+".fa.gz",'wb')
for f in files:
gfile=gzip.open(f)
outfile.write(gfile.read())
gfile.close()
outfile.close()
if __name__ == '__main__':
integra | te_genome() |
mwreuter/arcade | experimental/a_quick_test5.py | Python | mit | 4,042 | 0.000247 | """
This example uses OpenGL via Pyglet and draws
a bunch of rectangles on the screen.
"""
import random
import time
import pyglet.gl as GL
import pyglet
import ctypes
# Set up the constants
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
RECT_WIDTH = 50
RECT_HEIGHT = 50
class Shape():
def __init__(self):
self.... | glTranslatef(shape.x, shape.y, 0)
GL.glDrawArrays(GL.GL_QUADS, i * 8, 8)
# GL.glDrawArrays(GL.GL_QUADS,
# 0,
# self.rect_vbo.size)
elapsed = time.time() - start
print(elapsed)
def main():
window = pyglet.window.Window(SCREEN_WIDTH, SCREEN_HE... | window.clear()
app.on_draw()
pyglet.app.run()
main()
|
catapult-project/catapult | third_party/gsutil/gslib/vendored/boto/boto/cloudformation/stack.py | Python | bsd-3-clause | 14,230 | 0.001195 | from datetime import datetime
from boto.resultset import ResultSet
class Stack(object):
def __init__(self, connection=None):
self.connection = connection
self.creation_time = None
self.description = None
self.disable_rollback = None
self.notification_arns = []
self... | \"" % (self.key, self.value)
class Capability(object):
def __init__(self, connection=None):
self.connection = None
self.value = Non | e
def startElement(self, name, attrs, connection):
return None
def endElement(self, name, value, connection):
self.value = value
def __repr__(self):
return "Capability:\"%s\ |
CALlanoR/virtual_environments | web/api_rest/mini_facebook/python_users_relationships_service_api_llano/manual_tests/consumer.py | Python | apache-2.0 | 1,939 | 0.009799 | import json
import datetime
import http.client
from time import time
########################################################################################################################
##################################################### ENVIRONMENTS #####################################################
########... | 1/friends", headers=headers)
#Friends of the friends of a person
#conn.request("GET", "/persons/0/mayYouKnow", headers=headers)
#Add a new relationship
conn.request("POST", "/persons/person1/3/person2/4", headers=headers)
#Delete a relationship
# conn.request | ("POST", "/persons/delete/person1/3/person2/4", headers=headers)
start = datetime.datetime.now()
res = conn.getresponse()
end = datetime.datetime.now()
data = res.read()
elapsed = end - start
print(data.decode("utf-8"))
print("\"" + str(res.status) + "\"")
print("\"" + str(res.reason) + "\"")
print("\"elapsed sec... |
cmutel/pandarus | tests/test_maps.py | Python | bsd-3-clause | 3,212 | 0.001868 | from pandarus.maps import Map, DuplicateFieldID
from rtree import Rtree
import fiona
import os
import pandarus
import pytest
dirpath = os.path.abspath(os.path.join(os.path.dirname(__file__), "data"))
grid = os.path.join(dirpath, "grid.geojson")
duplicates = os.path.join(dirpath, "duplicates.geojson")
raster = os.path... | 0, 1.0), (2.0, 1.0), (2.0, 0.0), (1.0, 0.0)]]
},
'properties': {'name': 'grid cell 2'},
'id': '2',
| 'type': 'Feature'
}
assert m[2] == expected
assert hasattr(m, "_index_map")
@pytest.mark.skipif('TRAVIS' in os.environ,
reason="No GPKG driver in Travis")
def test_getitem_geopackage():
print("Supported Fiona drivers:")
print(fiona.supported_drivers)
m = Map(countri... |
wdbm/datavision | datavision_examples_histograms_1.py | Python | gpl-3.0 | 1,130 | 0.040708 | #!/usr/bin/env python
import numpy
import datavision
def main():
print("\ngenerate two arrays of data")
a = numpy.random.normal(2, 2, size = 120)
b = numpy.random.normal(2, 2, size = 120)
print("\narray 1:\n{array_1}\n\narray 2:\n{array_2}".format(
array_1 = a,
array_2 = b
))
... | = "",
title = "comparison of a and b",
filename = filename
)
if __name__ == "__main_ | _":
main()
|
dajohnso/cfme_tests | cfme/containers/template.py | Python | gpl-2.0 | 3,341 | 0.001497 | # -*- coding: utf-8 -*-
import random
import itertools
from functools import partial
from navmazing import NavigateToAttribute, NavigateToSibling
from widgetastic_manageiq import Table
from cfme.base.ui import BaseLoggedInPage
from cfme.common import SummaryMixin, Taggable
from cfme.containers.provider import L | abelable
from cfme.fixtures import pytest_selenium as sel
from cfme.web_ui import toolbar as tb, match_location,\
PagedTable, CheckboxTable
from .provider import details_page
from utils.appliance import Navigatable
from utils.appliance.implementations.ui import navigator, CFMENavigateSte | p,\
navigate_to
list_tbl = CheckboxTable(table_locator="//div[@id='list_grid']//table")
paged_tbl = PagedTable(table_locator="//div[@id='list_grid']//table")
match_page = partial(match_location, controller='container_templates', title='Container Templates')
class Template(Taggable, Labelable, SummaryMixin, Nav... |
nicfit/eyed3 | tests/test_jsonyaml_plugin.py | Python | gpl-2.0 | 1,938 | 0.001032 | import os
import sys
import stat
from eyed3 import main, version
from . import RedirectStdStreams
def _initTag(afile):
afile.initTag()
afile.tag.artist = "Bad Religion"
afile.tag.title = "Suffer"
afile.tag.album = "Suffer"
afile.tag.release_date = "1988"
afile.tag.recording_date = "1987"
a... | % dict(path=audio_file.path, version=version,
size_bytes=size_bytes)
def testJsonPlugin(audiofile):
_initTag(audiofile)
_assertFormat("json", audiofile, """
{
"path": "%(path)s",
" | info": {
"time_secs": 10.68,
"size_bytes": %(size_bytes)d
},
"album": "Suffer",
"artist": "Bad Religion",
"best_release_date": "1988",
"recording_date": "1987",
"release_date": "1988",
"title": "Suffer",
"track_num": {
"count": 9,
"total": 15
},
"_eyeD3": "%(version)s"
}
""")
def t... |
bittner/django-allauth | allauth/socialaccount/providers/jupyterhub/tests.py | Python | mit | 614 | 0 | from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase
from .provider import JupyterHubProv | ider
class JupyterHubTests(OAuth2TestsMixin, TestCase):
provider_id = JupyterHubProvider.id
def get_mocked_response(self):
return MockedResponse(200, """
{
"kind": "u | ser",
"name": "abc",
"admin": false,
"groups": [],
"server": null,
"pending": null,
"created": "2016-12-06T18:30:50.297567Z",
"last_activity": "2017-02-07T17:29:36.470236Z",
"servers": null}
""")
|
VanceKingSaxbeA/MarketsEngine | engine.py | Python | mit | 3,899 | 0.020518 | /*Owner & Copyrights: Vance King Saxbe. A.*/""" Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxb... | time = markettime[lisj[2].replace('"','')]
mktime = mtime.split("-")
i | f mktime[1] < mktime[0]:
righto = mktime[1].split(":")
close = str(str(int(righto[0])+24)+":"+righto[1])
else:
close ... |
bregmanstudio/cseparate | cseparate.py | Python | mit | 2,850 | 0.04386 | import numpy as np
from bregman.suite import *
from cjade import cjade
from scipy.optimize import curve_fit
from numpy.linalg.linalg import svd
def cseparate(x, M=None, N=4096, H =1024, W=4096, max_iter=200, pre_emphasis=True, magnitude_only=False, svd_only=False, transpose_spectrum=False):
"""
complex-valued freque... | Phi_hat, usewin=True)
x_hat = []
for k in np.arange(M):
if svd_only:
AS = np.dot(A[:,k][:,np.newaxis],S[k,:][np.newaxis,:]).T
else:
AS = np.array(A[:,k]*S[k,:]). | T
if transpose_spectrum:
AS = AS.T
X_hat = np.absolute(AS)
if pre_emphasis:
#X_hat = (XX.T / (w)).T
X_hat = (XX.T * pre_func(xx,*popt)).T
Phi_hat = phs_rec(AS, F.dphi)
x_hat.append(F.inverse(X_hat=X_hat, Phi_hat=Phi_hat, usewin=True))
return x_hat, x_hat_all
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractJstranslationBlogspotCom.py | Python | bsd-3-clause | 564 | 0.033688 |
def extractJstranslationBlogspotCom(item):
'''
Parser for 'jstr | anslation.blogspot.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 | '),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
SymbiFlow/python-fpga-interchange | tests/example_netlist.py | Python | isc | 13,854 | 0.000289 | #/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
""" This file uses the fpga_interchange to crea... | d_site_instance(site_name='IOB_X0Y24', site_type='IOB33')
clk_buf_placement = Placement(
cell_type='BUFG',
cell_name='clk_buf',
site='BUFGCTRL_X0Y0',
| bel='BUFG')
clk_buf_placement.add_bel_pin_to_cell_pin(bel_pin='I0', cell_pin='I')
clk_buf_placement.add_bel_pin_to_cell_pin(bel_pin='O', cell_pin='O')
phys_netlist.add_placement(clk_buf_placement)
phys_netlist.add_site_instance(site_name='BUFGCTRL_X0Y0', site_type='BUFG')
ff_placement = Placement... |
tomasjames/citsciportal | app/agentex/migrations/0004_lastlogins.py | Python | gpl-3.0 | 591 | 0.001692 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('agentex', '0003_auto_20150622_1101'),
]
operations = [
migrations.CreateModel(
name='LastLogins',
fi... | d', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_leng | th=255)),
('slug', models.SlugField(unique=True)),
],
),
]
|
dims/heat | heat/engine/clients/os/glance.py | Python | apache-2.0 | 4,221 | 0 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle | ss required by applicable law or agreed to in writing, software
# distributed under the License is distributed | on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from glanceclient import client as gc
from glanceclient import exc
from glanceclient.openstack.common.apiclient... |
EmbeditElectronics/Python_for_PSoC | API_Python/setup.py | Python | mit | 3,289 | 0.057464 | #!/usr/bin/env python
#from distutils.core import setup
from setuptools import setup
import subprocess
import os
import platform
import re
def get_pi_version():
pi_versions = {
"0002" : "Model B Revision 1.0",
"0003" : "Model B Revision 1.0",
"0004" : "Model B Revision 2.0",
"0005" : "Model B Revision 2.0", ... | ART",
"Model A": "UART",
"Model B Revision 2.0": "UART",
"Model B+": "UART",
"Compute Module": "UART",
"Model A+": "UART",
"Pi 2 Model B": "UART",
"PiZero": "UART",
"Pi3 Model B" : "I2C",
"Unknown": "I2C",
"unresolved": "I2C"
}
plat = None
if platform.platform().... | e on linux... Is it a pi?
if os.uname()[4][:3] == 'arm': #probably a pi
plat = get_pi_version()
if plat is None: #oh no! Maybe another SBC?
plat = "unresolved"
if plat is None: #Likely on a PC of some sort...
DEPENDS_ON.append("pyserial==2.7")
elif ba... |
ilyanesterov/browser-csp-compatibility | utils/server.py | Python | mit | 4,620 | 0 | import os
import subprocess
import requests
import time
from urlparse import urlparse
from config import config
class Server(object):
"""
Simple helper to start/stop and interact with a tests server
TODO: add method to check what request has been send last by browser
might need this for connect-src ... | ess = address
self.port = port
self.logfile_name = config['server_log_f | ilename']
self.log = None
self.log_pointer = 0
def start(self):
"""
Starts test server with stdout and stderr output to /dev/null
"""
FNULL = open(os.devnull, 'w')
command_line = ['python', 'server/server.py']
self.process = subprocess.Popen(command_l... |
cloudviz/agentless-system-crawler | crawler/plugins/applications/apache/feature.py | Python | apache-2.0 | 1,135 | 0.000881 | from collections import namedtuple
def get_feature(stats):
feature_attributes = ApacheFeature(
stats['BusyWorkers'],
stats['IdleWorkers'],
stats['waiting_for_connection'],
stats['starting_up'],
stats['reading_request'],
stats['sending_reply'],
stats['keepali... | ],
stats['BytesPerSec'],
stats['BytesPerReq'],
stats['ReqPerSec'],
stats['Uptime'],
stats['Total_kBytes'],
stats['Total_Accesses']
)
return feature_attributes
ApacheFeature = namedtuple('ApacheFeature', [
'BusyWorkers',
'IdleWorkers',
'waiting_for_con... | ,
'logging',
'graceful_finishing',
'idle_worker_cleanup',
'BytesPerSec',
'BytesPerReq',
'ReqPerSec',
'Uptime',
'Total_kBytes',
'Total_Accesses'
])
|
urbn/kombu | kombu/connection.py | Python | bsd-3-clause | 38,239 | 0.000026 | """Client (Connection)."""
from __future__ import absolute_import, unicode_literals
import os
import socket
import sys
from collections import OrderedDict
from contextlib import contextmanager
from itertools import count, cycle
from operator import itemgetter
try:
from ssl import CERT_NONE
ssl_available = T... | t, 'ssl': ssl,
'transport': | transport, 'connect_timeout': connect_timeout,
'login_method': login_method, 'heartbeat': heartbeat
}
if hostname and not isinstance(hostname, string_t):
alt.extend(hostname)
hostname = alt[0]
params.update(hostname=hostname)
if hostname:
... |
bewiwi/sauna | sauna/scheduler.py | Python | bsd-2-clause | 3,120 | 0 | import time
import fractions
from functools import reduce
import logging
class Scheduler:
def __init__(self, jobs):
"""
Create a new Scheduler.
> | >> s = Scheduler([Job(1, max, 100, 200)])
>>> for jobs in s:
... time.sleep(s.tick_duration)
:param jobs: Sequence of jobs to schedule
"""
periodicities = {jo | b.periodicity for job in jobs}
self.tick_duration = reduce(lambda x, y: fractions.gcd(x, y),
periodicities)
self._ticks = self.find_minimum_ticks_required(self.tick_duration,
periodicities)
self._jobs = jo... |
alexey-grom/django-userflow | userflow/forms/signin.py | Python | mit | 2,222 | 0.00045 | # encoding: utf-8
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.core.exceptions import MultipleObjectsReturned
from django import forms
from django.utils.translation import ugettext_lazy as _
__all__ = ()
class SigninForm(forms.Form):
email = forms.EmailField(requir... | self.user_cache = self.check_user(**data)
except forms.ValidationError as e:
self.add_error('email', e)
return data
@proper | ty
def username_field(self):
model = get_user_model()
username_field = model.USERNAME_FIELD
return get_user_model()._meta.get_field(username_field)
def check_user(self, email=None, password=None, **kwargs):
credentials = {self.username_field.name: email,
'... |
portfoliome/postpy | postpy/pg_encodings.py | Python | mit | 627 | 0 | from encodings import normalize_encoding, aliases
from types import MappingProxyType
from psycopg2.extensions import encodings as _PG_ENCODING_MAP
PG_ENCODING_MAP = MappingP | roxyType(_PG_ENCODING_MAP)
# python to postgres encoding map
_PYTHON_ENCODING_MAP = {
v: k for k, v in PG_ENCODING_MAP.items()
}
def get_postgres_encoding(python_encoding: str) -> str:
"""Python to postgres encoding map."""
encoding = normalize_encoding(python_encoding.lower())
encoding_ = aliases | .aliases[encoding.replace('_', '', 1)].upper()
pg_encoding = PG_ENCODING_MAP[encoding_.replace('_', '')]
return pg_encoding
|
jlongever/redfish-client-python | on_http_redfish_1_0/models/power_1_0_0_power_supply.py | Python | apache-2.0 | 11,886 | 0.001599 | # coding: utf-8
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... | 'oem': 'Oem',
'power_supply_type': 'PowerSupplyType',
'redundancy': 'Redundancy',
'redundancyodata_count': '[email protected]',
'redundancyodata_navigation_link': '[email protected]',
'related_item': 'RelatedItem',
'related... | igation_link': '[email protected]',
'status': 'Status'
}
self._line_input_voltage_type = None
self._member_id = None
self._oem = None
self._power_supply_type = None
self._redundancy = None
self._redundancyodata_count = None
self... |
vgrem/Office365-REST-Python-Client | office365/communications/callrecords/call_record.py | Python | mit | 630 | 0.003175 | from office365.directory.identities.identity_set import IdentitySet
from office365.entity import Entity
class CallRecord(Entity):
"""Represents a single peer-to-p | eer call or a group call between multiple participants,
sometimes referred to as an online meeting."""
@property
def join_web_url(self):
"""Meeting URL associated to the call. May not be available fo | r a peerToPeer call record type."""
return self.properties.get("joinWebUrl", None)
@property
def organizer(self):
"""The organizing party's identity.."""
return self.properties.get("organizer", IdentitySet())
|
will-Do/avocado-vt | scripts/regression.py | Python | gpl-2.0 | 20,876 | 0.002299 | #!/usr/bin/python
"""
Program that parses standard format results,
compute and check regression bug.
:copyright: Red Hat 2011-2012
:author: Amos Kong <[email protected]>
"""
import os
import sys
import re
import commands
import warnings
import ConfigParser
import MySQLdb
def exec_sql(cmd, conf="../../global_config.i... | ger than 1!"
sys.exit(1)
self.desc = """<hr>Machine Inf | o:
o CPUs(%s * %s), Cores(%s), Threads(%s), Sockets(%s),
o NumaNodes(%s), Memory(%.1fG), NICs(%s)
o Disks(%s | %s)
Please check sysinfo directory in autotest result to get more details.
(eg: http://autotest-server.com/results/5057-autotest/host1/sysinfo/)
<hr>""" % (cpunum, cpumodel, corenum, threadnum, socketnum, num... |
nrz/ylikuutio | external/bullet3/examples/pybullet/gym/pybullet_envs/deep_mimic/env/humanoid_stable_pd.py | Python | agpl-3.0 | 42,338 | 0.010345 | from pybullet_utils import pd_controller_stable
from pybullet_envs.deep_mimic.env import humanoid_pose_interpolator
import math
import numpy as np
chest = 1
neck = 2
rightHip = 3
rightKnee = 4
rightAnkle = 5
rightShoulder = 6
rightElbow = 7
leftHip = 9
leftKnee = 10
leftAnkle = 11
leftShoulder = 12
leftElbow = 13
join... | 40, 40, 30, 50, 50, 50, 50, 50, 40, 40, 40, 40, 40, 40, 40, 40, 30
]
self._jointIndicesAll = [
chest, neck, rightHip, rightKnee, rightAnkle, rightShoulder, rightElbow, leftHip, leftKnee,
leftAnkle, | leftShoulder, leftElbow
]
for j in self._jointIndicesAll:
#self._pybullet_client.setJointMotorControlMultiDof(self._sim_model, j, self._pybullet_client.POSITION_CONTROL, force=[1,1,1])
self._pybullet_client.setJointMotorControl2(self._sim_model,
j,
... |
gr33ndata/rivellino | ruleset/__init__.py | Python | mit | 4,470 | 0.003803 | import os
import sys
import yaml
from etllib.conf import Conf
from etllib.yaml_helper import YAMLHelper
from plugins import PluginEngine
class RulesEngine(list):
def __init__(self):
self.rules_path = os.path.dirname(os.path.realpath(__file__))
self.conf = Conf()
self.load()
self.f... | .get_rule_by_name(subrule_name)
return self.apply_rule_ingress(subrule)[subrule_field]
else:
return action
elif isinstance(action, dict):
for key, val in action.iteritems():
action[key] = self.expand_action(val)
| return action
else:
return action
def apply_rule_ingress(self, rule):
ingress_plugin_name = rule['ingress_plugin']
ingress_plugin_runnable = self.pe[ingress_plugin_name].init(rule)
data = ingress_plugin_runnable.run(rule, None)
ingress_plugin_runnable... |
JonnyWong16/plexpy | lib/pyparsing/__init__.py | Python | gpl-3.0 | 9,095 | 0.001649 | # module pyparsing.py
#
# Copyright (c) 2003-2021 Paul T. McGuire
#
# 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, cop... | _string",
"srange",
"string_end",
"string_start",
"trace_parse_action",
"unicode_string",
"with_attribute",
"indentedBlock",
"original_text_for",
| "ungroup",
"infix_notation",
"locatedExpr",
"with_class",
"CloseMatch",
"token_map",
"pyparsing_common",
"pyparsing_unicode",
"unicode_set",
"condition_as_parse_action",
"pyparsing_test",
# pre-PEP8 compatibility names |
guaix-ucm/numina | numina/util/objimport.py | Python | gpl-3.0 | 1,031 | 0.00097 | #
# Copyright 2011-2019 Universidad Complutense de Madrid
#
# This file is part of Numina
#
# SPDX-License-Identifier: GPL-3.0+
# License-Filename: LICENSE.txt
#
"""Import objects by name"""
import importlib
import inspect |
import warnings
def imp | ort_object(path):
"""Import an object given its fully qualified name."""
spl = path.split('.')
if len(spl) == 1:
return importlib.import_module(path)
# avoid last part for the moment
cls = spl[-1]
mods = '.'.join(spl[:-1])
mm = importlib.import_module(mods)
# try to get the last... |
jskDr/jamespy_py3 | kmath.py | Python | mit | 3,201 | 0.000312 | # Python3
import numpy as np
import math
def nCr(n,r):
f = math.factorial
return f(n) // f(r) // f(n-r)
def long_to_int64_array(val, ln):
sz = ln / 64 + 1
ar = np.zeros(sz, dtype=int)
i64 = 2**64 - 1
for ii in range(sz):
ar[ii] = int(val & i64)
val = val >> 64
return ar
... |
It returns the number of elements which are equal to
the target value.
In order to resolve when x is an array with more than
one dimensions, converstion from array to list is used.
"""
if inverse is False:
x = np.where(np.array(a_l) == a)
else:
x = np.where(np.array(a_l) != ... | orr_kmlee_k(y, k):
ybar = np.mean(y)
N = len(y)
# print( N)
# cross_sum = np.zeros((N-k,1))
cross_sum = np.zeros(N - k)
# print( cross_sum.shape, N, k)
# Numerator, unscaled covariance
# [Matlab] for i = (k+1):N
for i in range(k, N):
# [Matlab] cross_sum(i) = (y(i)-ybar)*(y(... |
eapearson/eapearson_TestRichReports | test/eapearson_TestRichReports_server_test.py | Python | mit | 5,023 | 0.004181 | # -*- coding: utf-8 -*-
import unittest
import os # noqa: F401
import json # noqa: F401
import time
import requests
from os import environ
try:
from ConfigParser import ConfigParser # py2
except:
from configparser import ConfigParser # py3
from pprint import pprint # noqa: F401
from biokbase.workspace.c... | /Login',
data='token={}&fields=user_id'.format(token)).json()['user_id']
# WARNING: don't call any lo | gging methods on the context object,
# it'll result in a NoneType error
cls.ctx = MethodContext(None)
cls.ctx.update({'token': token,
'user_id': user_id,
'provenance': [
{'service': 'eapearson_TestRichReports',
... |
anntzer/scipy | scipy/special/utils/convert.py | Python | bsd-3-clause | 3,448 | 0.00058 | # This script is used to parse BOOST special function test data into something
# we can easily import in numpy.
import re
import os
# Where to put the data (directory will be created)
DATA_DIR = 'scipy/special/tests/data/boost'
# Where to pull out boost data
BOOST_SRC = "boostmath/test"
CXX_COMMENT = re.compile(r'^\s... | pile(r'[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?')
HEADER_REGEX = re.compile(
r'const boost::array\<boost::array\<.*, (\d+)\>, (\d+)\> ([a-zA-Z_\d]+)')
IGNORE_PATTERNS = [
| # Makes use of ldexp and casts
"hypergeometric_1F1_big_double_limited.ipp",
"hypergeometric_1F1_big_unsolved.ipp",
# Makes use of numeric_limits and ternary operator
"beta_small_data.ipp",
# Doesn't contain any data
"almost_equal.ipp",
# Derivatives functions don't exist
"bessel_y01_p... |
RobMcZag/python-algorithms3 | graph/tests/bfs_test.py | Python | apache-2.0 | 2,306 | 0.000434 | import unittest
import graph
class BreadthFirstSearchTest(unittest.TestCase):
__runSlowTests = False
def testTinyGraph(self):
g = graph.Graph.from_file('tinyG.txt')
bfs = graph.BreadthFirstSearch(g, 0)
self.assertEqual( | 7, bf | s.count())
self.assertFalse(bfs.connected(7))
self.assertIsNone(bfs.path_to(7))
self.assertFalse(bfs.connected(8))
self.assertIsNone(bfs.path_to(8))
self.assertFalse(bfs.connected(9))
self.assertIsNone(bfs.path_to(9))
self.assertFalse(bfs.connected(12))
s... |
danielfrg/datasciencebox | datasciencebox/cli/install.py | Python | apache-2.0 | 6,874 | 0.004946 | from __future__ import absolute_import
import click
from datasciencebox.cli.main import cli, default_options
@cli.group(short_help='Install packages, applications and more')
@click.pass_context
def install(ctx):
pass
@install.command('miniconda', short_help='Install miniconda in the instances')
@click.option(... | tep 3/4: Mesos')
out = p | roject.salt('state.sls', args=['mesos.cluster'], target='*', ssh=ssh)
click.echo(out)
click.echo('Step 4/4: Spark on Mesos')
out = project.salt('state.sls', args=['mesos.spark'], target='head', ssh=ssh)
click.echo(out)
@install.command('impala', short_help='Install Impala')
@click.option('--ssh', is_f... |
zhangwenyu/packages | volt/volt/openstack/common/sslutils.py | Python | apache-2.0 | 2,842 | 0 | # Copyright 2013 IBM Corp.
#
# | Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in complian | ce with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, ei... |
pombredanne/core-serializers | core_serializers/renderers.py | Python | bsd-2-clause | 2,026 | 0 | from jinja2 import Environment, PackageLoader
import json
env = Environment(loader=PackageLoader('core_serializers', 'templates'))
class FormRenderer:
template_name = 'form.html'
def render_field(self, field_result, **options):
field, value, error = field_result
class_name = field.__class__.... | base = 'textarea.html'
else:
base = 'input.html'
context = {'input_type': 'text'}
template_name = 'fields/' + layout + '/' + base
template = env.get_template(template_n | ame)
return template.render(field=field, value=value, **context)
def render(self, form, **options):
style = getattr(getattr(form, 'Meta', None), 'style', {})
layout = style.get('layout', 'vertical')
template = env.get_template(self.template_name)
return template.render(form=... |
2mv/raapija | last_transactions_parser.py | Python | isc | 884 | 0.015837 | import csv
import tempfile
import os
from transaction import Transaction
class LastTransactionsParser:
LAST_TRANSACTIONS_FILENAME = os.path.join(tempfile.gettempdir(), 'raapija_transactions_last.csv')
@staticmethod
def read():
try:
with open(LastTransactionsParser.LAST_TRANSACTIONS_FILENAME, 'r', e... | sParser.LAST_TRANSACTIONS_FILENAME, 'w', encoding='utf-8') as csvfile:
csv_fieldnames = transactions[0].__dict__.keys()
writer = csv.Dic | tWriter(csvfile, csv_fieldnames)
writer.writeheader()
for transaction in transactions:
writer.writerow(transaction.__dict__)
|
mprinc/McMap | src/scripts/CSN_Archive2/parse_csvn.py | Python | mit | 7,899 | 0.019243 | #!/usr/bin/env python
# Copyright (c) 2015, Scott D. Peckham
#------------------------------------------------------
# S.D. Peckham
# July 9, 2015
#
# Tool to break CSDMS Standard Variable Names into
# all of their component parts, then save results in
# various formats. (e.g. Turtle TTL format)
#
# Example of use at... | t('_')
root_quantity = quantity_parts[-1]
ro | ot_quan_string = " '" + root_quantity + "' "
root_quan_prefix = indent + "csn:root_quantity"
out_unit.write( root_quan_prefix + root_quan_string + ".\n" ) # (Notice "." vs. ";" here.)
out_unit.write( '\n' ) # (blank line)
root_quan_list.append( root_quantity ) # (save in root_quan_li... |
teoreteetik/api-snippets | client/response-twiml/response-twiml.5.x.py | Python | mit | 383 | 0 | from flask import Flask, Response
import twilio.twiml
app = Flask(__name__)
@app.route("/voice", methods=['POST'])
def get_voice_twiml():
"""Respond to incoming calls with a simple text mes | sage."""
resp = | twilio.twiml.Response()
resp.say("Thanks for calling!")
return Response(str(resp), mimetype='text/xml')
if __name__ == "__main__":
app.run(debug=True)
|
VinnieJohns/ggrc-core | src/ggrc_workflows/migrations/versions/20140715214934_26d9c9c91542_add_cycletaskgroupobject_object.py | Python | apache-2.0 | 1,141 | 0.006135 | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Add CycleTaskGroupObject.object
Revision ID: 26d9c9c91542
Revises: 19a67dc67c3
Create Date: 2014-07-15 21:49:34.073412
"""
# revision identifiers, used by Alembic.
revision = '26d9c9c91542'
down_revis... | sk_group_objects.object_id = task_group_objects.object_id,
cycle_task_group_objects.object_type = task_group_objects.object_type;
''')
def downgrade():
op.drop_column('cycle_task_group_objects', 'object_type') |
op.drop_column('cycle_task_group_objects', 'object_id')
|
linkinwong/word2vec | src/crf-paper-script/preprocessor6_ssr_rep_increase_5_scale.py | Python | apache-2.0 | 8,443 | 0.008923 | # coding: utf-8
__author__ = 'linlin'
import os
import logging
import re
import pdb
logger = logging.getLogger(__name__)
################################################################
root_dir = '/home/linlin/time/0903_classify_false_start/1003_raw_features/'
separator = '\t\t'
#####################################... | ' in filespath:
test_path = os.path.join(root, filespath)
#pdb.set_trace()
result_path = dest_path + '/' + 'result.txt'
os.system('crfsuite learn -e2 ' + train_path + " " + test_path + " > " + result_path )
def FindNeig | hborTokenSubscript(first_token_list, current_pos , up_or_down ):
pos = current_pos
ind = up_or_down
li = first_token_list
if ind == 1:
i = 1
while len(li[pos+i]) < 1:
i += 1
return pos+i
if ind == -1:
i = 1
while len(li[pos-i]) < 1:
i ... |
orangeduck/PyMark | tests/test3.py | Python | bsd-2-clause | 247 | 0 | import pymark
pets_mod = pymark.unpack_file("pets_two.pmk")
print "TypeID: %i" % | pets_mod["pets"]["catherine"]["typ | e"]
print "Name: %s" % pets_mod["pets"]["catherine"]["name"]
print "Color: (%i, %i, %i)" % pets_mod["pets"]["catherine"]["color"]
|
MungoRae/home-assistant | homeassistant/components/sensor/mvglive.py | Python | apache-2.0 | 6,071 | 0 | """
Support for real-time departure information for public transport in Munich.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.mvglive/
"""
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.confi... | ng,
vol.Optional(CONF_DESTINATIONS, default=['']): cv.ensure_list_csv,
vol.Optional(CONF_DIRECTIONS, default=['']): cv.ensure_list_csv,
vol.Optional(CONF_LINES, default=['']): cv.ensure_list_csv,
vol.Optional(CONF_PRODUCTS, default=DEFAULT_PRODUCT):
cv.ensure_list_csv,
... | EOFFSET, default=0): cv.positive_int,
vol.Optional(CONF_NAME): cv.string}]
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the MVGLive sensor."""
sensors = []
for nextdeparture in config.get(CONF_NEXT_DEPARTURE):
sensors.append(
MVGLiveSensor(
... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_language_tools/inspect_getsource_method.py | Python | apache-2.0 | 76 | 0 | import inspect
import examp | le
print(inspect.getsource(example.A | .get_name))
|
rsimba/cloudelements | tests/__init__.py | Python | mit | 197 | 0.010152 | '''
cloudelements: tests module.
Meant for use | with py.test.
Organize tests into files, each named xxx_test.py
Read more here: http:// | pytest.org/
Copyright 2015, LeadGenius
Licensed under MIT
''' |
IfcOpenShell/IfcOpenShell | src/ifcopenshell-python/ifcopenshell/api/profile/add_parameterized_profile.py | Python | lgpl-3.0 | 1,101 | 0 | # IfcOpenShell - IFC toolkit and geometry engine
# Copyright (C) 2021 Dion Moult <[email protected]>
#
# This file is part of IfcOpenShell.
#
# IfcOpenShell 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 Foundat... | nShell 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with IfcOpenShell. If not,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.