code stringlengths 1 199k |
|---|
import os
import sys
import logging
import openerp
import openerp.netsvc as netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID
from openerp im... |
import tempfile
def tmp_file_sink(prefix=None, suffix=None):
tmpfile = tempfile.NamedTemporaryFile(delete=True,
prefix=prefix,
suffix=suffix)
tmpfile.close()
return tmpfile.name |
from aiohttp import web
from aiohttp_jinja2 import render_template
from aiohttp_session_flash import flash
async def error_middleware(app, handler):
async def middleware_handler(request):
try:
response = await handler(request)
if response.status in [400, 403, 404, 405]:
... |
from superdesk.metadata.item import metadata_schema
from superdesk.resource import Resource
blogs_schema = {
'title': metadata_schema['headline'],
'description': metadata_schema['description_text'],
'picture_url': {
'type': 'string',
'nullable': True
},
'picture_renditions': {
... |
import logging
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404
from seriesly.series.models import Show, Episode
from seriesly.helper import is_get, is_post
def update(request):
shows = Show.get_all_ordered()
for show in shows:
show.add_u... |
import csv
from io import BytesIO, StringIO
from zipfile import ZIP_DEFLATED, ZipFile
_station_list_csv_headers = [
"id",
"Name",
"Short name",
"Type",
"Owner",
"Start date",
"End date",
"Abscissa",
"Ordinate",
"SRID",
"Approximate",
"Altitude",
"SRID",
"Water bas... |
try:
from settings_common import *
except ImportError:
print "The settings_common.py file does not exist."
print "Your installation is improperly configured."
exit()
INSTALLED_APPS += (
# 'debug_toolbar',
# paiji2 apps
'paiji2_utils',
'paiji2_weather',
'paiji2_infoconcert',
'paij... |
import os
import sys
import MySQLdb
import time
import re
import urllib
import traceback
from pyconst import *
DOWNLOAD_INTERVAL=120 #s
SICAV_COUNT_PER_DOWNLOAD=50
def GetUrlStream( action_list):
#returl="http://fr.old.finance.yahoo.com/d/quotes.csv?s="
returl="http://download.finance.yahoo.com/d/quotes.csv?s="... |
import logging
from PyQt5.QtCore import Qt, QSortFilterProxyModel, QStringListModel, QThread
from PyQt5.QtGui import QPalette, QTextCursor
from PyQt5.QtWidgets import QCompleter, QHeaderView, QMessageBox, QProgressDialog
from setools import UserQuery
from ..logtosignal import LogHandlerToSignal
from ..models import SET... |
import mapnik
merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over')
longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
mapfile = "osm.xml"
m = mapnik.Map(600,300)
mapnik.load_map(m,mapfile)
m.srs = ... |
import os, sys
from datetime import datetime
sys.path.insert(0, os.path.abspath(".."))
from pysignfe.nf_e import nf_e
if __name__ == '__main__':
nova_nfe = nf_e()
#Associacao.pfx nao e valido, utilize um certificado valido
caminho_certificado = "certificado/Associacao.pfx"
with open(caminho_certificado,... |
"""
This module defines so called result driver classes. A result driver is used
in order to generate ready to use result objects from objects returned by a
store.
"""
from __future__ import print_function, absolute_import, division
import numpy
import quantities as pq
import odml
import odml.base
import odml.section
i... |
from spack import *
class RZoo(RPackage):
"""An S3 class with methods for totally ordered indexed observations. It is
particularly aimed at irregular time series of numeric vectors/matrices and
factors. zoo's key design goals are independence of a particular
index/date/time class and consistency with ts... |
import dbus
from twisted.words.xish import xpath
from twisted.words.protocols.jabber.client import IQ
from servicetest import (assertEquals, EventPattern, TimeoutError)
from gabbletest import exec_test, make_result_iq, sync_stream, make_presence
import constants as cs
from caps_helper import compute_caps_hash, \
te... |
"""
Some common classes and functions
@author: Stijn De Weirdt (Ghent University)
"""
import os
try:
from vsc.utils.fancylogger import getLogger
except:
from logging import getLogger
def get_subclasses(klass):
"""
Get all subclasses recursively
"""
res = []
for cl in klass.__subclasses__():
... |
import fs_haul_shared
name = "pid"
class p_haul_type:
def __init__(self, id):
self.pid = int(id)
#
# Initialize itself for source node or destination one
#
def init_src(self):
pass
def init_dst(self):
pass
# Get tuple of name and id to construct the
# same object on the remote host
def id(self):
return... |
import os
from docutils import nodes, writers
from sphinx import version_info as SPHINX_VERSION
from sphinx.util import logging
from sphinx.writers.text import TextTranslator, Table, Cell
if False:
# For type annotation
from typing import Any, Callable, Tuple, Union # NOQA
from sphinx.builders.text import ... |
"""Buttons"""
class GnrCustomWebPage(object):
py_requires = "gnrcomponents/testhandler:TestHandlerBase"
dojo_theme = 'tundra'
def test_1_basic(self, pane):
"""Basic button"""
pane.button('i am a button', action='alert("you clicked me")')
def test_2_styled(self, pane):
"""Styled b... |
"""Test of radio menu item output."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(KeyComboAction("<Control>f"))
sequence.append(TypeAction("Application class"))
sequence.append(KeyComboAction("Return"))
sequence.append(KeyComboAction("Return"))
sequence.append(KeyComboAction(... |
"""
voice_nav.py allows controlling a mobile base using simple speech commands.
Based on the voice_cmd_vel.py script by Michael Ferguson in the pocketsphinx ROS package.
"""
import roslib; roslib.load_manifest('qbo_communicator')
import rospy
from geometry_msgs.msg import Twist
from std_msgs.msg import String
from ... |
import unittest
from primo2.networks import BayesianNetwork
from primo2.nodes import RandomNode, DiscreteNode
class BayesNetTest(unittest.TestCase):
def setUp(self):
self.bn = BayesianNetwork()
def test_add_node(self):
n = RandomNode("Node1")
self.assertEqual(len(self.bn), 0)
sel... |
r"""
Test file to execute all the tests from the unittest library within the pentago code using nose.
Notes
-----
"""
import nose
import dstauffman2.games.pentago as pentago
if __name__ == '__main__':
nose.run(pentago) |
"""
Unit tests for
:func:`iris.fileformats.pp_rules._convert_scalar_vertical_coords`.
"""
from __future__ import (absolute_import, division, print_function)
import iris.tests as tests
from iris.coords import DimCoord, AuxCoord
from iris.aux_factory import HybridPressureFactory, HybridHeightFactory
from iris.fileformats... |
"""
Methods that handles rotation of seismograms as extension to Obspy.
It can rotate `12`, `EN` and `RT`, forward and backward.
:copyright:
Wenjie Lei (lei@princeton.edu), 2016
:license:
GNU Lesser General Public License, version 3 (LGPLv3)
(http://www.gnu.org/licenses/lgpl-3.0.en.html)
"""
from __future__... |
"""
Tweak of profile plots.
"""
import pickle
import matplotlib.pylab as plt
import numpy as np
from subprocess import Popen
import os, sys
commonDir = os.path.abspath("./../../../common")
sys.path.append(commonDir)
from CELMAPy.plotHelpers import PlotHelper, seqCMap3
folder = "../../CSDXMagFieldScanAr/visualizationPhy... |
from datetime import datetime
import decimal
import math
import re
G__ = r'( {%d})'
G_N = r'(\d{%d})'
G_N_ = r'([0-9 ]{%d})'
G_A = r'(\w{%d})'
G_A_ = r'([a-zA-Z ]{%d})'
G_AN = r'([a-zA-Z0-9]{%d})'
G_AN_ = r'([a-zA-Z0-9 ]{%d})'
G_AMT = r'(\d{13}[{}A-R]{1})'
G_ALL = r'(.{%d})'
class ParsingError(Exception):
"""Simple... |
""" Exceptions, which can be thrown by validators.
"""
class ValidationError(Exception):
""" Basic validation error.
""" |
"""
Author: Nicolas VERDIER (contact@n1nj4.eu)
Original idea from @huntergregal (https://github.com/huntergregal/mimipenguin)
This is a port in python of @huntergregal's bash script mimipenguin.sh with some improvments :
- possibility to clean passwords found from memory
- possibility to sea... |
"""
Views for Indivo JS UI
"""
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, HttpResponseForbidden, HttpResponseServerError, Http404, HttpRequest
from django.contrib.auth.models import User
from django.core.exceptions import *
from django.core.urlresolvers import reverse
from djang... |
import cadquery
from cqparts.params import *
from .base import ScrewDrive, register
@register(name='slot')
class SlotScrewDrive(ScrewDrive):
"""
.. image:: /_static/img/screwdrives/slot.png
"""
width = PositiveFloat(None, doc="slot width")
def initialize_parameters(self):
if self.width is No... |
"""
This file is part of PyZ80.
PyZ80 is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PyZ80 is distributed in the hope that it will be... |
"""
@package bapp.interfaces
@brief Most basic interfaces for general usage, useful in all host applications !
@author Sebastian Thiel
@copyright [GNU Lesser General Public License](https://www.gnu.org/licenses/lgpl.html)
"""
from __future__ import unicode_literals
__all__ = ['IPlatformService', 'IContextController',
... |
import binascii
import os
from twisted.internet.defer import Deferred
import libtorrent as lt
from Tribler.Core.DownloadConfig import DownloadStartupConfig
from Tribler.Core.Libtorrent.LibtorrentDownloadImpl import LibtorrentDownloadImpl
from Tribler.Core.SessionConfig import SessionStartupConfig
from Tribler.Core.Torr... |
import pytest
import os
test_cfg = """name: rw_test
test: this is just a test.
one:
- pink: martini
red: apples #this one will change
blue: berry
two:
- a: true
b: false
c: null
"""
test_cfg2 = """name: rw_test
test: this is just a test.
one:
- pink: martini
red: strawberry #this one will change
blue: berry... |
import sys
sys.path.append("../") #not good!
sys.path.append("../../src/") #not good!
from pypdflib.writer import PDFWriter
from pypdflib.widgets import *
from pypdflib.styles import *
import pango
import os
from HTMLParser import HTMLParser
from pyquery import PyQuery as pq
import urllib
import urlparse
import urll... |
import ply.lex as lex
import string
states = (('enum', 'inclusive'), ('function', 'inclusive'), ('variable', 'inclusive'),\
('block', 'exclusive'), ('sipStmt', 'exclusive'), ('filename', 'exclusive'), \
('string', 'exclusive'), ('dottedname', 'exclusive'), ('keypairs','exclusive'), \
('key... |
from pathlib import Path
from typing import Union
from .simple import Serializable
from .simple import decode
from .simple import encode
from .simple import is_object_serializable
from .simple import to_dict
from .simple import from_dict
def save(obj, path_file: Union[str, Path], allow_implicit_simples=False):
path... |
import os
import pyblish_maya
import pyblish_magenta.plugin
class ExtractMayaAscii(pyblish_magenta.api.Extractor):
"""Extract as Maya Ascii"""
label = "Maya ASCII"
hosts = ["maya"]
families = ["model", "rig"]
optional = True
def process(self, instance):
from maya import cmds
# De... |
from django.core.management.base import BaseCommand
from django.utils import timezone
from generator.models import Page
class Command(BaseCommand):
help = "Truncate non-saved pages that have existed for 24 hours"
def handle(self, *args, **options):
print("Truncating pages")
old_datetime = timezo... |
import json
import time
import types
import uuid
from difflib import SequenceMatcher
__doc__ = """
malibu.design.brine
-------------------
Brine is a play on Python's pickle module, which is used for
serializing data. Brine is used for serialization as well, but
into JSON, not a binary structure.
"""
METHOD_TYPES = [ty... |
import string
import collections
def read_grammar(_file):
productions = []
productions_options = collections.OrderedDict()
with open(_file, 'r') as grammar_file:
for line in grammar_file:
line = line.replace('\n', '')
production = line.split('->') # Token
termi... |
""" Youtube track source module """
import os
from apiclient.discovery import build # pylint:disable=import-error
from oauth2client.client import GoogleCredentials
from voiceplay.utils.score import VideoScoreCalculator
from .basesource import TrackSource
class YoutubeSource(TrackSource):
"""
Youtube track sour... |
from django import forms
from demoapp import app_settings
from django.utils.translation import ugettext_lazy as _
class DemoLoginForm(forms.Form):
password = forms.CharField(label=_('Password'), widget=forms.PasswordInput)
def clean_password(self):
password = self.cleaned_data['password']
if pas... |
from types import *
class ResultFileInfo:
def __init__(self):
self.__dict__['openStatus'] = 0
self.__dict__['file'] = ''
def __getattr__(self, name):
if name == 'openStatus':
return self.__dict__['openStatus']
if name == 'file':
return self.__dict__['file'... |
import dsz
import dsz.lp.alias
import dsz.lp.cmdline
import dsz.path
import dsz.version
import os
import re
import sys
import xml.dom.minidom
class NewTerminal:
def __init__(self):
self.bFocus = False
self.bClose = False
self.bDisable = False
self.dst = dsz.script.Env['target_address... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import * # noqa
import logging
import http.client
from urllib.parse import urlparse
f... |
"""Library for interacting with databases via Python DB API.
Sample usage:
connection = ... # Create connection to your DB of choice.
client = db_api_bq.Client(connection)
result = client.Query(query)
"""
from __future__ import absolute_import
import six
from verily.bigquery_wrapper.bq_base import (BQ_PATH... |
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec
_REQUEST_MESSAGE_TYPE = 394240
_RE... |
"""
Dumbo provides a few generic Mappers and Reducers implemented as functions,
The purpose of this module is to write a few canonical Map and Reduce
patterns as classes so that they can be reused or extended.
"""
from identity import *
from statistics import * |
"""
Updated by Lin Xiong Oct-30, 2017
Modified by Lin Xiong Oct-31, 2017 (add SE building block)
"""
import argparse,logging,os
import mxnet as mx
from symbol_se_inception_resnet_v2 import get_symbol
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(message)s')
co... |
import time
import socket
import json
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.contrib.hooks.jenkins_hook import JenkinsHook
import jenkins
from jenkins import JenkinsException
from requests import Request
im... |
"""
>>> getfixture('inject_matchers')
>>> allure_report = getfixture('allure_report')
>>> assert_that(allure_report,
... all_of(
... has_property('test_cases', has_length(32)),
... has_property('test_groups', has_length(0))
... )) # doctest: +SKIP
>>> for test_cas... |
'''
Run as follows:
python Stein.py <data directory name>
Suffix `.data` will be appended to the directory name.
If data has already been generated, the analysis can be run as follows:
python Stein.py <data directory name> --no-run
TODO:
We could run several simulations in the same lifsim() function by defi... |
"""The processing engine."""
import os
from artifacts import errors as artifacts_errors
from artifacts import reader as artifacts_reader
from artifacts import registry as artifacts_registry
from dfvfs.helpers import file_system_searcher
from dfvfs.lib import errors as dfvfs_errors
from dfvfs.path import factory as path... |
from diarc.topology import *
class RosSystemGraph(Topology):
def __init__(self):
super(RosSystemGraph,self).__init__()
@property
def nodes(self):
return dict([(v.name,v) for v in self.vertices])
@property
def topics(self):
return dict(filter(lambda x: None not in x, [(topic.n... |
"""Registry of algorithm names for `rllib train --run=<alg_name>`"""
import traceback
from ray.rllib.contrib.registry import CONTRIBUTED_ALGORITHMS
def _import_sac():
from ray.rllib.agents import sac
return sac.SACTrainer
def _import_appo():
from ray.rllib.agents import ppo
return ppo.APPOTrainer
def _i... |
"""SymbolicOperator is the base class for FermionOperator and QubitOperator"""
import abc
import copy
import itertools
import re
import warnings
import numpy
from six import add_metaclass, string_types
from openfermion.config import EQ_TOLERANCE
@add_metaclass(abc.ABCMeta)
class SymbolicOperator:
"""Base class for ... |
from django.conf import settings
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
if not settings.PRO... |
import logging
import re
from modules.antivirus.base import AntivirusWindows
log = logging.getLogger(__name__)
class SophosWin(AntivirusWindows):
name = "Sophos Endpoint Protection (Windows)"
# ==================================
# Constructor and destructor stuff
# ==================================
... |
'''
Created on Oct 3, 2013
@author: lauril
'''
import numpy as np
from decimal import Decimal
from matplotlib.font_manager import FontProperties
from mpltools import layout
from mpltools import color
import matplotlib.pyplot as plt
from defines import colors_5
test={'waf -j1 build':
{'m1.medium': 2291.236293,... |
from scriptcore.testing.testcase import TestCase
from scriptcore.config.config import Config
class TestConfig(TestCase):
def test_get(self):
"""
Test get
:return: void
"""
# Make ini-file
path = self.write_temp_file("""
[section1]
string1: string1
""")
conf... |
import logging
logging.debug('Beginning main.py')
import os
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template, Request, Response
from google.appengine.ext.webapp.util import run_wsgi_app
import dec... |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
from toontown.toonbase import ToontownGlobals
from toontown.catalog import CatalogItem
from toontown.catalog.CatalogItemList import CatalogItemList
from toontown.catalog.CatalogPoleItem import Catal... |
"""Collection classes and helpers."""
import itertools
import weakref
import operator
from .compat import threading
EMPTY_SET = frozenset()
class KeyedTuple(tuple):
"""``tuple`` subclass that adds labeled names.
E.g.::
>>> k = KeyedTuple([1, 2, 3], labels=["one", "two", "three"])
>>> k.one
... |
"""Handles collecting stats for various parts in the learner."""
import contextlib
import socket
import time
from log import falken_logging
import common.generate_protos # pylint: disable=unused-import
import data_store_pb2 as falken_schema_pb2
FALKEN_PROCESS_EVENT_NAME = 'process'
FALKEN_MAIN_TRAINING_LOOP_EVENT_NAME... |
import re
import random
import jsonlines
from textblob import TextBlob
exceptions = set(['injured', 'died', 'ill', 'fatal', 'dead', 'death', 'dies', 'stabbing', 'stabbed', 'stabs', 'crash', 'drowns', 'drowned', 'crash', 'crashed'])
def prove_carcinogenic_effect_with_science(headlines_file_path, use_actual_science):
... |
"""
link
~~~~~~~~~~~~
The link module helps you connect to all of the data sources you need through a
simple configuration
Sample Config to connect to mysql::
{
"dbs":{
"my_db": {
"wrapper": "MysqlDB",
"host": "mysql-master.123fakestreet.net",
"password... |
"""Updates an existing autoscale vm group."""
from baseCmd import *
from baseResponse import *
class updateAutoScaleVmGroupCmd (baseCmd):
typeInfo = {}
def __init__(self):
self.isAsync = "true"
"""the ID of the autoscale group"""
"""Required"""
self.id = None
self.typeInf... |
import sys
import platform
if __name__ == "__main__":
assert('python3_test.runfiles/python3/python3/bin/' in sys.executable)
assert(platform.python_version() == "3.10.1") |
from absl.testing import absltest
from tensorflow_privacy.privacy.privacy_tests.secret_sharer import generate_secrets as gs
class UtilsTest(absltest.TestCase):
def __init__(self, methodname):
"""Initialize the test class."""
super().__init__(methodname)
def test_generate_random_sequences(self):
"""Test ... |
"""Wrapper for inverting a Distrax Bijector."""
from typing import Tuple
from distrax._src.bijectors import bijector as base
from distrax._src.utils import conversion
Array = base.Array
BijectorLike = base.BijectorLike
BijectorT = base.BijectorT
class Inverse(base.Bijector):
"""A bijector that inverts a given bijecto... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import os, re, sys, time
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import conf... |
import json
from oslo.config import cfg
from oslo_log import log as logging
import six
import webob.exc
from glance.api import policy
from glance.common import exception
from glance.common import utils
from glance.common import wsgi
import glance.db
import glance.gateway
from glance import i18n
import glance.notifier
i... |
from __future__ import unicode_literals
from django.contrib import admin
from .models import *
admin.site.register(guardia) |
from __future__ import print_function
import os
import requests
import re
import time
import xml.dom.minidom
import json
import sys
import math
import subprocess
import ssl
import threading
DEBUG = False
MAX_GROUP_NUM = 2 # 每组人数
INTERFACE_CALLING_INTERVAL = 5 # 接口调用时间间隔, 间隔太短容易出现"操作太频繁", 会被限制操作半小时左右
MAX_PROGRESS_LEN ... |
import contextlib
import posixpath
from oslo_log import log as oslo_logging
from six.moves import http_client
from six.moves import urllib
from cloudbaseinit import conf as cloudbaseinit_conf
from cloudbaseinit.metadata.services import base
from cloudbaseinit.osutils import factory as osutils_factory
from cloudbaseinit... |
__author__ = 'yinjun'
import unittest
import os
import imp
class TestSolutionFuncs(unittest.TestCase):
def setUp(self):
path = os.getcwd() + '/solution.py'
so = imp.load_source('solution', path)
self.s = so.Solution()
# common = os.path.dirname(os.path.dirname(os.getcwd())) + '/commo... |
from django.urls import reverse
from django.test.client import Client
from mixer.backend.django import mixer
from ibms.tests import IbmsTestCase
from sfm.models import FinancialYear, Quarter, SFMMetric, MeasurementType, CostCentre, MeasurementValue
class SfmViewsTest(IbmsTestCase):
"""Test that sfm application view... |
"""Utils for use from the console.
Includes functions that are used by interactive console utilities such as
approval or token handling.
"""
import getpass
import os
import time
import logging
from grr.lib import access_control
from grr.lib import aff4
from grr.lib import data_store
from grr.lib import flow
from grr.li... |
"""
Tests for group_snapshot code.
"""
import ddt
import mock
from six.moves import http_client
import webob
from cinder.api import microversions as mv
from cinder.api.v3 import group_snapshots as v3_group_snapshots
from cinder import context
from cinder import db
from cinder import exception
from cinder.group import a... |
from __future__ import print_function
import ttfw_idf
@ttfw_idf.idf_example_test(env_tag='Example_GENERIC', target=['esp32', 'esp32c3'])
def test_cpp_rtti_example(env, extra_data):
dut = env.get_dut('cpp_rtti', 'examples/cxx/rtti')
dut.start_app()
dut.expect('Type name of std::cout is: std::ostream')
du... |
import numpy
from keras.layers import Embedding, Input
from keras.models import Model
from deep_qa.layers.attention.weighted_sum import WeightedSum
class TestWeightedSumLayer:
def test_call_works_on_simple_input(self):
batch_size = 1
sentence_length = 5
embedding_dim = 4
matrix_input... |
"""
A script that runs the tests with --collect-only, but instead of just printing
the tests' names, prints the information added by the tools.decorators.known_failure
decorator.
This is basically a wrapper around the `nosetests` command, so it takes the
same arguments, though it appends some arguments to sys.argv. In ... |
from rest_framework import status
from test_utils import serialized_time
def test_get_profile(
api_client, enable_premium_requirement, profile_factory, user_factory
):
"""
Premium users should be able to view their own profile.
"""
password = "password"
user = user_factory(has_premium=True, pass... |
"""ImageNet input pipeline with MLPerf preprocessing."""
import itertools
from init2winit.dataset_lib import data_utils
from init2winit.dataset_lib import mlperf_input_pipeline
import jax
from ml_collections.config_dict import config_dict
import tensorflow.compat.v2 as tf
NUM_CLASSES = 1000
DEFAULT_HPARAMS = config_dic... |
"""
Creates, updates, and deletes a job object.
"""
from os import path
from time import sleep
import yaml
from kubernetes import client, config
JOB_NAME = "pi"
def create_job_object():
# Configureate Pod template container
container = client.V1Container(
name="pi",
image="perl",
command... |
import logging
import os
import platform
import sys
try:
import syslog
except ImportError:
syslog = None
import tempfile
import time
import mock
from oslo_config import cfg
from oslo_config import fixture as fixture_config # noqa
from oslo_context import context
from oslo_context import fixture as fixture_cont... |
"""Minimal Gnip API using HTTP requests."""
import textwrap
import requests
from .search import SearchManager
class Gnip(object):
"""Simple binding to Gnip search API."""
session_class = requests.Session
default_params = {
'publisher': 'twitter',
'maxResults': 500,
}
def __init__(sel... |
from resourcehelper import ResourceHelper
def no_generator(top):
result = []
i = 0
while i < top:
result.append(i)
i += 1
return result
if __name__ == '__main__':
rh = ResourceHelper(__file__)
for i in no_generator(10000):
pass
rh.usage() |
"""
Port of NNVM version of MobileNet to Relay.
"""
from tvm import relay
from . import layers
from .init import create_workload
def conv_block(data, name, channels, kernel_size=(3, 3), strides=(1, 1),
padding=(1, 1), epsilon=1e-5):
"""Helper function to construct conv_bn-relu"""
# convolution + ... |
from guicore.displayscreen import EventDispatch
from controlevents import CEvent
import debug
def MouseOther(event):
debug.debugPrint('Touch', 'Other mouse event {}'.format(event))
if CEvent.MouseUp not in EventDispatch:
EventDispatch[CEvent.MouseUp] = MouseOther
if CEvent.MouseMotion not in EventDispatch:
EventDisp... |
import copy
import eventlet
from itertools import chain as iter_chain
from itertools import combinations as iter_combinations
import mock
import netaddr
from oslo_log import log
import oslo_messaging
from oslo_utils import uuidutils
from testtools import matchers
from neutron.agent.common import config as agent_config
... |
"""
Transpiler pass to remove diagonal gates (like RZ, T, Z, etc) before
a measurement. Including diagonal 2Q gates.
"""
from qiskit.circuit import Measure
from qiskit.extensions.standard import RZGate, ZGate, TGate, SGate, TdgGate, SdgGate, U1Gate,\
CzGate, CrzGate, Cu1Gate, RZZGate
from qiskit.transpiler.basepass... |
from .describe_dns_aliases import DescribeDNSAliasesAction
from .associate_dns_alias import AssociateDNSAliasAction
from .dissociate_dns_aliases import DissociateDNSAliasesAction
from .get_dns_label import GetDNSLabelAction
__all__ = [GetDNSLabelAction, DescribeDNSAliasesAction,
AssociateDNSAliasAction, Dissoci... |
"""Utility functions for parsing and building Ethernet packet/contents."""
import ipaddress
import socket
import struct
from ryu.lib import addrconv
from ryu.lib.packet import (
arp, bpdu, ethernet,
icmp, icmpv6, ipv4, ipv6,
lldp, slow, packet, vlan)
from ryu.lib.packet.stream_parser import StreamParser
fro... |
"""Tests for `tf.data.TFRecordDataset`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import pathlib
import zlib
from absl.testing import parameterized
from tensorflow.python.data.kernel_tests import checkpoint_test_base
from tensor... |
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1
from google.api_core import grpc_helpers_async
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
i... |
BOT_NAME = 'quotes_crawler'
SPIDER_MODULES = ['quotes_crawler.spiders']
NEWSPIDER_MODULE = 'quotes_crawler.spiders'
ROBOTSTXT_OBEY = True |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v8.enums",
marshal="google.ads.googleads.v8",
manifest={"ImagePlaceholderFieldEnum",},
)
class ImagePlaceholderFieldEnum(proto.Message):
r"""Values for Advertiser Provided Image placeholder fields. """
class I... |
"""Policy Changes from Git.
---------------------------
Using custodian in accordance with infrastructure as code principles,
we store policy assets in a versioned control repository. This
provides for an audit log and facilitate change reviews. However this
capability is primarily of use to humans making semantic
inte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.