code stringlengths 1 199k |
|---|
from __future__ import absolute_import
import atexit
import shutil
import signal
import tempfile
import threading
import grpc
from apache_beam.options import pipeline_options
from apache_beam.portability.api import beam_job_api_pb2_grpc
from apache_beam.runners.portability import local_job_service
from apache_beam.util... |
from django.core.urlresolvers import reverse
from django import http
from horizon.workflows import views
from mox import IsA # noqa
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.networks import tests
from openstack_dashboard.test import helpers as test
INDEX_URL = reverse('horizon:adm... |
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/rafa/cws/install/include".split(';') if "/home/rafa/cws/install/include" != "" else []
PROJECT_CATKIN_DEPENDS = "roscpp;rospy;std_msgs;message_runtime;geometry_msgs".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []... |
"""Views for creating/editing GCI Tasks.
"""
import datetime
from google.appengine.ext import db
from django import forms as django_forms
from django.forms.util import ErrorList
from django.utils.translation import ugettext
from soc.logic import cleaning
from soc.views import forms
from soc.views.helper import access_c... |
"""Routes for the googledrive addon.
"""
from framework.routing import Rule, json_renderer
from . import views
auth_routes = {
'rules': [
##### OAuth #####
Rule(
['/oauth/connect/googledrive/'],
'post',
views.auth.googledrive_oauth_start,
json_renderer... |
from django.shortcuts import render, redirect, render_to_response
import ast
from ..forms import selecttForm
from ..forms import applicationForm
from ..utils import ApplicationUtil
from ..utils import ApplicationHistoryUtil
from ..utils import EnvironmentUtil
from ..utils import StringUtil
from ..utils.PathUtil import ... |
"""Simple parsers for registry keys and values."""
import re
import logging
from grr.lib import artifact_lib
from grr.lib import parsers
from grr.lib import rdfvalue
from grr.lib import type_info
from grr.lib import utils
SID_RE = re.compile(r"^S-\d-\d+-(\d+-){1,14}\d+$")
class CurrentControlSetKBParser(parsers.Registr... |
"""Multi Head DQN agent with fixed replay buffer(s)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from batch_rl.fixed_replay.replay_memory import fixed_replay_buffer
from batch_rl.multi_head import multi_head_dqn_agent
import gin
import tensorflow.compa... |
'''
This is the base module which is then subclassed by the language chosen
There are three basic graph elements defined:
Graph: Which represents namespaces or classes
Node: Which represents functions
Edge: Which represents function calls
Then, there are two other classes:
Sourcecode: An object to hold and mani... |
"""
HponConf - command ``/sbin/hponcfg -g``
=======================================
Get the iLO firmware revision from the ``hponcfg`` command.
This is a 3rd party utility from HP and isn't shipped with RHEL. However,
it's useful for detecting possible hardware incompatibilities.
There are only five pieces of informat... |
import os.path
import re
import subprocess
import sys
from in_file import InFile
import in_generator
import license
HEADER_TEMPLATE = """
%(license)s
namespace WebCore {
enum CSSValueID {
%(value_keyword_enums)s
};
const int numCSSValueKeywords = %(value_keywords_count)d;
const size_t maxCSSValueKeywordLength = %(max_v... |
from ..utils.base import NbConvertBase
from IPython.utils.traitlets import Bool
class NotebookPreprocessor(Preprocessor):
def preprocess(self, nb, resources):
"""
Preprocessing to apply on each notebook.
Must return modified nb, resources.
If you wish to apply your preprocessing to e... |
"""
data.world API
data.world is designed for data and the people who work with data. From professional projects to open data, data.world helps you host and share your data, collaborate with your team, and capture context and conclusions as you work. Using this API users are able to easily access data and ma... |
import gzip
import paddle.v2 as paddle
import reader
import vgg
DATA_DIM = 3 * 224 * 224
CLASS_DIM = 1000
BATCH_SIZE = 128
def main():
# PaddlePaddle init
paddle.init(use_gpu=True, trainer_count=4)
image = paddle.layer.data(
name="image", type=paddle.data_type.dense_vector(DATA_DIM))
lbl = paddl... |
from itertools import cycle
import sys, math, random
import matplotlib.pyplot as plt
import numpy as np
from dataset import load_dataset
ed = lambda p1,p2: math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)
class Cluster(object):
ficou_sem_ponto = False
def __init__(self, pontos):
self.pontos = pontos
... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
from form_designer.models import FormDefinition
class FormDesignerLink(ContentItem):
form_definition = models.ForeignKey(FormDefinition, verbose_name=_('Form'))
class Meta:
... |
from functools import cmp_to_key
class Solution:
# @param {integer[]} nums
# @return {string}
def largestNumber(self, nums):
def comparator(s1, s2):
return s1+s2 < s2+s1
nums = [str(x) for x in nums]
# nums.sort(key=lambda x, y: y+x < x+y)
for i in range(len(nums)... |
"""Converts between json & ubjson"""
from __future__ import print_function
from sys import argv, stderr, stdout, stdin, exit # pylint: disable=redefined-builtin
from json import load as jload, dump as jdump
from .compat import STDIN_RAW, STDOUT_RAW
from . import dump as ubjdump, load as ubjload, EncoderException, Deco... |
import nox
DEFAULT_PYTHON_VERSION = "3.8"
@nox.session(python=DEFAULT_PYTHON_VERSION)
def blacken(session):
session.install('black')
session.run('black', 'docuploader', 'tests')
@nox.session(python=DEFAULT_PYTHON_VERSION)
def lint(session):
session.install('mypy', 'flake8', 'black', 'types-pkg_resources')
... |
"""An implementation of AbstractJob that uses in-memory constructs
and a provided sampler to execute circuits."""
from typing import cast, List, Optional, Sequence, Tuple
import concurrent.futures
import cirq
from cirq_google.engine.client import quantum
from cirq_google.engine.calibration_result import CalibrationResu... |
"""Run masked_lm pre-training for BERT.
Modifies the original BERT run_pretraining.py to remove the NSP objective.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from bert import modeling
from bert import optimization
import tensorflow.compat.v... |
"""Fake HP client exceptions to use when mocking HP clients."""
class HTTPConflict(Exception):
http_status = 409
message = "Conflict"
def __init__(self, error=None):
if error and 'message' in error:
self._error_desc = error['message']
def get_description(self):
return self._e... |
__authors__ = ['"Wei Keke" <keke.wei@cs2c.com.cn>']
__version__ = "V0.1"
'''
'''
import TestData.Disk.ITC08_SetUp as ModuleData
'''---------------------------------------------------------------------------------------------------
@note: PreData
--------------------------------------------------------------------------... |
from cloudbaseinit.openstack.common import cfg
from cloudbaseinit.openstack.common import log as logging
from cloudbaseinit.osutils import factory as osutils_factory
from cloudbaseinit.plugins import base
from cloudbaseinit.plugins.windows import x509
from cloudbaseinit.plugins.windows import winrmconfig
LOG = logging.... |
''' main.py '''
from __future__ import print_function
import logging
import os
import signal
import sys
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.log
import tornado.template
from tornado.httpclient import AsyncHTTPClient
from tornado.options import define
from tornado.web import url... |
from google.cloud import dataplex_v1
async def sample_delete_environment():
# Create a client
client = dataplex_v1.DataplexServiceAsyncClient()
# Initialize request argument(s)
request = dataplex_v1.DeleteEnvironmentRequest(
name="name_value",
)
# Make the request
operation = client.... |
from django.test import TestCase
from django.urls import resolve, reverse
from mock import patch, Mock
from .views import dashboard, show_searches
class SequenceSearchTest(TestCase):
def setUp(self):
self.data = {
"all_searches_result": {"count": 14602, "avg_time": "0:01:10"},
"last_... |
from django.contrib import admin
from markdownx.admin import MarkdownxModelAdmin
from .models import BirthCertificate
class BirthCertificateAdmin(MarkdownxModelAdmin):
fields = ['location', 'article']
admin.site.register(BirthCertificate, BirthCertificateAdmin) |
""" This creates a log along the lines of the apache
common log format, but with info about the OAuth apps.
This is the format:
[timestamp] app_pk\t"app_name"\tuser_name\t"METHOD URI"
response_status response_size
"""
from django.utils.deprecation import MiddlewareMixin
from datetime import datetime
imp... |
import sys,hashlib,os
isDEV=0
def getDefaultVal(flg):
dict={}
if str(flg)=="1":
dict['house_flag']=1
dict['borough_name']=""
dict['house_addr']=""
dict['house_title']=""
dict['house_city']=""
dict['house_region']=""
dict['house_section']=""
dict['h... |
import getpass
from selenium import webdriver
from selenium.webdriver.support.select import Select
import sys
import urllib.parse
import room
BALLOT_URL = 'https://my.trin.cam.ac.uk/apps/accommodation/ballot_rooms_available'
BALLOT_URL_PARSED = urllib.parse.urlparse(BALLOT_URL)
MYTRIN_HOME_URL = 'https://mytrin.trin.ca... |
'''
Command line option definitions
'''
def add_params(subparsers):
# list
list_parser = subparsers.add_parser(
'list',
help='List VMware objects on your VMware server'
)
list_parser.add_argument(
'--type',
required=True,
help='Object type, e.g. Network, VirtualMa... |
"""Test suite for XenAPI."""
import ast
import base64
import contextlib
import copy
import functools
import os
import re
import mock
import mox
from oslo.config import cfg
from nova.compute import api as compute_api
from nova.compute import flavors
from nova.compute import power_state
from nova.compute import task_stat... |
import os
import sys
import time
import protoparser
import protoobjects
import utils
INDENT = " "
CSS_CLASSES = {
protoobjects.NUMBER: "number",
protoobjects.BUFFER: "string",
protoobjects.BOOLEAN: "boolean",
}
def indent(count): return count * INDENT
def print_doc(file, field, depth):
if field.doc:
... |
from __future__ import print_function
import os
import sys
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from h2o.estimators.infogram import H2OInfogram
from tests import pyunit_utils
def test_infogram_iris_plot():
"""
Check to make sure infogram can be plotted
:return:
"""
fr = h2o.im... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.jvm.subsystems.jvm import JVM
from pants_test.test_base import TestBase
class TestJvm(TestBase):
def create_JVM(self, **kwargs):
# Note: don't ... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import json
import os
from collections import defaultdict
from twitter.common.collections import OrderedSet
from pants.backend.core.targets.resources import Resources
f... |
from time import time
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
contourParams = dict(
zdir='z',
alpha=0.5,
zorder=1,
antialiased=True,
cmap=cm.PuRd_r
)
surfaceParams = dict(
rstride=1,
cstride=1,
linewidth=0.1,
edgecolors='k',
alpha=0.5,
ant... |
from .cmdwrapper import SimpleCMDWrapper as pyCMD
from .enum import EnumTypes |
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_... |
from CommonClasses import *
from solution import Solution
class TestSuite:
def run(self):
self.test000()
self.test001()
self.test002()
self.test003()
self.test004()
def test000(self):
print 'test 000\n'
i = []
n = []
startTime = time.clock(... |
import pytest
import salt.config
import salt.version
pytestmark = [
pytest.mark.slow_test,
]
def test_ping(
mm_master_1_salt_cli, salt_mm_minion_1, mm_master_2_salt_cli, salt_mm_minion_2
):
"""
test.ping
"""
ret = mm_master_1_salt_cli.run("test.ping", minion_tgt=salt_mm_minion_1.id)
assert r... |
"""Utilities to dynamically load plugin modules.
Modules imported this way remain accessible to static imports, regardless of
the order in which they are imported. For modules that are not part of an
existing package tree, use create_subpackage() to dynamically create a package
for them before loading them.
"""
import ... |
"""
This function should be part of the hypothesis class.
Is is used when calculating the fitness.
"""
def errorFunc(database, c):
"""
The database is self-explanatory, but the c
input is a scalar weight that indicates how
important the "tautology"-part of the error
is.
... |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
import re
verstr='0.0.0'
VERSIONFILE="maasutil/__init__.py"
verstrline = open(VERSIONFILE, "... |
import sys, time, requests, json
from distance import read_distance # 距離を測る関数
interval=5 if len(sys.argv)==1 else int(sys.argv[1])
while True:
start_time = time.time()
print "- 距離を計測します"
distance = read_distance()
if distance:
print "距離: %.1f cm" % (distance)
headers = {'Content-Type': '... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
import re
from abc import abstractmethod
from pants.build_graph.source_mapper import SpecSourceMapper
from pants.goal.workspace import ScmWorkspace
from ... |
import subprocess, os, shlex, time, sys
os.chdir("/home/ubuntu/sparrow/python")
subprocess.call("echo \"\" > Finish.txt", shell = True)
commandFrontend = "java -cp ../target/sparrow-1.0-SNAPSHOT.jar edu.berkeley.sparrow.examples.BFrontend -c ../Conf/conf.Frontend"
startTime = time.time()
sparrowFrontend = subprocess.Po... |
from google.cloud import retail_v2
async def sample_import_user_events():
# Create a client
client = retail_v2.UserEventServiceAsyncClient()
# Initialize request argument(s)
input_config = retail_v2.UserEventInputConfig()
input_config.user_event_inline_source.user_events.event_type = "event_type_val... |
from django import template
from django.urls import reverse as r
from django.utils import timezone
register = template.Library()
@register.simple_tag
def services_url(slug, delta):
today = timezone.now()
date = today - timezone.timedelta(delta)
return r('services:day', args=(slug, date.year, str(date.month)... |
import logging
import pytest
import os
from kubeflow.testing import util
def test_create_cluster(record_xml_attribute, cluster_name, eks_cluster_version, cluster_creation_script, values):
"""Test Create Cluster For E2E Test.
Args:
cluster_name: Name of EKS cluster
eks_cluster_version: Version of EKS cluster... |
from azurelinuxagent.conf import ConfigurationProvider
from azurelinuxagent.distro.default.osutil import DefaultOSUtil
from azurelinuxagent.distro.default.daemon import DaemonHandler
from azurelinuxagent.distro.default.init import InitHandler
from azurelinuxagent.distro.default.monitor import MonitorHandler
from azurel... |
import os
import properties_user_links_get
TEST_PROPERTY_ID = os.getenv("GA_TEST_PROPERTY_ID")
TEST_USER_LINK_ID = os.getenv("GA_TEST_PROPERTY_USER_LINK_ID")
def test_properties_user_links_get(capsys):
properties_user_links_get.get_property_user_link(
TEST_PROPERTY_ID, TEST_USER_LINK_ID
)
out, _ = c... |
"""Platform-specific logic for Ubunutu Oneiric components.
"""
import tempfile
import time
from devstack.components import db
from devstack import log as logging
from devstack import shell as sh
from devstack import utils
from devstack.packaging import apt
LOG = logging.getLogger(__name__)
class DBInstaller(db.DBInstal... |
from cv2 import namedWindow, imshow, waitKey, cvtColor, COLOR_RGB2BGR
from hand_grabber import PyOpenNIHandGrabber
from pose_recognizer import PyPoseRecognizer
from my_fun import *
from sklearn.externals import joblib
from hand import *
import time
import socket
WIDTH = 640
HEIGHT = 480
USE_CPU = False
if __name__=="__... |
import threading
class MobileyeData:
def __init__(self, mobileye_pb=None):
self.mobileye_pb = mobileye_pb
self.lane_data_lock = threading.Lock()
self.next_lane_data_lock = threading.Lock()
self.obstacle_data_lock = threading.Lock()
self.left_lane_x = []
self.left_lane... |
import datetime
import inspect
import os.path
import time
import unittest
import re
import tempfile
from os.path import splitext
from os import mkdir, rmdir, remove
from stratuslab.Monitor import Monitor
from stratuslab.Registrar import Registrar
from stratuslab.marketplace.Uploader import Uploader as marketplaceUpload... |
from google.cloud import aiplatform_v1beta1
def sample_list_tensorboard_experiments():
# Create a client
client = aiplatform_v1beta1.TensorboardServiceClient()
# Initialize request argument(s)
request = aiplatform_v1beta1.ListTensorboardExperimentsRequest(
parent="parent_value",
)
# Make... |
'''
Created on Oct 5, 2016
@author: svanhmic
@license: Apache 2.0
@summary: Imports a compiled csv file with accounts and transforms them into a new csv file containing all unique columns from all accounts.
Meaning one row will consist of an accoount.
'''
from pyspark import SparkContext
from pyspark.sql import SQLCont... |
from mldb import mldb, MldbUnitTest, ResponseException
class LikeTest(MldbUnitTest): # noqa
def test_like_select(self):
ds = mldb.create_dataset({ "id": "sample", "type": "sparse.mutable" })
ds.record_row("a",[["x", "acrasial", 0]])
ds.record_row("b",[["x", "blaternation", 0]])
ds.r... |
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from common import public
class rjzzq():
"""中标"""
need_check_ziduan = [
u'_id',
u'data_source',
u'bbd_dotime',
u'key',
u'rawdata',
u'retain1',
u'retain2',
u'bbd_uptime',
u'bbd_url',
... |
import os
from vent.api.plugins import Plugin
from vent.api.templates import Template
def test_add():
""" Test the add function """
instance = Plugin()
status = instance.add('https://github.com/cyberreboot/vent', build=False)
assert isinstance(status, tuple)
assert status[0] == True
status = ins... |
from google.protobuf.message import Message
from ....logger import traceback_and_raise
from ....proto.util.data_message_pb2 import DataMessage
from ....util import get_fully_qualified_name
from ....util import validate_type
from .types import Deserializeable
def _serialize(
obj: object,
to_proto: bool = True,
... |
from setuptools import setup, find_packages
setup(
name='uncurl',
version='0.0.7a',
description='A library to convert curl requests to python-requests.',
author='Steve Pulec',
author_email='spulec@gmail',
url='https://github.com/spulec/uncurl',
entry_points={
'console_scripts': [
... |
import logging
from kubeflow.testing import github_repo_manager # pylint: disable=no-name-in-module
import pytest
def test_parse_git_url():
result = github_repo_manager._parse_git_url("git@github.com:kubeflow/manifests.git") # pylint: disable=protected-access
assert result == github_repo_manager.GIT_TUPLE("git@gith... |
import os.path as osp
import unittest
from celery import Celery
from celery.result import AsyncResult
import yaml
import backache
celery = Celery()
class TestRedirect(unittest.TestCase):
# A -> B -> C -> D
# ^
# |
# E
# ^
# |
# F
REDIRECTS = {
'A': '... |
import logging
import shutil
from shutil import copy2, move
from os import path, scandir, makedirs
import os
from sys import maxsize
from guessit import guessit
import configparser
from .cinefiles import Cinefiles
class Cinefolders:
def __init__(self, *args, **kwargs):
self.configdict = { 'configfile':'',
... |
DOCUMENTATION = '''
---
module: bigip_selfip
short_description: Manage Self-IPs on a BIG-IP system
description:
- Manage Self-IPs on a BIG-IP system
version_added: "2.2"
options:
address:
description:
- The IP addresses for the new self IP
required: true
floating_state:
description:
- The ... |
"""Slack platform for notify component."""
import asyncio
import logging
import os
from urllib.parse import urlparse
from aiohttp import BasicAuth, FormData
from aiohttp.client_exceptions import ClientError
from slack import WebClient
from slack.errors import SlackApiError
import voluptuous as vol
from homeassistant.co... |
import inspect
import logging
from collections import namedtuple
from copy import deepcopy
from os.path import abspath, dirname, realpath
from pathlib import Path
from typing import Any, List, Mapping, Set, Tuple
import nbformat
import pandas as pd
import progressbar
from nbconvert.preprocessors import ExecutePreproces... |
import pytest
from chaosmonkey.engine.app import configure_engine, shutdown_engine
from chaosmonkey.engine.cme_manager import manager as cme_manager
from chaosmonkey.api.app import flask_app
def pytest_addoption(parser):
"""Options to configure attacks and planners root"""
parser.addoption("--root", action="sto... |
import datetime
from prettyjson import PrettyJSONWidget
from django.contrib.admin import SimpleListFilter
from django.contrib.gis import admin
from django.contrib.postgres.fields import JSONField
from .models import DataPoint, DataBundle, DataSource, DataSourceGroup, \
DataPointVisualization, Report... |
from setuptools import setup, find_packages
setup(
name = "subprocess-signal",
version = "0.1",
author = "Andrew Bortz",
author_email = "andrew@abortz.net",
url = "http://github.com/abortz/python-subprocess-signal",
packages=find_packages(),
setup_requires=["cffi>=1.0.0"],
install_requir... |
"""Django template library for Lantern."""
import base64
import cgi
import logging
import os
import re
import urlparse
from google.appengine.ext import db
from google.appengine.api import memcache
from google.appengine.api import users
import django.template
import django.utils.safestring
from django.core.urlresolvers ... |
"""Classes for generic sequence alignment.
Contains classes to deal with generic sequence alignment stuff not
specific to a particular program or format.
"""
from __future__ import print_function
__docformat__ = "restructuredtext en" # Don't just use plain text in epydoc API pages!
from Bio.Seq import Seq
from Bio.Seq... |
"""Benchmark TODO."""
from __future__ import print_function
import timeit
NAME = "TODO"
REPEATS = 3
ITERATIONS = 1000000
COUNT = [0] # use a list to allow modification within nested scopes
def print_version():
"""Print the TAP version."""
print("TAP version 13")
def print_summary(total, passing):
"""Print ... |
'''
This is a barebones script to print information about cloning inside
the BAT database. Two types of clones are stored:
* identical clones: all files of the package are the same. This could be
because the packages are identical, or because the number of files that BAT
would process is actually really really small. T... |
from datetime import datetime
utc_time = datetime.strptime("2015-09-15T17:13:29.380Z", "%Y-%m-%dT%H:%M:%S.%fZ")
utc_time2 = datetime.strptime("2018-05-29T22:09:30.380Z", "%Y-%m-%dT%H:%M:%S.%fZ")
milliseconds = (utc_time - datetime(1970, 1, 1))
timestamp = utc_time.timestamp()
timestamp2 = utc_time2.timestamp()
print(mi... |
from cloudferry.lib.utils.console_cmd import BC
cd_cmd = BC("cd %s")
qemu_img_cmd = BC("qemu-img %s")
mkdir_cmd = BC("mkdir -p %s")
move_cmd = BC("mv -f %s %s")
move_with_cd_cmd = cd_cmd & move_cmd
rbd_cmd = BC("rbd %s")
base_ssh_cmd = BC("ssh %s")
ssh_cmd = base_ssh_cmd("-oStrictHostKeyChecking=no %s '%s'")
ssh_cmd_po... |
from network_stay import StayAttribute |
"""
$ python main.py 1000
21124
"""
import sys
def spell(n):
digits = [
'zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
]
tens = [
... |
from random import seed
from random import randrange
from csv import reader
from math import sqrt, log2
from crawler.downloadhelper import DownloadHelper
def load_csv(filename):
dataset = list()
with open(filename, 'r') as file:
csv_reader = reader(file)
for row in csv_reader:
if not... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
import re
import base64
from datetime import datetime
from Crypto.Cipher import XOR
from pecan import conf
from pecan import abort
xorkey = conf.get('xorkey') or 'default'
def encrypt(key, plaintext):
cipher = XOR.new(key)
data = cipher.encrypt(plaintext)
data = base64.b64encode(data)
return data.decode... |
from auto_scan_test import PassAutoScanTest, IgnoreReasons
from program_config import TensorConfig, ProgramConfig, OpConfig
import numpy as np
import paddle.inference as paddle_infer
from functools import partial
from typing import Optional, List, Callable, Dict, Any, Set
import unittest
import hypothesis
from hypothes... |
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
from google.cloud import compute_v1
def create_template_with_subnet(
project_id: str, network: str, subnetwork: str, template_name: str
) -> compute_v1.InstanceTemplate:
"""
Create an instance template that uses a provided subnet.
Args:
project_id: project ID or project number of the Cloud proje... |
"""Shelly helpers functions."""
from datetime import timedelta
import logging
from typing import List, Optional, Tuple
import aioshelly
from homeassistant.const import EVENT_HOMEASSISTANT_STOP, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import singlet... |
"""Tests for Stax library."""
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from jax._src import test_util as jtu
from jax import random
from jax.example_libraries import stax
from jax import dtypes
from jax.config import config
config.parse_flags_with_absl()
def random_inp... |
"""A Django template tag library containing list helpers.
"""
from django import template
register = template.Library()
@register.inclusion_tag('soc/templatetags/_as_lists.html')
def as_lists(lists_data):
"""Prints multiple lists as html.
"""
return {
'list': lists_data,
}
@register.inclusion_tag('soc/tem... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import unittest
from contextlib import contextmanager
from pants.base.build_file import BuildFile
from pants.base.build_root import BuildRoot
from pants.base.... |
import sys
import nose
from nose.tools.trivial import ok_
from nose.tools.trivial import eq_
from pyslash.cmd.slash import _parse_args
class Test_slash(object):
def test_tap_list_default(self):
sys.argv = ['pyslash', 'tap-list']
args = _parse_args()
eq_(args.format, 'table')
eq_(args... |
"""Handles all requests relating to compute resources (e.g. guest VMs,
networking and storage of VMs, and compute hosts on which they run)."""
import base64
import functools
import re
import string
import uuid
from oslo.config import cfg
import six
from nova import availability_zones
from nova import block_device
from ... |
from collections import OrderedDict
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credenti... |
import socket
import select
import logging
from xudd.actor import Actor
_log = logging.getLogger(__name__)
class Server(Actor):
def __init__(self, hive, id, request_handler=None):
super(Server, self).__init__(hive, id)
self.message_routing.update({
'respond': self.respond,
'l... |
from __future__ import print_function
import contextlib
import errno
import json
import os
import re
import ssl
import subprocess
import sys
try:
import threading as _threading
except ImportError:
import dummy_threading as _threading
import time
from pyversion import is_python3
if is_python3():
import urllib.requ... |
import doctest
import pytest
from insights.parsers import spamassassin_channels
from insights.parsers.spamassassin_channels import SpamassassinChannels
from insights.tests import context_wrap
DEFAULT = """
/etc/mail/spamassassin/channel.d/sought.conf:CHANNELURL=sought.rules.yerp.org
/etc/mail/spamassassin/channel.d/spa... |
"""Utility tool for cirq modules.
It can be used as a python library for python scripts as well as a CLI tool for
bash scripts and interactive use.
Features:
listing modules:
- Python: see list_modules
Version management:
- Python: get_version and replace_version
- CLI:
- python3 dev_tools/modules.py print_versi... |
import os
MODEL_CONFIG = {
# The number of timesteps used in the model.
# This value must match the sequence length used in the java pipeline.
'timesteps': 5,
'features': [
'timeseries_x-value-LAST', # 'timeseries_x-value-FIRST',
'timeseries_x-value-LAST_... |
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.ya... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.