text stringlengths 2 999k |
|---|
from flatdata.generator.tree.nodes.references import StructureReference
from .base import ResourceBase
class Vector(ResourceBase):
def __init__(self, name, properties=None, type=None):
super().__init__(name=name, properties=properties)
self._type = type
@staticmethod
def create(properties... |
""" Store packages in GCS """
import logging
import os
import posixpath
from datetime import timedelta
from google.auth import compute_engine
from google.auth.transport import requests
from google.cloud import storage
from pyramid.settings import asbool
from pypicloud.models import Package
from .object_store import O... |
"""
Miscellaneous enums used in jina
To use these enums in YAML config, following the example below:
.. highlight:: yaml
.. code-block:: yaml
!Flow
with:
logserver_config: yaml/test-server-config.yml
optimize_level: !FlowOptimizeLevel IGNORE_GATEWAY
# or
optimize_level: IGNORE_GATEWA... |
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
#
# Copyright (C) Open End AB 2007-2011, All rights reserved
# See LICENSE.txt
#
"""
Controlling browsers for javascript testing
"""
import sys, urllib
import subprocess
try:
import json
except ImportError:
import simplejson as json
from oejskit.serving import Serve, ServeFiles, Dispatch
from oejskit.modular i... |
import re
try:
import curses
except ImportError:
curses = None
import os
import sys
from StringIO import StringIO
COLORS = ("BLUE", "RED", "GREEN", "YELLOW", "WHITE", "BLACK")
class OutputHandler:
"""A handler that hooks up with the error bundler to colorize the
output of the application for *nix-ba... |
"""
ASGI config for backend_project project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJAN... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class PreCheckInfo:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is at... |
# encoding=utf-8
# Author: Yu-Lun Chiang
# Description: Get news
import logging
from bs4 import BeautifulSoup
from src.crawler.media.base import BaseMediaNewsCrawler
from src.utils.struct import NewsStruct
logger = logging.getLogger(__name__)
class TVBSNewsCrawler(BaseMediaNewsCrawler):
"""Web Crawler for TVB... |
numero = input("inserire un numero intero positivo: ")
primo = False
contatore = 1
if numero % 2 == 0:
primo = False
print numero, "e' un numero pari"
else:
divisore = 1.0
while divisore < numero:
divisore = contatore * 2 + 1
quoziente = numero / (1.0 * divisore)
resto = numero ... |
#!/usr/bin/env python
import base_filters
COPY_GOOGLE_DOC_KEY = '1b3bLJyb8HbMEFOU8Z0i9U9-0DB16dyQWIkSLzGHtCx8'
USE_ASSETS = False
# Use these variables to override the default cache timeouts for this graphic
# DEFAULT_MAX_AGE = 20
# ASSETS_MAX_AGE = 300
JINJA_FILTER_FUNCTIONS = base_filters.FILTERS
|
"""
zmq_debugger - General Purpose ZeroMQ Debugger
Usage:
gpdb -s TYPE -e ENDPOINT (-b|-c) (-i|-o) [-x] [-t TOPIC]
Options:
-s TYPE PUB, SUB, PUSH, ... (http://api.zeromq.org/4-2:zmq-socket)
-e ENDPOINT Endpoint on which to listen or send transactions to.
"tcp://*:14637". Listen on tcp p... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
colordict = {
"Pb": "#85807b",
"Pb++": "#db653d",
"PbO": "#e04a16",
"PbO2": "#3ec760",
"Pb3O4": "#2a8744",
"Pb++++": "#c92840",
"HPbO2-": "#db7d42",
"PbO3--": "#bf3939",
"Hc": "#191cf7",
"PbCO3": "#007BA7", ... |
# Copyright 2016 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... |
# -*- coding: utf-8 -*-
from anima.ui.base import AnimaDialogBase, ui_caller
from anima.ui.lib import QtCore, QtWidgets
def UI(app_in=None, executor=None, **kwargs):
"""
:param app_in: A Qt Application instance, which you can pass to let the UI
be attached to the given applications event process.
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 (http://hl7.org/fhir/StructureDefinition/UsageContext) on 2017-03-22.
# 2017, SMART Health IT.
from . import element
class UsageContext(element.Element):
""" Describes the context of use for a conformance or knowledge resource.
... |
import itertools
import operator
first = operator.itemgetter(0)
def windows(iterable, length):
args = itertools.tee(iterable, length)
# advance each iterator as many steps as its rank-1
# thus, advance the 1st iterator none, 2nd iterator once. etc.
for i in range(len(args)-1, 0, -1):
for iter_... |
import matplotlib.pyplot as plt
import numpy as np
SMALL_SIZE = 8
MEDIUM_SIZE = 14
BIGGER_SIZE = 20
plt.rc('font', size=BIGGER_SIZE) # controls default text sizes
plt.rc('axes', titlesize=BIGGER_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=BIGGER_SIZE) # fontsize of the x and y labels
p... |
import math
def my_Cosine(p):
sum = 0
for n in range(86):
sum += ((-1)**(n))*((p)**(2*n))/(math.factorial(2*n))
return sum
angle = math.pi/2
print(my_Cosine(angle))
angle = math.pi
print(my_Cosine(angle))
angle = 3*math.pi/2
print(my_Cosine(angle))
angle = 2*math.pi
print(my_Cosine(angle))
|
"""
TODO:
- add a test to test each solver many times on different populations,
and record the error.
"""
from __future__ import print_function
import numpy as np
import pytest
import nengo
from nengo.dists import UniformHypersphere
from nengo.utils.compat import range
from nengo.utils.numpy import rms, norm
fr... |
from __future__ import division
import pandas as pd
import numpy as np
# import matplotlib.pyplot as plt
# import datetime
# plt.interactive(False)
df_sales = pd.read_csv('../data/Haiku_shirt_sales_analyzed.csv', parse_dates=['birth', 'order_date'],
infer_datetime_format=True, index_col = 'order... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt5 (Qt v5.5.1)
#
# WARNING! All changes made in this file will be lost!
from qtpy import QtCore
qt_resource_data = b"\
\x00\x00\x04\xbb\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x20\x00... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('test.jpg')
if img is None:
print('No such image.')
else:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(gray, 25, 0.01, 10)
points = np.int0(corners)
print(corn... |
import datetime
from enum import Enum
from typing import Any, Callable, Dict, Optional
from choicesenum import ChoicesEnum
from .exceptions import ExifError
ExifType = Dict[str, Dict[str, Any]]
class Orientation(ChoicesEnum, Enum): # NOTE inherits from `Enum` to make `mypy` happy
LANDSCAPE = 'landscape'
P... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Batch processing for GRD products
"""
import os
import json
import itertools
import logging
import pandas as pd
from pathlib import Path
from godale._concurrent import Executor
from ost import Sentinel1Scene
from ost.s1 import grd_to_ard
from ost.helpers import ras... |
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=35):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Olá, Meu nome é {self.nome}'
@staticmethod
def metodo_estatico():
return 42
@classm... |
from __future__ import absolute_import
import email.utils
import mimetypes
import six
def guess_content_type(filename, default='application/octet-stream'):
"""
Guess the "Content-Type" of a file.
:param filename:
The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param defa... |
import micropython
# Tests both code paths for built-in exception raising.
# mp_obj_new_exception_msg_varg (exception requires decompression at raise-time to format)
# mp_obj_new_exception_msg (decompression can be deferred)
# NameError uses mp_obj_new_exception_msg_varg for NameError("name '%q' isn't defined")
# set... |
import numpy as np
from ... import operators
__all__=['moving_average',]
def moving_average(vector,av_cof, mode='postw'):
'''
Simple Moving Average or Weighted Moving Average
Parameters
-------------
* vector: 1d ndarray,
input vector.
* av_cof: int or 1d ndarray,
> if a... |
import warnings
warnings.filterwarnings("ignore")
import os
import sys
import env
import tensorflow as tf
import numpy as np
import pickle
from bm.dbm import DBM
from bm.rbm.rbm import BernoulliRBM, logit_mean
from bm.init_BMs import * # helper functions to initialize, fit and load RBMs and 2 layer DBM
from bm.utils.d... |
from __future__ import absolute_import
from sage.rings.integer import Integer
from sage.structure.sage_object import SageObject
from sage.lfunctions.dokchitser import Dokchitser
from .l_series_gross_zagier_coeffs import gross_zagier_L_series
from sage.modular.dirichlet import kronecker_character
class GrossZagierLser... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
PY3 = sys.version_info >= (3, 0)
PY37 = sys.version_info >= (3, 7)
if PY3:
unicode = str
else:
unicode = unicode
if PY37:
OrderedDict = dict
else:
from collections import OrderedDict
__all__ = ("unicode", "OrderedDict")
|
"""growth_studio URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cl... |
#!/usr/bin/python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# This script creates yaml files to build conda environments
# For generating a conda file for running only python code:
# $ python generate_conda_file.py
#
# For generating a conda file for running python ... |
"""
Analyze the grades of the students.
Here's an example of the data
.. code-block::
111111004 5.0 5.0 6.0
111111005 3.75 3.0 4.0
111111006 4.5 2.25 4.0
Every line represents a grading of a student. It starts with her matriculation number,
followed by space-delimited grades (between 1.0 and 6.0,... |
##############################################################################
#
# Copyright (c) 2001-2012 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THI... |
from copy import deepcopy
import tensorflow as tf
from wandb import util
from wandb.apis.file_stream import Chunk
from wandb.data_types import history_dict_to_json
from wandb.tensorboard import *
import wandb
if hasattr(tf.estimator, 'SessionRunHook'):
# In tf 1.14 and beyond, SessionRunHook is in the estimator ... |
"""
Created on Thu Dec 3 2020
@author: Maria Kuruvilla
Goal - proportion of individuals that startle (using only masked data)
"""
import os
import pathlib
from pprint import pprint
import numpy as np
from scipy import stats
from scipy.spatial import distance
import matplotlib.pyplot as plt
from matplotlib.pyplot i... |
"""Load an action in Blender."""
import logging
from pathlib import Path
from pprint import pformat
from typing import Dict, List, Optional
from avalon import api, blender
import bpy
import pype.hosts.blender.api.plugin
logger = logging.getLogger("pype").getChild("blender").getChild("load_action")
class BlendActio... |
"""Unit test for app_group websocket API.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import jsonschema
import six
from treadmill.websocket.api import app_group
class WSAppGroupAPITest(unit... |
import logging
from copy import deepcopy
from collections import OrderedDict
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import EmptyPage, PageNotAnInteger
from django.db import transacti... |
# Copyright (c) 2016-2017 Intel Corporation
#
# 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... |
from __future__ import print_function
import FWCore.ParameterSet.Config as cms
import sys
import os
process = cms.Process("DTDQM")
unitTest = False
if 'unitTest=True' in sys.argv:
unitTest=True
#----------------------------
#### Event Source
#----------------------------
if unitTest:
process.load("DQM.Integr... |
# Read the maven-generated classpath file and reformat it with one line per jar.
#
# $ mvn dependency:build-classpath -Dmdep.outputFile=classpath.txt
# $ python3 classpath.py classpath > classpath
# $ python3 classpath.py jar_contents > jar_contents.sh
#
# Chris Joakim, Microsoft, 2018/03/14
import sys
if __name__ =... |
from __future__ import print_function
import traceback
from cloudmesh_base.locations import config_file
from cloudmesh_base.ConfigDict import ConfigDict
from cloudmesh_base.logger import LOGGER
from pymongo import MongoClient
from mongoengine import connect
# Changes of import in existing cloudmesh code:
#
## FROM:
... |
#!/usr/bin/env python3
# Copyright 2017- European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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/LICE... |
import pytest
from sqlalchemy.orm import Session
from sqlalchemy import Column, Integer
from sqlalchemy_oso.flask import AuthorizedSQLAlchemy
from sqlalchemy_oso.session import Permissions
from .models import Post, ModelBase
flask = pytest.importorskip("flask")
flask_sqlalchemy = pytest.importorskip("flask_sqlalche... |
"""
Support for ISY994 locks.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/lock.isy994/
"""
import logging
from typing import Callable # noqa
from homeassistant.components.lock import LockDevice, DOMAIN
from homeassistant.components.isy994 import (IS... |
# PyTorch utils
import logging
import math
import os
import subprocess
import time
from contextlib import contextmanager
from copy import deepcopy
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
import torchvision
try:
import thop ... |
#!/usr/bin/env python3
import sys
for line in sys.stdin:
sentences = line.split('\n')
for sentence in sentences:
print(sentence.strip())
|
"""network2.py
~~~~~~~~~~~~~~
An improved version of network.py, implementing the stochastic
gradient descent learning algorithm for a feedforward neural network.
Improvements include the addition of the cross-entropy cost function,
regularization, and better initialization of network weights. Note
that I have... |
from protocols.generateprotocol import GenerateProtocol
from operations.ledmatrix.ledmatrixoperationutils import LEDMatrixOperationUtils
import time
class LEDMatrixOperation():
def __init__(self, number, group_id, robot_status, start_check, write):
self._GenerateProtocolInstance = GenerateProtocol(number, ... |
# python3.7
"""Contains the runner for StyleGAN3."""
from copy import deepcopy
from .base_runner import BaseRunner
__all__ = ['StyleGAN3Runner']
class StyleGAN3Runner(BaseRunner):
"""Defines the runner for StyleGAN3."""
def build_models(self):
super().build_models()
g_ema_img = self.confi... |
from twisted.internet import defer
from test_jcli import jCliWithoutAuthTestCases
class SmppccmTestCases(jCliWithoutAuthTestCases):
# Wait delay for
wait = 0.3
def add_connector(self, finalPrompt, extraCommands = []):
sessionTerminated = False
commands = []
commands.append... |
from project.server.log import INFO, WARN
from flask import request, make_response, jsonify
from flask.views import MethodView
from project.server import db
from project.server.models import Example
class AddExampleAPI(MethodView):
"""
Add Example Resource
"""
def post(self):
try:
... |
"""MS COCO object detection dataset."""
from __future__ import absolute_import
from __future__ import division
import os
import numpy as np
import mxnet as mx
from .utils import try_import_pycocotools
from ..base import VisionDataset
__all__ = ['COCOInstance']
class COCOInstance(VisionDataset):
"""MS COCO instan... |
#-------------------------------------------------------------------------------
#
# WPS Literal Data - units of measure
#
# Project: EOxServer <http://eoxserver.org>
# Authors: Martin Paces <martin.paces@eox.at>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2014 EO... |
from typing import List
''' Medium '''
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution_1:
def __init__(self):
self.maps = {}
def generat... |
import json
import threading
import time
import os
import stat
import ssl
from decimal import Decimal
from typing import Union, Optional
from numbers import Real
from copy import deepcopy
from . import util
from . import constants
from .util import (user_dir, make_dir,
NoDynamicFeeEstimates, format... |
__version__ = "3.2.4"
|
#!/usr/bin/env python3
import argparse
import json
import numpy
import os
import random
import re
import subprocess
import sys
import time
args = None
logFile = None
unlockTimeout = 999999999
fastUnstakeSystem = './fast.refund/eosio.system/eosio.system.wasm'
systemAccounts = [
'eosio.bpay',
... |
from torch.nn import Conv2d, MaxPool2d
from torch import no_grad, round
from torch.nn.functional import interpolate
from itertools import chain
class PRISM:
_excitations = []
_hook_handlers = []
_is_orig_image = True
def _excitation_hook(module, input, output):
# for better output sharpness w... |
import sys
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
grandfatherdir = os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__))))
sys.path.append(parentdir)
sys.path.append(grandfatherdir)
dir_path = os.path.dirname(os.path.realpath(__file__)) |
#!/usr/bin/env python
from __future__ import print_function
import shutil
import unittest
from ruffus import pipeline_run, pipeline_printout, Pipeline, formatter, originate, subdivide, split
import time
import sys
"""
test_split_subdivide_checkpointing.py
"""
import os
tempdir = os.path.relpath(os.path.abspath(... |
"""This package includes circuit minimizer implementations."""
from __future__ import annotations
from bqskit.ir.opt.minimizers.lbfgs import LBFGSMinimizer
__all__ = ['LBFGSMinimizer']
|
from .toplevel import *
__version__ = "0.0.3"
|
# -*- coding: utf-8 -*-
'''
This code calculate running average of temperature (global mean and gridded results)
based on 1850-2019 transient simulation
Preindustrial global mean temperature derived from a 110-year 1850 repeating cycle simulation is also calcualted
by Yixuan Zheng (yxzheng@carnegiescience.edu)
''' ... |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
import functools
import json
import time
import libcloud.compute.providers as cloud_provider
import libcloud.compute.types as cloud_types
from . import BaseComputeNodeDriver
from .. import arvados_node_fqdn, arvados_timestamp, ARVADOS_TIME... |
# @Author: Joey Teng
# @Email: joey.teng.dev@gmail.com
# @Filename: paired_t_test.py
# @Last modified by: Joey Teng
# @Last modified time: 31-Jul-2018
import argparse
import json
import numpy
import scipy.stats
def main(args):
pathA, pathB = args.i
print(pathA, pathB, flush=True)
dataA = numpy.matrix... |
# start by importing version, because for some weird reason, I sometimes get
# networkx as over-riding the version here (no idea why...)
try:
# should work if installed through normal means: setup.py-based with
# pip, conda, easy_install, etc.
from . import version
except ImportError: # pragma: no cover
... |
# coding=utf-8
import csv
import itertools
import logging
import os
import re
import time
import tempfile
import xlrd
from celery.task import TaskSet
from django.utils.text import slugify
from celery import Task
from django.core.cache import cache
from django.conf import settings
from django.contrib.gis.geos import Po... |
"""Auto-generated file, do not edit by hand. 351 metadata"""
from ..phonemetadata import NumberFormat
PHONE_ALT_FORMAT_351 = [NumberFormat(pattern='(\\d{3})(\\d{3})(\\d{3})', format='\\1 \\2 \\3', leading_digits_pattern=['2[12]']), NumberFormat(pattern='(\\d{2})(\\d{3})(\\d{2})(\\d{2})', format='\\1 \\2 \\3 \\4', lead... |
#!/usr/bin/env python
import datetime
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext import ndb
from fileset.thirdparty import secrets
class Error(Exception):
pass
class FilesetAuthToken(ndb.Model):
description = ndb.StringProperty()
created_b... |
# This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Reuters topic classification dataset.
"""
from __future__ import print_function as _print_function
import sys as _sys
from tensorflow.python.keras.datasets.reuters import get_word_inde... |
dados = dict()
dados1 = list()
somaidade = 0
while True:
dados['nome'] = str(input('Nome: '))
while True:
dados['sexo'] = str(input('Sexo: [F/M] ')).upper()[0]
if dados['sexo'] in 'MF':
break
print('Error!! Digite novamente.')
dados['idade'] = int(input('Idade: '))
d... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'acq4/modules/Patch/PatchTemplate.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
... |
"""
Model inspired by: https://github.com/natasasdj/anomalyDetection
"""
import tensorflow as tf
from tensorflow.keras.layers import (
Input,
Dense,
Conv2D,
MaxPooling2D,
UpSampling2D,
BatchNormalization,
GlobalAveragePooling2D,
LeakyReLU,
Activation,
concatenate,
Flatten,
... |
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
#
# Copyright (c) 2022 Tom Kralidis
#
# 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 ... |
"""Map Filter Zip List Comprehensions
Higher order functions
A function that takes a function as a parameter and/or returns a function as it's return value
Example: sorted
map _
|
-- modern alternative -> list comprehensions and generator expressions
... |
from setuptools import setup, find_packages
VERSION = "0.0.1"
DESCRIPTION = "An infix-to-postfix expression parser for evaluating math expressions."
setup(
name="tinypost",
version=VERSION,
author="Nathan Abraham",
author_email="abnathan123@gmail.com",
description=DESCRIPTION,
packages=find_pa... |
from checkers_ai.config import *
from checkers_ai.state import State
from checkers_ai.trajectory import Trajectory
from checkers_ai.player import HumanPlayer
class Game:
"""
PLAYER2
00 01 02 03
04 05 06 07
08 09 10 11
12 13 14 15
16 17 18 19
20 21 22 23
... |
import sys
import importlib
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import os
# Plot configuration
PLOT_VERTICALLY = 0
PLOT_HORIZONTALLY = 1
PLOT_CONFIG = PLOT_VERTICALLY
# List of valid figures to plot. Must be the names of the plotting script without the .py ext... |
import cv2 as cv
img = cv.imread("testeOpenCV.jpg")
#cv.imshow("Joelma", img)
#cv.waitKey(0)
print(img.size)
print(img.dtype)
# Número de linhas, colunas e canais (se for imagem colorida)
print(img.shape)
|
from django.shortcuts import render
from .models import Book, Author, BookInstance, Genre
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
def index(request):
"""View function for home page of site."""
# Generate counts of some of the main objects
num_books = Book... |
"""
Helper functions for creating Form classes from Django models
and database field objects.
"""
from collections import OrderedDict
from contextlib import suppress
from itertools import chain
from django.core.exceptions import (
NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError,
)
from django.... |
import requests
import sys
from urllib.parse import urljoin
import arrow
import config
import db_utils
import slack_utils
BASE_URL = "https://cdn-api.co-vin.in"
def make_covin_request(request_url, params=None) -> requests.Response:
num_retries = 3
response = requests.get(
request_url,
para... |
class ShortcutsException(Exception):
'''Base exception for shortcuts'''
class UnknownActionError(ShortcutsException):
'''Action is not supported'''
def __init__(self, itype, action_dict=None):
message = f'''
Unknown shortcut action: "{itype}"
Please, check documentation to... |
"""Configuration for Sonos tests."""
from unittest.mock import AsyncMock, MagicMock, Mock, patch as patch
import pytest
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.components.sonos import DOMAIN
from homeassistant.const import CONF_HOSTS
from tests.common import MockConfi... |
import numpy as np
from itertools import combinations
from matplotlib import pyplot as plt
from .scalpplot import positions
class Layout:
def __init__(self, channel_names, points):
self.channel_names = channel_names
self.points, self.box_width, self.box_height = _box_size(points)
self.sca... |
import os
import datetime
import argparse
import numpy
import networks
import torch
modelnames = networks.__all__
import datasets
datasetNames = datasets.__all__
parser = argparse.ArgumentParser(description='Flow-Directed Interpolation Kernel')
parser.add_argument('--debug',action = 'store_true', help='Enable debug... |
from pytest import raises
from beyond.env.jpl import create_frames
from beyond.io.ccsds import dumps, loads, CcsdsError
def test_dump_opm(orbit, datafile, ccsds_format, helper):
ref = datafile("opm")
txt = dumps(orbit, fmt=ccsds_format)
helper.assert_string(ref, txt)
def test_dump_opm_cov(orbit_cov,... |
# -*- coding: utf-8 -*-
import os
import webtest
from datetime import datetime, timedelta
from uuid import uuid4
from copy import deepcopy
from openprocurement.api.tests.base import BaseTenderWebTest, PrefixedRequestClass
from openprocurement.api.utils import apply_data_patch
from openprocurement.api.models import get_... |
# DarkCoder
def sum_of_series(first_term, common_diff, num_of_terms):
"""
Find the sum of n terms in an arithmetic progression.
>>> sum_of_series(1, 1, 10)
55.0
>>> sum_of_series(1, 10, 100)
49600.0
"""
sum = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_d... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
from collections import OrderedDict
import numpy as np
from detectron2.evaluation import DatasetEvaluator
logger = logging.getLogger(__name__)
class PredictionCountEvaluator(DatasetEvaluator):
"""
... |
from __future__ import absolute_import, division, print_function
import copy
import errno
import json
import os
from builtins import range
import pkg_resources
import six
import six.moves.cPickle as pickle
from dxtbx.datablock import (
BeamComparison,
DataBlockFactory,
DataBlockTemplateImporter,
Dete... |
#!/usr/bin/env python
import argparse
import os
import toml
from compiler_tester.tester import run_test, color, style, fg
def main():
parser = argparse.ArgumentParser(description="LPython Test Suite")
parser.add_argument("-u", "--update", action="store_true",
help="update all reference results")... |
from collections import OrderedDict
from dataclasses import dataclass
from typing import Callable
from gym import Space
from gym.spaces import Discrete, Dict, MultiBinary, Tuple
import numpy as np
from sorting_gym.envs.sort_interface_base import NeuralSortInterfaceEnv
@dataclass(frozen=True)
class Instruction:
... |
import pytest
from semver import Version
@pytest.mark.parametrize(
"version, index, expected",
[
# Simple positive indices
("1.2.3-rc.0+build.0", 0, 1),
("1.2.3-rc.0+build.0", 1, 2),
("1.2.3-rc.0+build.0", 2, 3),
("1.2.3-rc.0+build.0", 3, "rc.0"),
("1.2.3-rc.0+... |
import math
if __name__ == '__main__':
AB,BC=int(input()),int(input())
hype=math.hypot(AB,BC) #to calculate hypotenuse
res=round(math.degrees(math.acos(BC/hype))) #to calculate required angle
degree=chr(176) #for DEGREE symbol
print(res,degree, sep='')
# AB,BC ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.