content stringlengths 5 1.05M |
|---|
class FrozenClass(object):
__isfrozen = False
def __setattr__(self, key, value):
if self.__isfrozen and not hasattr(self, key):
raise TypeError( "%r is a frozen class" % self )
object.__setattr__(self, key, value)
def _freeze(self):
self.__isfrozen = True
"""
# Turorial... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 03 19:19:16 2011
@author: Chris Lee-Messer
"""
import numpy as np
import stockwell.smt as smt
import stockwell
import matplotlib.pyplot as plt
Fs = 200 # frequency
P = 1.0/Fs # time steps
T = 10.0 # max time
t = np.arange(0,... |
"""
Removes stop words produced from the script SemanticParser.py when deriving the method call dependency graph.
ex. python remove_stop_words.py [input].csv [output].csv
"""
import csv
import sys
ebc_stop_words = ['com', 'ibm', 'elastic', 'build', 'cloud', 'api', 'core', 'external', 'system', 'bundle', 'feature', '... |
from discord import Channel
from discord.ext import commands as c
from accounts import level
from helpers import pretty_datetime
class Messages:
"""Message management plugin.
The star of the show is message cross-posting and moving, but this plugin handles
pinning as well.
"""
def __init__(sel... |
'''
Copyright (C) 2017-2020 Bryant Moscon - bmoscon@gmail.com
Please see the LICENSE file for the terms and conditions
associated with this software.
'''
import hashlib
import hmac
import logging
import time
from decimal import Decimal
from time import sleep
import pandas as pd
import requests
from so... |
"""empty message
Revision ID: 235512b65610
Revises:
Create Date: 2021-04-14 17:56:09.390948
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '235512b65610'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
# Copyright (c) 2019-2021, Manfred Moitzi
# License: MIT License
import pytest
from ezdxf.math import BoundingBox, BoundingBox2d, Vec2, Vec3
from itertools import permutations
class TestBoundingBox:
def test_init(self):
bbox = BoundingBox([(0, 0, 0), (10, 10, 10)])
assert bbox.extmin == (0, 0, 0)... |
######################################################################################
#LEDNet: A Lightweight Encoder-Decoder Network for Real-Time Semantic Segmentation
#Paper-Link: https://arxiv.org/abs/1905.02423
######################################################################################
import to... |
from dnnv.errors import DNNVError
class VerifierError(DNNVError):
pass
class VerifierTranslatorError(DNNVError):
pass
__all__ = ["VerifierError", "VerifierTranslatorError"]
|
from PySide2.QtWidgets import *
from PySide2.QtCore import *
class TableView(QTableView):
"""define hover functionality of TableView"""
hover_index_changed = Signal(QModelIndex)
def __init__(self, parent):
super(TableView, self).__init__(parent)
self.hover_index = QModelIndex()
def m... |
import re
def parse(data):
return [{'x':x, 'y':y, 'vx':vx, 'vy':vy} for x,y,vx,vy in [map(int,re.findall(r'-?\d+', d)) for d in data.split('\n')]]
def draw_board(points):
p = [(_['x'], _['y']) for _ in points]
for j in xrange(min(p, key=lambda x: x[1])[1], max(p, key=lambda x: x[1])[1]+1):
for i i... |
import json
import family_class
json_file_name = "data/family_data.json"
with open(json_file_name, "r") as reader:
family_json_data = json.load(reader)
parents = family_json_data["parents"]
new_family = family_class.Family(parents);
kids = family_json_data["kids"]
for kid in kids:
new_kid = fami... |
#! /usr/bin/env python
"""Function to oad wavefront OBJ files
See http://www.fileformat.info/format/wavefrontobj/.
At the moment only v and f keywords are supported
"""
import numpy as np
def read_obj(filename):
faces = []
vertices = []
fid = open(filename, "r")
node_counter = 0
while True:
... |
import re
import os
workingpath = "C:\\Users\\Jack\\Downloads\\blogs\\male"
files = os.listdir(workingpath)
# print(files)
count = 0
posts = []
failedfiles = []
with open(r"C:\Users\Jack\Downloads\blogs\male\1169202.male.26.Science.Libra.xml", encoding="latin-1") as file:
text = file.read()
m = re.findall('<... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.contrib.h... |
from mistune import AstRenderer, create_markdown
def create_heading_id(string):
string = string.replace("`", "")
return "-".join(string.lower().split())
# noinspection PyMethodMayBeStatic
class DmcRenderer(AstRenderer):
def heading(self, children, level):
text = "".join(children)
return ... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.db.models import Q
from django.utils import timezone
from .models import Tier
def make_exempt(modeladmin, request, queryset):
queryset.update(tier_enforcement_exempt=True)
make_exempt.short_... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 12:53:15 2020
@author: rdamseh
"""
import numpy as np
import scipy.integrate as integrate
class DiffusionGradient:
def __init__(self, shape=(10,10,10),
b=10, #s/mm2
delta_big=.5, #ms
... |
from django.apps import AppConfig
class PlaceEditorConfig(AppConfig):
name = 'good_spot.place_editor'
|
#Diccionario
edad = {}
edad["Juan"] = 32
edad["Ricardo"] = 26
edad["Antonio"] = 18
edad["Carla"] = 23
nombre = input("Busqueda: ")
if nombre in edad.keys(): #
print(nombre+ " esta en el diccionario. Tiene "+ str(edad[nombre])+ " años")
else:
print(nombre+ " no esta en el diccionario.")
print("Las siguientes p... |
import re
import musicbrainzngs
from .base import BaseScraper
musicbrainzngs.set_useragent("salmon", "1.0", "noreply@salm.on")
class MusicBrainzBase(BaseScraper):
url = site_url = "https://musicbrainz.org"
release_format = "/release/{rls_id}"
regex = re.compile("^https?://(?:www\.)?musicbrainz.org/rel... |
def ride_is_optimal(vehicle, ride):
if vehicle[4] == ride[4]:
return True
def write_output(vehicles):
submission = open('output.txt', 'w')
for vehicle in vehicles:
dim = len(vehicle[-1])
submission.write("%d " % dim)
for i in range(dim):
submission.write("%d " ... |
"""
Run all tests in a file called "tests.json" (should be located in the current directory
"""
from pathlib import Path
from os import path
import sys
import json
base_dir = Path(__file__).parent.resolve()
common_services_dir = (base_dir / '../src').resolve()
sys.path.insert(0, str(common_services_dir))
from baseli... |
from google.cloud import vision
import spacy
import io
import numpy as np
from PIL import Image
import tensorflow as tf
tf.enable_eager_execution()
IMAGE_SIZE = 64
EMBEDDING_SIZE = 300
# Read image files as byte array.
# Input(path: String), Output(byte array)
def read_image_bytes(path):
img = Image.open(path, "... |
#!/usr/bin/env python3
"""
This program generates meme by giving image and text. It provides save option
too!
"""
import os
import sys
import argparse
from PIL import Image, ImageDraw, ImageFont
def generate_meme(image_path, meme_text):
"""
Generate meme with image and text
"""
pic = Image.open(imag... |
import os
kafka_bootstrap_server_host = os.environ.get('KAFKA_BOOTSTRAP_SERVER_HOST', 'localhost:9092')
mongo_server_host = os.environ.get('MONGO_CLUSTER_URL', 'mongodb://localhost:27017,localhost:27018/?replicaSet=foo')
mongo_translator_db = os.environ.get('MONGO_TRANSLATOR_DB', 'anuvaad-etl-translator-db')
mongo_tra... |
import argparse
import os
import math
import ruamel.yaml as yaml
import numpy as np
import random
import time
import datetime
import json
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from models.model_captioning import XVLM
import utils
from utils.checkp... |
from flask import (abort, current_app, g, safe_join,
send_from_directory, url_for)
from flask.views import MethodView
from ..app_view import AppRouteView, response
from ..auth import login_required
from ..models import Asset, db
class ResourceFile(MethodView):
def get(self, content_type, clien... |
from Section3.UnitTests.SandwichCalculator import Calculator
class Menu:
def __init__(self, items):
self.items = items
def print_header(self):
print("~~~~~~~~~~ Melissa's Sandwiches ~~~~~~~~~~")
print("___________________________________________________ \n")
def print_menu(self):... |
#!/usr/bin/python3
import yaml
from optparse import OptionParser
import os.path
known_dirs = {}
includes = []
opts = set()
def process(options):
yaml_fname = options.yaml_filename
prefix = os.path.realpath(options.top_directory)
with open(yaml_fname, 'r') as f:
y = yaml.load(f, Loader=yaml.CLoad... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from enum import Enum
__all__ = [
'DataSourceKind',
'EntityStatus',
'MachineGroupType',
'SkuNameEnum',
]
class DataSourceKind(str, E... |
from . import credentials
from . import migrate |
from django.apps import AppConfig
class CmsContactsConfig(AppConfig):
name = 'cms.contacts'
label = 'cmscontacts'
|
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
def readme():
with open('README.MD', 'r') as fh:
return fh.read()
def get_version(rel_path: str):
codes = ''
with open(path.join(here, rel_path), 'r') as fh:
codes = fh.read()
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2019 sistemicorp
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... |
from __future__ import with_statement
from django.db import models
from django.db.models import Q
from django import forms
from django.utils.translation import ugettext_lazy as _
from sorl.thumbnail import default
__all__ = ('ImageField', 'ImageFormField')
class South(object):
"""
Just a south introspection... |
"""A collection of functions which have a known integral
when integrated over the unit sphere.
These functions take cartesian input, i.e. (x,y,z) from the unit sphere
and return a scalar f(x,y,z), together with the known integral.
The inputs x,y and z can also be numpy arrays, then also f(x,y,z) is an
array of the same... |
import numpy as np
from ..utils import download_dataset
# https://github.com/deepmind/dsprites-dataset
_urls = {
"https://github.com/deepmind/dsprites-dataset/blob/master/dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz": "dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz"
}
def load(path=None):
"""greyscale im... |
import pandas as pd
class DoctorPageParser(object):
def doctor_page_parser(self):
all_doctor_url = set()
# df = pd.read_csv('D:\PythonProject\gitClone\Python_play_now\songxin\L3\/all_doctor_csv', error_bad_lines=False,sep=',')
# print('用read_table读取csv文件:', df)
# for d in df:
... |
from spaceone.inventory.connector.aws_sns_connector.connector import SNSConnector
|
#!/usr/bin/env python
#
# Copyright the CoLL 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 law or ... |
def print_sum(a, b):
print(a+b)
print(__name__) |
import sqlalchemy
import flask_sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
from flask import Flask
import datetime as dt
import numpy as np
engine = create_engine("sqlite:///Resources... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: wxnacy(wxnacy@gmail.com)
"""
"""
from .git import Git
from .github import Github
__all__ = ['Git', 'Github']
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'fancyears'
__mtime__ = '2020/2/7'
# code is far away from bugs with the god animal protecting
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import csv
from typing import List
from pkg.pdfdoc import PDFdoc
class Auction46PDF(PDFdoc):
def get_bidders_from_txt(self, key: str, txt: str) -> List[str]:
lines = txt.splitlines()
found = False
result = list()
for l in l... |
import pandas as pd
from sklearn.decomposition import PCA
from matplotlib import pyplot as plt
from sklearn import preprocessing
df_Xtrain = pd.read_csv("./data/Xtrain.csv")
df_Xtest = pd.read_csv("./data/Xtest.csv")
df_Xtrain.drop(columns=['Unnamed: 0'], axis=1, inplace=True)
df_Xtest.drop(columns=['Unnamed: 0'], axi... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from datetime import datetime, timedelta
from backlogapiprocessmodule.utils.time_utils import TimeUtils
class Issue(object):
def __init__(self, issueKey, client, logger, beginDate, endDate):
self.issueKey = issueKey
self.client = client
self.lo... |
#standard libraries
import os
import glob
#external libraries
import numpy as np
import joblib
# from keras.applications.inception_v3 import InceptionV3 # ,preprocess_input
# from keras.applications.resnet50 import ResNet50
from keras.preprocessing.image import load_img, img_to_array
from keras.applications.inception_... |
# pylint: disable=R0201, C0116
"""
Test cases for AVA.data_wizard.FieldInfo
"""
import random
import pytest
from AVAPy import FieldInfo
class TestClassFieldInfo:
"""
Test cases for AVAPy.FieldInfo
"""
def test_valid_args(self):
"""
Invalid arguments should be handled.
"""
... |
from typing import List, Optional, Union
from vedro.core import Dispatcher, Plugin
from vedro.events import ArgParseEvent
from ._reporter import Reporter
__all__ = ("Director",)
class Director(Plugin):
def __init__(self, reporters: Optional[List[Reporter]] = None) -> None:
self._reporters = {r.name: r ... |
__author__ = 'matthew harris'
|
"""
ID: hsfncd31
LANG: PYTHON3
TASK: fence9
"""
import os
import typing
def main():
base_filename = 'test' if os.name == 'nt' else 'fence9'
with open('{}.in'.format(base_filename), 'r') as infile,\
open('{}.out'.format(base_filename), 'w') as outfile: # type: typing.IO[str]
def get_line()... |
"""Private prediction on combined features from several clients"""
import tf_encrypted as tfe
from common import LogisticRegression
from common import PredictionClient
num_features = 10
model = LogisticRegression(num_features)
prediction_client_0 = PredictionClient("prediction-client-0", num_features // 2)
prediction... |
def problem244():
pass
|
# 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 ... |
from dataclasses import dataclass
from pathlib import Path
DOCKER_ROOT = Path("/gobbli")
@dataclass
class ContainerTaskContext:
"""
Encapsulates filesystem organization for tasks which take some
input and produce some output using directories mapped between
the host and a container.
Provide nece... |
from . import launchable
import re
@launchable.subset
def subset(client):
prev_cls_name = None
for line in client.stdin():
match = re.match(r'^INSTRUMENTATION_STATUS: class=(.+)$', line)
if match:
cls_name = match.group(1)
if prev_cls_name != cls_name:
c... |
from gym_cellular_automata.forest_fire.helicopter.helicopter_v0 import (
ForestFireEnvHelicopterV0,
)
|
#!/usr/bin/python3
# import math
from math import pi
raio = 15.3
print('Área do círculo', pi*raio**2)
|
from stack import Stack
def multi_bracket_validation(input):
lefty = '({['
righty = ')}]'
ss = Stack()
for item in input:
if item in lefty:
ss.push(item)
elif item in righty:
if ss.top is None:
return False
if righty.index(item) != l... |
import unittest
import numpy as np
from sklearn import datasets
from sklearn import ensemble
from sklearn import tree
from sklearn import utils
from sklearn.utils import estimator_checks
import starboost as sb
class ScikitLearnL1Loss(sb.losses.L1Loss):
"""scikit-learn does two things different than StarBoost fo... |
# -*- coding: utf-8 -*-
"""
Test a forward pass of the different Torch neural network.
"""
import lmdb
import numpy as np
import torch
from .context import recoprot
DATA_DIR = "tests/data/diff_file"
PROT_NAME = "1A2K"
class OneProteinAtomsDataset(recoprot.AtomsDataset):
PROT_NAMES = [PROT_NAME]
class OnePro... |
"""
Module which contain definition for all algorithms used for training model
"""
from learner.models import (
bayes_model, logistic_regression_model, ada_boost_model, bayes_optimizer,
logistic_regression_optimizer, random_forest_classifier_model,
random_forest_regressor_model, xgboost_classifier, train_d... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from pages import index
from pages import page_1
from pages import page_2
print(dcc.__version__) # 0.6.0 or above is required
app = dash.Dash()
app.config.suppress_callback_exceptions = True... |
db_host_src = '10.10.10.1'
db_host_dst = '10.10.10.2'
TABLES_CHECK = {"test": ["table1"]}
DB_SOURCE = {'db_host': db_host_src,
'db_port': 3306,
'db_user': 'root',
'db_pass': '123456',
'db_charset': 'utf8mb4',
'result_charset': 'utf-8'}
DB_TARGET = {'db_host': d... |
from setuptools import setup
setup(
name='pytricks',
version='0.1.2',
py_modules=['pytricks'],
install_requires=['forbiddenfruit'],
description='python no more python'
)
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import numpy as np
import pandas as pd
from torch import nn
from torch import optim
from torch.utils.data import Dataset
from . import training_data
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__(... |
import nacl.secret
import nacl.utils
class Safe:
def __init__(self, key: str):
self.key = bytes.fromhex(key)
self.box = nacl.secret.SecretBox(self.key)
def decrypt_userinfo(self, encrypted: bytes) -> list:
return self.box.decrypt(encrypted).decode().split(", ")
def encrypt_userin... |
import xraylib
f = open("CompoundsNIST.dat", 'w')
header = """#F CompoundsNIST.dat
#C This file has been created by CompoundsNIST.py using xraylib
#C This file belongs to the DABAX library.
#C DABAX files are at: http://ftp.esrf.eu/pub/scisoft/DabaxFiles/
#UT NIST Compounds and Mixtures (formula, density and comp... |
#!/usr/bin/env python3
# Copyright 2020 Google LLC
#
# Licensed under the the Apache License v2.0 with LLVM Exceptions (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law ... |
import os
import psutil
from datetime import timedelta
import time
import numpy as np
import pandas as pd
from num2words import num2words
def genData(NX=3, num_active_tfs=2, NY=50, AvgNTF=0.5):
# Start generating simulated data
# The TFs: Number of TF and activation state of each
# the target genes: Numb... |
number = int(input())
if number%2 == 0 and ((number >= 2 and number <= 5) or number > 20):
print("Not Weird")
else:
print("Weird")
|
from __future__ import absolute_import, division, print_function, \
with_statement, unicode_literals
import pandas as pd
import numpy as np
import yaml
import warnings
from .._compat import string_types
from .internals import Attributes, Container, Coordinates, Variables
import xarray as xr
class Series(Containe... |
import json
import unittest
from bunch import bunchify
from ddt import ddt
from ddt import file_data
from google_analytics_pipeline.core.transform.map_protocol import MapMeasurementProtocolFn
@ddt
class TestMapProtocol(unittest.TestCase):
def setUp(self):
self.maxDiff = None
config_file_path = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Пример для первой лекции про TkInter
Закрытие окошка в постинтерактивном режиме
'''
from Tkinter import *
from random import randint
import random
TKroot = Tk()
TKroot.title("Hello")
root = Frame(TKroot)
root.place(relx=0, rely=0, relheight=1, relwidth=1)
root.co... |
from keras import backend as K
import numpy as np
import os
import os
import logging
import argparse
from tqdm import tqdm
from sklearn.metrics import accuracy_score,recall_score,f1_score,precision_score
import random
import torch
from sklearn import metrics
def zero_loss(y_true, y_pred):
return K.zeros_like(y_pr... |
# SPDX-FileCopyrightText: 2021 Wolfgang Traylor <wolfgang.traylor@senckenberg.de>
#
# SPDX-License-Identifier: MIT
import math
import os
import xarray as xr
from termcolor import cprint
from trace_for_guess.skip import skip
def get_longitude(dataset):
"""Get longitude dimension from XArray dataset object."""
... |
from django.urls import reverse
from .decorators import allow, datarequired, require
from .http import *
from .middleware import FrameworkCommonExceptionHandler
from .serializers import deserialize, serialize
from .tests import APIClient
def abs_reverse(request, viewname, args=None, kwargs=None, current_app=None):
... |
import pandas as pd
from ambient import Ambient
from compressor import Compressor
from tank import Tank
from turbine import Turbine
variables = ['dt',
'pwr_i','pwr_o', # Power
'm_tank', # Mass stored
'm0', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', # Mass flow
... |
import os
import random
import psycopg2
from discord import Embed, RawReactionActionEvent
from discord.ext import commands as c
from module import battle, db
class Cog(c.Cog):
def __init__(self, bot):
self.bot = bot
@c.command(description='ランキングが知れます')
@c.cooldown(10, 2, c.BucketType.user)
... |
def parse(source_str):
variables = {
"PTSIZE" : 512
}
conv_table = {
"\n" : 0x01,
"(" : 0x3a,
")" : 0x3b,
"," : 0x3c,
"-" : 0x3d,
"." : 0x3e,
"/" : 0x3f,
"?" : 0x5c,
"!" : 0x5d,
"+" : 0x8b,
"\'" : 0x8e,
... |
import chainer
import numpy
import tgan2
from tgan2.utils import make_instance
def _expand(option):
if isinstance(option, (list, tuple)):
return option
elif option:
return [2, 2, 2]
else:
return [1, 1, 1]
def subsample(x, stride=2):
offset = numpy.random.randint(stride)
... |
import sys
print(sys.version)
def main():
a = 0
for i in range(10):
print(i)
a += 1
if __name__ == '__main__':
main()
|
# echo.py
# echo mixin
from .event import Event
class EchoMixin(object):
"""
Adds functionality to print to IO driver
"""
def __init__(self):
self.on_echo = Event()
# call the next mixin constructor, if it exists
# this makes multiple inheritance work
super(EchoMixin... |
#!/usr/bin/env python3
import os
import re
import xml.etree.ElementTree as ET
import sys
# Parse our spec file
handled = []
fd = open('gles12api.py', 'r')
for line in fd:
if '#' in line:
try:
ext = re.search('# (GL_.*)', line).group(1).strip()
handled.append(ext)
except:
... |
import numpy as np
import quandl
from sklearn import preprocessing
from sklearn import model_selection
from sklearn import linear_model
from matplotlib import pyplot as plot
from sklearn.preprocessing import PolynomialFeatures
data_frame = quandl.get("YALE/SPCOMP")
data_frame.fillna(-100, inplace=True)
# We shift th... |
#!/usr/bin/python
# dumpuse.py
# Dump the servers' various usage stats to the log file.
from NewTraceFac import NTRC,ntrace,ntracef
import logoutput as lg
from globaldata import G,P
import util
#-----------------------------------------------------------
# d u m p S e r v e r U s e S t a t s
@ntracef("DMPU")
d... |
import numpy as np
from game.displays.null_display import NullDisplay
from game.displays.asci_display import ASCIDisplay
class RandomPlayer:
def __init__(self, player_no):
self.player_no = player_no
def get_input(self, board):
empty_indexes = np.where(board == 0)
zipped = np.column_stack(empty_indexes... |
#!/usr/bin/python
# 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... |
from typing import final
from matplotlib import image
import psycopg2
from psycopg2 import pool
from configparser import ConfigParser
import cv2
from Structs import Image, Tag, Video
from constants import BASE_PATH
class DBWrapper:
def __init__(self):
self.connPool = psycopg2.pool.ThreadedConnectionPool(1,8,data... |
from abc import ABC
from typing import Type
import peewee as pw
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse
class ExceptionHandler(ABC):
EXCEPTION: Type[Exception]
def __call__(self, request: Request, exc: Exception) -> Response:
raise NotImplementedErro... |
from logzero import logger
import tempfile
from pracmln import MLN
from approxWFOMC.logic import Constant
def convert2mln(clauses, domain_size):
"""
Clauses example:
[
[-aux1(X), -stress(X), smokes(X)],
[aux1(X), stress(X)],
[aux1(X), -smokes(X)],
[-aux2(X,Y), -friends(X,... |
from decouple import config
import random
import discord # https://pypi.org/project/discord.py/
from discord.ext import commands
import json
DISCORD_TOKEN = config('DISCORD_TOKEN')
DATAFILE_PATH = config('DATAFILE_PATH')
COMMAND_PREFIX = config('COMMAND_PREFIX', default='/')
REACTION_EMOJI = config('REACTION_EMOJI', d... |
from .baseagent import BaseAgent
import numpy as np
class AgentOnes(BaseAgent):
pass
# def get_action(self):
# return 0
|
# create miniImageNet dataset
import os, shutil
import random as rd
rd.seed(1)
data_dir = 'unchi0'
dst_dir = 'unchi1'
minitrain = open('outputs/sourcetrain.txt', 'w')
minival = open('outputs/sourceval.txt', 'w')
minitest = open('outputs/sourcetest.txt', 'w')
imagenet_train_dir = 'train.txt'
class_list =... |
import pytest
from utils.hots import nexuscompendium
class Tests:
def test_ranked(self):
try:
embed = nexuscompendium.ranked()
except:
pytest.fail("Ранкед не отвечает")
def test_sales(self):
try:
embed = nexuscompendium.sales()
except:
... |
from os import cpu_count
from lxml import etree
from utils import exetime
from configparser import ConfigParser, ExtendedInterpolation
import os
from pprint import pprint
from collections import namedtuple
from enum import Enum
import operator
cfg = ConfigParser(interpolation=ExtendedInterpolation())
cfg.read("config... |
# -*- coding: utf-8 -*-
extensions = [
'sphinx.ext.todo',
]
templates_path = ['_templates']
source_suffix = ['.rst', '.md']
master_doc = 'index'
project = u'resume'
copyright = '2015, Clayton Parker'
author = u'Clayton Parker'
language = None
# There are two options for replacing |today|: either, you set today to ... |
import pytest
@pytest.mark.asyncio
async def test_command_hooks(tile38_with_follower):
tile38 = tile38_with_follower
# TODO: test after tile38.set_hook
response = await tile38.hooks()
assert response.ok
response = await tile38.follower().hooks()
assert response.ok
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.