code
stringlengths
1
199k
import sympy as sp import symbtools as st e = sp.symbols("epsilon") x1, x2, x3, x4, x5, x6 = sp.symbols("x1, x2, x3, x4, x5, x6") vec_x = sp.Matrix([x1, x2, x3, x4, x5, x6]) vec_xdot = st.time_deriv(vec_x, vec_x) xdot1, xdot2, xdot3, xdot4, xdot5, xdot6 = vec_xdot F_eq = sp.Matrix([ [xdot4*sp.cos(x3) - (xdot5+1)*sp.sin...
import config import util import aptable def writeHeader22degrees(fid): fid.write("""G75* G70* %OFA0B0*% %FSLAX25Y25*% %IPPOS*% %LPD*% %AMOC8* 5,1,8,0,0,1.08239X$1,22.5* % """) def writeHeader0degrees(fid): fid.write("""G75* G70* %OFA0B0*% %FSLAX25Y25*% %IPPOS*% %LPD*% %AMOC8* 5,1,8,0,0,1.08239X$1,0.0* % """) d...
import inspect import logging import traceback import weakref from enum import Enum from threading import RLock from types import MethodType, BuiltinMethodType from PyQt5.QtCore import QEvent, QObject from PyQt5.QtWidgets import QApplication from lisp.core.decorators import async from lisp.core.util import weak_call_pr...
import sys, time, datetime, re, threading from electrum_pkb.i18n import _ from electrum_pkb.util import print_error, print_msg import os.path, json, ast, traceback from PyQt4.QtGui import * from PyQt4.QtCore import * from electrum_pkb import DEFAULT_SERVERS, DEFAULT_PORTS from util import * protocol_names = ['TCP', 'SS...
from __future__ import absolute_import import datetime import os import re from . import generic from .. import logger import sg_helpers from lib.tvinfo_base.exceptions import * import sickbeard import encodingKludge as ek import exceptions_helper from exceptions_helper import ex from lxml_etree import etree from six i...
from __future__ import absolute_import, division, print_function from cryptography import utils from cryptography.hazmat.primitives import interfaces def _check_iv_length(self, algorithm): if len(self.initialization_vector) * 8 != algorithm.block_size: raise ValueError("Invalid IV size ({0}) for {1}.".forma...
import sys sys.path.append('..') from pycompgeom import * segments = random_segments(1000, visual=True) a = VPoint2(color=BLUE) pause()
""" wpbf is a general audit and bruteforce tool to remotely test the WordPress blogging software Copyright 2011 Andres Tarantini (atarantini@gmail.com) 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, ...
from __future__ import absolute_import, division, print_function from wtforms import validators from wtforms.fields import Flags from wtforms.widgets import ( HTMLString, HiddenInput, Select, TextInput, html_params, ) from inspire_schemas.api import load_schema from inspirehep.modules.forms.field_wi...
import os DEBUG = False TEMPLATE_DEBUG = False ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) TIME_ZONE = 'Europe/Madrid' APPLICATION_DIR = os.path.dirname(globals()['__file__']) DATABASES = { 'default': { # Add 'postgresql_psycopg2','postgresql','mysql','sqlite3','oracle' 'ENGINE': 'dja...
"""Test scriptworker.task """ import asyncio import glob import json import os import sys import time from unittest.mock import MagicMock import arrow import mock import pytest import taskcluster.exceptions from taskcluster.exceptions import TaskclusterFailure import scriptworker.log as log import scriptworker.task as ...
"""Scripts to migrate legacy objects in existing databases.""" import logging # pragma: no cover from adhocracy_core.evolution import log_migration from adhocracy_core.evolution import migrate_new_sheet logger = logging.getLogger(__name__) # pragma: no cover @log_migration def remove_spd_workflow_assignment_sheet(roo...
from .addresses import OrderAddressEditView from .detail import OrderDetailView, OrderSetStatusView from .edit import OrderEditView, UpdateAdminCommentView from .list import OrderListView from .log import NewLogEntryView from .payment import OrderCreatePaymentView, OrderDeletePaymentView, OrderSetPaidView from .refund ...
import math import uuid try: from lxml.etree import parse from lxml.etree import XMLSyntaxError from lxml.etree import tostring from lxml.etree import fromstring from lxml.etree import Element except ImportError: from xml.etree.ElementTree import parse from xml.etree.ElementTree import Parse...
from lepl.support.lib import fmt from lepl._test.base import BaseTest from lepl.stream.core import s_empty, s_fmt, s_line, s_next, s_stream from lepl.stream.factory import DEFAULT_STREAM_FACTORY class GenericTest(BaseTest): def test_empty(self): f = DEFAULT_STREAM_FACTORY for (constructor, data) in ...
from openerp.osv import orm from ..model.sync_typo3 import Sync_typo3 class delegate_child_wizard(orm.TransientModel): _inherit = 'delegate.child.wizard' def delegate(self, cr, uid, ids, context=None): child_ids = self._default_child_ids(cr, uid, context) child_obj = self.pool.get('compassion.ch...
from openerp import models class test(models.Model): """""" _inherit = 'kinesis_athletics.test' def onchange_type(self, cr, uid, ids, type, context=None): v = {} if type == 'selection': v['has_range'] = False return {'value': v} def on_change_has_range(self, cr, uid, ...
import os import sys DEBUG = True SECRET_KEY = "topsecret" DATABASES = { "default": { "ENGINE": "django.contrib.gis.db.backends.postgis", "NAME": "enhydris", "USER": "enhydris", "PASSWORD": "topsecret", "HOST": "localhost", "PORT": "5432", } } SITE_ID = 1 STATIC_U...
from uuid import uuid4 def get_username(strategy, details, user=None, *args, **kwargs): storage = strategy.storage if user: return {'username': storage.user.get_username(user)} prefix = strategy.setting('ACCOUNT_USERNAME_PREFIX', 'user') max_length = storage.user.username_max_length() uuid_l...
import unittest2 import openerp.tests.common as common from openerp.osv.orm import except_orm class test_base(common.TransactionCase): def setUp(self): super(test_base,self).setUp() self.res_partner = self.registry('res.partner') # samples use effective TLDs from the Mozilla public suffix ...
from openerp import models, fields class ir_actions_report(models.Model): _inherit = 'ir.actions.report.xml' sale_order_state = fields.Selection( [('draft', 'Quotation'), ('progress', 'In Progress')], 'Sale Order State', required=False) def get_domains(self, cr, model, record, context=None):...
from __future__ import absolute_import "spam, bar, blah" from __future__ import print_function
import sys from resources.datatables import WeaponType def setup(core, object): object.setAttackSpeed(1) object.setMaxRange(64) object.setDamageType('energy') object.setMinDamage(400) object.setMaxDamage(775) object.setWeaponType(WeaponType.HEAVYWEAPON) object.setStringAttribute('wpn_elemental_type', 'heat') ob...
try: from modelos.main_model2 import model keys=[] for elem in data: keys.append(elem) if data["action"].value=="publicarNoticia": l=[] l2=["email","password","name","lastname","rank","avatar","department_id","position_id"] for elem in l2: if elem not in keys: print "No llenastes el campo ",elem ...
from __future__ import print_function from openturns import * TESTPREAMBLE() RandomGenerator.SetSeed(0) try: # Instanciate one distribution object distribution = Skellam(10.0, 5.0) print("Distribution ", repr(distribution)) print("Distribution ", distribution) # Is this distribution elliptical ? ...
import sys import os import string import re import subprocess def makeJsonFromNgramTinaCsv(inFilePath): patt = re.compile(',"((\w| |\.|-)*)","\[.*]",(\d+)') outJson = [] theFile = open(inFilePath,"r") for l in theFile.readlines(): ff = re.search(patt,l) if ff!=None: ngram = ff.group(1) nocc = int(ff.grou...
''' fit best estimate of magnetometer offsets ''' import sys, time, os, math sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) from optparse import OptionParser parser = OptionParser("magfit.py [options]") parser.add_option("--no-timestamps",dest="notimestamps", action='store_true', he...
""" Support virtualenv in pymode. """ import os.path from .environment import env @env.catch_exceptions def enable_virtualenv(): """ Enable virtualenv for vim. :return bool: """ path = env.var('g:pymode_virtualenv_path') enabled = env.var('g:pymode_virtualenv_enabled') if path == enabled: ...
"""Command for listing snapshots.""" from googlecloudsdk.compute.lib import base_classes class List(base_classes.GlobalLister): """List Google Compute Engine snapshots.""" @property def service(self): return self.compute.snapshots @property def resource_type(self): return 'snapshots' List.detailed_hel...
from __future__ import print_function __author__ = 'Bill Farner' import base64 import cookielib import mimetools import os import getpass import json import sys import urllib2 from urlparse import urljoin from urlparse import urlparse VERSION = '0.8-precommit' class APIError(Exception): pass class RepositoryInfo: "...
"""Gradient checker for any ops, graphs. The gradient checker verifies numerically that an op/graph properly computes the gradients """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from...
from unittest.mock import Mock from genty import genty, genty_dataset from app.master.atom import Atom from app.master.atomizer import Atomizer from app.master.job_config import JobConfig from app.master.subjob_calculator import compute_subjobs_for_build from app.project_type.project_type import ProjectType from test.f...
from a10sdk.common.A10BaseClass import A10BaseClass class LdapServer(A10BaseClass): """Class Description:: Configure LDAP server information. Class ldap-server supports CRUD Operations and inherits from `common/A10BaseClass`. This class is the `"PARENT"` class for this module.` :param DeviceProxy: T...
from __future__ import print_function print("Module name is", __name__) class SomeClass: pass print("Class inside main module names its module as", repr(SomeClass.__module__)) if __name__ == "__main__": print("Executed as __main__:") import sys, os # The sys.argv[0] might contain ".exe", ".py" or no suf...
""" Tests for Backup code. """ import json from xml.dom import minidom import mock from oslo_utils import timeutils import webob import cinder.backup from cinder import context from cinder import db from cinder import exception from cinder.i18n import _ from cinder.openstack.common import log as logging from cinder imp...
from tapiriik.settings import WEB_ROOT, ENDOMONDO_CLIENT_KEY, ENDOMONDO_CLIENT_SECRET, SECRET_KEY from tapiriik.services.service_base import ServiceAuthenticationType, ServiceBase from tapiriik.services.interchange import UploadedActivity, ActivityType, ActivityStatistic, ActivityStatisticUnit, Waypoint, WaypointType, ...
"""Tests for KMeans.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import time import numpy as np from sklearn.cluster import KMeans as SklearnKMeans import tensorflow as tf from tensorflow.python.platform import benchmark FLAGS = tf.app.flag...
""" Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os import re from six import ite...
from ..wrapped_decorator import wrap_decorator from ..framework import in_dygraph_mode import warnings import paddle from paddle import _C_ops def _inplace_apis_in_dygraph_only_(func): def __impl__(*args, **kwargs): if not in_dygraph_mode(): origin_api_name = func.__name__[:-1] warni...
from google.cloud.aiplatform import schema import create_and_import_dataset_video_sample import test_constants as constants def test_create_and_import_dataset_video_sample( mock_sdk_init, mock_create_video_dataset ): create_and_import_dataset_video_sample.create_and_import_dataset_video_sample( project=...
import os from dvc.main import main from tests.basic_env import TestDvc class TestUnprotect(TestDvc): def test(self): ret = main(["config", "cache.type", "hardlink"]) self.assertEqual(ret, 0) ret = main(["add", self.FOO]) self.assertEqual(ret, 0) cache = os.path.join( ...
from solum.api.controllers import common_types from solum.api.controllers.v1.datamodel import types as api_types class Services(api_types.Base): """CAMP v1.1 services resource.""" service_links = [common_types.Link] """This attribute contains Links to the service resources that represent the services a...
import abc import six @six.add_metaclass(abc.ABCMeta) class ServiceVMAgentBase(object): @abc.abstractmethod def create(self, info): pass @abc.abstractmethod def delete(self, info): pass @abc.abstractmethod def update(self, info): pass
"""This example creates a test network. You do not need to have a DFP account to run this example, but you do need to have a new Google account (created at http://www.google.com/accounts/newaccount) that is not associated with any other DFP networks (including old sandbox networks). Once this network is created, you ca...
from django.contrib.auth.models import User from django.test import TestCase from rest_framework.authtoken.models import Token from rest_framework.reverse import reverse from rest_framework.test import APIRequestFactory from bestiary.models import Monster, GameItem from herders import api_views, models import json clas...
import logging import unittest from mozurestsdk import mozuclient from mozurestsdk.platform.tenant import Tenant from mozurestsdk.apiexception import ApiException; class Tenant_Test(unittest.TestCase): def setUp(self): logging.basicConfig(level=logging.INFO); client = mozuclient.configure(config="c:\projects\mozuc...
import hashlib import mimetypes import os import requests import logging import threading from rdflib import Graph, Literal, URIRef from classes import ldp, ore from classes.exceptions import RESTAPIException from namespaces import dcterms, iana, pcdm, rdf from operator import attrgetter ns = pcdm class Repository(): ...
from vpp_interface import VppInterface from vpp_papi import VppEnum INDEX_INVALID = 0xffffffff def find_vxlan_gbp_tunnel(test, src, dst, vni): ts = test.vapi.vxlan_gbp_tunnel_dump(INDEX_INVALID) for t in ts: if src == str(t.tunnel.src) and \ dst == str(t.tunnel.dst) and \ t.tunnel....
import sqlalchemy as sql from migrate.changeset.constraint import ForeignKeyConstraint def upgrade(migrate_engine): # Upgrade operations go here. Don't create your own engine; bind # migrate_engine to your metadata meta = sql.MetaData() meta.bind = migrate_engine if 'mysql' in str(meta): acc...
from case import Case class Case5_6(Case): DESCRIPTION = """Send text Message fragmented into 2 fragments, one ping with payload in-between.""" EXPECTATION = """A pong is received, then the message is echo'ed back to us.""" def onOpen(self): ping_payload = "ping payload" fragments = ["fragment1", "...
''' crcchecker is a tool to used to enforce that .api messages do not change. API files with a semantic version < 1.0.0 are ignored. ''' import sys import os import json import argparse import re from subprocess import run, PIPE, check_output, CalledProcessError ROOTDIR = os.path.dirname(os.path.realpath(__file__)) + '...
""" Exposes regular REST commands as services. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/hassio/ """ import asyncio import logging import os import aiohttp import async_timeout from homeassistant.components.http import ( CONF_API_PASSWORD, CONF_S...
import errno import os import stat import sys import unittest try: # Python 2.x (str) from cStringIO import StringIO except ImportError: # Python 3.x (unicode) from io import StringIO sys.path.insert(1, '../') import payu import payu.fsops import payu.laboratory class Test(unittest.TestCase): def se...
"""Various learning rate decay functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensor...
"""Class that generates ecosystem+package and ecosystem+package+version tuples.""" class GremlinPackageGenerator: """Class that generates ecosystem+package and ecosystem+package+version tuples.""" PACKAGES = { "npm": { "sequence": ["3.0.0"] }, "maven": { "io.vertx...
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>" __date__ = "$Jul 31, 2015 18:00:05 EDT$" import argparse import hashlib import itertools import os import re import shutil import subprocess import sys import time import threading import webbrowser if sys.version_info.major == 2: from httplib import BadStatus...
"""Base classes for artifacts.""" import logging from grr.lib import aff4 from grr.lib import artifact_lib from grr.lib import config_lib from grr.lib import flow from grr.lib import rdfvalue from grr.lib import registry from grr.lib import utils from grr.proto import flows_pb2 class AFF4ResultWriter(object): """A wr...
''' FanFilm 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 later version. This pr...
"""scaling group tenant binding table Revision ID: 357cd913dae6 Revises: 3c7123f2aeba Create Date: 2016-06-02 17:47:12.736929 """ revision = '357cd913dae6' down_revision = '3c7123f2aeba' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( "a1...
from orchestra.tests.helpers import OrchestraTestCase from orchestra.utils.models import ChoicesEnum class ModelUtilsTests(OrchestraTestCase): def test_choices_enum(self): class TestEnum(ChoicesEnum): val0 = 'desc0' val1 = 'desc1' val2 = 'desc2' self.assertEqual(T...
""" Exceptions raised by the Horizon code and the machinery for handling them. """ import logging import os import sys import six from django.core.management import color_style # noqa from django.http import HttpRequest # noqa from django.utils import encoding from django.utils.translation import ugettext_lazy as _ f...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tasks', '0032_task_catalogs'), ] operations = [ migrations.AddField( model_name='task', name='locked', field=models.BooleanField(default=False, help_text='De...
"""CLI interface for cinder management.""" import collections import collections.abc as collections_abc import errno import glob import itertools import logging as python_logging import os import re import sys import time from oslo_config import cfg from oslo_db import exception as db_exc from oslo_log import log as lo...
from designate.api.v2.views import base as base_view from designate.openstack.common import log as logging LOG = logging.getLogger(__name__) class NameServerView(base_view.BaseView): """ Model a NameServer API response as a python dictionary """ _resource_name = 'nameserver' _collection_name = 'nameservers'...
import base58 import pytest from common.serializers.serialization import state_roots_serializer from crypto.bls.bls_multi_signature import MultiSignature, MultiSignatureValue from plenum.common.constants import DOMAIN_LEDGER_ID from plenum.common.util import get_utc_epoch from plenum.test.constants import GET_BUY num =...
from bin import ambaribuild def unittest(): # parse result = ambaribuild.parse(["test"]) assert result.is_deep_clean == False assert result.is_test == True assert result.is_rebuild == False assert result.stack_distribution == None assert result.supplemental_distribution == None assert result.is_install_server =...
import random import uuid from oslo_config import cfg from six.moves import http_client from six.moves import range from keystone.common import controller from keystone import exception from keystone.tests import unit from keystone.tests.unit import test_v3 from keystone.tests.unit import utils CONF = cfg.CONF class As...
from __future__ import print_function import RMF import unittest import shutil import os import sys class Tests(unittest.TestCase): def get_filename_key(self, fh): cat = fh.get_category("provenance") return fh.get_key(cat, "structure filename", RMF.string_tag) def make_test_node(self, fh): ...
class MediaContentHandlerBase(object): def get_iframe_template(self, content_id, **kwargs): raise NotImplementedError def get_iframe_code(self, content_id, **kwargs): raise NotImplementedError def get_javascript_code(self, **kwargs): raise NotImplementedError def get_thumbnail_ur...
""" Copyright (c) 2016 - Sean Bailey - All Rights Reserved Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed t...
""" SQLAlchemy models for application data. """ from oslo.config import cfg from sqlalchemy.ext import declarative from solum import objects from solum.openstack.common.db import exception as db_exc from solum.openstack.common.db.sqlalchemy import models from solum.openstack.common.db.sqlalchemy import session as db_se...
import sys if sys.version >= '3': basestring = unicode = str from py4j.java_gateway import JavaClass from pyspark import RDD, since from pyspark.rdd import ignore_unicode_prefix from pyspark.sql.column import _to_seq from pyspark.sql.types import * from pyspark.sql import utils __all__ = ["DataFrameReader", "DataFr...
from oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-attach-interfaces' POLICY_ROOT = 'os_compute_api:os-attach-interfaces:%s' DEPRECATED_REASON = """ Nova API policies are introducing new default roles with scope_type capabilities. Old policies are deprecated and silently...
from oslo_config import cfg from oslo_policy import policy from monasca_api import policies CONF = cfg.CONF DEFAULT_AUTHORIZED_ROLES = policies.roles_list_to_check_str( cfg.CONF.security.default_authorized_roles) READ_ONLY_AUTHORIZED_ROLES = policies.roles_list_to_check_str( cfg.CONF.security.read_only_authoriz...
""" :mod:`tests` -- Utility methods for tests. =================================== .. automodule:: utils :platform: Unix :synopsis: Tests for Nova. """ import subprocess from urllib import unquote try: EVENT_AVAILABLE = True except ImportError: EVENT_AVAILABLE = False from proboscis.asserts import assert_...
"""Tests for mnist.train.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl.testing import parameterized import numpy as np import tensorflow as tf import train FLAGS = flags.FLAGS mock = tf.test.mock class TrainTest(tf.test....
import cloud from cloudferrylib.os.identity import keystone from cloudferrylib.os.network import neutron from cloudferrylib.os.compute import nova_compute from cloudferrylib.utils import utils LOG = utils.get_log(__name__) class Grouping(object): def __init__(self, config, group_file, cloud_id): self.config...
from typing import Any, Dict from django.http import HttpRequest, HttpResponse from zerver.decorator import webhook_view from zerver.lib.actions import check_send_private_message from zerver.lib.request import REQ, RequestNotes, has_request_variables from zerver.lib.response import json_success from zerver.models impor...
"""Registering ops in mxnet.numpy for imperative programming.""" from __future__ import absolute_import from ..base import _init_np_op_module from ..ndarray.register import _make_ndarray_function _init_np_op_module(root_module_name='mxnet', np_module_name='numpy', mx_module_name=None, make_op_func=_m...
import twitter import logging import sys import pprint _loggingLevel = logging.INFO logger = logging.getLogger(__name__) logging.basicConfig(level=_loggingLevel) def IterChunks(sequence, chunk_size): res = [] for item in sequence: res.append(item) if len(res) >= chunk_size: yield res...
"""Functions for configuring TensorFlow execution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Union from tensorflow.python.eager import context from tensorflow.python.framework import errors from tensorflow.python.util import _pywra...
https://www.hackerrank.com/challenges/taum-and-bday import sys t = int(raw_input().strip()) for a0 in xrange(t): b,w = raw_input().strip().split(' ') b,w = [long(b),long(w)] x,y,z = raw_input().strip().split(' ') x,y,z = [long(x),long(y),long(z)] print min(b*x+w*y,(b*(y+z))+w*y,b*x+(w*(x+z)))
"""Support for Blink Home Camera System.""" import asyncio from copy import deepcopy import logging from blinkpy.auth import Auth from blinkpy.blinkpy import Blink import voluptuous as vol from homeassistant.components import persistent_notification from homeassistant.components.blink.const import ( DEFAULT_SCAN_IN...
"""Add a column to track the encryption state of the 'Extra' field in connection Revision ID: bba5a7cfc896 Revises: bbc73705a13e Create Date: 2016-01-29 15:10:32.656425 """ import sqlalchemy as sa from alembic import op revision = 'bba5a7cfc896' down_revision = 'bbc73705a13e' branch_labels = None depends_on = None airf...
import base64 import os import re import sys import googleapiclient import gam from gam.var import * from gam import fileutils from gam import gapi from gam import utils def build_gapi(): return gam.buildGAPIObject('storage') def get_cloud_storage_object(s, bucket, ...
""" Implements a blob store backed by an Impala table. Schema is always (key STRING, value STRING). Can be initialized to an already existing blob store table. Supports getting binary data from the store. Also support putting data in from Impala (via a SQL query). Sending data is more fraught, as the data must be en...
from uliweb.utils.sorteddict import SortedDict def test_1(): """ >>> d = SortedDict() >>> d[2] = {'id':'a', 'name':'a2'} >>> d[4] = {'id':'d', 'name':'a4'} >>> d[3] = {'id':'c', 'name':'a3'} >>> d[1] = {'id':'b', 'name':'a1'} >>> d.items() [(2, {'id': 'a', 'name': 'a2'}), (4, {'id': 'd',...
from math import floor import struct from ..errors import * TYPE = 'T' STRUCT_ZSET_SCORE = '!d' STRUCT_ZSET_ITEM_COUNT = '!i' STRUCT_ZSET_VALUE = '!ici' STRUCT_ZSET_SCORE_KEY = '!icicd' STRUCT_ZSET_SCORE_POSITION = '!icicdi' STRUCT_ZSET_ELEMENT = '!icic' STRUCT_ZSET_ELEMENT_VALUE = '!di' def _zset_key(db, id): retu...
""" Predictions widget """ import sys from collections import OrderedDict, namedtuple import numpy from PyQt4 import QtCore, QtGui from PyQt4.QtCore import Qt, pyqtSlot as Slot import Orange import Orange.evaluation from Orange.base import Model from Orange.data import ContinuousVariable, DiscreteVariable from Orange.w...
from __future__ import print_function import re from streamlink.plugin import Plugin from streamlink.plugin.api import http from streamlink.plugin.api import validate from streamlink.stream import HDSStream from streamlink.stream import HLSStream class Dogus(Plugin): """ Support for live streams from Dogus site...
from __future__ import print_function, absolute_import, division import itertools import numpy as np from numba import jit, utils from numba import unittest_support as unittest from .support import TestCase, forbid_codegen from .enum_usecases import * DBL_EPSILON = 2**-52 FLT_EPSILON = 2**-23 INF = float('inf') NAN = f...
from __future__ import unicode_literals from future.builtins import int, str from collections import defaultdict from mezzanine.conf import settings from mezzanine.twitter import (QUERY_TYPE_USER, QUERY_TYPE_LIST, QUERY_TYPE_SEARCH) from mezzanine.twitter.models import Tweet, TwitterQuery...
from .conf import AppConf
from django.db.models import Transform from django.db.models.lookups import Exact, PostgresOperatorLookup from .search import SearchVector, SearchVectorExact, SearchVectorField class DataContains(PostgresOperatorLookup): lookup_name = 'contains' postgres_operator = '@>' class ContainedBy(PostgresOperatorLookup)...
from numpy import * parameter_list = [[10,3,15,0.9,1,2000,1],[20,4,15,0.9,1,5000,2]] def classifier_larank (num_vec,num_class,distance,C=0.9,num_threads=1,num_iter=5,seed=1): from shogun import MulticlassLabels from shogun import LaRank from shogun import Math_init_random import shogun as sg # reproducible results...
from django.test import SimpleTestCase from ..utils import render, setup multiline_string = """ Hello, boys. How are you gentlemen. """ class MultilineTests(SimpleTestCase): @setup({'multiline01': multiline_string}) def test_multiline01(self): output = render('multiline01') self.assertEqual(outp...
""" =============================================== :mod:`ec` -- Evolutionary computation framework =============================================== This module provides the framework for creating evolutionary computations. .. Copyright 2012 Inspired Intelligence Initiative .. This program is fre...
from django.contrib.auth.models import Group from django.test import TestCase from django.urls import reverse from wagtail.admin.site_summary import PagesSummaryItem from wagtail.core.models import GroupPagePermission, Page, Site from wagtail.tests.testapp.models import SimplePage from wagtail.tests.utils import Wagtai...
"""Test cases for Zinnia's admin widgets""" from django.test import TestCase from django.test.utils import override_settings from django.utils.encoding import smart_text from zinnia.admin.widgets import MPTTFilteredSelectMultiple from zinnia.admin.widgets import MiniTextarea from zinnia.admin.widgets import TagAutoComp...
from admin_enhancer.admin import EnhancedModelAdminMixin from cms.admin.placeholderadmin import PlaceholderAdminMixin, FrontendEditableAdminMixin from copy import deepcopy from django.contrib import admin from django.conf import settings from django.contrib.auth import get_user_model from parler.admin import Translatab...