text stringlengths 2 999k |
|---|
"""The implementation of the Disable move.
This move inflicts the Disable status effect. No damage is directly inflicted, but the opponent is
unable to use certain moves until Disable is removed. The probability of Success depends on the
user's Special.
"""
import random
from utils import Printer
NAME = 'Disable'
PP... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Rastislav Szabo <raszabo@cisco.com>, Lukas Macko <lmacko@cisco.com>"
__copyright__ = "Copyright 2016, Cisco Systems, Inc."
__license__ = "Apache 2.0"
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compl... |
from typing import Callable, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn as nn
from sklearn.cluster import KMeans
from torch.utils.data.dataloader import DataLoader, default_collate
from tqdm import tqdm
from ptdec.utils import cluster_accuracy, target_distribution
def train(
dataset:... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import copy
import math
from pathlib import Path
import warnings
from typing import Callable, Tuple, Union, List
import decord
from einops.layers.torch import Rearrange
import matplotlib.pyplot as plt
import numpy ... |
# -*- coding: utf-8 -*-
HELP = (
"To tccli help text, you can run:\n"
"\n"
" tccli help\n"
" tccli configure help\n"
" tccli service[cvm] help\n"
" tccli service[cvm] action[RunInstances] help\n"
)
USAGE = (
"tccli [options] <command> <subcommand> [<subcommand> ...] [parameters]\n"
... |
from aoc2015.core import dispatch
def test_dispatch_fail(capsys):
'''Dispatch fails properly when passed a bad day'''
# capsys is a pytest fixture that allows asserts agains stdout/stderr
# https://docs.pytest.org/en/stable/capture.html
dispatch(['204'])
captured = capsys.readouterr()
assert '... |
#! /usr/bin/env python3
from mule_local.postprocessing.pickle_PlaneData_KineticEnergy import *
# process all time frames
if len(sys.argv) > 1:
pickle_PlaneData_KineticEnergy(params=[], job_dirs=sys.argv[1:])
else:
pickle_PlaneData_KineticEnergy(params=[])
|
from .queue import get_dowonload_queue
from cone.tools import get_md5
class Request(dict):
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'}
def __init__(self, url=None, callback=None, method='GET', headers=No... |
"""
File: augment
Description: Evaluate the performance of MLP's (trained on various levels
of noisy data) on the validation set.
Author Lawrence Stewart <lawrence.stewart@ens.fr>
License: Mit License
"""
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import pandas as pd
from sklearn im... |
from pysc2.lib import actions as sc2_actions
from pysc2.lib import features
__author__ = "Ruo-Ze Liu"
debug = True
# Minimap index
_M_HEIGHT = features.MINIMAP_FEATURES.height_map.index
_M_VISIBILITY = features.MINIMAP_FEATURES.visibility_map.index
_M_CAMERA = features.MINIMAP_FEATURES.camera.index
_M_RELATIVE = fea... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
'''
Contaisn the functions for printing the evaluation results in an HTML file
Contact: Lasha.Abzianidze@gmail.com
'''
def coda_html(num, ill_drs_ids, counts, measures, types, cr_mdict):
'''Gets the number of CLFs, ids of ill DRSs, counts for produced, gold and matching ... |
print("Abaixo digite o valor da temperatura em graus para saber sua conversão em fahrenheit")
temp = int(input('digite a temperatura'))
conversor = temp * (9/5) + 32
print(conversor,"°") |
"""
Paddlewheel
===========
"""
from ..metal_complex import MetalComplex
from ..vertices import MetalVertex, BiDentateLigandVertex
from ...topology_graph import Edge
class Paddlewheel(MetalComplex):
"""
Represents a metal complex topology graph.
.. moldoc::
import moldoc.molecule as molecule
... |
# coding: utf-8
# Copyright (C) 2016 UKP lab
#
# Author: Daniil Sorokin (ukp.tu-darmstadt.de/ukp-home/)
#
import nltk
np_grammar = r"""
NP:
{(<NN|NNS>|<NNP|NNPS>)<NNP|NN|NNS|NNPS>+}
{(<NN|NNS>+|<NNP|NNPS>+)<IN|CC>(<PRP\$|DT><NN|NNS>+|<NNP|NNPS>+)}
{<JJ|RB|CD>*<NNP|NN|NNS|NNPS>+}
{<NNP|NN|NNS|NNPS... |
# 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, software
# distributed under t... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
from common import *
GRAPH_ID = "g"
redis_graph = None
class testNodeByIDFlow(FlowTestsBase):
def __init__(self):
self.env = Env(decodeResponses=True)
global redis_graph
redis_con = self.env.getConnection()
redis_graph = Graph(redis_con, GRAPH_ID)
self.populate_graph()
... |
"""Plotting functions with error bands"""
import numpy as np
from vedo import *
from vedo.pyplot import plot
# Make up same data
x = np.arange(0, 6, 0.1)
y = 2+2*np.sin(2*x)/(x+1)
ye= y**2 / 10
miny = np.min(y-ye)
idx = np.argmax(y)
# Plot the two variables, return a Plot(Assembly) object:
plt = plot(x,y,
... |
"""
Django settings for portfolio project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib... |
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import collections
import copy
import hashlib
import json
import multiprocessing
import os.path
import re
import signal
import subprocess
import sys
... |
from panovel import run_pandoc_filter, CodeBlock
def check(self):
return isinstance(self.elem, CodeBlock) and self.classes == self.tags
if __name__ == "__main__":
run_pandoc_filter(["frontmatter"], '{text}', '{text}', '{text}', check=check)
|
from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:11082")
else:
access = Se... |
# This module performs the conversion between ADM
# spacetime variables in Spherical or Cartesian coordinates
# given as *numerical* expressions (i.e., ADM quantities
# are only given to floating-point precision; e.g., in the
# case of an initial data solver), to rescaled BSSN-in-curvilinear
# coordinate quantities, as... |
# Generated by Django 3.2.7 on 2021-09-14 21:03
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
('id', model... |
import ChromaPy32 as Chroma # Import the Chroma Module
from time import sleep
Keypad = Chroma.Keypad() # Initialize a new Keypad Instance
RED = (255, 0, 0) # Initialize a new color by RGB (RED,GREEN,BLUE)
Keypad.setbyRow(2, RED) # sets the whole third row of the Keyboad-Grid to red
Keypad.applyGrid() # applies... |
import discord
import secret
import io
from random import *
import requests
import time
import asyncio
from datetime import datetime
import re
import os
import websockets
import aiohttp
import json
from googletrans import Translator
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont, Ima... |
'''
Add a route handler for static content.
[static]
url = /static/
path = static/
'''
async def setup(app, config):
app.router.add_static(config['url'], config['path'])
|
import datetime
import time
import unittest
from SimpleTimeManagement import Hourglass
from SimpleTimeManagement.hourglass import HourglassError
class HourglassTest(unittest.TestCase):
"""
Tests of ``SimpleTimeManagement.Hourglass`` class.
"""
def setUp(self):
pass
def test_01_init_no_a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# log_Check.py
# Created on: 2014-06-13
# Description: Checks log creation status
# ---------------------------------------------------------------------------
# This script checks for the prese... |
# -*- coding: utf-8 -*-
#
# AT1 documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a def... |
#!/usr/bin/env python3
# imports go here
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from sklearn.isotonic import IsotonicRegression
from sklearn.utils import check_random_state
#
# Free Coding session for 2015-06-07
# Written by Matt Warren
#
n = 100
x = np.a... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/food/crafted/shared_drink_jawa_beer.iff"
result.attribute_template_... |
import unittest
import numpy as np
import openmdao.api as om
from openmdao.utils.assert_utils import assert_check_partials
from openaerostruct.common.reynolds_comp import ReynoldsComp
class Test(unittest.TestCase):
def test_reynolds_derivs(self):
comp = ReynoldsComp()
prob = om.Probl... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# copyright 2016 twitter. 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... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Gdrcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the getchaintips RPC.
- introduce a network split
- work on chains of different lengths
- join th... |
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
ans = 999999
tmp = 0
i = 0
j = 0
while j<len(nums):
tmp +=nums[j]
while tmp>=target:
ans = min(j+1-i, ans)
tmp+=-nums[i]
i+=1... |
#!/usr/bin/env python
import sys, os
from setuptools import setup, find_packages
# Hack to prevent "TypeError: 'NoneType' object is not callable" error
# in multiprocessing/util.py _exit_function when setup.py exits
# (see http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
import multiprocessing
... |
import traceback
import webbrowser
from time import sleep
import json
import os
import logging
from datetime import datetime
import random
import requests
log = logging.getLogger(__name__)
class GSpread:
def __init__(self, access_token, access_token_path, spreadsheet_id, host, port):
self.access_token... |
load("@npm//@bazel/concatjs:index.bzl", _ts_library = "ts_library")
load("@npm//@bazel/typescript:index.bzl", _ts_project = "ts_project")
load("//bazel/esbuild:index.bzl", _esbuild = "esbuild", _esbuild_config = "esbuild_config")
load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test", _pkg_npm = "pkg_npm")... |
from pyopenproject.api_connection.exceptions.request_exception import RequestError
from pyopenproject.api_connection.requests.get_request import GetRequest
from pyopenproject.business.exception.business_error import BusinessError
from pyopenproject.business.services.command.status.status_command import StatusCommand
fr... |
import sys
from PIL import Image
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.db import models
from django.contrib.auth.models import User
class Inward(models.Model):
""" The inward correspondence registry table"""
date_of_letter = models.DateField(auto_no... |
from dataclasses import dataclass, field
from .io_utils import process_file, save_yaml, read_yaml, data_name, patch_decorator, patch, prepend_baseurl, \
remove_ending, find_key, process_subs
from .md import build_markdown
from .content import process_content
from .jekyll import create_jekyll_home_header, create_jek... |
# -*- coding: utf-8 -*-
# Authors: MNE Developers
#
# License: BSD (3-clause)
import datetime
import numpy as np
from ..io.egi.egimff import _import_mffpy
from ..io.pick import pick_types, pick_channels
from ..utils import verbose
@verbose
def export_evokeds_mff(fname, evoked, history=None, *, verbose=None):
"... |
# Copyright 2014 The Oppia 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 ... |
import FWCore.ParameterSet.Config as cms
from CommonTools.RecoAlgos.sortedPFPrimaryVertices_cfi import sortedPFPrimaryVertices
primaryVertexAssociation = sortedPFPrimaryVertices.clone(
qualityForPrimary = cms.int32(2),
produceSortedVertices = cms.bool(False),
producePileUpCollection = cms.bool(False),
produce... |
# Author: Guilherme Aldeia
# Contact: guilherme.aldeia@ufabc.edu.br
# Version: 1.0.0
# Last modified: 08-20-2021 by Guilherme Aldeia
"""
Decision tree regressor. This method is considered a white-box for most
authors.
This regressor extends the scikit-learn
[DecisionTreeRegressor](https://scikit-learn.org... |
import datetime
import json
import locale
import os
import shutil
import numpy as np
import pandas as pd
import pytest
import great_expectations as ge
from great_expectations.core import (
ExpectationConfiguration,
ExpectationSuite,
ExpectationValidationResult,
expectationSuiteSchema,
)
from great_exp... |
import glob
import grovepi
import time
import math
import sys
from influxdb import InfluxDBClient
client = InfluxDBClient(host='54.186.121.136')
temp_sensor1 = '/sys/bus/w1/devices/28-01204fe74e92/w1_slave'
temp_sensor_id = 'tps02'
sensor = 4
blue = 0
def read_temp_raw():
f = open(temp_sensor1, 'r')
sensor1_l... |
# 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 u... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... |
# Generated by Django 2.2.12 on 2020-08-11 18:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('plugins', '0012_auto_20200603_1924'),
]
operations = [
migrations.RemoveField(
model_name='plugin',
name='documenta... |
import numpy as np
import scipy.ndimage as ndi
from moviepy.video.VideoClip import ImageClip
def findObjects(clip,rem_thr=500, preview=False):
"""
Returns a list of ImageClips representing each a separate object on
the screen.
rem_thr : all objects found with size < rem_Thr will be
... |
budget = int(input())
season = input()
fisherman_count = int(input())
ship_rent = 0
if season == "Spring":
ship_rent = 3000
elif season == "Summer" or season == "Autumn":
ship_rent = 4200
elif season == "Winter":
ship_rent = 2600
if 11 >= fisherman_count > 6:
ship_rent = ship_rent * 0.85
elif fisherm... |
import cv2
img = cv2.imread('python.jpg')
cv2.imshow('sample image',img)
cv2.waitKey(0) # waits until a key is pressed
cv2.destroyAllWindows()
|
# -*- 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... |
from bing_search_app.search_command import SearchCommand
from bing_search import BingSearch as BingSearchInput
import sys
class BingSearch(SearchCommand):
def __init__(self, query, offset=0, count=50, search_type="search"):
# Save the parameters
self.query = query
self.offset = int(offset... |
import os
import sqlite3
class DBRecorder:
def __init__(self, config):
self.config = config
self.conn = None
self.cursor = None
def connect_db(self):
path = os.path.expanduser(self.config['output']['dir'])
if not os.path.exists(path):
os.makedirs(path)
... |
# Copyright 2015 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 by applicable law or agreed t... |
import jax
jax.config.update("jax_enable_x64", True)
import numpy as onp
from numpy.random import randn, rand, randint, seed
seed(2021)
from scipy.optimize import minimize
from jax import numpy as np, value_and_grad, jit, vmap
from jax.ops import index_update, index
from timemachine.potentials.nonbonded import no... |
# 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 ... |
class Solution:
def search(self, nums, target: int) -> int:
def find_rotate_index(start, end):
if nums[start] < nums[end]:
return 0
while start <= end:
mid = (start + end) // 2
if nums[mid] > nums[mid + 1]:
return mi... |
import argparse
import torch
import mmcv
from mmcv.runner import load_checkpoint, parallel_test, obj_from_dict
from mmcv.parallel import scatter, collate, MMDataParallel
from mmdet import datasets
from mmdet.core import results2json_videoseg, ytvos_eval
from mmdet.datasets import build_dataloader
from mmdet.models im... |
import websocket, json, pprint, talib, numpy
from binance.client import Client
from binance.enums import *
SOCKET = "wss://stream.binance.com:9443/ws/xmrbtc@kline_5m"
closes = []
in_position = False
client = Client(<>, <>, tld='com')
def on_open(ws):
print('opened connection')
def on_close(ws):
print('cl... |
class Trainer():
def __init__(self, name):
self.name = name
self.pokemon = []
def add_pokemon(self, pokemon):
if pokemon not in self.pokemon:
self.pokemon.append(pokemon)
return f'Caught {pokemon.name} with health {pokemon.health}'
return f'This pokemon ... |
# Copyright(c) 2018, Intel Corporation
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the followi... |
# -*- coding: utf-8 -*-
import unittest
import numpy as np
import pytest
from pytest import approx
import allel
from allel.test.tools import assert_array_equal as aeq, assert_array_almost_equal
from allel.util import ignore_invalid, mask_inaccessible
from allel import GenotypeArray, HaplotypeArray, SortedIndex, All... |
"""
Django settings for oh_app_demo project.
"""
import os
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Customization for Heroku-specific settings
ON_HEROKU = os.getenv('ON_HEROKU', 'false').lowe... |
import argparse
import itertools
import os
from abc import ABCMeta, abstractmethod
import torch
import torch.nn as nn
from six import add_metaclass
from torch.nn import functional
from torchvision.utils import save_image
import pyro
from pyro.contrib.examples import util
from pyro.distributions import Bernoulli, Norm... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('oyster', '0008_taskrule_uuid'),
]
operations = [
migrations.AddField(
model_name='taskrule',
name='c... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 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 proper accounting with a double-spend conflict
#
from test_framework.test_framework import Bitc... |
def selectionSort(arr):
for i in range(len(arr) - 1):
# 记录最小数的索引
minIndex = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[minIndex]:
minIndex = j
# i 不是最小数时,将 i 和最小数进行交换
if i != minIndex:
arr[i], arr[minIndex] = arr[minIndex], arr[... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ChangeServerOsWithoutCloudInitResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
... |
import os
import sys
from shapeworks import *
success = True
def meanCurvatureEllipsoidTest():
mesh = Mesh(os.environ["DATA"] + "/ellipsoid_0.ply")
arr = mesh.curvature(Mesh.CurvatureType.Mean)
mesh.setField("MeanCurvature", arr, Mesh.Point)
ground_truth = Mesh(os.environ["DATA"] + "/meanCurvatureEllipsoid.... |
#
# Copyright (c) 2020 JinTian.
#
# This file is part of alfred
# (see http://jinfagang.github.io).
#
# 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 ... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
inner_list = views.InnerViewSet.as_view({
'get': 'list',
'post': 'create'
})
inner_detail = views.InnerViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',... |
"""Common tests for HomematicIP devices."""
from homematicip.base.enums import EventType
from homeassistant.components.homematicip_cloud import DOMAIN as HMIPC_DOMAIN
from homeassistant.components.homematicip_cloud.hap import HomematicipHAP
from homeassistant.const import STATE_ON, STATE_UNAVAILABLE
from homeassistant... |
"""
This file tests that $ref resolution works as expected, and that
allOfs are populated as expected as well.
"""
import pytest
from openapi3 import OpenAPI
from openapi3.schemas import Schema
def test_ref_resolution(petstore_expanded_spec):
"""
Tests that $refs are resolved as we expect them to be
"""
... |
# -*- coding: utf-8 -*-
#
# 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
#... |
from toy_project.src.folder_0.file_0 import func_sum
from toy_project.src.folder_1.file_1 import func_sum_product
def main():
a, b, c, d = 1., 2., 3., 4.
print(func_sum(a, b)) # 3
print(func_sum(c, d)) # 7
print(func_sum_product(a, b, c, d)) # 21
if __name__ == '__main__':
main() |
import matplotlib.pyplot as plt
import numpy, json
import matplotlib
"""
This files has some function to draw the traing results. Like training losses, accuraces
"""
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 22}
lines = {
'linewidth': 7,
}
matplotlib.rc('lines', **... |
from PyQt5.QtCore import Qt
#window
window_width = 1200
window_height = 800
window_x_margin = 100
window_y_margin = 100
window_title = 'Random strike'
#paint timer
paint_timer_delay = 40 #ms
#player
player_hp = 3
player_speed = 500 #px per second
first_player_up = Qt.Key_W
first_player_down = Qt.Key_S
first_pl... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2009 Edgewall Software
# Copyright (C) 2006-2007 Alec Thomas <alec@swapoff.org>
# Copyright (C) 2007 Christian Boos <cboos@edgewall.org>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this ... |
from setuptools import setup
from Cython.Build import cythonize
setup(
name='main',
ext_modules=cythonize("main.pyx", annotate=True),
zip_safe=False,
)
|
from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
# 补充字段
mobile = models.CharField(
unique=True,
verbose_name='手机号',
null=True,
max_length=11
)
class Meta:
db_table = 'tb_users'... |
# coding=utf-8
# *** WARNING: this file was generated by the Kulado Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import kulado
import kulado.runtime
from .. import utilities, tables
class VirtualMachine(kulado.CustomRes... |
import shutil
from datetime import timedelta
from os import path, mkdir
from uuid import uuid4
import cv2 as cv
import numpy as np
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils import timezone
from faker import Faker
from ..models import (
Face,
... |
# -*- coding: utf-8 -*-
"""Test configs."""
from bpapp.app import create_app
from bpapp.settings import DevConfig, ProdConfig
def test_production_config():
"""Production config."""
app = create_app(ProdConfig)
assert app.config['ENV'] == 'prod'
assert app.config['DEBUG'] is False
assert app.config... |
"""
This module implements the `se semanticate` command.
"""
import argparse
from rich.console import Console
import se
import se.formatting
def semanticate() -> int:
"""
Entry point for `libro semanticate`
"""
parser = argparse.ArgumentParser(description="Automatically add semantics to Standard Ebooks source... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Copyright (c) 2014-2019 The DigiByte Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet import RPCs.
Test rescan behavior o... |
"""
urlresolver XBMC Addon
Copyright (C) 2012 Bstrdsmkr
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 3 of the License, or
(at your option) any later version.... |
import tensorflow as tf
def make_unet(X, training):
input_layer = X / 127.5 - 1
conv1 = tf.layers.conv2d(inputs=input_layer, filters=8, kernel_size=[5, 5],padding="same",activation=tf.nn.relu,kernel_regularizer=tf.contrib.layers.l2_regularizer(0.1), name="conv_layer_1")
bn1 = tf.layers.batch_normalization(... |
"""
num_digits() method will return the number of digits of a number in O(1) time using math.log10() method.
"""
import math
def num_digits(n):
n = abs(n)
if n == 0:
return 1
return int(math.log10(n)) + 1
|
# coding: utf-8
"""
NetBox API
API to access NetBox # noqa: E501
OpenAPI spec version: 2.8
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class IPAddressInterface(object):
"""NOTE: This class is auto generated by th... |
# Generated by Django 4.0.1 on 2022-01-10 21:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('countries', '0001_initia... |
"""A Volume can have multiple
scalars associated to each voxel"""
from vedo import *
import numpy as np
vol = Volume(dataurl+'vase.vti')
nx, ny, nz = vol.dimensions()
r0,r1 = vol.scalarRange()
vol.addScalarBar3D(title='original voxel scalars')
# create a set of scalars and add it to the Volume
sc1 = np.linspace(r0,r... |
from freezegun import freeze_time
from posthog.api.test.base import BaseTest
from posthog.models import Action, ActionStep, Event, Filter, Person, Team
from posthog.queries.stickiness import Stickiness
class TestStickiness(BaseTest):
def _create_multiple_people(self):
person1 = Person.objects.create(team... |
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
def phi(px):
''' Função característica da PMF P(x) '''
rads = np.linspace(-np.pi, np.pi, 100)
ret = { w : np.sum([px[x] * np.exp(w*1j*x) for x in px.keys()]) for w in rads}
return ret
def phi_plot(px, ax):
fphi = phi(px)
ax.p... |
# VERIFICANDO ITENS ESPECIAIS EM UMA LISTA
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out off green peppers right now.")
else:
print("adding " + requested_topping ... |
"""
numpy.nditer 객체: 반복문(for, while)을 쓰기 쉽게 도와주는 객체
"""
import numpy as np
np.random.seed(1231)
a = np.random.randint(100, size=(2, 3))
print(a)
# 40 21 5 52 84 39
for row in a:
for x in row:
print(x, end=' ')
print()
i = 0
while i < a.shape[0]:
j = 0
while j < a.shape[1]:
print(a[i, j], ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.