content stringlengths 4 20k |
|---|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from aubio import midi2note
import unittest
list_of_known_midis = (
( 0, 'C-1' ),
( 1, 'C#-1' ),
( 38, 'D2' ),
( 48, 'C3' ),
( 59, 'B3' ),
( 60, 'C4' ),
( 127, 'G9' ),
)
class midi2note_good_values(unittest... |
import sys
try:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.common.google import GoogleBaseError, QuotaExceededError, \
ResourceExistsError, ResourceNotFoundError
_ = Provider.GCE
except ImportError:
print("failed=True " + ... |
"""
=============================
Ledoit-Wolf vs OAS estimation
=============================
The usual covariance maximum likelihood estimate can be regularized
using shrinkage. Ledoit and Wolf proposed a close formula to compute
the asymptotically optimal shrinkage parameter (minimizing a MSE
criterion), yielding th... |
"""Unit test for the gtest_json_output module."""
import json
import os
import gtest_json_test_utils
import gtest_test_utils
GTEST_OUTPUT_SUBDIR = 'json_outfiles'
GTEST_OUTPUT_1_TEST = 'gtest_xml_outfile1_test_'
GTEST_OUTPUT_2_TEST = 'gtest_xml_outfile2_test_'
EXPECTED_1 = {
u'tests':
1,
u'failures':... |
# -*- coding: utf-8 -*-
"""
SQLpie License (MIT License)
Copyright (c) 2011-2016 André Lessa, http://sqlpie.com
See LICENSE file.
"""
import os, time
import sys
sys.path.append(os.getcwd())
from flask import Flask, current_app, g
from flask import jsonify
from flaskext.mysql import MySQL
import sqlpie
# load globa... |
"""Abstract class for AES."""
class AES(object):
def __init__(self, key, mode, IV, implementation):
if len(key) not in (16, 24, 32):
raise AssertionError()
if mode != 2:
raise AssertionError()
if len(IV) != 16:
raise AssertionError()
self.isBlockC... |
# -*- coding: utf-8 -*-
from openerp import http
from openerp.http import request
from openerp.addons.website.models.website import slug
class WebsiteDoc(http.Controller):
@http.route(['/forum/how-to', '/forum/how-to/<model("forum.documentation.toc"):toc>'], type='http', auth="public", website=True)
def toc... |
"""
MIT License
Copyright (c) 2017 Hajime Nakagami<<EMAIL>>
Copyright (c) 2019 Claude SIMON (https://q37.info/s/rmnmqd49)
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 restricti... |
# coding: utf-8
'''
read performance results of 2D cylinder flow, Re40
'''
import os
from matplotlib import pyplot
from parsePetIBMperformance import *
def plotOneCylinderFig(
caseNames, caseNameDict, events, timing, plotOrder, figName, save):
'''
Plot the figures for cylinder flow tests.
'''
... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from .dataObject import DatatypeProperty, ObjectProperty, Alias
from .muscle import Muscle
from .cell import Cell
from .biology import BiologyType
from .network import Network
from .worm_common import WORM_RDF_TYPE
class Worm(BiologyType):
""" A repr... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2010 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
# stdlib
import logging, logging.config, os
# SQLAlchemy
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import create_engine
# YAML
import... |
from __future__ import absolute_import
from datetime import datetime
from django.test import TestCase
from .models import Article, Person
class EarliestOrLatestTests(TestCase):
"""Tests for the earliest() and latest() objects methods"""
def tearDown(self):
"""Makes sure Article has a get_latest_by... |
import agents as ag
import envgui as gui
import random
# ______________________________________________________________________________
loc_A, loc_B = (1, 1), (2, 1) # The two locations for the Vacuum world
def RandomVacuumAgent():
"Randomly choose one of the actions from the vacuum environment."
p = ag.Ra... |
#copied from salt thanks
import sys,traceback,urllib2,re, urllib,xbmc, base64
import cookielib, urlparse
def _get_sucuri_cookie(html):
if 'sucuri_cloudproxy_js' in html:
match = re.search("S\s*=\s*'([^']+)", html)
if match:
s = base64.b64decode(match.group(1))
s = s.r... |
import subprocess
from datetime import datetime
from libcloud.storage.types import Provider, ContainerDoesNotExistError
from libcloud.storage.providers import get_driver
driver = get_driver(Provider.CLOUDFILES_US)('username', 'api key')
directory = '/home/some/path'
cmd = 'tar cvzpf - %s' % (directory)
object_name ... |
""" Testing mio5_utils Cython module
"""
from __future__ import division, print_function, absolute_import
import sys
from io import BytesIO
cStringIO = BytesIO
import numpy as np
from nose.tools import (assert_true, assert_equal, assert_raises)
from numpy.testing import (assert_array_equal)
from scipy._lib.six i... |
"""
Loads an autoencoder model, plots the latent space for the test set and the
plots sounds from a directory on top of that space, with arrows pointing to
each of the overlaid sounds. The arrows have labels that are the file names
of the sounds (without the extension).
"""
import argparse
import matplotlib.pyplot as p... |
import antlr3
import testbase
import unittest
class t005lexer(testbase.ANTLRTest):
def setUp(self):
self.compileGrammar()
def lexerClass(self, base):
class TLexer(base):
def emitErrorMessage(self, msg):
# report errors to /dev/null
p... |
import asyncio
import calendar
import datetime
import logging
from bson import objectid
from vj4 import app
from vj4 import constant
from vj4 import job
from vj4.handler import base
from vj4.model import builtin
from vj4.model import document
from vj4.model import domain
from vj4.model import record
from vj4.model imp... |
"""
main.py for esp8266 sensornode with dht11 & bh1750
read temp, humidity & luminosity, publish to mqtt
"""
try:
import time
START_MS = time.ticks_ms()
import gc
import machine
import ujson
from bh1750 import BH1750
from bme280 import BME280
from umqtt.robust import MQTTClient
de... |
from __future__ import absolute_import, division, unicode_literals
from xml.dom import Node
from ..constants import namespaces, voidElements, spaceCharacters
__all__ = ["DOCUMENT", "DOCTYPE", "TEXT", "ELEMENT", "COMMENT", "ENTITY", "UNKNOWN",
"TreeWalker", "NonRecursiveTreeWalker"]
DOCUMENT = Node.DOCUMEN... |
# -*- mode: python; fill-column: 100; comment-column: 100; -*-
import os
import sys
import unittest
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import base_test
from client.exceptions import InvalidCookieDomainException, UnableToSetCookieException
class CookieTest( base... |
# -*- 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):
# Deleting field 'Invoice.company_email'
db.delete_column('shoppingcart_invoice', 'company_email')
... |
import optparse
from telemetry import decorators
from telemetry.internal import story_runner
from telemetry.internal.util import command_line
from telemetry.page import page_test
from telemetry.web_perf import timeline_based_measurement
Disabled = decorators.Disabled
Enabled = decorators.Enabled
class InvalidOption... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'set_manager.ui'
#
# by: PyQt5 UI code generator 5.2.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObject... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import collections
from copy import deepcopy
from ansible.module_utils.basic import Ansible... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Product.upc'
db.alter_column(u'catalogue_product', 'up... |
from __future__ import unicode_literals
import os
import subprocess
import sickrage
from sickrage.notifiers import Notifiers
class synoIndexNotifier(Notifiers):
def __init__(self):
super(synoIndexNotifier, self).__init__()
self.name = 'synoindex'
def notify_snatch(self, ep_name):
pa... |
import os
import subprocess
from git_remote_helpers.util import check_call
def sanitize(rev, sep='\t'):
"""Converts a for-each-ref line to a name/value pair.
"""
splitrev = rev.split(sep)
branchval = splitrev[0]
branchname = splitrev[1].strip()
if branchname.startswith("refs/heads/"):
... |
# -*- coding: utf-8 -*-
"""SQLite parser plugin for Google Hangouts conversations database files."""
from dfdatetime import posix_time as dfdatetime_posix_time
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import definitions
from plaso.parsers import sqlite
from plaso.par... |
import sys
import six
from django.db import models
from django.core.exceptions import ImproperlyConfigured
from django import forms
from django.conf import settings
import warnings
try:
from keyczar import keyczar
except ImportError:
raise ImportError('Using an encrypted field requires the Keyczar module. '
... |
import contextlib
import mock
from oslo.config import cfg
from neutron.api.v2 import attributes
from neutron.common import test_lib
from neutron import context
from neutron.extensions import agent
from neutron.plugins.vmware.api_client import version
from neutron.plugins.vmware.common import sync
from neutron.tests.u... |
import os
import math
import xml.etree.ElementTree as ET
NS="{http://www.aldebaran-robotics.com/schema/choregraphe/position.xsd}"
def _makeJointDict(motors, use_radians = True):
pose = {}
for p in motors.findall(NS + "Motor"):
name = p.find(NS + 'name').text
value = float(p.find(NS + 'value').... |
import pytest
from indy_client.test.state_proof.helper import submit_operation_and_get_replies
from plenum.common.constants import TARGET_NYM, TXN_TYPE, RAW
from indy_common.constants import GET_ATTR
from indy_client.test.test_nym_attrib import \
addedRawAttribute, attributeName, attributeValue, attributeData
de... |
# -*- coding: utf-8 -*-
'''
Genesis Add-on
Copyright (C) 2015 lambda
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 ... |
import sqlite3 as sq
import os
import sys
import time
def getWindowsDrives():
import win32api
import win32file
drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
phys=[]
for d in drives:
if win32file.GetDriveType(d) == win32file.DRIVE_FIXED:
phys.... |
# -*- coding: utf-8 -*-
from gluon import current
def config(settings):
"""
Template settings for Turkmenistan
- designed to be used in a Cascade with an application template
"""
#T = current.T
# Pre-Populate
settings.base.prepopulate.append("locations/TM")
# Uncomment to re... |
"""
The :mod:`sklearn.decomposition` module includes matrix decomposition
algorithms, including among others PCA, NMF or ICA. Most of the algorithms of
this module can be regarded as dimensionality reduction techniques.
"""
from .nmf import NMF, ProjectedGradientNMF
from .pca import PCA, RandomizedPCA
from .incrementa... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat import unittest
from units.compat.mock import MagicMock
from ansible import constants as C
from ansible.plugins.action.gather_facts import ActionModule
from ansible.playbook.task import Task
from ansible.template... |
from ducktape.services.service import Service
from ducktape.mark import parametrize
from ducktape.mark import matrix
from kafkatest.tests.kafka_test import KafkaTest
from kafkatest.services.performance import ProducerPerformanceService, EndToEndLatencyService, ConsumerPerformanceService
TOPIC_REP_ONE = "topic-replic... |
from __future__ import unicode_literals
import os
from io import BytesIO, StringIO, UnsupportedOperation
from django.core.files.utils import FileProxyMixin
from django.utils import six
from django.utils.encoding import (
force_bytes, force_str, python_2_unicode_compatible, smart_text,
)
@python_2_unicode_compat... |
"""
A module that implements tooling to enable easy warnings about deprecations.
"""
from __future__ import absolute_import
import logging
import warnings
class PipDeprecationWarning(Warning):
pass
class Pending(object):
pass
class RemovedInPip10Warning(PipDeprecationWarning):
pass
class RemovedInP... |
"""Standalone script which parses a gtest log for json.
Json is returned returns as an array. This script is used by the libvpx
waterfall to gather json results mixed in with gtest logs. This is
dubious software engineering.
"""
import getopt
import json
import os
import re
import sys
def main():
if len(sys.arg... |
import sys
from contextlib import contextmanager
from functools import wraps
from io import StringIO
def _set_replaced_stream(name, replacement=None):
stream = getattr(sys, name)
def andBackAgain():
setattr(sys, name, stream)
streamReplacement = StringIO() if replacement is None else replacement
... |
"""Test script for poplib module."""
# Modified by Giampaolo Rodola' to give poplib.POP3 and poplib.POP3_SSL
# a real test suite
import poplib
import asyncore
import asynchat
import socket
import os
import time
import errno
from unittest import TestCase
from test import test_support
from test.test_support import HOS... |
from airflow.hooks.hive_hooks import HiveServer2Hook
from airflow.hooks.mysql_hook import MySqlHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from tempfile import NamedTemporaryFile
class HiveToMySqlTransfer(BaseOperator):
"""
Moves data from Hive to MySQL, n... |
#!/usr/bin/env python2
"""
This is the Japanese Novel Analyser.
It reads in novels from files in aozora formatting, strips this formatting,
invokes the mecab morphological analysis and counts word frequencies.
Then it stores them in a database for later use. Repeated invokations
add to the existing frequencies, unless... |
import argparse
import logging
import time
import mxnet as mx
import numpy as np
from get_data import get_movielens_iter, get_movielens_data
from model import matrix_fact_model_parallel_net
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser(description="Run model parallel version of matrix fac... |
__doc__ = """Defines a multi-dimensional array and useful procedures for Numerical computation.
Functions
- array - NumPy Array construction
- zeros - Return an array of all zeros
- empty - Return an unitialized array
- shape ... |
data = (
'cyess', # 0x00
'cyeng', # 0x01
'cyej', # 0x02
'cyec', # 0x03
'cyek', # 0x04
'cyet', # 0x05
'cyep', # 0x06
'cyeh', # 0x07
'co', # 0x08
'cog', # 0x09
'cogg', # 0x0a
'cogs', # 0x0b
'con', # 0x0c
'conj', # 0x0d
'conh', # 0x0e
'cod', # 0x0f
'col', # 0x10
'colg', ... |
from boto.mws.connection import MWSConnection, api_call_map, destructure_object
from boto.mws.response import (ResponseElement, GetFeedSubmissionListResult,
ResponseFactory)
from boto.exception import BotoServerError
from tests.compat import unittest
from tests.unit import AWSMockServic... |
# Wrapper for loading templates from eggs via pkg_resources.resource_string.
try:
from pkg_resources import resource_string
except ImportError:
resource_string = None
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from django.conf import settings
class Loa... |
"""Miscellaneous utility functions."""
import contextlib
import datetime
import errno
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
# UTC datetime corresponding to zero Unix timestamp.
EPOCH = datetime.datetime.utcfromtimestamp(0)
def parse_rfc3339_epoch(value):
"""... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
ExtractorError,
parse_iso8601,
qualities,
)
class SRGSSRIE(InfoExtractor):
_VALID_URL = r'(?:https?://tp\.srgssr\.ch/p(?:/[^/]+)... |
#!/usr/bin/env python
"""[License: GNU General Public License v3 (GPLv3)]
This file is part of FuMa.
FuMa 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 opti... |
from spack import *
class PyMemoryProfiler(PythonPackage):
"""A module for monitoring memory usage of a python program"""
homepage = "https://github.com/fabianp/memory_profiler"
url = "https://pypi.io/packages/source/m/memory_profiler/memory_profiler-0.47.tar.gz"
version('0.47', 'ed340aaaa0c711... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import difflib
import json
import sys
import warnings
from copy import deepcopy
from ansible import constants as C
from ansible.module_utils._text import to_text
from ansible.utils.color import stringc
from ansible.vars import str... |
""" Module to give helpful messages to the user that did not
compile the scikit properly.
"""
import os
INPLACE_MSG = """
It appears that you are importing a local scikit-learn source tree. For
this, you need to have an inplace install. Maybe you are in the source
directory and you need to try from another location.""... |
"""Inputs and Readers. See the @{$python/io_ops} guide.
@@placeholder
@@placeholder_with_default
@@sparse_placeholder
@@ReaderBase
@@TextLineReader
@@WholeFileReader
@@IdentityReader
@@TFRecordReader
@@FixedLengthRecordReader
@@decode_csv
@@decode_raw
@@VarLenFeature
@@FixedLenFeature
@@FixedLenSequenceFeature
@@Spars... |
import csv
from CiphersInfo.CipherInfo import CipherInfo
from CiphersInfo import Constants
__author__ = 'daniel.dinu'
class CiphersInfo:
def __init__(self):
"""
Initialize ciphers info
"""
self.ciphers_info = []
with open(Constants.CIPHER_INFO_CSV_FILE_PATH) as csv_fi... |
import csv
from django.http import HttpResponse
from django.core.exceptions import PermissionDenied
from django.contrib.admin import helpers
from django.contrib.admin.util import get_deleted_objects, model_ngettext
from django.db import router
from django.template.response import TemplateResponse
from django.utils.enco... |
"""
Tests for django admin commands in the verify_student module
Lots of imports from verify_student's model tests, since they cover similar ground
"""
from nose.tools import assert_equals
from mock import patch
from django.test import TestCase
from django.conf import settings
from student.tests.factories import Use... |
import argparse
import json
import sys
from gpu_tests import path_util
import gpu_project_config
path_util.SetupTelemetryPaths()
from telemetry.testing import browser_test_runner
def PostprocessJSON(file_name):
def TrimPrefix(s):
return s[1 + s.rfind('.'):]
with open(file_name) as f:
test_result = json.... |
"""
Sphinx/docutils extension to create links to pyDoctor documentation using a
RestructuredText interpreted text role that looks like this::
:tx:`python_object_to_link_to <label>`
for example::
:tx:`twisted.internet.defer.Deferred <Deferred>`
The label is optional, hence you can also use
:tx:`twisted.... |
# This admin command is to save having to do a series of manual steps
# when merging to people in Pombola.
import sys
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand, CommandError
from django.core.urlresolvers import reverse
from django.db import transact... |
"""Self-citations searcher
"""
from invenio.legacy.dbquery import run_sql
from intbitset import intbitset
def get_self_cited_by(recid):
sql = "SELECT citer FROM rnkSELFCITEDICT WHERE citee = %s"
return intbitset(run_sql(sql, [recid]))
def get_self_cited_by_list(recids, record_limit=None):
if not recids... |
# -*- coding: ISO-8859-1 -*-
# std library
from struct import unpack
# uhh I don't really like this, but there are so many constants to
# import otherwise
from constants import *
from EventDispatcher import EventDispatcher
class MidiFileParser:
"""
The MidiFileParser is the lowest level parser that s... |
"""
Syndication feed generation library -- used for generating RSS, etc.
Sample usage:
>>> from django.utils import feedgenerator
>>> feed = feedgenerator.Rss201rev2Feed(
... title="Poynter E-Media Tidbits",
... link="http://www.poynter.org/column.asp?id=31",
... description="A group Weblog by the sharpes... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import urlparse
from scrapy import log
from scrapy.http import Request
from base.base_wolf import Base_Wolf
class Wolf(Base_Wolf):
def __init__(self, *args, **kwargs):
super(Wolf, self).__init__(*args, **kwargs)
self.name = 'btpanda'
... |
# stdlib
import os
import shlex
import signal
import subprocess
import time
import unittest
# 3p
from nose.plugins.attrib import attr
@attr(requires='core_integration')
class TestAutoRestart(unittest.TestCase):
""" Test the auto-restart and forking of the agent """
def setUp(self):
self.agent_foregro... |
"""Symbol API of MXNet."""
from . import _internal, contrib, linalg, op, random, sparse
# pylint: disable=wildcard-import, redefined-builtin
try:
from .gen_op import * # pylint: disable=unused-wildcard-import
except ImportError:
pass
from . import register
from .op import *
from .symbol import *
# pylint: enab... |
#! /usr/bin/env python
#
# EXPERIMENTAL
# IRC <=> Zulip mirroring bot
#
# Setup: First, you need to install python-irc version 8.5.3
# (https://bitbucket.org/jaraco/irc)
import irc.bot
import irc.strings
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
import zulip
import optparse
IRC_DOMAIN = "irc.example... |
import unittest
from telemetry.unittest import gtest_unittest_results
from telemetry.unittest import simple_mock
class TestFoo(unittest.TestCase):
def __init__(self, methodName, mock_timer):
super(TestFoo, self).__init__(methodName)
self._mock_timer = mock_timer
# Test method doesn't have test- prefix ... |
#File Name Rules: Student_ID_SIS Login ID_File Name
import os
import glob
import sys
import gradeSettings
import re
import csv
import subprocess
import inspect
from quiet import quiet
from gradeParser import gradeParser
import signal
from contextlib import contextmanager
import threading
import _thread
import time
try:... |
from __future__ import absolute_import
import re
import makerbot_driver
from .LineTransformProcessor import LineTransformProcessor
class Rep2XDualstrusionPrimeProcessor(LineTransformProcessor):
def __init__(self):
super(Rep2XDualstrusionPrimeProcessor, self).__init__()
map_addendum = {
... |
from mmt_defaults import PATH_DATABASES,PATH_UNIREF90, PATH_SWISS_PROT,PATH_NR, PATH_PFAM_DATABASE
from functions_databases import (
pfam_build_task, build_diamond_task, build_blast_task, db2stitle_task)
from time import strftime
import gzip
import tarfile
import os
import json
import argparse
import sys
... |
"""
This module instantiates the Flask application and declares the main error
handling function ``make_json_error``.
"""
# IMPORTANT: updates to the following must also be done in setup.py.
__title__ = "birdlistn"
__version__ = "0.1.0"
__author__ = "Hugues Demers"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2013... |
"""This script generates a Python codec module from a Windows Code Page.
It uses the function MultiByteToWideChar to generate a decoding table.
"""
import ctypes
from ctypes import wintypes
from gencodec import codegen
import unicodedata
def genwinmap(codepage):
MultiByteToWideChar = ctypes.windll.kernel32.Multi... |
import re
def cssminify(css):
rules = (
(r"\/\*.*?\*\/", ""), # delete comments
(r"\n", ""), # delete new lines
(r"\s+", " "), # change multiple spaces to one space
(r"\s?([;:{},+>])\s?", r"\1"), # delete space where it is not needed
... |
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.hood.InteractiveAnimatedProp
from panda3d.core import Filename, TextNode, Vec3
from direct.actor import Actor
from direct.fsm import FSM
from direct.interval.IntervalGlobal import Sequence, ActorInterval, Wait, Func, SoundInterval, Parallel
from d... |
from django.contrib.gis.geos import fromstr, Point, LineString, LinearRing, Polygon
from django.utils.functional import total_ordering
from django.utils.safestring import mark_safe
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class GEvent(obje... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import numpy as np
from matplotlib.tri.triangulation import Triangulation
def triplot(ax, *args, **kwargs):
"""
Draw a unstructured triangular grid as lines and/or markers.
The triang... |
""" Tests for DiscussionXBLock"""
from collections import namedtuple
import ddt
import itertools
import mock
from nose.plugins.attrib import attr
import random
import string
from unittest import TestCase
from safe_lxml import etree
from openedx.core.lib.xblock_builtin.xblock_discussion.xblock_discussion import Discus... |
# -*- coding: utf-8 -*-
"""
Random Article Plugin For Pelican
========================
This plugin generates a html file which redirect to a random article
using javascript's window.location. The generated html file is
saved at SITEURL.
"""
from __future__ import unicode_literals
import os.path
from logging import... |
""" Expressions for encoding features """
import theano.tensor as T
def triangle_code(X, centroids):
"""
Compute the triangle activation function used in Adam Coates' AISTATS 2011
paper.
Parameters
----------
X : theano matrix
design matrix
centroids : theano matrix
k-mea... |
from pathlib import Path
import onnx_tf
import onnx
import argparse
import os
import sys
sys.path.insert(0, os.getcwd())
__doc__ = """
Converts ONNX file to TensorFlow saved_model bundle.
Command:
python3 unet_onnx_to_tensorflow.py
or
python3 unet_onnx_to_tensorflow.py --model $(ONNX_MODEL)
... |
{
'name': 'Multiple Analytic Plans',
'version': '1.0',
'category': 'Accounting & Finance',
'description': """
This module allows to use several analytic plans according to the general journal.
==================================================================================
Here multiple analytic line... |
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
from openerp.tools.translate import _
import product
class stock_landed_cost(osv.osv):
_name = 'stock.landed.cost'
_description = 'Stock Landed Cost'
_inherit = 'mail.thread'
_track = {
'state': {
's... |
#!/usr/bin/env python
# This example shows how to combine data from both the imaging and
# graphics pipelines. The vtkMergeFilter is used to merge the data
# from each together.
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Read in an image and compute a luminance value. The ... |
from time import sleep
import sys
import requests, json
# Reference:
# http://docs.python-requests.org/en/master/user/quickstart/
# http://docs.python-requests.org/en/master/api/?highlight=get#requests.get
if __name__ == "__main__":
# A few valid RLEs
N = 200
rles = []
rles.append("b,%d" % N**2)
rles.append("w... |
#!/usr/bin/env python
"""
This file is part of Pyew
Copyright (C) 2009, 2010 Joxean Koret
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any la... |
from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
from version import get_git_version
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here,... |
#!/usr/bin/env python
import json, sys
from common_paths import *
def assert_non_empty_string(obj, field):
assert field in obj, 'Missing field "%s"' % field
assert isinstance(obj[field], basestring), \
'Field "%s" must be a string' % field
assert len(obj[field]) > 0, 'Field "%s" must not be empty'... |
from __future__ import division, print_function, absolute_import
import threading
import scipy._lib.decorator
__all__ = ['ReentrancyError', 'ReentrancyLock', 'non_reentrant']
class ReentrancyError(RuntimeError):
pass
class ReentrancyLock(object):
"""
Threading lock that raises an exception for reent... |
import base64
import io
import json
import zlib
from pip._vendor.requests.structures import CaseInsensitiveDict
from .compat import HTTPResponse, pickle
def _b64_encode_bytes(b):
return base64.b64encode(b).decode("ascii")
def _b64_encode_str(s):
return _b64_encode_bytes(s.encode("utf8"))
def _b64_decode... |
import json
import time
import yaml
try:
import boto
import boto.cloudformation.connection
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def boto_exception(err):
'''generic error message handler'''
if hasattr(err, 'error_message'):
error = err.error_message
elif hasattr(err... |
# -*- coding: utf-8 -*-
import codecs
import logging
import os
import chardet
import pysrt
from .video import Episode, Movie
from .utils import sanitize, sanitize_release_group
logger = logging.getLogger(__name__)
#: Subtitle extensions
SUBTITLE_EXTENSIONS = ('.srt', '.sub', '.smi', '.txt', '.ssa', '.ass', '.mpl')... |
from south.db import db
from django.db import models
from apps.reader.models import *
class Migration:
def forwards(self, orm):
# Adding model 'Feature'
db.create_table('reader_feature', (
('id', orm['reader.feature:id']),
('description', orm['reader.feature:de... |
import json
import mcazurerm
# Load Azure app defaults
try:
with open('mcazurermconfig.json') as configFile:
configData = json.load(configFile)
except FileNotFoundError:
print("Error: Expecting vmssConfig.json in current folder")
sys.exit()
tenant_id = configData['tenantId']
app_id = configData['... |
"""Base classes for storage engines
"""
import datetime
import inspect
import math
from oslo_utils import timeutils
import six
from six import moves
import ceilometer
def iter_period(start, end, period):
"""Split a time from start to end in periods of a number of seconds.
This function yields the (start, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.