content stringlengths 5 1.05M |
|---|
from django.db import migrations, models
from django.db.migrations import operations
from django.db.migrations.optimizer import MigrationOptimizer
from django.test import SimpleTestCase
from .models import EmptyManager, UnicodeModel
class OptimizerTests(SimpleTestCase):
"""
Tests the migration autodetector.
... |
# Your App secret key
SECRET_KEY = '\2\1[SECRETKEY]\1\2\e\y\y\h'
# Set this API key to enable Mapbox visualizations
MAPBOX_API_KEY = '[MAPBOXAPIKEY]'
# ---------------------------------------------------------
# Superset specific config
# ---------------------------------------------------------
ROW_LIMIT = [ROWLIMIT... |
from time import sleep
class Repository:
def __init__(self, objList = []):
self.list = []
self.list += objList
def getByID(self, ID):
for obj in self.list:
if obj.getID() == ID:
return obj
return None
class User:
def __init__(self, name, ID, med... |
# django
from django import forms
# local django
from recommendation.models import CustomRecommendation
from recommendation.validators import CustomRecommendationValidator
from exam import constants
class UpdateCustomRecommendationForm(forms.ModelForm):
"""
Form to edit a custom recommendation.
... |
class BaseValidationError(Exception):
pass
class ValidationError(BaseValidationError):
pass
|
import struct
import time
import io
import gzip
MAGIC_HEADER = '\037\213\010'
FLAGS = '\004'
XFL_OS = '\000\003'
EMPTY_DATA = '\003\000'
#=================================================================
class LengthMetadata:
"""
Sample metadata which stores an 8-byte lengtg offset in the gzip header
Cou... |
print('Gerador de PA')
print('-=' * 15)
primeiro_termo = int(input('Primeiro termo da PA: '))
razao = int(input('Digite a Razão da PA: '))
termo = primeiro_termo
contador_termos = 0
while contador_termos < 10:
print(f'{termo} -> ', end='')
termo += razao
contador_termos += 1
print('FIM!')
|
from vilbert.vilbert import VILBertForVLTasks
from vilbert.vilbert import BertConfig
from vilbert.vilbert import GeLU
from vilbert.optimization import RAdam
from torch.nn import functional as F
from vilbert.datasets._image_features_reader import ImageFeaturesH5Reader
from pytorch_transformers import AdamW
from pytorc... |
""" Implements the game object that represents a black hole.
"""
from timeit import default_timer as timer
import pyg
from .game_object import GameObject
_MIN_SCALING_INTERVAL = 0.01
_SCALE_STEP_FACTOR = 1.02
_BLACK_HOLE_GRAVITY_FACTOR = 0.075
class BlackHole(GameObject):
""" Represents a black hole. """
... |
import boto3
from .quota_check import QuotaCheck, QuotaScope
class TopicCountCheck(QuotaCheck):
key = "ses_daily_sends"
description = "SES messages sent during the last 24 hours"
scope = QuotaScope.REGION
service_code = 'ses'
quota_code = 'L-804C8AE8'
@property
def current(self):
... |
from typing import TypedDict
import datetime as dt
class ISection_1_1_3(TypedDict):
wr_tot_cons_mu: float
wr_avg_cons_mu: float
wr_max_cons_mu: float
wr_max_cons_mu_date: str
wr_avg_cons_mu_perc_inc: float
wr_avg_cons_mu_last_yr: float |
"""/config/custom_components/cryptoportfolio"""
"""Support for Etherscan sensors."""
from datetime import timedelta
import logging
# import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from .constants import CONF_ADDRESS, CONF_NAME, CONF_TOKEN, CONF_TOKEN_ADDRESS, CON... |
"""
This Module handles the generation of results in the CLI, based on the ticker passed as the argument to the object of the Main class.
The execution begins by retrieving the financial data from yfinace library which is handled in the data module of stockDL.
After the data is collected the first trading day of each ... |
import unittest
import main
class TestMain(unittest.TestCase):
def test_get_current_layer_in_non_layer_line(self):
layer_at = main.get_current_layer(';Layer height: 0.2')
self.assertEqual(layer_at, None, "Parsed layer position should be None")
def test_get_current_layer_in_non_layer_... |
from __future__ import annotations
from pathlib import Path
import re
from typing import Union
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit, fmin
import sympy as sym
from sympy.utilities.lambdify import lambdify
# fro... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-12-02 17:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0014_auto_20161124_1615'),
]
operations = [
migrations.AddField(
... |
"""
@author: wangguanan
@contact: guan.wang0706@gmail.com
"""
import os, copy
from .reid_samples import ReIDSamples
class DukeMTMCreID(ReIDSamples):
"""DukeMTMC-reID.
Reference:
- Ristani et al. Performance Measures and a Data Set for Multi-Target, Multi-Camera Tracking. ECCVW 2016.
- Zh... |
from django import forms
from django.contrib.auth import authenticate, password_validation
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, PasswordResetForm
from django.utils.safestring import mark_safe
from accounts.models import EmailUser
from shared.forms import FormRenderMixin
from shar... |
import logging
import boto3
logger = logging.getLogger('logger')
logger.setLevel(logging.DEBUG)
def delete_birthday_from_dynamodb(key: str) -> None:
"""
Deletes birthday from dynamodb, with given unsubscribe key.
:param key: Unsubscribe key identifier.
:return: None.
"""
dynamodb_client = bo... |
"""
MA Model
===============================================================================
Overview
-------------------------------------------------------------------------------
This module contains MA models using four diferent parameter optimization
methods: SciPy's minimization, SciKit's Ridge linear model, S... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-05-09 11:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tt_storage', '0002_auto_20170509_1125'),
]
operations = [
migrations.AddFie... |
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from habt.database import Base, GetOrCreateMixin
class Architecture(GetOrCreateMixin, Base):
"""
Represents the hardware architecture
"""
__tablename__ = "architecture"
""" Database table name """
id ... |
from ebi.battleroyale.models import *
from django.contrib import admin
class StyleAdmin(admin.ModelAdmin):
list_display = ('name',)
admin.site.register(Style, StyleAdmin)
class SkillAdmin(admin.ModelAdmin):
list_display = ('player', 'style', 'level', 'experience')
admin.site.register(Skill, SkillAdmin)
class... |
from webtest import TestApp # type: ignore [import]
import liscopridge.cache
def pytest_configure(config):
liscopridge.cache._pytest = True
# https://github.com/Pylons/webtest/pull/227
TestApp.__test__ = False
|
import numpy as np
import yaml
import sys
import os
from nose.tools import assert_equal,assert_almost_equal,assert_not_equal
from ..__init__ import parser, command, user_run_defaults
from argparse import ArgumentParser
from mock import Mock, patch
sys.path.insert(0,'..')
from boids import BoidsMethod
class test_sess... |
from typing import TypeVar
from typing.io import IO
import click
import pytest
from adhoc_pdb.cli import cli
def test_cli_fails_on_wrong_signum():
with pytest.raises(click.UsageError) as e:
click.Context(cli).invoke(cli, signum="bla")
assert "bla" in str(e.value).lower()
def test_cli_fails_on_wron... |
# Generated by Django 3.2.7 on 2021-10-28 23:54
import django.core.validators
import django_inet.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("peeringdb_server", "0078_ix_add_error_ixf_import_status"),
]
operations = [
migratio... |
# -*- coding: utf-8 -*-
import datetime
from collections import defaultdict
from django import forms
from django.contrib import admin, messages
from django.core.exceptions import ValidationError
from django.forms.models import modelform_factory
from django.db.models.fields import BooleanField
from django.shortcuts imp... |
#! /usr/bin/python3
#
# Copyright (c) 2021 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
target = ttbl.test_target("t0")
ttbl.config.target_add(target)
|
FMT_TOK_STREAMER_NAME = "streamer_name"
FMT_TOK_STREAM_URL = "stream_url"
format_args = {
FMT_TOK_STREAMER_NAME: None,
FMT_TOK_STREAM_URL: None
}
def validate_format_tokens(phrase):
try:
phrase.format(**format_args)
except KeyError:
return False
return True
def text_looks_like_ur... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
from datadog_checks.vault import Vault
from .common import INSTANCES
def test_run(benchmark):
instance = INSTANCES['main']
c = Vault('vault', None, {}, [instance])
# Run once to get instantiation o... |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import torch
import torch.nn as nn
import numpy as np
# from .sparse_matrix_old import SparseTensor
from .custom_functions.sparse_matrix import sparsify, unsparsify
fro... |
# Pot - Discord bot which is pog. Pot.
# Version - 0.1
# Licensed under the MIT license - https://opensource.org/licenses/MIT
#
# Copyright (c) 2021 Vidhu Kant Sharma
import traceback
import discord
from discord.ext import commands
# to import from parent directory
import sys
sys.path.append('..')
# import ../phrase... |
import torch
from torch import nn
import torch.nn.functional as F
from .functions import ConvMotionFunction, InvConvMotionFunction, ConvClsFunction, LineFunction
import numpy as np
class NUConv2d(nn.Module):
def __init__(self):
super(NUConv2d, self).__init__()
def forward(self, x, mag, ori):
... |
from ws.RLUtils.monitoring.graphing.data_compaction.compaction_mgt import compaction_mgt
def plugin_for_skipping_mgt():
_median_xindex = None
def fn_compute_yval(number_of_entries, strand_num, yvals_for_strands):
computed_yval_strand = yvals_for_strands[strand_num][_median_xindex]
return comp... |
from .na_xerath_top import *
from .na_xerath_jng import *
from .na_xerath_mid import *
from .na_xerath_bot import *
from .na_xerath_sup import *
|
# coding: utf-8
from dataclasses import dataclass
from bookworm import typehints as t
from bookworm import app
from bookworm.paths import app_path
from bookworm.reader import get_document_format_info
from . import PLATFORM
@dataclass
class SupportedFileFormat:
format: str
ext: str
name: str
@proper... |
# This software was developed by employees of the National Institute
# of Standards and Technology (NIST), an agency of the Federal
# Government. Pursuant to title 17 United States Code Section 105, works
# of NIST employees are not subject to copyright protection in the United
# States and are considered to be in the... |
from django.contrib.auth.models import BaseUserManager
from django.db import models
from django.utils.translation import ugettext_lazy as _
class AccountManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None):
if not any([email, first_name, last_name]):
rais... |
# Copyright 2021 SpinQ Technology Co., Ltd.
#
# 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 ... |
# -------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ------------------------------------------------------------------... |
import torch
class Label_smoothing(torch.nn.Module):
def __init__(self,num_classes,eps=0.1):
super(Label_smoothing,self).__init__()
self.eps = eps
self.v = self.eps/num_classes
self.logsoft = torch.nn.LogSoftmax(dim=1)
def forward(self,inputs,label):#input... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import print_function
import os
import os.path as op
import sys
import logging
import numpy as np
from jcvi.formats.base import LineFile
from jcvi.apps.base import (
OptionParser,
ActionDispatcher,
need_update,
sh,
get_abs_path,
wh... |
"""SDS user rules management functions."""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import open
from future import standard_library
standard_library.install_aliases()
import os
import json
from dat... |
from models import MODEL_DICT
from parameters import DATA_PATH
import os
def train_model(model):
if not os.path.exists(DATA_PATH+'models'):
os.mkdir(DATA_PATH+'models')
print('Starting traning of ', model.NAME)
model.train(lang='pt')
model.train(lang='es')
if __name__ == "__main__":
import... |
from flask import Blueprint, redirect
from application.pypi_org.infrastructure import cookie_auth
from application.pypi_org.infrastructure.view_modifiers import response
from application.pypi_org.services import user_service
from application.pypi_org.viewmodels.account.index_viewmodel import IndexViewModel
from applic... |
import json
import torch
from torch.utils.data import Dataset, DataLoader
class ClassifierDataset(Dataset):
def __init__(self, json_path):
self.json_path = json_path
with open(json_path, 'r', encoding = 'UTF-8-sig') as j:
self.mwp_cpae = json.load(j)
def read_cpae(self, idx... |
"""
Utility routines for benchmarks on OT solvers
===================================================
"""
import time
import torch
import numpy as np
use_cuda = torch.cuda.is_available()
tensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor
numpy = lambda x : x.detach().cpu().numpy()
##################... |
raise NotImplementedError("_strptime is not yet implemented in Skulpt")
|
from gzip import open as gzopen
import struct
from itertools import izip_longest, imap
def data():
for l in open("prices0.txt"):
if l.strip() == "\N" : pass
else : yield float(l.strip())
linear = open("column0.txt", "wb")
#hexdump = open("column1.txt", "wb")
def toHex(s):
lst = []
for ch in s:
hv = hex(ord... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import scipy as sp
import matplotlib as mpl
import matplotlib.pyplot as plt
import scipy.misc
import scipy.integrate
def f(x):
return x**3 - 10*np.sin(x) - 4
def df(x):
return sp.misc.derivative(f, x)
@np.vectorize
def F(x):
return sp.int... |
import requests
import os
base = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial"
key = os.environ['KEY']
def get_driving_time(origin_lat, origin_lon, dest_lat, dest_lon):
parameters = {'origins': "{},{}".format(origin_lat, origin_lon), 'destinations': "{},{}".format(dest_lat, dest_lon),... |
"""
Various helper functions for use with Maxmind's GeoIP2 Library
Getting started with our GeoIP2 wrapper
---------------------------------------
Basic Usage::
>>> from privex.helpers import geoip
>>> res = geoip.geolocate_ip('185.130.44.5')
>>> print(f"Country: {res.country} || Code: {res.country_code}... |
from torch import nn
from torch.nn import functional as F
from ..box_head.roi_box_feature_extractors import ResNet50Conv5ROIFeatureExtractor
from maskrcnn_benchmark.modeling.poolers import Pooler
from maskrcnn_benchmark.modeling.make_layers import make_conv3x3
class ShapeClassMaskRCNNFPNFeatureExtractor(nn.Module):
... |
# IMPORTANT: as of now, this script does NOT support more than one unknown person on each frame. Please keep that in mind.
#
# The following script is used to annotate the real face positions on the video.
# Specify the name of the video in the "test" directory in the command line.
# In case it isn't specified, all vid... |
# Copyright 2021, Dylan Roger
#
# 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 use, copy, modify, merge, publish, distribu... |
# encoding: utf-8
#
# Copyright (c) 2017 Dean Jackson <deanishe@deanishe.net>
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2017-12-15
#
"""Common helper functions."""
from __future__ import print_function, absolute_import
from contextlib import contextmanager
from datetime import date, date... |
import tensorflow as tf
from ...utils.nn import weight, bias
from ...utils.attn_gru import AttnGRU
class EpisodeModule:
""" Inner GRU module in episodic memory that creates episode vector. """
def __init__(self, num_hidden, question, facts, is_training, bn):
self.question = question
self.fact... |
"""Config flow for Palgate integration."""
from __future__ import annotations
from typing import Any
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_DEVICE_ID, CONF_TOKEN
from homeassistant.data_entry_flow import FlowResult
from .const import DOMAIN as PALGATE... |
#!/usr/bin/env python
""" ROS node that approximates velocity based on actuated values
"""
import math
import rospy
from svea_msgs.msg import lli_ctrl
from geometry_msgs.msg import TwistWithCovarianceStamped
from svea.states import SVEAControlValues
__author__ = "Tobias Bolin"
__copyright__ = "Copyright 2020, Tobi... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""Other utilities."""
import os
import sys
try:
import winsound
except ModuleNotFoundError:
pass
def makeSound():
"""Make a sound for two seconds.
On linux you need to instal sox:
sudo apt install sox
On windows you need install winsound:
... |
import json
class Tree:
def __init__(self):
self.topics = []
class Topic:
def __init__(self):
self.lessons = []
class Lesson:
def __init__(self):
pass
def load(self, filename):
lesson = json.load(filename)
self.title = lesson.title
self.description = ... |
##PyBank
# Dependencies
import csv
import os
# file input
PyBank = os.path.join("Resources", "budget_data.csv")
# Variables & Counters
profit_loss=[]
total=0
total_months=0
subtract_MoM=0
tot_MoM=0
Avg_MoM=0
with open(PyBank) as csvfile:
budget_reader=csv.reader(csvfile,delimiter=',')
next(budget_reader)
... |
"""Tests for client config."""
from logging import INFO, DEBUG
from pprint import pprint
import pytest
from idact import get_default_retries
from idact.core.auth import AuthMethod
from idact.detail.config.client. \
client_cluster_config import ClusterConfigImpl
from idact.detail.config.client.client_config impor... |
# __init__.py
__module_name__ = "_format_string_printing_font.py"
__author__ = ", ".join(["Michael E. Vinyard"])
__email__ = ", ".join(
[
"vinyard@g.harvard.edu",
]
)
from ._SpotifyAnnoy import _SpotifyAnnoy as annoy |
# Copyright (c) 2020 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for details.
from __future__... |
cars = {}
n = int(input())
for _ in range(n):
name, mileage, fuel = input().split("|")
cars[name] = [int(mileage), int(fuel)]
command = input().split(" : ")
while not command[0] == "Stop":
if command[0] == "Drive":
car, distance, fuel_needed = command[1], command[2], command[3]
if int... |
#!/usr/bin/env python
import datetime
import json
import os
import sys
import tempfile
import time
import urllib2
def main ():
certbot_domain = os.getenv('CERTBOT_DOMAIN').strip()
certbot_validation = os.getenv('CERTBOT_VALIDATION').strip()
api_token = os.getenv('API_TOKEN').strip()
log('processing certbot d... |
#! /usr/bin/env python3
# coding=utf-8
#================================================================
# Copyright (C) 2020 * Ltd. All rights reserved.
#
# Editor : pycharm
# File name : train.py
# Author : oscar chen
# Created date: 2020-10-13 9:50:26
# Description :
#
#======================... |
# Generates a linked list of a length determined by user input,
# consisting of random nonnegative integers whose upper bound is also determined
# by user input, and reorders the list so that it starts with all odd values and
# ends with all even values, preserving the order of odd and even values in the
# original lis... |
import argparse
import pickle
import logging
import os
import uuid
from datetime import datetime
from time import time
from PIL import Image
import gym
import psutil
import ray
# This script will generate the dataset of state, action, new state tuple
# and store it locally as dataset.pkl.
# We make use of ray to gen... |
from django.contrib import admin
from product.models import (
Product,
ProductImage
)
admin.site.register(Product)
admin.site.register(ProductImage) |
import sys
import numpy as np
# Install pyngrok.
server_args = []
if 'google.colab' in sys.modules:
server_args = ['--ngrok_http_tunnel']
from meshcat.servers.zmqserver import start_zmq_server_as_subprocess
proc, zmq_url, web_url = start_zmq_server_as_subprocess(server_args=server_args)
from pydrake.sys... |
import warnings
warnings.filterwarnings('ignore')
import unittest
from preprocessing.data_explorer import outliers_detector
import numpy as np
np.random.seed(0)
data_points = np.random.randn(2000, 2)
avg_codisp, is_outlier = outliers_detector(data_points)
class TestOutliers(unittest.TestCase):
def test_outlie... |
from classes.Logger import Logger
from classes.Board import Board
from classes.Visualiser import Visualiser
class GameLogger:
"""
Hardcoded column values whose key map towards a piece's UID so we can "random" access files for "random"-ness sake
"""
__map = [119, 124, 129, 134, 139, 144, 149, 154, 159,... |
"""
Instruction for the candidate.
1) You are an avid rock collector who lives in southern California. Some rare
and desirable rocks just became available in New ork, so you are planning
a cross-country road trip. There are several other rare rocks that you could
pick up along the way.
... |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... |
/home/runner/.cache/pip/pool/b0/ea/23/8e93b04086b09945ebc0137943c1d94e8feedb1b3e345e78ea4b9fd225 |
# Generated by Django 2.1.7 on 2019-06-24 16:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organizaciones', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='contraparte',
na... |
#!/usr/bin/env python
'''
@package ion.processes.data.transforms
@file ion/processes/data/transforms/notification_worker.py
@author Brian McKenna <bmckenna@asascience.com>
@brief NotificationWorker class processes real-time notifications
'''
from datetime import datetime
from email.mime.text import MIMEText
import sm... |
# 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... |
from abc import ABC, abstractmethod
from PyQt5.QtGui import QIcon
class AbstractPlayer(ABC):
"""This is the abstract player class that provides a basic interface for all players in the game."""
def __init__(self, engine, is_ai=False):
self.name = None
self.tickets = None
self.locatio... |
from numpy import exp
try:
from plexus.low_level_drivers.simple_avr_cond_driver import SimpleCondSensorControl
from plexus.nodes.node import Command
from plexus.nodes.message import Message
from plexus.devices.base_device import BaseDevice
except Exception as e:
from src.plexus.low_level_drivers.... |
# Created by Xinyu Zhu on 2021/4/20, 17:58
import pysynth as ps
import numpy as np
import re
# 先限定音符12356 中国风五声调式 这样听起来比较自然
notes = np.array(["c4", "d4", "e4", "g4", "a4", ])
# 音符时值
durations = np.array([1, 2, 4, -2, -4, -8])
# 随机生成音符 重音穿插其中
sn = []
for t in range(16):
n = np.random.randint(0, len(notes))
note... |
# Shell sort - https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1093
def read_list(size):
lst = []
for i in range(size):
lst.append(input())
return lst
def out_of_place(lst, offset, length):
oop = []
# print('Offset: ', offset)
for i in ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Indufficient app conf."""
from django.apps import AppConfig
class InsufficientConfig(AppConfig):
"""Indufficient app conf."""
name = 'backend.insufficient'
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#LogMapper
#
#MIT License
#
#Copyright (c) 2018 Jorge A. Baena - abaena78@gmail.com
#
#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 restrict... |
from flask.ext.login import UserMixin
from app import db
class User(UserMixin,db.Document):
kaid = db.StringField(required=True, unique=True)
username = db.StringField(required=True, unique=True)
nickname = db.StringField(required=True)
access_token = db.StringField(required=True)
access_token_sec... |
import torch.nn as nn
from mmcv.cnn import normal_init, kaiming_init
from ..builder import HEADS
from .base import BaseHead
from ..builder import build_loss
from mmcv.cnn.bricks import build_norm_layer
def _init_weights(module, init_linear='normal', std=0.01, bias=0.):
assert init_linear in ['normal', 'kaiming']... |
# -*- coding: utf-8 -*-
import os
import json
import base64
import hashlib
import logging
import signal
from contextlib import contextmanager
from datetime import datetime, timedelta
from subprocess import run, STDOUT, PIPE, TimeoutExpired, CompletedProcess
from tempfile import NamedTemporaryFile
log = logging.getLogg... |
#!/usr/bin/env python3
import re
from string import Template
from mpi_constants import constants
from mpi_functions import functions
from mpi_constants_fortran import constants_fortran
from mpi_functions_fortran import functions_fortran
print()
print("// C constants")
for (tp, nm) in constants:
subs = {'abi_tp':... |
import os
import argparse
import pickle
import yaml
import torch
from glob import glob
from tqdm.auto import tqdm
from easydict import EasyDict
from models.epsnet import *
from utils.datasets import *
from utils.transforms import *
from utils.misc import *
def num_confs(num:str):
if num.endswith('x'):
re... |
from . import OverMind
from .client import Client |
class UserNotFoundException(Exception):
"""登録されていないユーザが利用した場合のエラー. """
pass
class BadShukkinStateException(Exception):
"""出勤の条件が整っていない場合のエラーエラー. """
pass
class BadTaikinStateException(Exception):
"""退勤の条件が整っていない場合のエラーエラー. """
pass
|
import time
import board
import busio
# from adafruit_ads1x15.differential import ADS1115
from adafruit_ads1x15.single_ended import ADS1115
import array
import touchio
def calc_mean(this_array):
return sum(this_array)/len(this_array)
adc_active = True
# adc_active = False
# Capacitive touch on D3
touch = touch... |
# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Modifications made by Cloudera are:
# Copyright (c) 2016 Cloudera, 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. A copy of
... |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2016 the HERA Collaboration
# Licensed under the 2-clause BSD license.
"""Define package structure."""
import numpy as np
from setuptools_scm import get_version
from pathlib import Path
from pkg_resources import get_distribution, DistributionNotFound
from .branch_sch... |
from object import *
import matplotlib
import matplotlib.pyplot as plt
class Cat(Object):
def update(self):
self.x = self.x + np.array([self.x[2], self.x[3], 100*np.random.randn(), 100*np.random.randn()])*self.step
self.t = self.t + self.step
self.check_wall()
self.check_obstacles(... |
def dd(L):
d1 = {}
for elem in L:
if elem not in d1:
d1[elem] = 1
else:
d1[elem] += 1
# print(d1)
return d1
def is_list_permutation(L1, L2):
'''
L1 and L2: lists containing integers and strings
Returns False if L1 and L2 are not permutations of each ... |
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
n = len(citations)
if n == 0:
return 0
counter = {}
for i in range(n + 1):
counter[i] = 0
for citation in citations:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.