content stringlengths 5 1.05M |
|---|
#! /usr/bin/env python
'''
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 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will... |
import cv2
from collections import defaultdict
from utils.timer import Timer
_GRAY = [218, 227, 218]
_RED = [0, 0, 255]
_GREEN = [18, 127, 15]
_BULE = [255, 144, 30]
_WHITE = [255, 255, 255]
_BLACK = [0, 0, 0]
colors = [_RED, _GREEN, _BULE, _WHITE]
def get_class_string(class_index, score, dataset):
class_text =... |
# The parsing logic is heavily borrowed from the python-nubia project, available at:
# https://github.com/facebookincubator/python-nubia
#
# In compliance with python-nubia's BSD-style license, its copyright and license terms
# are included below:
#
# BSD License
#
# For python-nubia software
#
# Copyright (c) Facebook... |
import re
f = open('Dockerfile')
data = f.read()
f.close()
resp = re.sub('RUN','sudo',data)
resp = re.sub('WORKDIR','cd',resp)
resp = re.sub('FROM.*','',resp)
cmd = re.findall('ENTRYPOINT\s+\[(.*?)].*?CMD\s+\[(.*?)\]',resp,re.DOTALL)
if cmd:
cmd = cmd[0]
cmd = cmd[0].strip() + ' ' + cmd[1].strip()
cmd = cm... |
# flush
import time
import yaqc
from .._pump import *
def run():
# Flush
# (all volumes in mL unless specified differently)
if True:
print("flush")
for i in range(65):
print(i)
return
# pall_flow_rates is the flow rate of one DSP
# FILL IN PUMP FLOW RATE BE... |
from bs4 import BeautifulSoup as bs
from splinter import Browser
import time
import pandas as pd
import lxml
# full "scrape" function, comprised of the four subfunctions
# defined below
def scrape():
# create the overall dictionary to hold all the results
# which will be returned by this function to the flask... |
# -*- coding: utf-8 -*-
from shuup_workbench.settings.utils import get_disabled_migrations
from shuup_workbench.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'myapp.sqlite3'
}
}
|
#!/usr/bin/env python
import ConfigParser
import log
import obslog
import os
from pyraf import iraf
import shutil
import utils
# ----------------------------------------------------------------------------------------------------------------------
def start(configfile):
"""
Parameters are loaded from gnirs-p... |
def jackpot():
if 10*"@" in first_half and 10*"@" in second_half:
return ["True", "@", 10]
elif 10*"#" in first_half and 10*"#" in second_half:
return ["True", "#", 10]
elif 10*"$" in first_half and 10*"$" in second_half:
return ["True", "$", 10]
elif 10*"^" in first_half and 10*... |
from ...language.base import parse
from ...utils.ast_to_code import ast_to_code
from ..compiled import GraphQLCompiledDocument
from .schema import schema
def test_compileddocument_from_module_dict():
# type: () -> None
document_string = "{ hello }"
document_ast = parse(document_string)
document = Grap... |
import argparse
from random import seed
from yaml import dump
from utils.experiment import test
from utils.utils import *
if __name__ == "__main__":
seed(0)
parser = argparse.ArgumentParser(
description='Test error for a combination of ensembler and weak learner.')
parser.add_argument('dataset', ... |
# Copyright (c) 2009-2013, Monoidics ltd.
# Copyright (c) 2013-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_functi... |
import unittest
from rating.processing import rates
from rating.processing.utils import ConfigurationException
class TestConversion(unittest.TestCase):
def test_conversion_byte_second_to_hour_harder(self):
rating_unit = 'GiB-hours'
metric_unit = 'byte-seconds'
qty = 7e12
converted... |
from django.contrib import admin
from users.models import Profile, ConfirmedMail
# Represents Profile and ConfirmedMail models at admin site.
admin.site.register(Profile)
admin.site.register(ConfirmedMail)
|
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número '))
r = n1 + n2
print('O resultado da soma é {}'.format(r))
r = n1 - n2
print('O resultado da subtração é {}'.format(r))
r = n1 * n2
print('O resultado da multiplicação é {}'.format(r))
r = n1 / n2
print('O resultado da divisão é {}'.format(... |
import pdb, traceback, sys
try:
1/0
except:
extype, value, tb = sys.exc_info()
traceback.print_exc()
pdb.post_mortem(tb)
|
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
import importlib
import platform
if platform.architecture()[0] == '32bit':
globals().update(importlib.import_module('open3d.win32.32b.open3d').__dict__)
elif platform.architecture()[0] == '64bit':
globals()... |
from copy import copy
from contextlib import contextmanager
from logging import getLogger
import tensorflow as tf
from rl.utils.tf_utils import (purge_orphaned_summaries
as _purge_orphaned_summaries)
USE_DEFAULT = object()
logger = getLogger("rl")
class SummaryManager(object):
def ... |
num1 = 11
num2 =222
num3 =3333 |
""""
Copyright © Krypton 2021 - https://github.com/kkrypt0nn (https://krypt0n.co.uk)
Description:
This is a template to create your own discord bot in python.
Version: 4.1
"""
class UserBlacklisted(Exception):
"""
Thrown when a user is attempting something, but is blacklisted.
"""
def __init__(self,... |
a = [0, 0, 0, 1, 1, 1, 3, 3, 6, 6, 9, 9]
print(len(a))
def root(x):
while x != a[x]:
a[x] = a[a[x]]
print(x, a[x])
x = a[x]
return x
def root2(x):
if x != a[x]:
a[x] = root2(a[x])
return a[x]
root2(9)
print(a)
|
"""
@Note: Implementation of Knowledge Distillation Algorithms
@Author: LucasX
"""
import copy
import os
import sys
import time
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import confusion_matrix
from torch.o... |
import tensorflow as tf
import numpy as np
import os
# from sklearn.manifold._utils import _binary_search_perplexity
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
class TSNE:
def __init__(self,n_components=2, perplexity=30, early_exaggeration=12, learning_... |
n = int(input())
print(pow(2, n+1)-2)
|
import unittest
from typing import Generator, List
from common import open_fixture
BASE_PATTERN = (0, 1, 0, -1)
def decode(s: str) -> List[int]:
return [int(c) for c in s.strip()]
def pattern(position: int) -> Generator[int, None, None]:
skip = True
while True:
for i in range(len(BASE_PATTER... |
class newNode:
# Construct to create a newNode
def __init__(self, key):
self.data = key
self.left = None
self.right = None
self.hd = 0
# function should print the topView
# of the binary tree
def topview(root) :
if(root == None) :
return
q = []
mp = dict()
head = 0
root.head = head
# push no... |
import tensorflow as tf
import dnnlib.tflib as tflib
from training import dataset
from training import misc
from metrics import metric_base
class ACC(metric_base.MetricBase):
def __init__(self, num_images, minibatch_per_gpu, test_data_dir, test_dataset, **kwargs):
super().__init__(**kwargs)
self.n... |
#! /usr/bin/env python
"""
GaussLaguerre_doughnut.py
Calculates the intensity- and phase distributions of
Laguerre-Gauss doughnut laser modes.
cc Fred van Goor, May 2020.
"""
from LightPipes import *
import matplotlib.pyplot as plt
if LPversion < "2.0.0":
print(r'You need to upgrade LightPipes... |
from layers import *
class CNN(object):
"""
Implements Convolutional Neural Network
Input shape: [8, 3, 32, 32]---------->[batch size, channels, height, width]
Model Architecture:
----------------------------------------------------------------
Layer (type) Output Shape ... |
from collections import Counter
occurrence_list = [item.lower() for item in input().split()]
odd_occurrence = [key for key, value in Counter(occurrence_list).items() if value % 2 != 0]
print(', '.join(list(odd_occurrence)))
|
import requests
import wget
import time
r = requests.post("http://10.42.0.255:8000/start")
time.sleep(4)
r = requests.post("http://10.42.0.255:8000/stop")
file_url = 'http://10.42.0.100/get/10'
file_name = wget.download(file_url)
file_name.save(/'pictures/10_picture.png') |
#
# Get the language breakdown for a repo
# Usage: ghb langs USER/REPO
#
import operator
import sys
import requests
from .helpers import credentials
URL = "https://api.github.com/repos/%s/languages"
def average(total, number):
return round((number / float(total)) * 100, 2)
def main(args):
username, passw... |
# import all necessarily modules
import os.path
import subprocess
import sys
from configparser import ConfigParser
# working dir and extension types will be passed through CLI
try:
workDir = sys.argv[1]
extType = sys.argv[2]
newExtType = sys.argv[3]
except IndexError:
raise Exception("Usage: python3... |
import logging
from riffdog.data_structures import FoundItem
from riffdog.resource import register, ResourceDirectory
from ...aws_resource import AWSRegionalResource
logger = logging.getLogger(__name__)
@register("aws_lambda_function")
class AWSLambdaFunction(AWSRegionalResource):
"""
This is aws Lambda fu... |
# using: encoding-utf8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import time
import os
from six.moves import cPickle
import utils.opts as opts
import models
from util... |
# pylint: disable=C0103
import json
class CampaignObject():
def __init__(self, json_def):
if type(json_def) is str:
json_def = json.loads(json_def)
s = json_def
self.campaignTp = None if 'campaignTp' not in s else s['campaignTp']
self.customerId = None if 'custom... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2017 bily Huazhong University of Science and Technology
#
# Distributed under terms of the MIT license.
"""Save the paths of crops from the ImageNet VID 2015 dataset in pickle format"""
from __future__ import absolute_import
from __future__ import divi... |
import argparse
import datetime as dt
import os
from gpsynth.synthesizer import big_sweep, all_kernels
parser = argparse.ArgumentParser(description='Generate wavetables with Gaussian Processes')
parser.add_argument('path', metavar='path', type=str, nargs='?', default=None,
help='the parent directo... |
# coding=utf-8
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils
from torch.autograd import Variable
from torch.nn import Parameter, init
from torch.nn._functions.rnn import variable_recurrent_factory, StackedRNN
from torch.nn.modules.rnn import RNNCellBase
from torch... |
from flask import Flask, send_from_directory, request
from flask_restful import Api, Resource, reqparse
import json
import numpy as np
import datetime
import csv
import click
from dlw import DLWSubject
STATICS_LOCATION = 'dist'
app = Flask(__name__, static_url_path='', static_folder=STATICS_LOCATION)
api = Api(app)
... |
#!/usr/bin/env python
from strip import Strip
import random
import time
import signal
import logging
logger = logging.getLogger(__name__)
def init_logging(log_level):
logging.basicConfig(level=log_level)
# catch signals for tidy exit
_exiting = False
def signal_handler(signal, frame):
global _exiting
_... |
from flask_appbuilder import Model
from flask_appbuilder.models.mixins import AuditMixin, FileColumn, ImageColumn
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
"""
You can use the extra Flask-AppBuilder fields and Mixin's
AuditMixin will add automatic timestamp of... |
import pytest
from ergaleia import Mini
@pytest.fixture
def mini():
return Mini('foo value=bar')
def test_default(mini):
assert mini.foo == 'bar'
with pytest.raises(TypeError):
mini['foo']
def test_set_attribute(mini):
mini.foo = 'whatever'
assert mini.foo == 'whatever'
with pytest... |
import itertools
import pickle
import time
import tarfile
import sys
import uuid
import warnings
from collections import OrderedDict
from pathlib import Path
import hawkeslib as hl
import numpy as np
from joblib import Parallel, delayed
from sklearn.decomposition import NMF
from sklearn.cluster import KMeans, Spectral... |
# Copyright (c) Ye Liu. All rights reserved.
from .dynamic_bce import DynamicBCELoss
from .focal import (FocalLoss, FocalLossStar, GaussianFocalLoss, focal_loss,
focal_loss_star, gaussian_focal_loss)
from .ghm import GHMCLoss
from .lasso import (BalancedL1Loss, L1Loss, SmoothL1Loss, balanced_l1_los... |
import pandas as pd
t1 = pd.read_csv("lgb_pyst.csv")
t2 = pd.read_csv("lgb_pyst_Keras_4_0.967189916545.csv")
t2['click'] = t2['click']*0.8 +t1['click']*0.2
t2.to_csv('avg_lgb_pyst_Keras_4_2_8.csv', index=False) |
# Sum of Polygon Angles
print("Given an n-sided regular polygon n, return the total sum of internal angles (in degrees).")
n_sided = int(input("Enter your n-sided polygon : "))
angles = 2(n_sided)−4×90(n_sided)
print(angles) |
#Copyright ReportLab Europe Ltd. 2000-2008
#this test and associates functionality kinds donated by Ian Sparks.
#see license.txt for license details
"""
Tests for internal links and destinations
"""
__version__='''$Id: test_pdfgen_links.py 3288 2008-09-15 11:03:17Z rgbecker $'''
from reportlab.lib.testutils import setO... |
import os
from setuptools import setup
def pkg_dir(path):
return os.path.join(os.path.dirname(__file__), path)
with open(pkg_dir('VERSION'), 'r') as f:
version = f.read().strip()
with open(pkg_dir('README.md'), 'r') as f:
readme = f.read()
setup(
name='elasticsearch-collectd-plugin',
version... |
import os
import sys
import glob
import json
import scipy.signal as signal
import numpy.ma as ma
import numpy as np
import matplotlib
import matplotlib.pylab as plt
import matplotlib.dates as mdates
import datetime
import statsmodels.api as sm
lowess = sm.nonparametric.lowess
def savitzky_golay(y, window_size, order,... |
#!/usr/bin/env python
#
# Copyright 2019 YugaByte, Inc. and Contributors
#
# Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# https://github.com/YugaByte/yugabyte-db/blob/master/licenses... |
from __future__ import print_function
import json
import logging
import sys
import os
this_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append("{0}/../lib".format(this_dir))
sys.path.append("{0}/../src".format(this_dir))
from jsonschema import validate
from generator.generator import convert_to_imacro
l... |
import argparse
import traceback
import warnings
import torch
import wandb
from gym_carla.envs.carla_env import CarlaEnv
from gym_carla.envs.carla_pid_env import CarlaPidEnv
from termcolor import colored
from torch.utils.data import DataLoader
from bc.train_bc import get_collate_fn
from models.carlaAffordancesDataset... |
from odio_urdf import *
def assign_inertia(im):
return Inertia(ixx=im[0], ixy=im[1], ixz=im[2], iyy=im[3], iyz=im[4], izz=im[5])
my_robot = Robot("walker_a")
contact = Contact(Lateral_Friction("100"))
s = 1
inertia_matrix_body = [0.6363636364, 4.908571429, 4.51012987, 4.51012987, 0.6363636364, 4.908571429]
inert... |
import argparse
import constants
from data_support.tfrecord_wrapper import TFRecordWriter
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("data_dir", type=str, default='../resources/tf_data',
help="Directory where tfrecord files are stored")
parser.add_argumen... |
import copy
import json
import time
from io import open
from .exceptions import (
WebpackBundleLookupError,
WebpackError,
WebpackLoaderBadStatsError,
WebpackLoaderTimeoutError,
)
class WebpackLoader(object):
_assets = {}
def __init__(self, name, config):
self.name = name
self... |
import os
import shutil
from ptest.assertion import assert_true
from ptest.decorator import TestClass, BeforeMethod, Test, AfterMethod
from watchdog.events import FileCreatedEvent
from shirp.event import EventConf
from shirp.handler import HDFSHandler
HDFS_GROUP = "grp-hdfs"
@TestClass(run_mode="singleline")
class... |
"""Project-level configuration and state."""
import os.path
class Project(object):
"""A Project tracks the overall build configuration, filesystem paths,
registered plugins/keys, etc. and provides services that relate to that."""
def __init__(self, root, build_dir):
"""Creates a Project.
... |
# -*- coding: utf-8 -*-
import json
from bs4 import BeautifulSoup
from django.contrib.auth import get_user_model
from django.test import TestCase
class BaseTestCase(TestCase):
fixtures = [
'users.json',
]
USER_PWD = 'password'
# Superuser - admin/adminpassword
# User - neo/password
... |
from django.contrib import sitemaps
from django.urls import reverse
from booru.models import Post
class PostSitemap(sitemaps.Sitemap):
priority = 0.8
changefreq = 'daily'
def items(self):
return Post.objects.approved()
def location(self, item):
return item.get_absolute_url()
def ... |
from .utils import check_token
from .models import Entry
from .checks_models import EntryCheck
open_entry_checks = EntryCheck()
open_entry = Entry()
|
import requests
import pytest
from helpers import (create_user,
get_random_email,
login_user,
refresh_token, get_user)
from requests import HTTPError
HOST = 'localhost:5000'
def test_register():
email = get_random_email()
new_user = create_user(em... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. currentmodule:: test_Point
.. moduleauthor:: Pat Daburu <pat@daburu.net>
This is a unit test module.
"""
import unittest
from djio.geometry import GeometryException
class TestGeometryExceptionSuite(unittest.TestCase):
def test_initWithoutInner_verify(self):... |
#!/usr/bin/env python
import os
import uuid
import time
import zlib
import random
import numpy as np
from string import ascii_lowercase
list_chars = list(c.encode('utf8') for c in ascii_lowercase)
# Number of objects
#num_files_list = [1]
num_files_list = [1, 100, 1000, 10000, 100000, 1000000]
# Hash functions
#comp... |
_base_ = ['./rotated_retinanet_obb_r50_fpn_1x_dota_le90.py']
fp16 = dict(loss_scale='dynamic')
|
from tksheet import Sheet
import tkinter as tk
class Sheet_Listbox(Sheet):
def __init__(self,
parent,
values = []):
Sheet.__init__(self,
parent = parent,
show_horizontal_grid = False,
show_verti... |
# 1.
# C = float(input('输入摄氏温度'))
# F = (9/5)*C + 32
# print('%.2F 华氏度' %F)
# 2.
# import math
# r = float(input('输入圆柱半径:'))
# l = float(input('输入圆柱高:'))
# area = r*r*math.pi
# volume = area*l
# print('面积:%.2f' %area)
# print('体积:%.2f' %volume)
# 3.
# feet = float(input('请输入英尺数:'))
# meters = feet... |
# You are provided with a code that raises many exceptions. Fix it, so it works correctly.
# numbers_list = input().split(", ")
# result = 0
#
# for i in range(numbers_list):
# number = numbers_list[i + 1]
# if number < 5:
# result *= number
# elif number > 5 and number > 10:
# result /= ... |
#! /usr/bin/env python3
"""This is a prototype work manager which reads work requests from a file and
submits them as messages to a RabbitMQ queue.
This is development only. For a real system, you would get work from a
database or other entity.
"""
import os
import sys
import json
import logging
from argpa... |
# coding: utf-8
import numpy as np
from numpy import matrix as mat
import cv2
import os
import math
def undistort(img, # image data
fx, fy, cx, cy, # camera intrinsics
k1, k2, # radial distortion parameters
p1=None, p2=None, # ta... |
from http import HTTPStatus
import json
from src.common.encoder import PynamoDbEncoder
class HTTPResponse(object):
@classmethod
def to_json_response(cls, http_status, message=None):
"""
Access-Control-Allow-Origin is needed for CORS to work
Access-Control-Allow-Credentials is needed f... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-11-26 09:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('libretto', '0044_auto_20190917_1200'),
]
operations = [
migrations.AlterFi... |
from setuptools import setup, find_packages
classifiers = ['Development Status :: 4 - Beta',
'Operating System :: POSIX :: Linux',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Programming Language :: Python :: 2.7',
... |
"""============================================================================
The input is a file containing lines of the following form:
equation_name arg1 ...
For example:
energy 5.4 3.7 99
something 7 280.01
energy 88.94 73 21.2
whizbang 83.34 14.34 356.43 139593.7801
something .001 25
You ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sympy import init_printing,Integral,latex,pretty,pprint,sqrt,symbols,srepr
init_printing(use_unicode=True)
x,y,z = symbols('x y z')
print(Integral(sqrt(1/x),x))
print(srepr(Integral(sqrt(1/x), x)))
pprint(Integral(sqrt(1/x), x), use_unicode=False)
print(pretty(Integ... |
from django.contrib import admin
from django.contrib.admin import register
from bbbs.main.models import Main
from bbbs.users.utils import AdminOnlyPermissionsMixin
from .forms import MainAdminForm
@register(Main)
class MainAdmin(AdminOnlyPermissionsMixin, admin.ModelAdmin):
empty_value_display = "-пу... |
""" uTorrent migration to qBittorrent module """
from tkinter import Tk, StringVar, N, W, E, S, filedialog, messagebox, HORIZONTAL
from tkinter.ttk import Frame, Entry, Button, Label, Progressbar
from shutil import copy
from os import path
from hashlib import sha1
from time import time
from re import compile as ... |
#!/usr/bin/env python3
import argparse
import logging
import logging.config
import os
import sys
import time
import yaml
from cluster_manager import setup_exporter_thread, \
manager_iteration_histogram, \
register_stack_trace_dump, \
update_file_modification_time
sys.path.append(
os.p... |
import itertools
from numbers import Number
from graphgallery.utils.type_check import is_iterable
def repeat(src, length):
if src is None:
return [None for _ in range(length)]
if src == [] or src == ():
return []
if isinstance(src, (Number, str)):
return list(itertools.repeat(src, l... |
from __future__ import absolute_import
from __future__ import unicode_literals
import inspect
import logging
LOG = logging.getLogger(__name__)
def is_generator(func):
"""Return True if `func` is a generator function."""
return inspect.isgeneratorfunction(func)
|
#! /usr/bin/python
# -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Copyright (C) 2012 by Xose Pérez
#
# 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, ei... |
def countPattern(genome, pattern):
"""
Find the number of specific pattern in a genome sequence
"""
count = 0
for index in range(0, len(genome)-len(pattern)+1):
if genome[index:index+len(pattern)] == pattern:
count += 1
return count
def findPattern(genome, pattern):
"... |
import logging
import asyncio
from ..Errors import *
from ..utils import Url
logger = logging.getLogger(__name__)
class Commander:
"""
Manages looping through the group wall and checking for commands or messages
Attributes
-----------
prefix: :class:`str`
The command prefix
"""
... |
"""Class implementation for the scale_x_from_center interface.
"""
from typing import Dict
from apysc._animation.animation_scale_x_from_center_interface import \
AnimationScaleXFromCenterInterface
from apysc._type.attr_linking_interface import AttrLinkingInterface
from apysc._type.number import Number
fr... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.shell.lint.shfmt.rules import ShfmtFieldSet, ShfmtRequest
from pants.backend.shell.lint.s... |
#!/usr/bin/env python
__author__ = "Yaroslav Litvinov"
__copyright__ = "Copyright 2016, Rackspace Inc."
__email__ = "yaroslav.litvinov@rackspace.com"
from os import system
import psycopg2
import argparse
import configparser
from pymongo import DESCENDING
from collections import namedtuple
from datetime import datetim... |
# -*- coding: utf-8 -*-
from django.urls import path,re_path
from . import views
app_name = 'ajunivel'
urlpatterns = [
path('', views.index, name='index'),
path('index.html', views.index, name='index'),
path('index', views.index, name='index'),
path('menu', views.menu, name='menu'),
] |
import os
import socket
from pathlib import Path
class Config(object):
"""
Basic configuration, like socket default timeout, headers
"""
def __init__(self):
super(Config, self).__init__()
self.socket_timeout = 20
# set socket layer timeout as 20s
socket.setdefaulttimeout(self.socket_timeout)
# self.hea... |
from dataclasses import dataclass
@dataclass
class ModelException:
pass
|
import numpy as np
from torchmeta.utils.data import Task, MetaDataset
class Relu(MetaDataset):
"""
Parameters
----------
num_samples_per_task : int
Number of examples per task.
num_tasks : int (default: 2)
Overall number of tasks to sample.
noise_std : float, optional
... |
# flake8: noqa
CLOUDWATCH_EMF_SCHEMA = {
"properties": {
"_aws": {
"$id": "#/properties/_aws",
"properties": {
"CloudWatchMetrics": {
"$id": "#/properties/_aws/properties/CloudWatchMetrics",
"items": {
"$... |
import torch
from torchvision import transforms, datasets
import numpy as np
from PIL import Image
from skimage.color import rgb2lab, rgb2gray, lab2rgb
def count_params(model):
'''
returns the number of trainable parameters in some model
'''
return sum(p.numel() for p in model.parameters() if p.requir... |
from datetime import date
ano = int (input ('Digite o ano de nascimento: '))
idade = date.today().year - ano
if idade <= 9:
print ('Sua idade {}, Até 9 anos: Mirim'.format(idade))
elif idade > 9 and idade <= 14:
print ('Sua idade {}, Até 14 anos: Infantil'.format(idade))
elif idade > 14 and idade <= 19:
pri... |
# -*- coding: utf-8 -*-
"""
"""
from flask import flash, redirect, url_for, render_template, request
from sayhello import app, db
from sayhello.forms import HelloForm
from sayhello.models import Message
@app.route('/', methods=['GET', 'POST'])
def index():
"""
# TODO 分页BUG未解决
"""
form = HelloForm()
... |
from aws_google_auth import exit_if_unsupported_python
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
import unittest
import sys
import mock
class TestPythonFailOnVersion(unittest.TestCase):
@mock.patch('sys.stdout', new_callable=StringIO)
def test_python26(self, moc... |
import json
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.http import JsonResponse
from django.shortcuts import render, redirect
import re
import loggi... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: variable
Author: ken
CreateDate: 5/21/2018 AD
Description:
-------------------------------------------------
"""
__author__ = 'ken' |
import chess
from .external_chess_player import ExternalChessPlayer
MAX_RETRIES = 3
class ChessPlayer(object):
def __init__(self, external_player):
"""
:param external_player:
:type external_player: ExternalChessPlayer
"""
self.ext_player = external_player
def end_ga... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
from meanfield import MeanField
def d_tanh(x):
"""Derivative of tanh."""
return 1. / np.cosh(x)**2
def simple_plot(x, y):
plt.plot(x, y)
plt.xlim(0.5, 3)
plt.ylim(0, 0.25)
plt.xlabel('$\sigma_\omega^2$', fontsize=1... |
from tests.conftest import JiraTestCase
class PrioritiesTests(JiraTestCase):
def test_priorities(self):
priorities = self.jira.priorities()
self.assertEqual(len(priorities), 5)
def test_priority(self):
priority = self.jira.priority("2")
self.assertEqual(priority.id, "2")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.