text stringlengths 1 927k |
|---|
class Calculator():
def power(self, n, p):
if n >= 0 and p >= 0:
return n**p
raise Exception("n and p should be non-negative")
myCalculator=Calculator()
T=int(input())
for i in range(T):
n,p = map(int, input().split())
try:
ans=myCalculator.power(n,p)
print(ans)... |
# a colorful dataframe =)
data.corr().style.background_gradient(cmap='RdYlGn', low=0.2, high=0.2, axis=0) |
"""Tests for the codejams router."""
import pytest
from fastapi import FastAPI
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from api import models
from api.database import User
pytestmark = pytest.mark.asyncio
# This test fails when the database ... |
import numpy as np
from utils.test_env import EnvTest
class LinearSchedule(object):
def __init__(self, eps_begin, eps_end, nsteps):
"""
Args:
eps_begin: initial exploration
eps_end: end exploration
nsteps: number of steps between the two values of eps
""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/14 10:41 上午
# @Author : Browser
# @File : openvpn.py
# @Software: PyCharm
# @contact : browser_hot@163.com
import math
import os
import re
from flask import jsonify, send_from_directory, make_response, request
from lin import route_meta, group_requ... |
#!/usr/bin/env python3
import os
import sys
from trello import TrelloClient, ResourceUnavailable
def usage():
print("""Usage: list_trello_boards show
Shows ids and names of Trello boards that the user specified with
TRELLO_API_KEY, TRELLO_API_SECRET, TRELLO_TOKEN and TRELLO_TOKEN_SECRET
environment ... |
# Python does not have constants, but as a convention variables defined in ALL CAPS are considered constants
# This is a comment
MAX_VALUE = 123_456_789_987_654_321
print (MAX_VALUE) |
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# check_mk 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 in version 2. check_mk is distributed
# in the hope that it will be useful, but... |
import os
import sys
import logging
import importlib
from optparse import make_option
from django.core.management import BaseCommand, call_command
from django.conf import settings
from fixture_generator.signals import data_dumped
from django.test.runner import DiscoverRunner
from django.test.utils import get_runner
... |
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import os
import shutil
import sys
import tempfile
import time
import unittest
import ray
from ray import tune
from ray.rllib import _register_all
from ray.tune.checkpoint_manager import Checkpoint
from ray.tune.logger import DEFAULT_LOGGERS, ExperimentLogger, \
LegacyExperimentLogger
from ray.tune.ray_trial_execu... |
#!/usr/bin/env python
#
"""
Copyright 2016 Disney Connected and Advanced Technologies
Licensed under the Apache License, Version 2.0 (the "Apache License")
with the following modification; you may not use this file except in
compliance with the Apache License and the following modification to it:
Section 6. Trademark... |
import pandas as pd
def main(path: str) -> pd.DataFrame:
return pd.read_csv(path) |
import csv
import pandas as pd
CALIFORNIA = 6 # State Code to keep
data_dir = '/Volumes/T7/Box Sync/BEST-AIR/Data/AQ Monitoring/EPA Criteria Pollutants/PM Daily Data/'
pathname = data_dir + '2017/daily_88101_2017.csv'
# Create 'Monitor ID' = State Code + County Code + Site Num + Parameter Code
# Drop rows with 'Sa... |
import logging
from datetime import datetime
from fastlane.target import Target, TargetConfigSchema
import fastlane.utils as utils
from marshmallow import fields
import influxdb
import pandas as pd
LOGGER = logging.getLogger(__name__)
class TargetInfluxDB(Target):
def __init__(self, **kwargs):
super().... |
"""Module holding the core functions."""
import pandas as pd
import MDAnalysis as mda
import MDAnalysis.coordinates.XTC as XTC
from . import hydrogens
from . import geometry as geo
from . import writers
# For debugging.
# TODO: Remove it after implement logging feature
DEBUG=False
def buildHs_on_1C(atom, H_type, ... |
class ViewFields(object):
"""
Used to dynamically create a field dictionary used with the
RunstatView class
"""
def __init__(self):
self._fields = dict()
def _prockvargs(self, field, name, **kvargs):
if not len(kvargs):
return
field[name].update(kvargs)
... |
#!/usr/bin/python
from optparse import OptionParser
import pybullet
import json
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("-c", "--config-file", dest="config_filename",
help="Path to configuration JSON file", type="string")
parser.add_option("-f", "--filenam... |
"""
WSGI config for euctr 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.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTIN... |
import math
import numpy as np
import torch
import torchvision
import wandb
from torch.nn import functional as F
from torch import LongTensor
from lambo import transforms as gfp_transforms, dataset as gfp_dataset
from lambo.models.shared_elements import check_early_stopping
from lambo.utils import str_to_tokens
de... |
# Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... |
# This is a "null" plugin showing how to write your own.
# The procedure is as follows:
# 1 - Subclass B2YBank overriding the methods you need - typically just
# read_data(path_to_file). See docstrings below for explanations.
# 2 - provide build_bank(config_dict_bool) which should return an
# instance of yo... |
import pytest
def test_dog1():
assert True
def test_dog2():
assert True
def test_dog3():
assert True
def test_dog4():
assert True
def test_dog5_failing():
assert False
def test_dog6():
assert True |
import itertools
import numpy
import six
from chainer.backends import cuda
from chainer.utils.conv import get_conv_outsize
from chainer.utils import conv_nd_kernel
def as_tuple(x, n):
if hasattr(x, '__getitem__'):
assert len(x) == n
return tuple(x)
return (x,) * n
def im2col_nd_cpu(img, ksi... |
# Copyright 2014 OpenStack Foundation
# Copyright 2015 Chuck Fouts
# 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/L... |
# Filename : ooo.py
# Python Bytecode : 2.7
# Time Succses Decompiled : Sun Aug 16 17:06:48 2020
# Timestamp In Code : 2020-06-10 22:04:47
dat = []
for i in k:
dat.append(i)
open('list.py','a').write(str(dat))
[196, 35, 213, 23, 18, 152, 91, 166, 19, 48, 103, 44, 166, 119, 56, 192, 89, 253, 78, 216, 22, 131, 181, 6... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.19.15
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
f... |
#!/usr/bin/env python
# Foremast - Pipeline Tooling
#
# Copyright 2018 Gogo, LLC
#
# 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... |
#Logging
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
import os
import pyrogram
from chat import Chat
from config import Config
logging.getLogger('pyrogram').setLevel(logging.WARNING)
@... |
import math
from ds.graph.graph_core import GraphCore
def bellman_ford(graph, src):
"""
Complexity = O(EV)
Works for negative edges unlike Dijkstra.
"""
distances = {}
for vertex in graph.vertices:
distances[vertex] = math.inf
distances[src] = 0
for _ in range(len(graph.vertic... |
import slcrmit.questions.median_stream as subject
class TestMedianStream(object):
def test_median_stream(self):
ary = [1,2,3,4,5]
expected = [1,1.5,2,2.5,3]
median = subject.median_stream_brute_force(ary)
assert median == expected
def test_median_stream_complex(self):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
class Migration(migrations.Migration):
dependencies = [
('main', '0016_auto_20180216_1820'),
]
operations = [
migrations.AlterField(
model_name='newspost'... |
"""Edit the label and image list files in BDD100K format."""
import argparse
import json
from os.path import basename, join, splitext
from typing import Any, Callable, Dict, List
import yaml
from ..common.io import open_read_text, open_write_text
from ..common.logger import logger
LabelObject = Dict[str, Any] # ty... |
import numpy as np
import os
import sys
# To import from sibling directory ../utils
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
from data_loader.load_utils import load_obj
from data_loader.load_utils import try_to_load_as_pickled_object
from sklearn.model_selection import train_test_split
from d... |
# (C) Copyright 2019-2022 Hewlett Packard Enterprise Development LP.
# Apache License 2.0
import json
import logging
from pyaoscx.exceptions.generic_op_error import GenericOperationError
from pyaoscx.exceptions.response_error import ResponseError
from pyaoscx.exceptions.verification_error import VerificationError
fr... |
import sys, os
sys,path.append(os,pardir)
import pickle
import numpy as np
from collections import OrderdDict
from common.layers import *
class DeepConNet:
def __init__(self, input_dim=(1, 28, 28),
conv_param_1 = {'filter_num':16, 'filter_size':3, 'pad':1, 'stride':1},
conv_param_... |
from .resnest.restnest import get_model
from efficientnet_pytorch import EfficientNet
from options import opt
from .lambdaresnet import LambdaResNet50, LambdaResNet101, LambdaResNet152, LambdaResNet200, LambdaResNet270, LambdaResNet350, LambdaResNet420
def get_net(model):
if model[0:8]=='resnest':
get_mode... |
from config import config
from math import isnan
# Signals are defined in alphabetical order
class signals:
def buy_sma_crossover_rsi( self, ticker, data ):
# Moving Average Crossover with RSI Filter
# Credits: https://trader.autochartist.com/moving-average-crossover-with-rsi-filter/
# Buy ... |
# Databricks notebook source
# MAGIC %md
# MAGIC
# MAGIC ## Training and packaging a Tensorflow 2.x model with Model Hub
# MAGIC
# MAGIC - based on: https://www.tensorflow.org/text/tutorials/classify_text_with_bert
# MAGIC - Sentiment Analysis Model
# COMMAND ----------
# MAGIC %md
# MAGIC
# MAGIC #### Extra libra... |
#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# Copyright (c) 2009, Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# d... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
# RT Lib - Setting
from typing import (
TYPE_CHECKING, TypedDict, Optional, Union, Literal, Dict, Tuple, List,
overload, get_origin, get_args
)
from discord.ext import commands
import discord
from collections import defaultdict
from aiohttp import ClientSession
from functools import partial
from datetime imp... |
import os
def main():
print ('\033[31m============================================\033[1;m\n')
print('''\033[1;34m## ## ## ## ## ####### #####\033[1;m''')
print('''\033[1;34m#### #### ## ## #### ## ### # #\033[1;m''')
print('''\033[1;34m## ## ## ####### ## #### ### ... |
#!/usr/bin/python
##################################################################
# Copyright (c) 2012, Sergej Srepfler <sergej.srepfler@gmail.com>
# Test client added by L.Belov <lavrbel@gmail.com>
# February 2012 - March 2014
# Version 0.1.1, Last change on Mar 11, 2014
# This software is distributed under the te... |
import pytest
import json
from paretl import ParameterizingOut, Parameter, JSONType, Parameterized, ETL, In, Out, timeit, tim, Sweep
@pytest.fixture()
def par():
return Parameter('name', default="foo")
@pytest.fixture()
def par2():
return Parameter('size', default="bar", custom=[20])
@pytest.fixture()
def... |
from typing import Dict, List
from albumentations import BasicTransform, NoOp
class BaseTransformScheduler:
def __init__(self, **kwargs):
pass
def __call__(self, **kwargs):
return self.cur_transform(**kwargs)
def step(self, **kwargs):
pass
class TransformMultiStepScheduler(Bas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
import sys, os, re, shlex, shutil, glob, subprocess, collections
from os import path
from datetime import datetime
import numpy as np
from scipy import interpolate
import matplotlib as mpl
fr... |
import os
#Define backend as tensorflow
os.environ['KERAS_BACKEND']='tensorflow'
#It is important to import keras after changing backend
import keras
from flask import Flask, render_template,request
from scipy.misc import imsave, imread, imresize
import numpy as np
#import keras.models
import re
import sys
import os
... |
from contextlib import redirect_stdout
from dask.base import tokenize
import json
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Set,
Tuple,
)
import pendulum
import prefect
from prefect import config
from prefect.core import Edge, Task
from prefect... |
import sys, getopt, struct, time, termios, fcntl, sys, os, colorsys, threading, time, datetime, subprocess, random, os.path, math, json
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/fbtft')
from RenderManager import RenderManager
from WanemManager import WanemManager
from ScBase import ScBase
from gfx ... |
#
# This file contains the Python code from Program 2.3 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm02_03.txt
#
def factorial(n):
... |
def run(cluster, detect):
import os
import MySQLdb
import os, sys, anydbm, time
#from config import datb, dataloc
#from config_bonn import cluster
#cluster = sys.argv[1]
#detect = sys.argv[2]
SUBARUDIR = '/nfs/slac/g/ki/ki05/anja/SUBARU/'
output = SUBARUDIR + cluster + '/PHOTOMETRY_'... |
import click
import json
import sys
from prettytable import PrettyTable
from calm.dsl.api import get_api_client
from calm.dsl.builtins import Ref
from .task_commands import watch_task
from .constants import ERGON_TASK
from calm.dsl.config import get_context
from calm.dsl.store import Cache
from calm.dsl.constants impo... |
import os
from copy import deepcopy
import numpy as np
import pandas as pd
import pytest
from sklearn.datasets import load_iris
from fedot.core.data.data import InputData, OutputData
from fedot.core.data.multi_modal import MultiModalData
from fedot.core.repository.dataset_types import DataTypesEnum
from fedot.core.re... |
# Copyright 2015, Hitachi Data Systems.
#
# 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 la... |
from django.urls import path
from .views import slide
from .views import user
from .views import etc
from .views import rank
urlpatterns = [
path('', etc.index, name='index'),
path('main/slide', slide.get_main_slide_list, name='main_slide'),
path('main/slide/create/dummy', slide.create_dummy_slide, name='... |
from fireo.fields import TextField, NumberField
from fireo.models import Model
class City(Model):
name = TextField()
population = NumberField()
def test_issue_126():
city = City.collection.create(name='NYC', population=500000, no_return=True)
assert city == None |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import sys
import numpy as np
from vahun.corpus import Corpus
from vahun.genetic import evolution
from vahun.genetic import experiment
from vahun.tools import Timer
from vahun.tools import explog
fro... |
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Ansible, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
class ModuleDocFragment(object):
# Standard documentation fragment
D... |
import unittest
from data import Skills
from status import BallDirection, FieldZone, Possession
from backs_direction_matrix import BacksDirectionMatrix
class TestBacksDirectionMatrix(unittest.TestCase):
def setUp(self):
self.states = [
BallDirection.NONE, BallDirection.FORWARD,
Bal... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
import pandas as pd
from zipfile import ZipFile
import torch as th
import cv2
import numpy as np
import os
from glob import glob
import pydicom
from matplotlib import pyplot as plt
from segmentation_model import FPNSegmentation
def main():
train_image_fns = sorted(glob(os.path.join(
'dicom-images-train', '*/*... |
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ..featuredetection import CannySegmentationLevelSetImageFilter
def test_CannySegmentationLevelSetImageFilter_inputs():
input_map = dict(
advectionWeight=dict(argstr="--advectionWeight %f",),
args=dict(argstr="%s",),
cannyThreshold=... |
"""
Example showing for tkinter and ttk:
-- How to CONSTRUCT and DISPLAY a WIDGET
(in this case, a ttk.Button)
-- How to associate a widget (here, a ttk.Button)
with a CALLBACK function that is a LAMBDA (anonymous) function.
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
... |
#!/usr/bin/env python3
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the foll... |
"""
Auto Classfier for Graph Node Classification
"""
import time
import json
from copy import deepcopy
import torch
import numpy as np
import yaml
from .base import BaseClassifier
from ...module.feature import FEATURE_DICT
from ...module.model import BaseModel, MODEL_DICT
from ...module.train import TRAINER_DICT, ge... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import markdown
from django import template
from portfolio.models import (Artifact, FileArtifact, ImageArtifact,
TextArtifact)
register = template.Library()
@register.assignment_tag()
def get_artifact_list(project, artifa... |
import io
import os
import re
from setuptools import find_packages
from setuptools import setup
def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io.open(filename, mode="r", encoding="utf-8") as fd:
return re.sub(text_type(r":[a-z]+:`~?(.*... |
"""
Copyright 2020 The OneFlow Authors. 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 agr... |
from unittest import TestCase
from computer import (
evaluate,
BadExpression,
UndefinedVariable,
UnsupportedOperation,
)
class BasicMathTestCase(TestCase):
def test_addition(self):
self.assertEqual(evaluate('2 + 2'), 4)
def test_subtraction(self):
self.assertEqual(evaluate('5... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 31 12:22:57 2020
@author: Matt
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 20 14:50:25 2020
@author: Matt
"""
from kivy.clock import Clock
from kivy.properties import ListProperty
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty
fro... |
# Copyright 2017 The TensorFlow Authors. 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 applica... |
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# coding: utf-8
"""
validateapi
The validation APIs help you validate data. Check if an E-mail address is real. Check if a domain is real. Check up on an IP address, and even where it is located. All this and much more is available in the validation API. # noqa: E501
OpenAPI spec version: v1
Ge... |
# Copyright 2017 - Nokia
#
# 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 to in writing, sof... |
import numpy as np
class Tensor(object):
"""
a base class for tensor object
"""
__array_ufunc__ = None
def __init__(self, value, function=None):
"""
construct Tensor object
Parameters
----------
value : array_like
value of this tensor
f... |
import codecs
import os
import re
from setuptools import setup, find_packages
DESCRIPTION = 'A library that wraps pandas and openpyxl and allows easy styling of dataframes in excel. Documentation can be found at http://styleframe.readthedocs.org'
here = os.path.abspath(os.path.dirname(__file__)).lower()
def read(*... |
from flask.ext.login import UserMixin
from app.extensions import cache, bcrypt
from .. import db
from ..mixins import CRUDMixin
import datetime
class User(CRUDMixin, UserMixin, db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), nullable=Fal... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: release-1.16
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import... |
#!/usr/bin/python
import sys
import os
import signal
import time
import global_instance
from client_config import client_config
from json_utility import json_utility_instance
from file_handler import file_handler
from daemonize import daemonize
from datetime import datetime
from elasticsearch import Elasticsearch
from ... |
from django.http import HttpResponse, HttpResponseRedirect
from src.RumorValidator import settings
DEFAULT_REFIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.rumor.com:8000")
def wildcard_redirect(request, path=None):
new_url = DEFAULT_REFIRECT_URL
if path is not None:
new_url = DEFAU... |
# Copyright 2015 Google Inc.
#
# 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 to in writing, ... |
# qubit number=4
# total number=10
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(0) # number=1
pr... |
#! /usr/bin/env python
from datetime import datetime
import tzlocal
import sys
now = datetime.now(tzlocal.get_localzone())
hugo_date = now.strftime("%Y-%m-%dT%H:%M:%S%z")
hugo_date = hugo_date[:-2] + ':' + hugo_date[-2:]
sys.stdout.write(hugo_date) |
import datetime as dt
import os
import sys
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from airflow.operators.python_operator import PythonOperator
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from example_app.dag_functions import ... |
import functools
from datetime import datetime, timedelta
from typing import Dict, Iterable, List, Tuple, Optional
import werkzeug
from loguru import logger
from sqlalchemy import and_, func
from sqlalchemy.ext.hybrid import hybrid_method
from sqlalchemy.orm import backref
from server.api.database import db
from serv... |
# package imports
from bs4 import BeautifulSoup
import requests
from datetime import datetime
from threading import Thread
# local imports
import src.formattr as form
from src.configs_mt import AMAZON, WALMART, COSTCO, BESTBUY, scrape_ebay, scrape_target
#=======
#import src.scraper.formattr as form
#from src.scraper... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from mmdet.core import (auto_fp16, bbox_target, delta2bbox, force_fp32,
multiclass_nms)
from ..builder import build_loss
from ..losses import accuracy
from ..registry import HEADS
import ... |
import os
from fontbakery.profiles.universal import UNIVERSAL_PROFILE_CHECKS
from fontbakery.status import INFO, WARN, ERROR, SKIP, PASS, FAIL
from fontbakery.section import Section
from fontbakery.callable import check, disable
from fontbakery.utils import filesize_formatting
from fontbakery.message import Message
fr... |
from collections import OrderedDict
from typing import Dict, Any
from tensorboard.compat.proto.config_pb2 import RunMetadata
from tensorboard.compat.proto.graph_pb2 import GraphDef
from tensorboard.compat.proto.step_stats_pb2 import StepStats, DeviceStepStats
from tensorboard.compat.proto.versions_pb2 import VersionDe... |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from collections import Counter
from copy import deepcopy
from datetime import date, datetime
from uuid im... |
"""
distutils.command.upload
Implements the Distutils 'upload' subcommand (upload package to a package
index).
"""
import os
import io
import platform
import hashlib
from base64 import standard_b64encode
from urllib.request import urlopen, Request, HTTPError
from urllib.parse import urlparse
from distutils.errors imp... |
# -*- coding: utf-8 -*-
"""Data Manipulation
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1dnbNHRyDzukEq2IVv2Bx2tdzVEbLZJc0
"""
import pandas as pd
df1 = pd.read_csv("district_school_data.csv")
df2 = pd.read_csv("district_expense_data.csv")
d = {'D... |
def reverse_vowels(s):
"""Reverse vowels in a string.
Characters which re not vowels do not change position in string, but all
vowels (y is not a vowel), should reverse their order.
>>> reverse_vowels("Hello!")
'Holle!'
>>> reverse_vowels("Tomatoes")
'Temotaos'
>>> reverse_vowels("Re... |
from ..base import BaseHistoryItem, GenericHistoryItem
from ..utils import PolymorphicBase
class ApprovedHistoryItem(BaseHistoryItem):
field = "approved"
field_name = "Resolvability assessment: Approval"
def get_value(self, value):
if value is True:
return "Approved"
elif valu... |
"""
Tests for setting options in KalmanFilter, KalmanSmoother, SimulationSmoother
(does not test the filtering, smoothing, or simulation smoothing for each
option)
Author: Chad Fulton
License: Simplified-BSD
"""
from __future__ import division, absolute_import, print_function
import numpy as np
from statsmodels.tsa.... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os
import glob
import pandas as pd
import time
import datetime
import logging
import logging.config
# global configuration
import vprimer.glv as glv
import subprocess as sbp
from subprocess import PIPE
def start_log():
''' from conf.py _set_pat... |
'''
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
'''
from torchvision import datasets, transforms
import torch
import numpy as np
import random... |
import asyncio
import aiohttp
from aiohttp import ClientConnectorError
from tracardi_plugin_sdk.domain.register import Plugin, Spec, MetaData, Form, FormGroup, FormField, FormComponent
from tracardi_plugin_sdk.domain.result import Result
from tracardi_plugin_sdk.action_runner import ActionRunner
from tracardi_dot_notat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.