content stringlengths 4 20k |
|---|
def sv_main(obj_id=0, particle_sys=0):
in_sockets = [
['s', 'obj_id', obj_id],
['s', 'particle_sys', particle_sys]]
out_sockets = [
['v', 'locations', []]
]
objects = bpy.data.objects
if not obj_id < len(objects):
return in_sockets, out_sockets
obj = ob... |
"""
Unit tests for refactor.py.
"""
import sys
import os
import codecs
import io
import re
import tempfile
import shutil
import unittest
from lib2to3 import refactor, pygram, fixer_base
from lib2to3.pgen2 import token
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
FIXER_DIR = os.path.join(TEST_DATA... |
"""Train information for departures and delays, provided by Trafikverket."""
from datetime import date, datetime, timedelta
import logging
from pytrafikverket import TrafikverketTrain
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
... |
from navmazing import NavigateToSibling
from widgetastic.widget import Text
from widgetastic_patternfly import Button
from cfme.base import Server
from cfme.common import BaseLoggedInPage
from cfme.utils.appliance.implementations.ui import CFMENavigateStep
from cfme.utils.appliance.implementations.ui import navigator
... |
"""
logcat-color
Copyright 2012, Marshall Culpepper
Licensed under the Apache License, Version 2.0
Layouts for mapping logcat log data into a colorful terminal interface
"""
from colorama import Fore, Back, Style
from logcatcolor.column import *
from logcatcolor.format import Format
import re
from cStringIO import St... |
from openerp import models, fields, api
import openerp.addons.decimal_precision as dp
class DepositSlip(models.Model):
_name = 'deposit.slip'
_description = 'Deposit Slip'
_order = 'id desc'
_inherit = ['mail.thread']
_track = {
'state': {
'delivery_carrier_deposit.deposit_slip... |
"""
uWSGI
"""
import json
import logging
import re
from newrelic_python_agent.plugins import base
LOGGER = logging.getLogger(__name__)
class uWSGI(base.SocketStatsPlugin):
GUID = 'com.meetme.newrelic_uwsgi_agent'
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 1717
def add_datapoints(self, stats):
... |
#!/usr/bin/env python
"""
Reconstruction script that implements math algorithm of B0 mass reconstruction
Uses different models for fitting signal and background events
Usage: python reconstruction.py -i [INPUT_FILENAME] [-t [TREE_NAME]] [-n [MAX_EVENTS]] [-b] [-f] [-l] [-q] [-r] [-v]
Run python recons... |
from types import FunctionType, MethodType
from sqlalchemy import and_, or_
from sqlalchemy.ext.associationproxy import AssociationProxy
from sqlalchemy.sql.annotation import AnnotatedSelect
from sqlalchemy.sql.sqltypes import Text
from sqlalchemy.orm import RelationshipProperty
from database.types import ScalarSet
f... |
from odoo import api, fields, models, _
from odoo.exceptions import UserError
class IrFilters(models.Model):
_name = 'ir.filters'
_description = 'Filters'
_order = 'model_id, name, id desc'
name = fields.Char(string='Filter Name', translate=True, required=True)
user_id = fields.Many2one('res.user... |
"""Component for interacting with a Lutron RadioRA 2 system."""
import logging
from pylutron import Button, Lutron
import voluptuous as vol
from homeassistant.const import ATTR_ID, CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv
... |
"""Diagnostic functions, mainly for use when doing tech support."""
# Use of this source code is governed by the MIT license.
__license__ = "MIT"
import cProfile
from io import StringIO
from html.parser import HTMLParser
import bs4
from bs4 import BeautifulSoup, __version__
from bs4.builder import builder_registry
i... |
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
#os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
#from django.conf import settings
#settings.LANGUAGE_CODE = self.request.headers.get('Ac... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'GeoRecord.notes'
db.add_column('profiles_georecord', 'notes', self.gf('django.db.models.fi... |
#!/usr/bin/env python3
"""This is a test program for testing the code out on the host."""
import os
import struct
import sys
from bus import Bus, BusError
from log import log
class Scanner(object):
def __init__(self, bus):
self.bus = bus
self.ids = []
def dev_found(self, bus, dev_id):
... |
from .exceptions import (ItemNotFoundError, NoPathToItem)
def path_to_location(modulestore, usage_key):
'''
Try to find a course_id/chapter/section[/position] path to location in
modulestore. The courseware insists that the first level in the course is
chapter, but any kind of module can be a "sectio... |
from django.contrib.auth.models import User
from django.test.client import Client
from django.test import TestCase
from django.utils import simplejson as json
from codenode.frontend.bookshelf import views
from codenode.frontend.bookshelf.models import Folder
class TestBookshelf(TestCase):
def setUp(self):
... |
# -*- coding: utf-8 -*
#
# Test links:
# https://s.basketbuild.com/filedl/devs?dev=pacman&dl=pacman/falcon/RC-3/pac_falcon-RC-3-20141103.zip
# https://s.basketbuild.com/filedl/gapps?dl=gapps-gb-20110828-signed.zip
import re
from ..internal.SimpleHoster import SimpleHoster
class BasketbuildCom(SimpleHoster):
... |
from networking_mlnx._i18n import _, _LE, _LI
from oslo_log import log as logging
from networking_mlnx.eswitchd.common import constants
LOG = logging.getLogger(__name__)
class BasicMessageHandler(object):
MSG_ATTRS_MANDATORY_MAP = set()
def __init__(self, msg):
self.msg = msg
def execute(self)... |
import logging
import re
import os
import signal
from avocado.utils import path
from avocado.utils import process
from avocado.utils import linux_modules
from .versionable_class import VersionableClass, Manager, factory
from . import utils_misc
# Register to class manager.
man = Manager(__name__)
class ServiceMan... |
# -*- coding: utf-8 -*-
"""Riak result store backend."""
from __future__ import absolute_import, unicode_literals
import sys
from kombu.utils.url import _parse_url
from celery.exceptions import ImproperlyConfigured
from .base import KeyValueStoreBackend
try:
import riak
from riak import RiakClient
from... |
"""Cloud resource filter expression rewrite backend classes.
These classes are alternate resource_filter.Compile backends that rewrite
expressions instead of evaluating them. To rewrite a filter expression string:
rewriter = resource_expr_rewrite.Backend()
rewritten_expression_string = rewriter.Rewrite(filter_exp... |
# coding: utf-8
import numpy as np
from PIL import Image, ImageDraw
from math import sin,cos
from numpngw import write_apng
W,H = 1024,1024
COLOR_BLACK = (0x00, 0x00, 0x00, 0x00)
COLOR_WHITE = (0xF0, 0xF0, 0xE0)
COLOR_BLUE = (0x0D, 0x36, 0xFF)
COLOR_BLYNK = (0x2E, 0xFF, 0xB9)
COLOR_RED = (0xFF, 0x10, 0x... |
# -*- coding: utf-8 -*-
import mock
import pytest
from api.base.settings.defaults import API_BASE
from osf_tests.factories import (
AuthUserFactory,
)
from website.settings import MAILCHIMP_GENERAL_LIST, OSF_HELP_LIST
@pytest.fixture()
def user_one():
return AuthUserFactory()
@pytest.fixture()
def user_two()... |
import datetime
import os
import unittest
from airflow import settings
from airflow.models import DAG, TaskInstance as TI, XCom, clear_task_instances
from airflow.operators.dummy_operator import DummyOperator
from airflow.utils import timezone
from airflow.utils.session import create_session
from airflow.utils.state i... |
import dns
from oslo import messaging
from oslo.config import cfg
from designate import exceptions
from designate.openstack.common import log as logging
from designate.i18n import _LI
from designate.i18n import _LW
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
class NotifyEndpoint(object):
RPC_NOTIFY_API_VE... |
import bisect
import supriya.commands
from supriya.nonrealtime.bases import SessionObject
class Buffer(SessionObject):
"""
A non-realtime buffer.
"""
### CLASS VARIABLES ###
__documentation_section__ = "Session Objects"
__slots__ = (
"_buffer_group",
"_channel_count",
... |
from __future__ import print_function
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
from six.moves import range
pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
save = pickle.load(f)
train_dataset = save['train_dataset']
train_labels = save['train_labels']... |
import numpy as np
import cv2
import os
import math
import matplotlib.pyplot as plt
'''img = cv2.imread('Messi.jpg', -1)
cols, rows, channels = img.shape
#res = cv2.resize(img, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC)
#res = cv2.getRotationMatrix2D((col/2, row/2), 65, 1)
M = cv2.getRotationMatrix2D((cols... |
"""
Name types.
"""
#-------------------------------------------------------------------------
#
# Python modules
#
#-------------------------------------------------------------------------
from ..const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext
#------------------------------------------------... |
from django.utils.translation import gettext_lazy as _
from rest_framework import decorators, response
from rest_framework import serializers as rf_serializers
from rest_framework import status, viewsets
from waldur_core.core import exceptions as core_exceptions
from waldur_core.core import validators as core_validato... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
ErrorSummaryDialog
A QGIS plugin
Gestion de Plans d'Aménagement Général du Grand-Duché de Luxembourg
-------------------
begin :... |
"""
Code browser tools.
"""
import abc
from docutils import nodes
from flask import request
from .tool import Tool, Role, Directive
class CodeBrowser(Tool):
"""Abstract class for code browser tools."""
__metaclass__ = abc.ABCMeta
def __init__(self, project_name, ribbon=None):
self.project_name... |
"""A wait callback to allow psycopg2 cooperation with eventlet.
Use `make_psycopg_green()` to enable eventlet support in Psycopg.
"""
# Copyright (C) 2010 Daniele Varrazzo <<EMAIL>>
# and licensed under the MIT license:
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softwar... |
from mock import patch
import six
import unittest
import neutronclient.common.exceptions as q_cli_exceptions
from oslo_utils import uuidutils
from tricircle.network import helper
class FakeClient(object):
def __init__(self, region_name=None):
pass
def create_ports(self, context, body):
for ... |
# -*- coding: utf-8 -*-
# NOT SECURE, only an experiment, do NOT run this in production
def process_follow(status, settings):
return dict(follow=True, dm="Ok, now tell me... (simply DM me 'bye' so I'll unfollow)")
def process_dm(status, settings):
if status.direct_message.sender_screen_name != settings.user... |
#!/usr/bin/env python
__author__ = 'Jeremy B. Merrill'
__email__ = '<EMAIL>'
__license__ = 'Apache'
__version__ = '0.1'
from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Trajec... |
import maya.cmds as cmds
import os
import string
class UILabel:
"""
Wrapper class around UI labels and buttons. It allows us to define
a piece of UI once and use it across multiple UI elements.
"""
def __init__(self, label=None, annotation=None, image=None, command=None, command_pack... |
import socket, re
version = '1.0'
def dequote(str):
"""Will remove single or double quotes from the start and end of a string
and return the result."""
quotechars = "'\""
while len(str) and str[0] in quotechars:
str = str[1:]
while len(str) and str[-1] in quotechars:
str = str[0:-1... |
from seleniumbase import BaseCase
class MyTourClass(BaseCase):
def test_google_maps_tour(self):
self.open("https://www.google.com/maps/@42.3598616,-71.0912631,15z")
self.wait_for_element("#searchboxinput", timeout=20)
self.wait_for_element("#minimap", timeout=20)
self.wait_for_ele... |
RELEASE_LEVELS = [ALPHA, BETA, RELEASE_CANDIDATE, FINAL] = ['alpha', 'beta', 'candidate', 'final']
RELEASE_LEVELS_DISPLAY = {ALPHA: ALPHA,
BETA: BETA,
RELEASE_CANDIDATE: 'rc',
FINAL: ''}
# version_info format: (MAJOR, MINOR, MICRO, RELEASE_L... |
import numpy as np
import matplotlib.pyplot as plot
import time
import instrument
""" Capture data from a DSO1002A oscilloscope and plot it"""
def performMeasurement():
# start running
scope.write(":SINGLE")
while(True):
scope.write("*OPC?")
ans = scope.read(100).strip()
# print "\n\n *OPC? :" ,... |
from Tkinter import *
root = Tk()
# http://effbot.org/zone/tkinter-scrollbar-patterns.htm
#frame = Frame(root, bd=2, relief=SUNKEN)
frame = Frame(root)
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)
xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
xscrollbar.grid(row=1, column=0, stic... |
import pickle
import pprint
import sys
from argparse import ArgumentParser
from collections import Counter
from enum import IntEnum
class TraversalMode(IntEnum):
predecessors = 0
successors = 1
class TreeNode:
def __init__(self, char):
self.char = char
self.children = None
self.c... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Example of extensions template for inkscape
'''
import inkex # Required
import simplestyle # will be needed here for styles support
import os # here for alternative debug method only - so not usually required
# many other useful ones in exten... |
"""
util.py
=======
Utility functions
cluster, and calc_average are used for cluster calculations
conv_era returns era string
ceil_05 rounds up to nearest half-ton
ceil_5 rounds up to nearest five ton
gettext, get_child, and get_child_data are used for parsing xml
"""
import sys
from math import ceil
CLUSTER_TAB... |
import zipfile
import wordbridge.xmlparsing
import wordbridge.openxml
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge import styles
def convert_to_html(docx_file):
document_string = docx_file.read("word/document.xml")
tree = wordbridge.xmlparsing.parse_string... |
"""
I{Documint} error types.
"""
class XMLSyntaxError(Exception):
"""
Wrapper around L{lxml.etree.XMLSyntaxError} that requires no additional
arguments.
"""
class ExternalProcessError(RuntimeError):
"""
An external process returned an exit status indicating failure.
@type binary: C{str... |
#!/usr/bin/python
'''
Created on 04.03.2015
Copyright (C) 2015-2019 Kay Hannay
This file is part of efaLive.
efaLiveSetup 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 ... |
"""
Misc utils for deep internal usage of Python.
"""
import struct
def infer_int_pack(arg) -> str:
"""
Attempt to infer the correct struct format for an int.
:param arg: The integer argument to infer.
:return: A character for the struct string.
"""
# Short
if (-32768) <= arg <= 32767:
... |
"""Parent class and utility class for producing a scansion pattern for a line of Latin verse.
Some useful methods
* Perform a conservative i to j transformation
* Performs elisions
* Accents vowels by position
* Breaks the line into a list of syllables by calling a Syllabifier class which may be injected
into this cl... |
#!/usr/bin/env python
from __future__ import division
import abc
import logging
import numpy as np
import theano
import theano.tensor as T
from learning.dataset import DataSet
from learning.model import Model
from learning.monitor import Monitor
from learning.models.rws import f_replicate_batch, f_logsumexp
impo... |
"""
logan.runner
~~~~~~~~~~~~
:copyright: (c) 2012 David Cramer.
:license: Apache License 2.0, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
from django.core import management
from optparse import OptionParser
import os
import re
import sys
from logan import importer
from ... |
"""
Manipulating with dynamic libraries.
"""
import os.path
from PyInstaller.utils.win32 import winutils
__all__ = ['exclude_list', 'include_list', 'include_library']
import os
import re
from PyInstaller.compat import is_win, is_unix, is_aix, is_darwin
import PyInstaller.log as logging
logger = logging.getLog... |
from __future__ import absolute_import
from __future__ import print_function
import os
import migrate
import migrate.versioning.api
import sqlalchemy as sa
from twisted.internet import defer
from twisted.python import log
from buildbot.db import connector
from buildbot.test.fake import fakemaster
from buildbot.test... |
"""
Regional scale model of wave propogation and associated sediment transport.
Important:
The wave model is based on **Airy wave theory** and takes into account wave refraction based on
**Huygen's principle**.
Airy wave theory:
.. image:: img/airy.png
:scale: 90 %
:alt: airy wave theory
:align: cen... |
from Screen import Screen
from Screens.HelpMenu import HelpableScreen
from Screens.MessageBox import MessageBox
from Components.InputDevice import iInputDevices, iRcTypeControl
from Components.Sources.StaticText import StaticText
from Components.Sources.List import List
from Components.config import config, ConfigYesNo... |
from horizons.util.python import Const
from horizons.util.shapes import Shape
class Point(Shape):
def __init__(self, x, y):
self.x = x
self.y = y
def copy(self):
return Point(self.x, self.y)
def to_tuple(self):
"""Returns point as a tuple"""
return (self.x, self.y)
@property
def center(self):
"""R... |
from __future__ import division
import healpix
import numpy as np
from matplotlib import pyplot as plt
from numpy import pi
from cmb import as_matrix
import os
from nose import SkipTest
from nose.tools import eq_, ok_, assert_raises
from numpy.testing import assert_almost_equal
from numpy.linalg import norm
from cPic... |
""" Agador Metaservice
Usage:
agador [options]
Options:
-c --config URI # Service config URI
-d --debug # Run in debug mode
-h --host HOST # Host IP [default: 0.0.0.0]
-p --port PORT # Port no [default: 8500]
"""
import furi
from envopt import envopt
from f... |
from django.conf import settings
import django.core.exceptions
from django.http import HttpResponsePermanentRedirect
from django.utils import translation
# TODO importing undocumented function
from django.utils.translation.trans_real import parse_accept_lang_header
from localeurl import settings as localeurl_settings
f... |
QUOTE = "'"
def split_quoted(s):
"""Split a string with quotes, some possibly escaped, into a list of
alternating quoted and unquoted segments. Raises a ValueError if there are
unmatched quotes.
Both the first and last entry are unquoted, but might be empty, and
therefore the length of the resul... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Template.metadata'
db.add_column('popcorn_template', 'metadata',
self.... |
from rest_framework.metadata import SimpleMetadata
from collections import OrderedDict
from django.utils.encoding import force_text
from rest_framework import serializers
class ChoicesMetadata(SimpleMetadata):
def format_choices(self, items):
choices = OrderedDict()
choices['choices'] = [
... |
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
import copy
import hashlib
import logging
import re
from urllib.parse import parse_qs
from urllib.parse import urlparse
from svtplay_dl.error import ServiceError
from svtplay_dl.fetcher.dash import dashparse
from svtplay_dl.fetche... |
"""Information about mxnet."""
from __future__ import absolute_import
import os
import platform
import logging
def find_lib_path(prefix='libmxnet'):
"""Find MXNet dynamic library files.
Returns
-------
lib_path : list(string)
List of all found path to the libraries.
"""
lib_from_env =... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.parsing import DataLoader
class TaskResult:
'''
This class is responsible for interpretting the resulting data
from an executed task, and provides helper methods for determining
the result of a given t... |
"""Script to run benchmarks."""
import asyncio
import argparse
from contextlib import suppress
from datetime import datetime
import logging
from timeit import default_timer as timer
from homeassistant.const import (
EVENT_TIME_CHANGED, ATTR_NOW, EVENT_STATE_CHANGED)
from homeassistant import core
from homeassistan... |
import subprocess
import os
import json
import sys
import random
cli = sys.argv
"""
Utility script that creates GDesktop files for Wine and other window backed applications.
"""
def handleCli():
if cli[1] == 'get_process':
try:
process = subprocess.check_output('cat /proc/{}/cmdline'.format(c... |
from gi.repository import Gtk, GObject, GLib, Gdk, Gio
from gettext import gettext as _
from gnomepublisher import log
import logging
logger = logging.getLogger(__name__)
class GenericView(Gtk.Stack):
# __gsignals__ = {
# 'open-article': (GObject.SignalFlags.RUN_FIRST, None, (GObject.GObject,)),
# }
... |
import os
import sys
# Exported functions
class mzb_atom(str):
pass
def notify(metric, value):
_mzbench_pipe.write("M {{{0}, {1}}}.\n".format(_encode_metric(metric), value))
def get_metric_value(name):
return _call(mzb_atom('mzb_metrics'), mzb_atom('get_value'), [name])
def _call(module, function, a... |
# -*- coding: utf-8 -*-
"""
This module is a part fo OnlinePython project created at DTU
for the course Data Mining Using Python.
This module contains tests for the system.
Created on Sat Nov 29 21:08:36 2014
@author: Harri
"""
#Python modules
import os
import string
import random
import unittest
#Own modules
impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Point Cloud Widget
"""
__author__ = "Argentina Ortega Sainz"
__copyright__ = "Copyright (C) 2015 Argentina Ortega Sainz"
__license__ = "MIT"
__version__ = "2.0"
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QMimeData, Qt
from PyQt4.QtGui import... |
""" This module contains algorithms for the calculation of centrality, i.e. ranking nodes by their structural importance
to the network """
__author__ = "Christian Staudt"
__credits__ = ["Christian Staudt", "Elisabetta Bergamini", "Henning Meyerhenke", "Marc Nemes", "Maximilian Vogel"]
# extension imports
# TODO: (+... |
"""
Module containing all configuration functionality.
The supported schema for any lein configuraton file is as follows:
<task1>
description: <description> (optional | default: '')
command: <cmd1> (optional | default: [])
folder: <folder> (optional | default: CWD)
<task2>
description: <description>
command... |
__author__ = """unknown <unknown>"""
__docformat__ = 'plaintext'
# There are three ways to inject custom code here:
#
# - To set global configuration variables, create a file AppConfig.py.
# This will be imported in config.py, which in turn is imported in
# each generated class and in this file.
# - T... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <markdowncell>
# Challenge Description:
#
# Our marketing department has just negotiated a deal with several local merchants that will allow us to offer exclusive discounts on various products to our top customers every day. The catch is that we can only offer eac... |
#!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
readme = open('README.rst').read()
doclink = """
Documentation
-------------
The full... |
from __future__ import unicode_literals
import unittest
from scorched.strings import (RawString, WildcardString)
from scorched.search import LuceneQuery
class TestStrings(unittest.TestCase):
def test_string_escape(self):
""" Ensure that string characters are escaped correctly for Solr queries.
""... |
"""Tests for model_coverage_lib.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tempfile
import numpy as np
from tensorflow.lite.python import lite
from tensorflow.lite.testing.model_coverage import model_coverage_lib as model_cover... |
import numpy as np
def stetson_mean(x, weight=100., alpha=2., beta=2., tol=1.e-6, nmax=20):
"""An iteratively weighted mean used in the Stetson variability index"""
mu = np.median(x)
for i in range(nmax):
resid = x - mu
resid_err = np.abs(resid) * np.sqrt(weight)
weight1 = weight /... |
"""
Evaluation of Python code in |jedi| is based on three assumptions:
* The code uses as least side effects as possible. Jedi understands certain
list/tuple/set modifications, but there's no guarantee that Jedi detects
everything (list.append in different modules for example).
* No magic is being used:
- metac... |
# -*- coding: utf-8 -*-
'''
fasta.py
Read in FASTA files
'''
import re
import io
from typing import (
Dict,
List,
Tuple,
Union,
Generator
)
_fasta_re: str = r'>(.+)[\n\r]+((?:[^>\S]|[{}]+[\n\r]+)+)'
_ALPHABETS: Dict[str, str] = {
'DNA': r'ACGTWSMKRYBDHVN',
'RNA': r'ACGUWSMKRYBDHVN',
'A... |
import inspect
import keyword
import re
import black as blk
import click
import jinja2
from bmipy import Bmi
BMI_TEMPLATE = """# -*- coding: utf-8 -*-
{% if with_hints -%}
from typing import Tuple
{%- endif %}
from bmipy import Bmi
import numpy
class {{ name }}(Bmi):
{% for func in funcs %}
def {{ func }}{{ f... |
import sys
import unittest
class SetupOnceError(Exception):
def __init__(self, cause):
super(SetupOnceError, self).__init__('caused by ' + repr(cause))
self.cause = cause
class TeardownOnceError(Exception):
def __init__(self, cause):
super(TeardownOnceError, self).__init__('caused by ... |
# coding: utf-8
import asyncio
import csv
import logging
import os.path
from typing import (
Callable,
Dict,
List,
Optional,
Text,
Tuple,
Union,
)
import aionotify
from bernard.conf import (
settings,
)
logger = logging.getLogger('bernard.i18n.loaders')
TransDict = Dict[Optional[Tex... |
from __future__ import absolute_import, unicode_literals
from contextlib import contextmanager
from flask import current_app
from random import random
from time import sleep
class UnableToGetLock(Exception):
pass
@contextmanager
def lock(conn, lock_key, timeout=3, expire=None, nowait=False):
if expire is N... |
from builtins import object
import logging
logger = logging
class RPPATableConfig(object):
"""
Configuration class for a BigQuery table accessible through RPPA feature
definitions.
"""
def __init__(self, table_id, genomic_build, gene_label_field, value_field, internal_table_id, program):
... |
#!/usr/bin/env python
"""
a release-master multitool
"""
from __future__ import print_function, unicode_literals
import sys
from path import path
from git import Repo, Commit
from git.refs.symbolic import SymbolicReference
import argparse
from datetime import date, timedelta
from dateutil.parser import parse as parse_d... |
import re
import pytz
import datetime
from collections import defaultdict
import lxml.html
import scrapelib
from pupa.scrape import Scraper, Bill, VoteEvent
from .common import SESSION_TERMS, SESSION_SITE_IDS
motion_classifiers = {
'(Assembly|Senate)( substitute)? amendment': 'amendment',
'Report (passage|co... |
import flask
from oslo_log import log as logging
from designate.central import rpcapi as central_rpcapi
from designate import exceptions
from designate import objects
from designate import schema
from designate import utils
LOG = logging.getLogger(__name__)
blueprint = flask.Blueprint('records', __name__)
record_sch... |
import sys
sys.path = ['.', '..'] + sys.path
from db import DbTools
import re
import CONST
"""
Contains tools to page/scan through a video in the db
TODO - candidate algorithm to search text w/o a vid id
"""
def text_search( urlid, text ):
"""
returns a list of objects containing the matching caption and a ti... |
from __future__ import print_function
import re
import signal
import sys
from threading import Thread
import pychess
from pychess.compat import raw_input
from pychess.Players.PyChess import PyChess
from pychess.System import conf, fident
from pychess.Utils.book import getOpenings
from pychess.Utils.const import NORMA... |
import os
import datetime
from ..parameter_property import parameter_property
from ._parameters import (
Parameter, parameter_registry, UnutilisedDataWarning, ConstantParameter,
ConstantScenarioParameter, ConstantScenarioIndexParameter, AnnualHarmonicSeriesParameter,
ArrayIndexedParameter, ConstantScenarioP... |
import os
import json
import pandas
import numpy
from IPython.display import HTML
from datetime import datetime
import pandas_highcharts.core
title_name = 'Tasks'
file_name = 'tasks.csv'
css_dt_name = '//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css'
js_dt_name = '//cdn.datatables.net/1.10.12/js/jquery.data... |
from __future__ import unicode_literals
from django.contrib.auth.checks import (
check_models_permissions, check_user_model,
)
from django.contrib.auth.models import AbstractBaseUser
from django.core import checks
from django.db import models
from django.test import (
SimpleTestCase, override_settings, overrid... |
import praw
reddit = praw.Reddit('GETIN EVE Alliance:v0.1 (by /u/Celeodor)')
class OAuth:
def __init__(self, client_id, secret, authorize_url, callback_url, scope):
self.client_id = client_id
self.secret = secret
self.authorize_url = authorize_url
self.callback_url = callback_ur... |
from heat.common.i18n import _
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support
class ServerGroup(resource.Resource):
"""A resource for managing a Nova server group."""
support_status = support.SupportStatus(version='2014.... |
"""
cryptocurrency.py
A plugin that uses the CoinMarketCap JSON API to get values for cryptocurrencies.
Created By:
- Luke Rogers <https://github.com/lukeroge>
License:
GPL v3
"""
from collections import defaultdict
from datetime import datetime, timedelta
from operator import itemgetter
from threading impor... |
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.pyplot import cm
import numpy as np
from sklearn.cluster import KMeans
from sklearn.cluster import MiniBatchKMeans
import time
from scipy.sparse import csr_matrix
from scipy.optimize import nnls
from sklearn.preprocessing import norm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.