text stringlengths 2 999k |
|---|
from __future__ import unicode_literals
import importlib
def lazy_load(module_name, element):
def f(*args, **kwargs):
module = importlib.import_module(module_name, "moto")
return getattr(module, element)(*args, **kwargs)
return f
mock_acm = lazy_load(".acm", "mock_acm")
mock_apigateway = l... |
# Generated by Django 2.1.7 on 2019-02-28 21:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0041_feedbackdb_user'),
]
operations = [
migrations.AddField(
model_name='feedbackdb',
name='admincomment',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 10 10:49:24 2020
@author: RC
Validation test for comparing model outputs from python and cpp stationsim.
We do this as follows:
- Generate two random samples of models
- Calculate corresponding Ripley's K (RK) curves for each model
- Generate a da... |
# Code for "ActionCLIP: ActionCLIP: A New Paradigm for Action Recognition"
# arXiv:
# Mengmeng Wang, Jiazheng Xing, Yong Liu
import os
def get_model_path(ckpt):
if os.path.isfile(ckpt):
return ckpt
else:
print('not found pretrained model in {}'.format(ckpt))
raise FileNotFound... |
from ophyd import (EpicsMotor, PVPositioner, PVPositionerPC,
EpicsSignal, EpicsSignalRO, Device)
from ophyd import Component as Cpt
from ophyd import FormattedComponent as FmtCpt
from ophyd import DynamicDeviceComponent as DDC
from ophyd import (EpicsMCA, EpicsDXP)
from ophyd import DeviceStatus, Ord... |
import torch
from cogdl.tasks import build_task
from cogdl.datasets import build_dataset
from cogdl.models import build_model
from cogdl.utils import build_args_from_dict
def get_default_args():
cuda_available = torch.cuda.is_available()
default_dict = {
"hidden_size": 16,
"dropout": 0.5,
... |
"""
Module responsible for translating sequence annotation data
into GA4GH native objects.
"""
import json
import random
import candig.server.datamodel as datamodel
import candig.server.sqlite_backend as sqlite_backend
import candig.server.exceptions as exceptions
import candig.schemas.pb as pb
import candig.schemas... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "icat_site.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
import turtle
tortuguita= turtle.Turtle()
tortuguita.speed(100)
tortuguita.dot(30,"black")
tortuguita.forward(15)
tortuguita.left(90)
tortuguita.circle(50)
tortuguita.circle(70)
tortuguita.circle(90)
tortuguita.right(90)
tortuguita.up()
tortuguita.forward(15)
tortuguita.down()
tortuguita.dot(30,"black")
tortuguita.b... |
from typing import Callable, TypeVar
import reactivex
from reactivex import Observable
_T = TypeVar("_T")
def start_with_(*args: _T) -> Callable[[Observable[_T]], Observable[_T]]:
def start_with(source: Observable[_T]) -> Observable[_T]:
"""Partially applied start_with operator.
Prepends a sequ... |
from flask import Flask, redirect, url_for, render_template, send_from_directory
from pycoingecko import CoinGeckoAPI
from modules import news, email
from flask_cors import CORS
from flask import request
import datetime
import requests
import random
import string
import redis
import json
import os
# video:
json_file =... |
"""
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
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 without limitation the rights to ... |
from __future__ import division
import time
import logging
import numpy as np
import pylsl
from libmushu.amplifier import Amplifier
logger = logging.getLogger(__name__)
logger.info('Logger started.')
class LSLAmp(Amplifier):
"""Pseudo Amplifier for lab streaming layer (lsl).
This amplifier connects to a... |
# -*- coding: utf-8 -*-
# all the imports
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
question_0 = u"Реши задачу:\n2+2="
q_list = []
with open('quests.txt','rb') as q_file:
# 'quests.txt'
fullstr = q_file.read().decode('utf-8')
q_list = ... |
"""Extended DataFrame functionality."""
from typing import Any, Iterator, Optional, Sequence, Text, Tuple, Union, cast
import numpy as np
import pandas as pd
from snmp_fetch.utils import cuint8_to_int
from .types import ip_address as ip
def column_names(
n: Optional[int] = None, alphabet: Sequence[Text] = ... |
# Generated by Django 3.1.12 on 2021-07-05 00:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0012_auto_20200419_1255'),
]
operations = [
migrations.AlterField(
model_name='academicinfo',
name='regi... |
import graphene
from ..types import SynProject
from core import Synapse
class SynProjectQuery(graphene.ObjectType):
"""
Defines all the SynProject queries.
"""
syn_project = graphene.Field(
SynProject,
id=graphene.String(required=True)
)
def resolve_syn_project(self, info, id)... |
import re
from inspect import signature
import pkgutil
import inspect
import importlib
from typing import Optional
import pytest
from sklearn.utils import all_estimators
import sklearn
numpydoc_validation = pytest.importorskip("numpydoc.validate")
FUNCTION_DOCSTRING_IGNORE_LIST = [
"sklearn.cluster._kmeans.kmean... |
from pvterms.main import * |
# Copyright 2013-2019 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.package import PackageBase
from spack.directives import depends_on, variant, conflicts
import spack.variant
... |
import os
from buildtest.cli.build import BuildTest
from buildtest.defaults import BUILDTEST_ROOT, DEFAULT_SETTINGS_FILE
input_buildspecs = [
os.path.join(BUILDTEST_ROOT, "tutorials", "vars.yml"),
os.path.join(BUILDTEST_ROOT, "general_tests", "configuration"),
]
exclude_buildspecs = [
os.path.join(BUILDTE... |
# -*- coding: utf-8 -*-
"""
Zurich Instruments LabOne Python API Example
Python API Example for the Software Trigger (ziDAQRecorder) Core Module in Grid
Mode with averaging enabled. This example demonstrates how to obtain averaged
demodulator data when a demodulator's R value is larger than a specified
threshold using... |
"""Module that contains the command line app."""
import click
import halomod
import hmf
from hmf._cli import run_cli
from .halo_model import TracerHaloModel
main = click.Group()
@main.command(
context_settings={ # Doing this allows arbitrary options to override config
"ignore_unknown_options": True,
... |
import importlib
import inspect
import numpy
_footnotes = {}
def _get_functions(obj, exclude=None):
return set([
n for n, target in [(n, getattr(obj, n)) for n in dir(obj)]
if (
# not in exclude list
(exclude is None or n not in exclude)
# not module:
... |
from abc import get_cache_token
from typing import Collection
c = 'Y'
class color():
purple = '\033[95m'
cyan = '\033[96m'
darkcyan = '\033[36m'
blue = '\033[94m'
blued = '\033[92m'
yellow = '\033[93m'
red = '\033[91m'
silver = '\033[3;30;47m'
orange= '\033[31;43m'
bold = '\033[1m'
gr... |
#### 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 = Creature()
result.template = "object/creature/npc/droid/shared_red_protocol_base.iff"
result.attribute_template_i... |
import time
from datetime import datetime
import boto
import pytz
from boto.emr.bootstrap_action import BootstrapAction
from boto.emr.instance_group import InstanceGroup
from boto.emr.step import StreamingStep
import sure # noqa # pylint: disable=unused-import
from moto import mock_emr_deprecated
from tests.helpers... |
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from .... |
__author__ = "Haim Adrian"
import collections
import numpy as np
from matplotlib import pyplot as plt
import cv2
# Probability Density Function
# Result is a histogram containing weights (density) e.g. colorCount / sum(colorsCount)
def myPDF(tensor, p=8):
if not isinstance(tensor, np.ndarray):
... |
from .beam import Beam, DistributedLoadH, DistributedLoadV, PointLoadH, PointLoadV, x
|
#!/usr/bin/env python
"""
main.py -- Udacity conference server-side Python App Engine
HTTP controller handlers for memcache & task queue access
$Id$
created by wesc on 2014 may 24
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
import webapp2
from google.appengine.api import app_identity
from google.appe... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.item import Item, Field
class Sports5Item(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
fe... |
"""
=============
Miscellaneous
=============
IEEE 754 Floating Point Special Values:
-----------------------------------------------
Special values defined in numpy: nan, inf,
NaNs can be used as a poor-man's mask (if you don't care what the
original value was)
Note: cannot use equality to test NaNs. E.g.: ::
>>... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Brandmand and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class MovimientoInventario(Document):
pass
|
import torch
from scipy import optimize
import torch.nn.functional as F
import math
import numpy as np
from functools import reduce
from collections import OrderedDict
def branin(x, a=1., b=5.1/(4.*math.pi**2), c=5./math.pi, r=6., s=10.,
t=1./(8*math.pi)):
# branin function, global min of 0.397887 at
# x =... |
"""
ASGI config for untitled2 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.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SET... |
# -*- coding: utf-8 -*-
"""
Manage SNS Topics
Create and destroy SNS topics. Be aware that this interacts with Amazon's
services, and so may incur charges.
This module uses ``boto``, which can be installed via package, or pip.
This module accepts explicit AWS credentials but can also utilize
IAM roles assigned to t... |
# Copyright (c) 2013 Adobe Systems Incorporated. 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 ap... |
#!/usr/bin/env python3
# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang,
# Wei Kang)
# Copyright 2021 Pingfeng Luo
#
# See ../../../../LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Ver... |
from streamlink.plugins.playtv import PlayTV
from tests.plugins import PluginCanHandleUrl
class TestPluginCanHandleUrlPlayTV(PluginCanHandleUrl):
__plugin__ = PlayTV
should_match = [
"http://playtv.fr/television/arte",
"http://playtv.fr/television/arte/",
"http://playtv.fr/television/... |
# coding=utf-8
import os
import numpy as np
class DataLoader(object):
@staticmethod
def _load_inner(file_name):
X = []
y = []
with open(file_name, "r") as f:
for line in f:
try:
terms = line.strip().split("\t")
if len... |
# -*- coding: utf-8 -*-
from __future__ import division
from collections import namedtuple
import numpy as np
import torch
Transition = namedtuple('Transition', ('timestep', 'state', 'action', 'reward', 'nonterminal'))
blank_trans = Transition(0, torch.zeros(84, 84, dtype=torch.uint8), None, 0, False)
# Segment tr... |
# -*- 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... |
""" Utils for working with SSL models """
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from typing import Tuple
import torch
import torch.distributed as dist
import torch.nn as nn
@torch.no_grad()
def batch_shuffle(
batch: torch.Tensor,
distributed: bool = False
) -> Tuple[tor... |
#JES- Jython Environment for Students
#Copyright (C) 2002 Jason Ergle, Claire Bailey, David Raines, Joshua Sklare
#See JESCopyright.txt for full licensing information
#TODO - better type names
import java.awt as awt
import javax.swing as swing
import time
from java.awt.event import ActionListener
DEBUG_WINDOW_TITLE ... |
"""Test the TcEx API Module."""
# third-party
import pytest
# first-party
from tcex.api.tc.v3.tql.tql_operator import TqlOperator
from tests.api.tc.v3.v3_helpers import TestV3, V3Helper
class TestArtifactTypes(TestV3):
"""Test TcEx API Interface."""
v3 = None
def setup_method(self):
"""Configur... |
from huobi.model import *
class PriceDepthEvent:
"""
The price depth received by subscription of price depth.
:member
symbol: The symbol you subscribed.
timestamp: The UNIX formatted timestamp generated by server in UTC.
data: The price depth.
"""
def __init__(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 8 16:54:36 2011
@author: ProfMobius
@version: v1.2
"""
import sys
import logging
from optparse import OptionParser
from commands import Commands, CLIENT, SERVER, CalledProcessError
from mcp import decompile_side, updatemd5_side
def main():
parser = OptionParser(v... |
import argparse
import os, time
import torch
import shutil
import numpy as np
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
im... |
"""Runnable script to upload a file to AWS/S3"""
import time
import argparse
import logging
from os import environ
from std_traffic.utils import aws_utils
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s [%(module)s] - %(message)s',
handlers=[logging.StreamHandler()])
log =... |
# Copyright 2013-2020 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 RPsych(RPackage):
"""A general purpose toolbox for personality, psychometric theory and
... |
import re
import sys
from pytest import raises
from cppstream import OutStream
from cppstream import cout as _real_cout
def get_cout():
# need to dynamically replace the stream to the sys.stdout from this module
# rather than the preset one otherwise the test will fail
# see pull #2
# also pytest-de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import anndata
import numpy as np
import pandas as pd
import wot.io
def get_set_id_to_indices(cell_sets, tmap, is_columns):
cell_set_id_to_indices = {}
for i in range(len(cell_sets)):
cell_set_name = cell_sets[i]['name']
cell_ids... |
#%%
# Copyright 2015 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 app... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2021, Nigel Small
#
# 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
#
# Unle... |
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# 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... |
from django import template
register = template.Library()
@register.filter
def build_tags(lista):
return ','.join(lista['names']) |
"""
Implementation of binary tree
"""
from collections import deque
class Node(object):
def __init__(self,data=None):
self.val = data
self.left = self.right = None
class BinaryTree(object):
def insert(self,root,data):
if root == None:
root = Node(data)
... |
from __future__ import annotations
from typing import Literal
from prettyqt import network
from prettyqt.qt import QtNetwork
from prettyqt.utils import bidict
INTERFACE_FLAGS = bidict(
is_up=QtNetwork.QNetworkInterface.InterfaceFlag.IsUp,
is_running=QtNetwork.QNetworkInterface.InterfaceFlag.IsRunning,
c... |
from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func
class Note(db.Model):
id = db.Column(db.Integer, primary_key=True)
data = db.Column(db.String(10000))
date = db.Column(db.DateTime(timezone=True), default=func.now())
user_id = db.Column(db.Integer, db.ForeignKey('user.... |
foo = 7 + 2
|
import pymongo
from dotenv import load_dotenv
load_dotenv()
import os
class Mongo:
MONGODB_PASSWORD = os.environ.get("MONGODB_PASSWORD")
connection_url = "mongodb+srv://admin:" + MONGODB_PASSWORD + "@cluster0.jx3fl.mongodb.net/guitarappdb?retryWrites=true&w=majority"
print(connection_url)
client = py... |
#!/usr/bin/env python3
import os
import sys
import atexit
import importlib.util
R = '\033[31m' # red
G = '\033[32m' # green
C = '\033[36m' # cyan
W = '\033[0m' # white
fail = False
import platform
if platform.system() == 'Linux':
if os.geteuid() != 0:
print('\n' + R + '[-]' + C + ' Please Run as Root!' + '\n')
... |
import random
import string
from django.utils.text import slugify
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def unique_order_id_generator(instance,):
"""
This is for a Django project id order field.
... |
import subprocess
import pytest
from tests import utils
def check_metadata(file, log_file=None):
"""Runs metadata checks for the given file.
Args:
file (str): Name of the file to be tested.
log_file (str, optional): Name of the log file where warning
messages are stored.
"""
... |
# Copyright (C) 2021 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 to in wri... |
# Lint as: python3
# Copyright 2020 Google LLC. 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 ... |
import numpy as np
from PIL import Image
import torch
from torchvision import models
import torchvision.transforms as T
import os
def get_image(path, crop = []):
img = Image.open(path)
img = img.rotate(90, expand = 1)
return img.crop(crop)
def crop_grid(img, box_size = [900,500], top_offset = 0):
# ca... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from pyoneer.layers.layers_impl import ConcreteDropout
from pyoneer.regularizers.regularizers_impl import DropoutL2
class RegularizersTest(tf.test.TestCase):
def test_dropout_l2(s... |
import os
import re
import scrapy
from sohu.items import ZixunItem
class ZixunSpider(scrapy.Spider):
name = "zixun"
mediaName = '搜狐资讯'
def __init__(self, *args, **kwargs):
super(ZixunSpider, self).__init__(*args, **kwargs)
self.keyword = []
with open('/var/run/copm_spider/keyw... |
# Ignoring some linting rules in tests
# pylint: disable=redefined-outer-name
# pylint: disable=missing-docstring
import evaluation_benchmark as evaluation_benchmark
import fitness_benchmark as fitness_benchmark
import continous_local_opt_benchmarks as clo_benchmark
PROBLEM_SET_VERSION = 2
def print_stats(printer_li... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: test_gitwrapperlib.py
#
# Copyright 2018 Costas Tyfoxylos
#
# 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, includ... |
import winter
from .controller_1 import Controller1
@winter.route('controller_2/')
class Controller2:
@winter.route_get('')
def method_1(self) -> int: # pragma: no cover
return Controller1().method_1()
@winter.route_get('')
def method_2(self) -> int: # pragma: no cover
return 2
|
#!/usr/bin/env python3
# Copyright (c) 2014-2019 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 the wallet accounts properly when there is a double-spend conflict."""
from decimal import Decimal... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import math
import time
from pytext.common.constants import DatasetFieldName, Stage
from pytext.data import CommonMetadata
from pytext.metrics.language_model_metrics import (
LanguageModelMetric,
compute_language_mode... |
from gazette.spiders.base.fecam import FecamGazetteSpider
class ScAnitapolisSpider(FecamGazetteSpider):
name = "sc_anitapolis"
FECAM_QUERY = "cod_entidade:17"
TERRITORY_ID = "4201109"
|
import numpy as np
np.random.seed(123)
arr=np.random.randint(1,100,10)
print(arr) |
# pylint: disable=line-too-long
from .admin_get_third_party_config import AdminGetThirdPartyConfig
from .admin_update_third_party_config import AdminUpdateThirdPartyConfig
from .admin_create_third_party_config import AdminCreateThirdPartyConfig
from .admin_delete_third_party_config import AdminDeleteThirdPartyConfig
|
import tensorflow as tf
import pandas as pd
import numpy as np
import math, heapq, random, time
from utils import getHitRatio, getNDCG
class ActionNetwork(object):
"""
This class includes MLP networks to obtain the action space
(i.e., embedding vectors of (1) behavior models and (2) actions)
"""
def __init__(sel... |
# -*- coding: utf-8 -*-
# Copyright 2018 Dinar Gabbasov <https://it-projects.info/team/GabbasovDinar>
# Copyright 2018 Ilmir Karamov <https://it-projects.info/team/ilmir-k>
# License MIT (https://opensource.org/licenses/MIT).
{
"name": """Disable options in POS (restaurant extension)""",
"summary": """Control a... |
import logging
import os
from typing import Dict, Optional, Tuple
from ray import tune
import transformers
from transformers.file_utils import is_torch_tpu_available
from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
import torch
from torch.utils.data import Dataset
import wandb
logger = logging.getLogge... |
import sys
import os
from charset_normalizer import detect
from pandas import value_counts
from RegionGazeCounter import RegionGazeCounter
sys.path.append('Proctoring-AI')
import argparse
import asyncio
import json
import logging
import os
import ssl
import uuid
import numpy as np
import cv2
from aiohttp import web
f... |
#!/usr/bin/python3
import subprocess
commands = [
"sphinx-apidoc -f -o ./ ../nevopy",
"make clean",
"make html"
]
if __name__ == "__main__":
for c in commands:
subprocess.run(c, shell=True)
|
# -*- coding: utf-8 -*-
# Copyright 2022 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 unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase
class CommandTests(TestCase):
def test_wait_for_db_ready(self):
"""Test waiting for db when db is available"""
with patch('django.db.util... |
"""
csv.py - read/write/investigate CSV files
"""
import re
from functools import reduce
from _csv import Error, __version__, writer, reader, register_dialect, \
unregister_dialect, get_dialect, list_dialects, \
field_size_limit, \
QUOTE_MINIMAL, QUOTE_ALL,... |
from vectors import *
from tools import *
def get_boost(agent, packet):
my_car = packet.game_cars[agent.index]
car_location = Vector2(my_car.physics.location.x, my_car.physics.location.y)
if my_car.boost > 40: agent.car_status = 'none'
closest_boost = get_closest_boost(agent, packet)
#Turn to the ... |
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni',
'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + reque... |
import random
import sys
def generatekey():
rng = random.SystemRandom()
return ''.join([str(rng.randint(1, 6)) for i in range(5)])
def generatephrase(number_of_words):
with open('beale.wordlist.txt') as wordlist:
words = {entry.split()[0]: entry.split()[1] for entry in wordlist}
return ' '.... |
# Copyright (C) 2017 TU Dresden
# Licensed under the ISC license (see LICENSE.txt)
#
# Author: Robert Khasanov
import pytest
from mocasin.common.graph import DataflowChannel, DataflowProcess, DataflowGraph
from mocasin.mapper.partial import ComFullMapper, ProcPartialMapper
from mocasin.platforms.odroid import Designe... |
from PIL import ImageDraw
def mark_image(image, objects):
draw = ImageDraw.Draw(image)
rectBox = ['left', 'top', 'right', 'bottom']
for object in objects:
box = object["box"]
rect = list(map(lambda k: box.get(k), rectBox))
draw.rectangle(rect, outline=(0, 181, 0))
... |
'''
This script contains scaffolding to run many experiments, listed in a config
file such as auto_exp_config.py.
This script will parse each line (= exp configuration) from the config file and
run the corresponding experiment. It can also run many experiments in parallel
by using the pool.apply_async calls instead of... |
_base_ = [
'../_base_/models/upernet_swin.py', '../_base_/datasets/cod10k.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'
]
model = dict(
# pretrained='pretrain/swin_tiny_patch4_window7_224.pth',
backbone=dict(
embed_dims=96,
depths=[2, 2, 6, 2],
num_h... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import account_voucher |
# Static data class for 2x Petra, 2x Gladiator's
class PetraGlad:
# Passive data
geoDMG = 0.15
atkPercent = 0.18
name = "Petra/Glad"
|
import requests
from sanic import blueprints
from sanic.request import Request
from app.cmd.http import user_service, sanic_adapter_middleware as middleware
user_controller = blueprints.Blueprint(__name__)
confirm_path = '/user/confirm/'
reset_password_path = '/user/reset_password/'
@user_controller.route('/', met... |
"""
WSGI config for shikshastudio 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/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO... |
# 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... |
# 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 ... |
import torch
x = torch.ones(1, requires_grad=True)
net = torch.nn.Linear(1, 1)
# optim_x = torch.optim.Adam([x], lr=1)
# optim_net = torch.optim.Adam(net.parameters(), lr=1)
y = net(x)
grads = torch.autograd.grad(y, net.parameters(), create_graph=True)
norms = [grad.norm(2) for grad in grads]
norm = torch.stack(norm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.