text
stringlengths
2
999k
"""Tests for `virtual_finance_api` package.""" import pytest from click.testing import CliRunner from virtual_finance_api import cli def test_000_something(): """Test something.""" # disabled due too: unresolved 'return cli.name or root' error def Xtest_command_line_interface(): """Test the CLI.""" r...
# coding: utf-8 """ LUSID API FINBOURNE Technology # noqa: E501 The version of the OpenAPI document: 0.11.3648 Contact: info@finbourne.com Generated by: https://openapi-generator.tech """ try: from inspect import getfullargspec except ImportError: from inspect import getargspec as getf...
import cirpy import aiohttp import asyncio async def test_request(): async with aiohttp.ClientSession() as session: smiles = await cirpy.resolve(session, '71-43-2', 'smiles') real_smiles = "c1ccccc1" assert real_smiles == smiles if __name__ == '__main__': loop = asyncio.get_event_loop() lo...
from datetime import date from dateutil.parser import parse import datetime from unidecode import unidecode from math import log import hashlib def __timeconversion(timein): ''' such as 12:30:56 ''' strs = timein.split(':') if len(strs)==3: timeout = strs[0] + ':' + strs[1] + ":00" ...
from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Tag, Recipe from ..serializers import TagSerializer TAGS_URL = reverse('recipe:tag-list') class PublicTa...
from experiments import MLMExperiment import torch import argparse from pathlib import Path import numpy as np import os USE_CUDA = torch.cuda.is_available() device = torch.device("cuda" if USE_CUDA else "cpu") def main(delay, batch_size, rnn_units, layers, bidi, experiment_name, data_dir, output_dir, mode...
import sys sys.path.insert(1, '../pyKinectAzure/') import numpy as np from pyKinectAzure import pyKinectAzure, _k4a, postProcessing import cv2 # Path to the module # TODO: Modify with the path containing the k4a.dll from the Azure Kinect SDK modulePath = 'C:\\Program Files\\Azure Kinect SDK v1.4.1\\sdk\\windows-deskt...
from flask import Flask, jsonify, request import util app = Flask(__name__) @app.route('/') def all(): return jsonify(database) @app.route('/reseta', methods=['POST']) def reseta(): util.reseta() return 'banco resetado' @app.route('/alunos', methods=['GET']) def alunos(): retur...
from django.urls import path, include # from rest_framework import routers from color_augmenter.views import IllustrationSetList, IllustrationSetDetail app_name = "color_augmenter" color_augmenter_patterns = [ path( "illustrations/", IllustrationSetList.as_view(), name="api_illustration_s...
#!/usr/bin/env python3 from enum import Enum class NodeType(Enum): MEASURED = 1 LATENT = 2 ERROR = 3 SESSION = 4 RANDOMIZE = 5 LOCK = 6 NO_TYPE = 7 def __str__(self): return self.name
#!/usr/bin/python # # Copyright (C) 2020 ByteDance 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 l...
from operator import getitem from functools import partial import pytest from dask.utils_test import add, inc from dask.core import get_dependencies from dask.optimization import (cull, fuse, inline, inline_functions, functions_of, fuse_getitem, fuse_selections, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Python command line application to convert Markdown to PDF. .. currentmodule:: mdpdf .. moduleauthor:: Norman Lorrain <normanlorrain@gmail.com> """
from rest_framework import serializers from .models import Category, Brand, Supply, Unit, SupplyItem, Packaging, Product class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ('id', 'name') class BrandSerializer(serializers.HyperlinkedModelSerial...
import typing class UnionFind(): def __init__( self, n: int, ) -> typing.NoReturn: self.__a = [-1] * n def find( self, u: int, ) -> int: a = self.__a if a[u] < 0: return u a[u] = self.find(a[u]) return a[u] def unite( self, u: int, v: int, ) -> ty...
""" A collection of backend-agnostic utilities. The goal of this module is to provide a bridge between DyNet and Torch code, by providing commonly used functionality that allows writing code that works with either backend. This is *not* meant as a complete wrapper around each backend. Rather, only important high leve...
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.9.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re ...
import random from abc import ABC from abc import abstractmethod from dataclasses import dataclass from dataclasses import field from typing import Any from typing import Optional from omegaconf import MISSING from .tools import ConfigObj class IntNumber(ABC): """Abstract class castable to integer.""" @abs...
import turtle, random turtle.setup(500, 500) randy = turtle.Pen() while True: randy.forward(random.randint(-100, 100)) randy.setheading(random.randint(-360, 360)) if randy.xcor() >= 250 or randy.xcor() <= -250 or randy.ycor() >= 250 or randy.ycor() <= -250: randy.goto(0, 0)
"""Overview plots of transcet""" import numpy as np import matplotlib.pyplot as plt from scipy.stats import linregress from os.path import join from src import Section, Config plt.ion() cf = Config() savedir = 'reports/jasa/figures' inputed = np.load('data/processed/inputed_decomp.npz') lvls = inputed['filled_lvls...
import tkinter as tk import tkinter.font from tkinter import ttk from optimize_images_x import __version__ from optimize_images_x.calcs import human from optimize_images_x.global_setup import APP_NAME from optimize_images_x.global_setup import CREDITS, APP_LICENSE class ThanksWindow: def __init__(self): ...
Dizest = wiz.model("dizest/scheduler") db = season.stdClass() db.workflow = wiz.model("dizest/db").use("workflow") def running(wiz): running = Dizest.running() for i in range(len(running)): wpid = running[i] workflow = db.workflow.get(id=wpid, fields="id,title,logo") dizest = Dizest(wpi...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provides a web interface for dumping graph data as JSON. This is meant to be used with /load_from_prod in order to easily grab data for a graph to a loca...
import os from typing import Iterator import pytest from dagster_graphql.schema import create_schema from gql import Client, gql from dagster.utils import file_relative_path @pytest.fixture(scope="session", name="validator_client") def get_validator_client() -> Client: return Client(schema=create_schema()) de...
import torch import torch.nn as nn import torch.nn.functional as F from torchvision.transforms import transforms # estimate the gradient of the confidence score w.r.t. the input data def nes_gradient_est(model, device, data, lbl, n_query=100, sigma=0.001): model.eval() g = torch.zeros_like(data) inds = ra...
# -*- coding: utf-8 -*- """Base command-line interface.""" from __future__ import absolute_import, print_function, unicode_literals import argparse import json import os import random import re import sys import warnings from collections import defaultdict from heapq import heappush from pprint import pformat from ce...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sphinx_bootstrap_theme # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' project = 'glucose' copyright = '2017, Neil Vice' author = 'Neil Vice' version = '0.0.5' release = '0.0.5' extensions = [ 'sph...
from dataclasses import dataclass from torch import nn import torch from data.dataset import * from typing import List from torch_scatter import scatter_mean, scatter_add, scatter_max from layers import * from constants import * class MegnetLayer(nn.Module): def __init__(self, n_hidden_1=600, n_hidden_2=300): ...
from ..pojo import * class CommandExecutor(object): """ just a template class of commandExecutor """ def execute(self, runs: Message) -> bool: """ when the command activated to call this function :param runs:the message :return:is this command runs well? """ ...
import boto3 from django.conf import settings def is_property_in_image(img): client = boto3.client( "rekognition", aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, region_name=settings.AWS_REGION_NAME, ) response = client.d...
# -*- coding: utf-8 -*- ############################################################ # # Autogenerated by the KBase type compiler - # any changes made here will be overwritten # ############################################################ from __future__ import print_function # the following is a hack to get the basec...
from decimal import Decimal from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from oscar.core.compat import AUTH_USER_MODEL @python_2_unicode_compatible class AbstractProductRecord(models.Model): """ A record of...
import os import re import json import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import style from tqdm import tqdm style.use("ggplot") ''' READING FILES ''' dirs = ["biorxiv_medrxiv","comm_use_subset","noncomm_use_subset","custom_license"] docs = [] for d in dirs: print...
import os import sys from rs2_listener import CWaitForMessage import rosbag from cv_bridge import CvBridge, CvBridgeError import numpy as np import tf import itertools import subprocess import rospy import time import rosservice global tf_timeout tf_timeout = 5 def ImuGetData(rec_filename, topic): # res['value']...
# Copyright (c) 2011 Citrix Systems, Inc. # Copyright 2011 OpenStack Foundation # Copyright (C) 2011 Nicira, Inc # 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 a...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © 2018 Ryan Collins <rlcollins@g.harvard.edu> # Distributed under terms of the MIT license. """ Apply final FILTER cleanup and QUAL score recalibration """ import argparse import sys import pysam import csv from numpy import median from svtk.utils import is...
from re import compile def require(value, message): if not value: raise ValueError(message) return value def match_validator(value, regex, message): if value and not regex.match(value): raise ValueError(message) return value class Contact: email_regex = compile( r"[a-z0...
from argparse import RawTextHelpFormatter import datetime import glob import os import zipfile from lxml import html import requests from django.conf import settings from django.core.management import BaseCommand from openprescribing.utils import mkdir_p class Command(BaseCommand): help = """ This command down...
# coding: utf-8 """ brownie ~~~~~~~ Brownie provides various different utilities and datastructures, which are commonly used in Python applications. :copyright: 2010-2011 by Daniel Neuhäuser :license: BSD, see LICENSE.rst for details """ #: A string containing the full version number. __versio...
import chess.pgn import math pgn = open("test-game.pgn") game = chess.pgn.read_game(pgn) board = game.board() for i, move in enumerate(game.main_line()): if (i % 2 == 0): print("turn " + str(math.ceil((i + 1) / 2))) print (board.san(move)) board.push(move) ...
import copy from torch import nn import numpy as np from PIL import Image from pytti.tensor_tools import named_rearrange SUPPORTED_MODES = ["L", "RGB", "I", "F"] class DifferentiableImage(nn.Module): """ Base class for defining differentiable images width: (positive integer) image width in pixels ...
import datetime import logging import math import time from decimal import Decimal import boto3 import numpy as np import pandas as pd import pyarrow as pa import pytest import awswrangler as wr from ._utils import ensure_data_types, get_df, get_df_cast, get_df_list logging.getLogger("awswrangler").setLevel(logging...
import numpy as np import pandas as pd from datetime import datetime, timedelta def read_lba_flux_data(path, folder_name): fid = '_Avg_month_qaqc.csv' fpath = path + folder_name + '/' + folder_name[-8:-5] + fid data = pd.read_csv(fpath) data = data.dropna() data.columns = data.iloc[0] data = ...
import tempfile import subprocess import warnings import os import codecs import tempfile import copy import sys import time from tree import SeqTree, RelativeLevelTreeEncoder """ Transforms a list of list into a single list """ def flat_list(l): flat_l = [] for sublist in l: for item in sublist: ...
import torch import torch.nn as nn import torch.nn.functional as F from collections import OrderedDict import math import requests import tempfile import shutil import pickle import os class _DenseLayer(nn.Module): def __init__(self, num_input_features, growth_rate, bottleneck_width, drop_rate): super(_Den...
# Code Listing #9 """ Multi chat server using gevent """ # gevent_chat_server.py import gevent from gevent import monkey from gevent import socket from gevent.server import StreamServer monkey.patch_all() participants = set() def new_chat_channel(conn, address): """ New chat channel for a given connection ...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
"""user_remove_roles Revision ID: 4c6ca48245be Revises: d5b5eb2e8dd0 Create Date: 2021-03-08 11:37:13.600415 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '4c6ca48245be' down_revision = 'd5b5eb2e8dd0' branch_labels = None depends_on = None def upgrade(): ...
# Copyright (c) 2007-2010 Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.cred.strcred}. """ import os import StringIO from twisted import plugin from twisted.trial import unittest from twisted.cred import credentials, checkers, error, strcred from twisted.plugins import cred_file, cr...
# # Copyright John Reid 2009 # """ Some matrices to use as examples for structural basis for gapped PWMs. """ import numpy from itertools import imap, ifilter cebp_M00912_seqs = """ TTGC-TAAACT TTGC-GCAAGA TTGC-TCAATT TTTC-TCAATA TTGCTTGAATA TTGC-CCAACT """ mef2_M00941_seqs = """ GGTTATTTTTAA- GGTTATAATTAA- AGT...
from __future__ import unicode_literals, division, absolute_import import urllib import urllib2 import logging import re import socket from flexget import plugin from flexget.entry import Entry from flexget.event import event from flexget.plugins.plugin_urlrewriting import UrlRewritingError from flexget.utils.soup imp...
from django.forms import ModelForm from codex.models import Course, Module, Lesson, Activity # Forms class ModuleForm(ModelForm): class Meta: model = Module fields = ['is_active', 'module_title']
from Algorithm import Algorithm #Base class """ Author: Caio Marcelo Campoy Guedes E-Mail: caiomcg@gmail.com License: MIT License Copyright (c) 2016 Caio Marcelo Campoy Guedes Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Soft...
#!/usr/bin/env python from __future__ import print_function import argparse import collections import errno import json import os import platform import shutil import subprocess import sys import multiprocessing #################################################################### # MSVC environment setup routines if...
#! /usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # # Copyright (c) 2015 Bartosz Janda # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including w...
from flask import url_for, request, current_app from app.auth.models import User, PreAllowedUser from app.extensions import db def test_register_and_login(client, database): # Register unconfirmed user response = client.post(url_for('auth.register'), data={ 'email': 'a@a.com', 'password': 'a'...
#------------------------------------------------------------------------------- # Copyright 2017 Cognizant Technology Solutions # # 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:...
import sys _,N,L=sys.argv B=[] P=[] for _ in[1]*8:B+=[*'.'*8], for x,y,s,q in L.split(','):P+=[x:=int(x),y:=int(y),x*4^56*y^5,s,0,q],;B[y][x]=s for _ in s*int(N): for p in P: x,y,n,s,c,q=p;n^=n<<13;n^=n>>17;n^=n<<5;z=1-2*(n%2);u,w=[x,y+z&7]if n&2else[x+z&7,y] if'R'<s:c+=1 if c>13:s='R' if('1'>q)*'/'>B[w][u]:B[...
def _cluck(*args,skip=1): """Warn with stack backtrace""" print(_longmess(*args, skip=skip), end='', file=sys.stderr)
"""Contains all functions for the purpose of logging in and out to Robinhood.""" import getpass import os import pickle import random from robin_stocks.robinhood.helper import * from robin_stocks.robinhood.urls import * def generate_device_token(): """This function will generate a token used when loggin on. ...
# Classification (U) """Program: setup.py Description: A setuptools based setup module. """ # Libraries and Global Variables # Standard import os import setuptools # Third-party # Local import version # Read in long description from README file. here = os.path.abspath(os.path.dirname(__file__)) with ope...
#coding:utf-8 import numpy as np import tensorflow as tf from PIL import Image _R_MEAN = 123.68 _G_MEAN = 116.78 _B_MEAN = 103.94 # colour map label_colours = [ (0, 0, 0), # 0=background # 1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), ...
# # OtterTune - fabfile.py # # Copyright (c) 2017-18, Carnegie Mellon University Database Group # ''' Admin tasks @author: dvanaken ''' import logging from collections import namedtuple from fabric.api import env, local, quiet, settings, task from fabric.state import output as fabric_output from website.settings imp...
""" @author: Dracovian @date: 2021-02-10 @license: WTFPL """ """ http.client.HTTPSConnection: Used to grab data from sites that use TLS or SSL encryption. """ from http.client import HTTPSConnection """ os.makedirs: Used to create a folder with subfolders. os.path: Used to combine and split file paths. """ fr...
#!/usr/bin/python import os from yate.ivr import YateIVR async def main(ivr: YateIVR): dirname = os.path.dirname(__file__) sndfile = os.path.join(dirname, "test.slin") await ivr.play_soundfile(sndfile, complete=True) ivr = YateIVR() ivr.run(main)
import re import sys import time if sys.version_info < (3,): range = xrange class Tailer(object): """\ Implements tailing and heading functionality like GNU tail and head commands. """ line_terminators = ('\r\n', '\n', '\r') def __init__(self, file, read_size=1024, end=False): sel...
#!/usr/bin/env python3 # Copyright (c) 2018-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoin-wallet.""" import hashlib import os import stat import subprocess import textwrap from c...
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RMlinterfaces(RPackage): """This package provides uniform interfaces to machine learning ...
# Generated by Django 2.0.4 on 2018-04-13 14:49 from django.db import migrations, models import versatileimagefield.fields class Migration(migrations.Migration): dependencies = [ ('listing', '0010_auto_20180412_2318'), ] operations = [ migrations.AlterField( model_name='list...
from unittest import TestCase from mock import patch from pyamp.player import SweepingInterpolationControlSource class TestSweepingInterpolationControlSource(TestCase): # These tests suffer a little from testing the implementation rather than # the general behaviour :-( def setUp(self): # We ha...
import torch from ..distances import CosineSimilarity from ..reducers import DivisorReducer from ..utils import common_functions as c_f from ..utils import loss_and_miner_utils as lmu from .base_metric_loss_function import BaseMetricLossFunction from .mixins import WeightRegularizerMixin # adapted from # https://git...
# Copyright 2017 Google Inc. 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 a...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=4 # total number=23 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np class Opty(cirq.PointOptimizer): def optimization_at( ...
""" Map marginals between each one another by Fermionic anticommutaiton relations A collection of methods that accept a RDM and map it to another RDM """ import numpy as np from itertools import product def map_d2anti_d1_sz(tpdm, normalization, bas, m_dim): """ construct the opdm from the tpdm and the basis ...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import TYPE_CHECKING, Union from libcst._flatten_sentinel import FlattenSentinel from libcst._metadata_dependent import Metadat...
# coding: utf-8 """ Iot API Collection of all public API endpoints. # noqa: E501 The version of the OpenAPI document: 2.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from arduino_iot_rest.configuration import Configuration class ArduinoSeri...
import numpy as np import pytest import pandas as pd from pandas import DataFrame, MultiIndex, Series import pandas._testing as tm class TestDataFrameIsIn: def test_isin(self): # GH#4211 df = DataFrame( { "vals": [1, 2, 3, 4], "ids": ["a", "b", "f", "n"...
#!/usr/bin/env python # --------------------------------------------------------------------- # OPRA Dataset # Copyright 2018 University of Southern California, Stanford University # Licensed under The MIT License [see LICENSE for details] # Written by Kuan Fang, Te-Lin Wu # -------------------------------------------...
#!/usr/bin/env python3 import rospy from std_msgs.msg import Int32 zodiac_num = 0 print("卯") def cb(message): global zodiac_num zodiac_num = message.data zodiac_num = zodiac_num - 1995 while zodiac_num > 12: if zodiac_num > 12: zodiac_num = zodiac_num - 12 elif zodiac_num...
# Copyright (c) AIRBUS and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations from typing import List, Dict, Union, Set, Any __all__ = ['VariableResourceConsumption', 'ConstantResourceConsumpti...
from dataclasses import dataclass from agent0.common.bench import bullet, mujoco7 @dataclass class Config: game: str = "HalfCheetah" algo: str = "ddpg" seed: int = 0 sha: str = "" exp_name: str = "mujoco_ddpg" restore_checkpoint: str = "" ckpt_freq: int = 50000 total_steps: int = int...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
SODA_SQL_VERSION = '2.1.0b2'
#!/usr/bin/env python import boto3 from nebula_sdk import Interface, Dynamic as D relay = Interface() session_token = None try: session_token = relay.get(D.aws.connection.sessionToken) except: pass sess = boto3.Session( aws_access_key_id=relay.get(D.aws.connection.accessKeyID), aws_secret_access_key=relay.ge...
# -*- coding: utf-8 -*- # Copyright 2018-2022 CERN # # 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 a...
from setuptools import setup setup( name="tiny-flask", packages=["tinyflask"], include_package_data=True, install_requires=["flask"], )
import csv import json import logging from django.contrib import messages from django.contrib.auth.decorators import user_passes_test from django.contrib.postgres.search import SearchVector from django.db import transaction from django.http import HttpResponse from django.shortcuts import redirect from django.utils im...
""" Routines for casting. """ from __future__ import annotations from datetime import ( date, datetime, timedelta, ) import functools import inspect from typing import ( TYPE_CHECKING, Any, Sized, TypeVar, cast, overload, ) import warnings import numpy as np from pandas._libs imp...
""" API Controller providing Galaxy Webhooks """ import importlib.util import logging from typing import Any from galaxy.web import expose_api_anonymous_and_sessionless from galaxy.webapps.base.webapp import GalaxyWebTransaction from . import BaseGalaxyAPIController log = logging.getLogger(__name__) class WebhooksC...
import requests from backend.variable import URL_WEATHER, URL_FORECAST def conf(): r_weather = requests.get(URL_WEATHER) data = r_weather.json() temp = round(data['main']['temp']) cond = data['weather'][0]['description'] return temp, cond def data(): result = {} r_forecast ...
import numpy as np from numba import njit # consav from consav import misc from consav import linear_interp # for linear interpolation # local modules import pens import utility import upperenvelope @njit def inv_mn_and_v(c,d,a,b,w,par): v = utility.func(c,par) + w m = a+c+d n = b-d-pens.func(d,par) ...
import random from ..types import ( DataAssetIdentifier, ValidationResultIdentifier, ) from ..types.base_resource_identifiers import ( DataContextKey, ) from ..util import safe_mmkdir import pandas as pd import six import io import os import json import logging logger = logging.getLogger(__name__) import i...
# # All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or # its licensors. # # For complete copyright and license terms please see the LICENSE at the root of this # distribution (the "License"). All use of this software is governed by the License, # or, if provided, by the license below or th...
# Evaluates semantic instance task # Adapted from the CityScapes evaluation: https://github.com/mcordts/cityscapesScripts/tree/master/cityscapesscripts/evaluation # Input: # - path to .txt prediction files # - path to .txt ground truth files # - output file to write results to # Each .txt prediction file look lik...
from leveleditorlibs import tool, resources, graphics, draw, level from pyglet.window import key class Rect(tool.Tool): x1, y1, x2, y2 = 0.0, 0.0, 0.0, 0.0 def select(self): self.snap = True def check_snap(self, x, y): if self.snap: xb = x - x % 50 yb ...
import numpy as np import torch import torch.fft ############ ### Numpy functions ### Not used in the code. Just to test the pytorch functions ############ def f_radial_profile(data, center=(None,None)): ''' Module to compute radial profile of a 2D image ''' y, x = np.indices((data.shape)) # Get a grid of x ...
#!/usr/bin/env python """List all those Python files that require a coding directive Usage: nocoding.py dir1 [dir2...] """ __author__ = "Oleg Broytmann, Georg Brandl" import sys, os, re, getopt # our pysource module finds Python source files try: import pysource except ImportError: # emulate the module wit...
import aiohttp_jinja2 import sqlalchemy as sa from vpa.db.trades import TradesTable async def market_handler(request): market = request.match_info.get('market') lines = [] points_buy = [] points_sell = [] async with request.app['pg'].acquire() as conn: async for row in conn.execute( ...
# coding=utf-8 # Copyright (c) DIRECT Contributors """MRI model engine of DIRECT.""" import gc import pathlib import time from abc import abstractmethod from collections import defaultdict from os import PathLike from typing import Callable, Dict, List, Optional, Tuple, Union import numpy as np import torch from tor...
# qubit number=4 # total number=39 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(3) # number=19 prog...