content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
from django.apps.registry import Apps, apps
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation
)
from django.contrib.contenttypes import management
from django.contrib.contenttypes.models import ContentType... |
# -*- coding: utf-8 -*-
from liblightbase.lbrest.core import LBRest
from liblightbase.lbutils.conv import document2json
from liblightbase.lbutils.conv import json2document
from liblightbase.lbbase.struct import Base
from liblightbase.lbsearch.search import Collection
from liblightbase.lbsearch.search import Search
from... |
"""Install vb2Py
Much of the following code is copied from the PythonCard installation script
because the original setup.py would copy files to all sorts of weird location
on Linux.
You must run this to create the setup distribution from the site-packages!
"""
WIN_DEFAULT_COMMAND = "install"
APPLICATION_NAME = "vb... |
__revision__ = "$Id$"
__all__ = ['new']
from Crypto.Random import OSRNG
from Crypto.Random import _UserFriendlyRNG
def new(*args, **kwargs):
"""Return a file-like object that outputs cryptographically random bytes."""
return _UserFriendlyRNG.new(*args, **kwargs)
def atfork():
"""Call this whenever you ca... |
import os
from django.template import Context, Engine, TemplateDoesNotExist
from django.template.loader_tags import ExtendsError
from django.template.loaders.base import Loader
from django.test import SimpleTestCase, ignore_warnings
from django.utils.deprecation import RemovedInDjango20Warning
from .utils import ROOT... |
"""
A place for code to be called from core C-code.
Some things are more easily handled Python.
"""
from __future__ import division, absolute_import, print_function
import re
import sys
from numpy.compat import asbytes, basestring
from .multiarray import dtype, array, ndarray
import ctypes
from .numerictypes import... |
from lago.plugins.service import (ServicePlugin, ServiceState, )
class SystemdService(ServicePlugin):
BIN_PATH = '/usr/bin/systemctl'
def _request_start(self):
super(SystemdService, self)._request_start()
return self._vm.ssh([self.BIN_PATH, 'start', self._name])
def _request_stop(self):
... |
"""
Infrastructure for test running and suites.
"""
from __future__ import division, absolute_import
import doctest
import gc
from twisted.python import components
from twisted.trial import itrial, reporter
from twisted.trial._synctest import _logObserver
pyunit = __import__('unittest')
from zope.interface import... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from io import BytesIO
from decimal import Decimal
from django.test import TestCase
from rest_framework_yaml.renderers import YAMLRenderer
from rest_framework_yaml.parsers import YAMLParser
class YAMLRendererTests(TestCase):
"""
Tests specific t... |
import uuid
from tempest_lib.common.utils import data_utils
from tempest_lib import exceptions as lib_exc
from tempest.api.compute.floating_ips import base
from tempest import config
from tempest import test
CONF = config.CONF
class FloatingIPsNegativeTestJSON(base.BaseFloatingIPsTest):
server_id = None
@... |
from . import giphy
try:
from unittest.mock import patch
except ImportError:
from mock import patch
import os
import pytest
PLUGIN_DIR = os.path.dirname(__file__)
TEST_DATA_DIR = os.path.join(PLUGIN_DIR, 'test_data')
@pytest.mark.parametrize('input,expected', [
(dict(gif_id='abc123'),
... |
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import splitString
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
import base64
import json
log = CPLog(__name__)
class Pushbullet(Notification):
url = 'https://... |
# Simple Huffman encoding/decoding, Steven Bird
# http://en.wikipedia.org/wiki/Huffman_coding
import nltk
from operator import itemgetter
def huffman_tree(text):
coding = nltk.FreqDist(text).items()
coding.sort(key=itemgetter(1))
while len(coding) > 1:
a, b = coding[:2]
pair = (a[0], b[0])... |
import utils
content_types = utils.invert_dict({"text/html": ["htm", "html"],
"application/json": ["json"],
"application/xhtml+xml": ["xht", "xhtm", "xhtml"],
"application/xml": ["xml"],
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
sphinx-autopackage-script
This script parses a directory tree looking for python modules and packages and
creates ReST files appropriately to create code documentation with Sphinx.
It also creates a modules index (named modules.<suffix>).
"""
# Copyright 2008 SociétÃ... |
RECORD_AS_MUCH_AS_POSSIBLE = 'record-as-much-as-possible'
RECORD_UNTIL_FULL = 'record-until-full'
RECORD_MODES = (RECORD_AS_MUCH_AS_POSSIBLE, RECORD_UNTIL_FULL)
class TracingOptions(object):
"""Tracing options control which core tracing systems should be enabled.
This simply turns on those systems. If those syst... |
import unittest
import os
import shutil
import numpy as np
from esp import specUtils
class testSpecUtils(unittest.TestCase):
@classmethod
def setUpClass(cls):
sample_wavelen = np.arange(50)
sample_flux = np.random.uniform(size=50)
cls.sample_spec = np.array([sample_wavelen, sample_f... |
import oils.utils.idl
from oils.utils.utils import md5sum
import osrf.json
def handle_login(srfsh, args):
''' Login w/ args '''
username = args[0]
password = args[1]
seed = srfsh.handle_request([
'open-ils.auth',
'open-ils.auth.authenticate.init',
'"%s"' % username
])
... |
"""A module providing information about the necessity of brackets"""
# Default precedence values for some basic types
PRECEDENCE = {
"Lambda":1,
"Relational":20,
"Add":40,
"Mul":50,
"Pow":60,
"Atom":1000
}
# A dictionary assigning precedence values to certain classes. These values are
# treate... |
from __future__ import unicode_literals
import re
class LineBuffer(object):
r"""
Buffer bytes read in from a connection and serve complete lines back.
>>> b = LineBuffer()
>>> len(b)
0
>>> b.feed(b'foo\nbar')
>>> len(b)
7
>>> list(b.lines()) == [b'foo']
True
>>> len(b)
... |
import numpy as np
from TestBase import TestBase
from TotalActivation.filters.cons import cons
class TestConsFilter(TestBase):
def testFacts(self):
np.testing.assert_allclose(cons(np.array([])), np.array([1]))
np.testing.assert_allclose(cons(np.array([1])), np.array([1, -2.718281828459046]))
... |
#!/usr/bin/env python
import sys
from argparse import ArgumentParser
try:
import cProfile as profile
except:
import profile
from . import helpers
from . import TEST_DIR
helpers.setup_path()
import pbxproj
def get_argument_parser():
parser = ArgumentParser()
parser.add_argument("file",
... |
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from oscar.core.application import Application
from oscar.core.loading import get_class
class BasketApplication(Application):
name = 'basket'
summary_view = get_class('basket.views', 'BasketView')
saved_view = get_... |
"""
Transforms needed by most or all documents:
- `Decorations`: Generate a document's header & footer.
- `Messages`: Placement of system messages stored in
`nodes.document.transform_messages`.
- `TestMessages`: Like `Messages`, used on test runs.
- `FinalReferences`: Resolve remaining references.
"""
__docformat__... |
from flask import request
from flask.ext import restful
from werkzeug.utils import secure_filename
from models import HashModel
from utils import Responder
from PIL import Image
from dhash import Dhash
from errors import ItemExistsError
from settings import get_flask_settings
import os
import time
import hashlib
clas... |
from fabric.api import *
def update():
"""Requires code_root env variable. Does a git pull and restarts the web server"""
require('code_root')
git_pull()
restart_web_server()
def git_pull():
"""Does a git stash then a git pull on the project"""
run('cd %s; git stash; git pull' % (env.code_... |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Pelix remote services: Zeroconf (mDNS) discovery and event notification
This module depends on the pyzeroconf project by Mike Fletcher, at
https://github.com/mcfletch/pyzeroconf
To work with ECF, the '.local.' checking in zeroconf.mdns.DNSQuestion must be
remo... |
"""generic_fk.py
Illustrates a so-called "generic foreign key", in a similar fashion
to that of popular frameworks such as Django, ROR, etc. This
approach bypasses standard referential integrity
practices, in that the "foreign key" column is not actually
constrained to refer to any particular table; instead,
in-appli... |
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
def sensu_check(module, path, name, state='present', backup=False):
changed = False
reasons = []
str... |
XMLIF_MINIDOM = "XMLIF_MINIDOM"
XMLIF_4DOM = "XMLIF_4DOM"
XMLIF_ELEMENTTREE = "XMLIF_ELEMENTTREE"
# namespace definitions
XINC_NAMESPACE = "http://www.w3.org/2001/XInclude"
# definition of genxmlif path
import os
GENXMLIF_DIR = os.path.dirname(__file__)
###############################... |
from random import randint
from sympy.ntheory.bbp_pi import pi_hex_digits
from sympy.utilities.pytest import raises
# http://www.herongyang.com/Cryptography/Blowfish-First-8366-Hex-Digits-of-PI.html
# There are actually 8336 listed there; with the preppended 3 there are 8337
# below
dig=''.join('''
3243f6a8885a308d3... |
import yaml
import sys
def document_fields(output, section, sections, path):
if "anchor" in section:
output.write("[[exported-fields-{}]]\n".format(section["anchor"]))
if "prefix" in section:
output.write("{}\n".format(section["prefix"]))
output.write("=== {} Fields\n\n".format(section["n... |
"""Operations on many graphs.
"""
# Copyright (C) 2012 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
try:
from itertools import izip_longest as zip_longest
except ImportError: # Python3 has zip_longest
from itertools import zi... |
"""Code-coverage tools for CherryPy.
To use this module, or the coverage tools in the test suite,
you need to download 'coverage.py', either Gareth Rees' `original
implementation <http://www.garethrees.org/2001/12/04/python-coverage/>`_
or Ned Batchelder's `enhanced version:
<http://www.nedbatchelder.com/code/modules... |
import logging
import copy
try:
from zabbix_api import ZabbixAPI, ZabbixAPISubClass
HAS_ZABBIX_API = True
except ImportError:
HAS_ZABBIX_API = False
# Extend the ZabbixAPI
# Since the zabbix-api python module too old (version 1.0, no higher version so far).
class ZabbixAPIExtends(ZabbixAPI):
def __i... |
#!/usr/bin/env python
"""Convert CSEPs to (X)HTML - courtesy of /F
Usage: %(PROGRAM)s [options] [<cseps> ...]
Options:
-u, --user
crystalspace3d.org username
-b, --browse
After generating the HTML, direct your web browser to view it
(using the Python webbrowser module). If both -i and -b are
given,... |
"""Module for testing the del auxiliary command."""
import unittest
if __name__ == "__main__":
import utils
utils.import_depends()
from brokertest import TestBrokerCommand
class TestDelAuxiliary(TestBrokerCommand):
def testdelunittest00e1(self):
self.dsdb_expect_delete(self.net["unknown0"].usa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This prog... |
from struct_generator import GenerateField
from struct_generator import GenerateStruct
import unittest
class StructGeneratorTest(unittest.TestCase):
def testGenerateIntField(self):
self.assertEquals('const int foo_bar',
GenerateField({'type': 'int', 'field': 'foo_bar'}))
def testGenerateStringField(se... |
from pants.testutil.pants_integration_test import run_pants, setup_tmpdir
def test_build_ignore_list() -> None:
with setup_tmpdir({"dir/BUILD": "files(sources=[])"}) as tmpdir:
ignore_result = run_pants([f"--build-ignore={tmpdir}/dir", "list", f"{tmpdir}/dir"])
no_ignore_result = run_pants(["list"... |
from __future__ import absolute_import
from .packages.six.moves.http_client import (
IncompleteRead as httplib_IncompleteRead
)
# Base Exceptions
class HTTPError(Exception):
"Base exception used by this module."
pass
class HTTPWarning(Warning):
"Base warning used by this module."
pass
class Po... |
"""
Team Deathmatch game mode.
Maintainer: Triplefox
"""
from pyspades.constants import *
import commands
def score(connection):
return connection.protocol.get_kill_count()
commands.add(score)
def apply_script(protocol, connection, config):
class TDMConnection(connection):
def on_... |
from io_scs_tools.internals.shaders.eut2.dif_spec import DifSpec
from io_scs_tools.internals.shaders.eut2.std_passes.lum import StdLum
from io_scs_tools.internals.shaders.flavors import alpha_test
from io_scs_tools.internals.shaders.flavors import blend_over
from io_scs_tools.internals.shaders.flavors import blend_add
... |
from django.forms.models import ModelForm, inlineformset_factory
from django.test import TestCase, skipUnlessDBFeature
from .models import Child, Parent, Poem, Poet, School
class DeletionTests(TestCase):
def test_deletion(self):
PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True, fields="__... |
from django.test import TestCase
from ai import tic_tack
# Create your tests here.
class tick_tack_test(TestCase):
def test_check_move_true(self):
self.assertEqual(tic_tack.check_move([' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], 0), True)
def test_check_move_False(self):
self.assertEqual(... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
from ... |
#!/usr/bin/pyhton
import csv
import time
import numpy as np
from sklearn import svm
from sklearn import tree
from sklearn import neighbors
from sklearn import preprocessing
from sklearn import multiclass
from sklearn import cross_validation
from sklearn import metrics
from sklearn import ensemble
from sklearn.pipeline... |
from __future__ import unicode_literals
import webnotes
class DocType():
def __init__(self, doc, doclist=[]):
self.doc = doc
self.doclist = doclist
def get_parent_bean(self):
return webnotes.bean(self.doc.parenttype, self.doc.parent)
def update_parent(self):
"""update status of parent Lead or Contact ... |
import numpy as np
from sklearn.datasets import load_boston
(x, y) = load_boston(True)
ss_total = ((y - y.mean()) ** 2).sum()
def evaluate(p):
return 1 - ((np.inner(x, p[:-1]) + p[-1] - y) ** 2).sum() / ss_total
iter_count = 10000
pop_size = 100
child_size = 30
params_len = 14
tau = 1.0 / np.sqrt(2.0 * params_... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : <EMAIL>
The... |
import unittest
import ddt
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from django.urls import reverse
from edx_django_utils.cache import RequestCache
from mock impor... |
"""
tests.test_component_logbook
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests the logbook component.
"""
# pylint: disable=protected-access,too-many-public-methods
import unittest
from datetime import timedelta
import homeassistant.core as ha
from homeassistant.const import (
EVENT_STATE_CHANGED, EVENT_HOMEASSISTANT_START,... |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
from androguard.core.bytecodes import dvm
from androguard.core.bytecodes import apk
from androguard.core.analysis import analysis
from androguard.core import androconf
import hashlib
def hexdump(src, length=8, off=0):
result = ... |
from opus_core.variables.variable import Variable
from urbansim.functions import attribute_label
from variable_functions import my_attribute_label
from opus_core.logger import logger
class number_of_jobs_without_resource_construction_sectors(Variable):
""" """
_return_type="int32"
def dependencie... |
"""The tests for generic camera component."""
import asyncio
from aiohttp.client_exceptions import ClientResponseError
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
# An infinitesimally small time-delta.
EPSILON_DELTA = 0.0000000001
def radar_map_url(dim: int = ... |
# -*- coding: utf-8 -*-
from datetime import datetime
from PBSQuery import PBSQuery, PBSError
import time
from django.contrib.auth.models import User
import pbs
from pytorque.models import PBSServer, PBSQueue, PBSJob
class Job():
__datetime_format = "%d-%m-%Y %H:%M"
jobId = None
state = None
user ... |
#!/usr/bin/env python3
import sys
import os
#sys.path.append(os.path.join(sys.path[0],"..","..","kicad_mod")) # load kicad_mod path
# export PYTHONPATH="${PYTHONPATH}<path to kicad-footprint-generator directory>"
sys.path.append(os.path.join(sys.path[0], "..", "..", "..")) # load parent path of KicadModTree
from mat... |
#!/usr/bin/env python
def submit_experiment(outfile, target_dir, dry_run=0, ntest=3, kernel=1, ts=0, nx=480, ny=480, nz=480, npx=1, npy=1, npz=1, nt=50, is_dp=1, tgs=1, cs=8192, exe_cmd='', tb=-1, nwf=-1, mwd_type=0, bsx=100000):
import os
import subprocess
from string import Template
from utils import ensure_... |
import odoo.tests
@odoo.tests.tagged('post_install', '-at_install')
class TestFrontend(odoo.tests.HttpCase):
def setUp(self):
super().setUp()
self.env = self.env(user=self.env.ref('base.user_admin'))
account_obj = self.env['account.account']
printer = self.env['restaurant.printer']... |
#!/usr/bin/python3
import urwid
import pykms
def exit_on_q(key):
if key in ('q', 'Q'):
raise urwid.ExitMainLoop()
elif key == 'a':
apply_mode()
alarm_handle = None
def recalc_info(l, d):
global alarm_handle
alarm_handle = None
for w in recalc_list:
w.recalc()
def div_or_zero(n, d):
if d == 0:
retur... |
"""
WSGI config for api project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
from website import settings
from api.base import settings as api_settings
if not settings.DEBUG_MODE... |
microcode = '''
def macroop CALL_NEAR_I
{
# Make the default data size of calls 64 bits in 64 bit mode
.adjust_env oszIn64Override
.function_call
limm t1, imm
rdip t7
# Check target of call
st t7, ss, [0, t0, rsp], "-env.dataSize"
subi rsp, rsp, ssz
wrip t7, t1
};
def macroop CALL_... |
from __future__ import unicode_literals
from gnuradio import gr
from gnuradio import audio
from gnuradio import blocks
from gnuradio.eng_arg import eng_float, intx
from argparse import ArgumentParser
class my_top_block(gr.top_block):
def __init__(self):
gr.top_block.__init__(self)
parser = Argume... |
"""Remove None from nodes' logs lists."""
import sys
import logging
from website.app import init_app
from website.models import Node
from scripts import utils as script_utils
from modularodm import Q
logger = logging.getLogger(__name__)
def do_migration(records, dry=False):
count = 0
for node in records:
... |
import sys
import subprocess
import pkgutil
import types
import importlib
import warnings
import numpy as np
import numpy
import pytest
try:
import ctypes
except ImportError:
ctypes = None
def check_dir(module, module_name=None):
"""Returns a mapping of all objects with the wrong __module__ attribute.""... |
# -*- coding: utf-8 -*-
"""
tests.test_api_multipart
~~~~~~~~~~~~~~~~~~~~~
Check Latex multipart compiling API.
:copyright: (c) 2019 Yoan Tournade.
:license: AGPL, see LICENSE for more details.
"""
import pytest
import requests
from .utils.pdf import snapshot_pdf
LATEX_HELLO_WORLD = (
"\\docum... |
from .pyjsparserdata import *
import six
class BaseNode:
def finish(self):
pass
def finishArrayExpression(self, elements):
self.type = Syntax.ArrayExpression
self.elements = elements
self.finish()
return self
def finishArray... |
email = 'YOUR-EMAIL-ADDRESS'
password = 'YOUR-PASSWORD'
# Options are "away, home, off"
# You can override this by passing the state as arguments, e.g. "python alarmsystem.py away"
default_alarm_state = 'home'
# You can generate a new device UUID from this website
# https://www.uuidgenerator.net
device_uuid = '62374... |
"""
Copyright 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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 ... |
try:
import pkg_resources
version = pkg_resources.require("Autobahn")[0].version
except:
## i.e. no setuptools or no package installed ..
version = "?.?.?"
import util
import httpstatus
import utf8validator
import websocket
import case
import report
import fuzzing
import prefixmap
import wam... |
"""
MapMyFitness OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/mapmyfitness.html
"""
from social.backends.oauth import BaseOAuth2
class MapMyFitnessOAuth2(BaseOAuth2):
"""MapMyFitness OAuth authentication backend"""
name = 'mapmyfitness'
AUTHORIZATION_URL = 'https://www.mapmyfitn... |
import copy
import numpy as np
from numpy.linalg import pinv
from statsmodels.sandbox import utils_old as utils
class ContrastResults(object):
"""
Results from looking at a particular contrast of coefficients in
a parametric model. The class does nothing, it is a container
for the results from T and F... |
"""
A synthesis.hdlist.cz parser
"""
import gzip
import re
import sys
__all__ = ['parse']
def _parse_rpm_name(name):
"""Returns (name, version, release, arch) tuple from a rpm
package name.
"""
# TODO This could be put in a package for general use in other
# scripts.
parts = name.split('-')... |
"""
This module contains functions and methods to authenticate with OpenID
providers.
"""
__revision__ = \
"$Id$"
from invenio.config import CFG_SITE_SECURE_URL
from invenio.external_authentication import ExternalAuth
from invenio.session import get_session
class ExternalOpenID(ExternalAuth):
"""
Contains... |
from django import forms
from .validators import IBAN_COUNTRY_CODE_LENGTH, BICValidator, IBANValidator
DEFAULT_DATE_INPUT_FORMATS = (
'%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06'
'%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y', ... |
"""
Implementation of an SSH2 "message".
"""
import struct
from paramiko import util
from paramiko.common import zero_byte, max_byte, one_byte, asbytes
from paramiko.py3compat import long, BytesIO, u, integer_types
class Message (object):
"""
An SSH2 message is a stream of bytes that encodes some combinatio... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: scaleway_server_facts
short_description: Gather facts abou... |
def check_field_existence(record, field, min_value, max_value=None, subfield=None, continuable=True):
"""
Checks field.subfield existence inside the record according to max and min values
@param record: BibFieldDict where the record is stored
@param field: Main json ID or field name to make test on
... |
"""
This is the Scrapy engine which controls the Scheduler, Downloader and Spiders.
For more information see docs/topics/architecture.rst
"""
import logging
from time import time
from twisted.internet import defer
from twisted.python.failure import Failure
from scrapy import signals
from scrapy.core.scraper import ... |
# Add the igl library to the modules search path
import sys, os
sys.path.insert(0, os.getcwd() + "/../")
import igl
b = igl.eigen.MatrixXi()
B = igl.eigen.MatrixXd()
bc = igl.eigen.MatrixXd()
lx = igl.eigen.MatrixXd()
ux = igl.eigen.MatrixXd()
Beq = igl.eigen.MatrixXd()
Bieq = igl.eigen.MatrixXd()
Z = igl.eigen.Matri... |
"""
"""
from abc import ABC, abstractmethod
from typing import Any, Sequence, Dict, List, Optional, Callable
from copy import copy
from vnpy.event import Event, EventEngine
from .event import (
EVENT_TICK,
EVENT_ORDER,
EVENT_TRADE,
EVENT_POSITION,
EVENT_ACCOUNT,
EVENT_CONTRACT,
EVENT_LOG,... |
"""Registration facilities for DOM. This module should not be used
directly. Instead, the functions getDOMImplementation and
registerDOMImplementation should be imported from xml.dom."""
from xml.dom.minicompat import * # isinstance, StringTypes
# This is a list of well-known implementations. Well-known names
# sho... |
import time
from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer)
# pylint: disable=line-too-long
# pylint: disable=too-many-lines
class EHNetworkCURDScenarioTest(ScenarioTest):
@ResourceGroupPreparer(name_prefix='cli_test_eh_network')
def test_eh_network(self, resource_group):
self.... |
from datetime import datetime
from django.utils import timezone
import calendar
import pytz
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
DATE_FORMAT = '%Y-%m-%d'
def parse_date_string_with_or_without_time(date_string):
try:
return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S')
except ValueError... |
"""
Copyright 2008, 2009 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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 ... |
import numpy as np
from six.moves import range
from ...utils.jaggedarray import JaggedArray
class CellGrid(object):
"""
Parameters
----------
vertices : array-like
Vertex IDs at each grid cell
vertices_per_cell : array-like
Number of vertices per grid cell
Returns
-------... |
from openerp.osv import fields,osv,orm
class crm_segmentation(osv.osv):
'''
A segmentation is a tool to automatically assign categories on partners.
These assignations are based on criterions.
'''
_name = "crm.segmentation"
_description = "Partner Segmentation"
_columns = {
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from map_display import *
from QLearning import*
import numpy as np
import matplotlib.pyplot as plt
import sys
import time
MAX_GOAL_TRIAL = 300
if __name__ == "__main__":
args = sys.argv
argc = len(args)
gui_flag = True
map_reward = np.loadtxt('data/map... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutStrings(Koan):
def test_double_quoted_strings_are_strings(self):
string = "Hello, world."
self.assertEqual(True, isinstance(string, str))
def test_single_quoted_strings_are_also_strings(self):
string =... |
#!/usr/bin/env python
from ciscoconfparse import CiscoConfParse
import re
from pprint import pprint
import markdown
def read_in_file(filename):
return CiscoConfParse(filename)
def generate_pointee_markdown(parsed_config, pointee_objects):
pointee_types = ['access-list', 'ip access-list', 'interface',
... |
'''tzinfo timezone information for Asia/Tehran.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Tehran(DstTzInfo):
'''Asia/Tehran timezone definition. See datetime.tzinfo for details'''
zone = 'Asia/Tehran'
_utc_tran... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import unified_strdate
class ATTTechChannelIE(InfoExtractor):
_VALID_URL = r'https?://techchannel\.att\.com/play-video\.cfm/([^/]+/)*(?P<id>.+)'
_TEST = {
'url': 'http://techchannel.att.com/play-video.cfm/2014/1/27... |
from __future__ import unicode_literals
import unittest
from django.core.exceptions import FieldError
from django.test import SimpleTestCase, TestCase
from .models import (
AdvancedUserStat, Child1, Child2, Child3, Child4, Image, Parent1, Parent2,
Product, StatDetails, User, UserProfile, UserStat, U... |
from twisted.internet.task import react
from twisted.internet.defer import inlineCallbacks as coroutine
from autobahn.twisted.wamp import Connection
# A single session joins a first realm, leaves and joins another realm
# all over the same, still running transport
@coroutine
def main(transport):
session = Applica... |
import ddt
import itertools
from xmodule.tests import BulkAssertionTest, BulkAssertionError
STATIC_PASSING_ASSERTIONS = (
('assertTrue', True),
('assertFalse', False),
('assertIs', 1, 1),
('assertEqual', 1, 1),
('assertEquals', 1, 1),
('assertIsNot', 1, 2),
('assertIsNone', None),
('as... |
from django.db import models
from django.db.models.sql.constants import LOOKUP_SEP
from django.db.models.deletion import Collector
from django.db.models.related import RelatedObject
from django.forms.forms import pretty_name
from django.utils import formats
from django.utils.html import escape
from django.utils.safestr... |
# -*- coding: utf-8 -*-
'''
Specto 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 l... |
from wazo_auth.services.helpers import BaseService
from xivo_bus.resources.auth.events import SessionDeletedEvent
class SessionService(BaseService):
def __init__(self, dao, tenant_tree, bus_publisher):
super().__init__(dao, tenant_tree)
self._bus_publisher = bus_publisher
def count(self, scop... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
import os
from ansible.module_utils.basic import AnsibleModule
class RabbitMqPlugins(object):
def __init__(sel... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import codecs
from setuptools import setup
def read(fname):
file_path = os.path.join(os.path.dirname(__file__), fname)
return codecs.open(file_path, encoding='utf-8').read()
setup(
name='pytest-diamond',
version='0.0.1',
author='Matt Roben... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.