text stringlengths 3.07k 12.6k |
|---|
import math
# constants
FRAG_BINS = 46
#---------------------------------------------------------------------
# metrics function
#---------------------------------------------------------------------
def getMetrics(vals):
# handle zero case
if len(vals) == 0:
outvec = tuple([0] * 6)... |
# MIT License
# Copyright (c) 2018 the NJUNLP groups.
# 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, me... |
#!/usr/bin/env python3
"""Convert JWK from/to PEM and other formats"""
import argparse
import json
from binascii import hexlify
from getpass import getpass
from typing import Optional
from cryptography.hazmat.primitives import serialization
from cryptojwt.jwk import JWK
from cryptojwt.jwk.ec import ECKey
from crypto... |
"""Components on datasets"""
import numpy as np
from .base import DatasetBunch, RuleBunch
def load_intents_from_mysql(configs: dict) -> DatasetBunch:
"""
Load intent dataset from mysql database.
Parameters
----------
configs: Configs of mysql connnection, which includes keys:
"host" - h... |
# LiveTime Work-Stoppage Notifier
import json
import time
import smtplib
from email.message import EmailMessage
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.supp... |
from functools import lru_cache
import boto3
import itertools
from collections import defaultdict
from operator import itemgetter
from typing import List, MutableMapping
from django.conf import settings
from rest_framework.fields import (
BooleanField, CharField, ChoiceField, DateField, DecimalField, EmailField, ... |
import json
import logging
import re
import time
from urllib.parse import unquote
from anime_downloader.config import Config
from anime_downloader.sites import helpers
from anime_downloader.sites.anime import Anime, AnimeEpisode, SearchResult
logger = logging.getLogger(__name__)
NINEANIME_SITE_REGEX = re.compile(r"(... |
import tensorflow as tf
import sys
import os
import tf_util
import multi_model as resnet_model
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../utils'))
def placeholder_inputs(batch_size, num_point, resolution, views, devices):
pointcloud... |
# coding: utf-8
__author__ = 'ZFTurbo: https://kaggle.com/zfturbo'
import numpy as np
def nms_standard(dets, thresh):
scores = dets[:, 0]
x1 = dets[:, 1]
y1 = dets[:, 2]
x2 = dets[:, 3]
y2 = dets[:, 4]
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
order = scores.argsort()[::-1]
keep = []
... |
import wx
import wx.grid
#---------------------------------------------------------------------------
class SimpleGrid(wx.grid.Grid):
def __init__(self, parent, log):
wx.grid.Grid.__init__(self, parent, -1)
self.log = log
self.CreateGrid(25, 25)
self.SetCellValue(6, 3, "You can... |
from __future__ import absolute_import, division, print_function
import torch
from torch import nn
from utils.interpolation import interpolate2d, my_grid_sample, get_coordgrid
def post_processing(l_disp, r_disp):
b, _, h, w = l_disp.shape
m_disp = 0.5 * (l_disp + r_disp)
grid_l = torch.linspace(0.0,... |
#!/usr/bin/python3
#
# Copyright (c) <NAME>, 2020
# <EMAIL>
#
# SPDX-License-Identifier: MIT
#
import subprocess
import pprint as p
import results
import shutil
import regex
import sys
import re
import os
# Note: findings shall not repeat themselves, if found more than once
findings = {}
# function that adds a po... |
"""
@file
@brief Implements a transform which modifies the target
and applies the reverse transformation on the target.
"""
import numpy
from sklearn.exceptions import NotFittedError
from sklearn.neighbors import NearestNeighbors
from .sklearn_transform_inv import BaseReciprocalTransformer
class FunctionReciprocalTra... |
#!/usr/bin/env python
__all__ = ['render', 'show', 'set_scene']
import numpy as np
from ..vec3 import Vec3
from .helper import intersect, show, set_scene
class RayType:
kUnknownRay, kCameraRay, kShadowRay = range(3)
class Ray:
def __init__(self, orig, direction):
self.orig = orig
self.dir... |
import torch
import os
from tqdm.auto import tqdm
import numpy as np
import sys
from argparse import ArgumentParser
try:
import IBA
except ModuleNotFoundError:
sys.path.insert(0, '..')
import IBA
import model.cxr_dataset as CXR
import model.merged_visualize_prediction as V
import cv2
import mmcv
from eva... |
import sys
# import libraries
import nltk
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('averaged_perceptron_tagger')
#nltk.download()
import pandas as pd
from sqlalchemy import create_engine
from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer
from nltk.stem.wordnet import... |
#!/usr/bin/env python
# Source : Werkov, Github, PyQt4 examples
# URL : https://github.com/Werkov/PyQt4/tree/master/examples/dbus/chat
# This is only needed for Python v2 but is harmless for Python v3.
import sip
sip.setapi('QString', 2)
from PyQt4 import QtCore, QtGui, QtDBus
import time
import tensorflow as tf
im... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.conf import settings
from git import Repo
from book.models import book
from chapter.models import chapter
from version.models import version
from reader.mo... |
import shutil
from argparse import ArgumentParser, FileType, ArgumentDefaultsHelpFormatter
import errno
from collections import namedtuple
from functools import partial
from glob import glob
from logging import basicConfig, getLogger, DEBUG
import os
from multiprocessing import Pool
from random import shuffle
from subp... |
from SPARQLWrapper import SPARQLWrapper, JSON
import json
import requests
def setup_query(person_complete_name: str):
"""
Return the SPARQL query for obtaining gender, birthdate and nationality (if available) of the given person from
DBpedia
:param person_complete_name: person whose metadata are of in... |
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.engine import Layer
from utils import apply_regr
from non_max_suppression import nm_suppress
class ROIPoolingLayer(Layer):
""" Implements Region Of Interest Max Pooling
for channel-first images and relative bounding box ... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
import PIL
import torch
from PIL import Image
import torch.nn as nn
from log_utils import get_logger
from feature_transforms import wct, wct_mask
from encoder_decoder_factory import Encoder, Decoder
import torchvision.transforms.functional as transforms
log = get_logger()
def stylize(level, content, style0, encoder... |
"""Classes for coarsening operations (i.e., clustering, or local pooling."""
from abc import ABC, abstractmethod
import torch
from torch import LongTensor, Tensor
from torch_geometric.data import Data
from graphnet.components.pool import (
group_by,
avg_pool,
max_pool,
min_pool,
sum_pool,
avg... |
import menu
# repos
import users
import admins
import credentials
import books
import lending
import session
# views
import view
import listView
import credentialView
import userView
import booksView
import searchView
ADMIN_MENU = "admin"
def AddUser():
view.printTitle("Enter user details: ")
cred = credentialV... |
import uuid
from datetime import date
from datetime import timedelta
import mapbox
from django.conf import settings
from django.contrib.gis.db.models import MultiPolygonField
from django.contrib.gis.db.models import PointField
from django.contrib.gis.geos import GEOSGeometry
from django.db import models
from django.ur... |
# -*- encoding: utf-8 -*-
from app import db, login_manager
import datetime
import bcrypt
from flask_login import UserMixin
from sqlalchemy import Binary, Column, Integer, String, JSON
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
class User(db.Model, User... |
from typing import Type, Optional, List, Sequence, Callable, Dict
import marshmallow
from marshmallow.fields import Function
from marshmallow_sqlalchemy import ModelConverter, auto_field, SQLAlchemySchema
from sqlalchemy import Enum
from drf_json_api_utils import CustomField
from drf_json_api_utils.sql_alchemy.types ... |
import pandas as pd
import numpy as np
# Import and store dataset
credit_card_data = pd.read_csv('creditcard.csv')
# print(credit_card_data)
# Splitting data into 4 sets
# 1. Shuffle/randomize data
# 2. One-hot encoding
# 3. Normalize
# 4. Splitting up X/Y values
# 5. Convert data_frames to numpy arrays (float32)
# 6... |
import numpy as np
from tqdm.notebook import tqdm
import nltk
import pandas as pd
def calculate_path_weight(Graph, path):
weight = 0
start = path[0]
for i in path[1:]:
weight += Graph.Edges[(Graph.Edges['in'] == start[0]) & (Graph.Edges.out == i[0])].weight.values[0]
start = i
return w... |
"""Collect a sequence of zero, dark and flat exposures, e.g.
stxlcalib --url http://10.0.1.3 --nzero 3 --ndark 3 --tdark 1 --nflat 3 --tflat 0.5,1,2 --outpath calibdata
For more options, use stxlcalib --help.
"""
import time
import argparse
import os.path
import sys
import glob
import re
import logging
import numpy ... |
"""
migrate_journey.py
~~~~~~~~~~~~~~~~~
This script parses a directory containg json and jpeg files from a backup of the Journey Two App, prepare each post
and send them to a specific section in a OneNote notebook
- shrink images to specific width
- converts to UTF-8 and handles Umlaute
- creates a valid OneN... |
import readtime
import json
from rest_framework import serializers, status
from django.db import models
from django.template.defaultfilters import slugify
from rest_framework import status
from authors.apps.authentication.serializers import UserSerializer
from authors.apps.profiles.serializers import ProfileSerializer... |
import streamlit as st
import altair as alt
import json
import pandas as pd
import plotly
import plotly.express as px
import geojson
from urllib.request import urlopen
import Neighborhood
def addLatLonGeometry(df):
df.loc[:, 'lon'] = df.geometry.centroid.x
df.loc[:, 'lat'] = df.geometry.centroid.y
return df
ci... |
from sklearn.neighbors import KDTree
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
import os
import cv2
from obj_utils import save_obj_v
from obj_utils import OBJLoader
class kdtree(object):
def __init__(self):
self.leaf_size = 2
self.k = 1
def build(self,... |
import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
from metrics import accuracy_score
from model_slection import train_test_splice
from preprocessing import StandardScaler
class LogisticRegression:
"""docstring for LogisticRegression"""
def __init__(self):
self.coef_ = No... |
from datetime import datetime, timedelta
import time
import requests
import json
from matplotlib.pylab import date2num
from matplotlib import pyplot as plt
import mpl_finance as mpf
from pandas import DataFrame
import talib as ta
import sys
sys.path.append('..')
import DictCode as dc
plt.rcParams['font.family'] = 'sa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# __author__ = 'Liantian'
# __email__ = "<EMAIL>"
#
# Copyright 2015-2016 liantian
#
# 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:... |
'''
This module implements routines use to construct the yy_action[] table.
'''
from struct import *
from ccruft import struct
# The state of the yy_action table under construction is an instance
# of the following structure.
#
# The yy_action table maps the pair (state_number, lookahead) into an
# action_number. ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 9 18:27:43 2019
@author: smrak
"""
import os
import yaml
import h5py
import numpy as np
from datetime import datetime
from argparse import ArgumentParser
def makeGrid(ylim=[25,50],xlim=[-110,-80],res=0.5):
"""
Make a grid for an image with... |
import os
from multiprocessing import Pool
from dataclasses import dataclass
from functools import partial
import json
import numpy as np
import argparse
@dataclass
class Params:
num_general_tags: int
num_characters: int
general_tag_ids: dict[str, int]
character_ids: dict[str, int]
character_impli... |
'''
In P2P model, client not only is just client, it also serve as a server
Having a socket to listen to requests for local file chunk is essential here
'''
import socket
from time import sleep
import os
import json
import threading
with open("../macro.json", 'r') as f:
params = json.load(f)
FILESIZE = par... |
import ast
import typing
from typedpy import Array, Map, Structure
INDENT = " " * 4
def get_imports(path):
with open(path) as fh:
root = ast.parse(fh.read(), path)
for node in ast.iter_child_nodes(root):
level = 0
if isinstance(node, ast.Import):
module = []
elif... |
import sys
import warnings
from time import time
from datetime import datetime
import partools as pt
from . import g
from . import file
from . import string
def write_log(str_in):
s = str(str_in)
g.logs.append(s)
if not g.log_file_initialised:
return
with open(g.log_path, 'a', encoding='utf... |
""" Nome - RGA:
<NAME> - 2015.1905.006-2
<NAME> - 2016.1907.032-4
<NAME> - 2016.1907.024-3
<NAME> - 2016.1907.013-8
Utilizar versão 3.6 do python ou superior para correta execução do programa
"""
import csv
import copy
import random
import matplotlib.pyplot as plt
# arquivos
inputpath = "./input.... |
"""
"""
from django.utils import unittest
from django.test.utils import override_settings
from django.test.client import Client
from django.core import management
from django.conf import settings
from django.contrib.auth.models import User
if 'djcelery' in settings.INSTALLED_APPS :
from djcelery.models import TaskMet... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Pascal's triangle:
Get the nth row of Pascal's triangle and the nth fibonacci number using
Pascal's triangle.
NOTE: As this algorithm uses recursion, the maximum number you can go to depends
on the recursion limit on your machine.
Terminal Usage:
Usage: python pasca... |
# -*- coding: utf-8 -*-
# Copyright 2017 Kakao, Recommendation 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 a... |
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import itertools
import datetime
import logging
from collections import OrderedDict, namedtuple
import scraperwiki
from table_names import _RAW_SALES_TABLE
_SECTOR_NAME = {
'central-gov': 'Central government',
'local-g... |
import numpy as np
from scipy.optimize import check_grad
from value_iter import value_iter
from utils import norm_distr, laplace_distr, printoptions
def compute_g(mdp, policy, p_0, T, d_last_step_list, expected_features_list):
nS, nA, nF = mdp.nS, mdp.nA, mdp.num_features
# base case
G = np.zeros((nS, n... |
import os
import warnings
import numpy as np
import cv2
import create_patch
import caffe
import pdb
def get_patch(bottom_data, c, output_size):
h, w = bottom_data.shape[2:]
patch_img = np.zeros((3, c[4], c[4]))
im_r0 = max(0, c[2]-c[4]/2)
im_c0 = max(0, c[3]-c[4]/2)
im_r1 = min(h, c[2]+c[4]/2)
... |
import os
import random
import cv2
import numpy as np
import torch
import torchvision.datasets as datasets
import tqdm
from dg_util.python_utils import drawing
from dg_util.python_utils import pytorch_util as pt_util
from dg_util.python_utils.persistent_dataloader import PersistentDataLoader
from sklearn.decomposition... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018, <NAME> and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _, throw, _dict
from frappe.model.document import Document
from frappe.utils.data import format_datetime
from frappe.utils imp... |
import argparse
import copy
import datetime
import json
import pkg_resources
from .DirectoryStorage import DirectoryStorage
from .GetarStorage import GetarStorage
class Scope(dict):
"""Simple dictionary that can parse callbacks.
A callback can be registered for a key via `set_call`. Subsequent
calls to `... |
#!/usr/bin/python3
# Import the client module
import json
import bs4
from deluge.ui.client import client
# Import the reactor module from Twisted - this is for our mainloop
from twisted.internet import reactor
import requests
import pickle
import re
import os
import logging.config
import time
logging.config.dictConf... |
"""
Test did_lib
"""
import pytest
from contracts_lib_py import Keeper
from common_utils_py.agreements.service_agreement import ServiceTypes
from common_utils_py.ddo.ddo import DDO
from common_utils_py.ddo.public_key_base import PublicKeyBase
from common_utils_py.ddo.public_key_rsa import PUBLIC_KEY_TYPE_ETHEREUM... |
import torchvision.transforms as transforms
from torch.utils import data
from torchvision.datasets import CIFAR100 as TorchVisionCIFAR100
from torchvision.datasets import SVHN as TorchVisionSVHN
from . import base_dataset as basedat
from . import memory_dataset as memd
from .dataset_config import dataset_config
def ... |
#!/usr/bin/python
# ---------------------------------------------------------------------------
# File: facility.py
# Version 12.8.0
# ---------------------------------------------------------------------------
# Licensed Materials - Property of IBM
# 5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21
# Cop... |
import time
import wave
import numpy as np
import scipy as sp
from scipy import signal
from scipy.io import wavfile
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('dark_background') # comment out for "light" theme
plt.rcParams["font.size"] = 16
class Tracke... |
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
import scipy.integrate as integrate
from scipy.optimize import brentq as root
import math
import numpy as np
import scipy.special as scp
from scipy.special import iv
# In[2]:
def rvonmises(n, mu, kappa):
vm = np.zeros(n)
a = 1 + (1 + 4 * (k... |
from enum import Enum
from grapheme.grapheme_property_group import GraphemePropertyGroup as G
from grapheme.grapheme_property_group import get_group
class FSM:
@classmethod
def default(cls, n):
if n is G.OTHER:
return True, cls.default
if n is G.CR:
return True, cls.c... |
from _libtimetag import *
import numpy as _np
import dateutil as _dateutil_imported
def read_sstt_header(filepath):
"""Reads the header file of a small simple time-tagged (SSTT) dataset
Parameters
----------
filepath : str
Filepath to the header file
Returns
-------
... |
#!/usr/bin/python3
from operator import xor
_port = None
def open_port(dummy_arg):
global _port
_port = open(dummy_arg, "wb")
if _port:
print("Open successful")
else:
print("Open failed")
# only for Linux, to make the Mac-style simplecoremidi API work:
def send_midi(input_tuple):
... |
## https://github.com/dsmorgan/yacgb
import datetime
from datetime import timezone
from calendar import monthrange
import logging
from model.ohlcv import OHLCV
logger = logging.getLogger(__name__)
def max_array_size(timeframe, year, month):
if timeframe == '1m':
return(60)
elif timeframe == '1h':
... |
#
# Copyright <NAME> 2008
#
"""
Code to partition Transfac factors into equivalent sets.
"""
import biopsy.transfac as T
import biopsy
import boost.graph as bgl
from cookbook.lru_cache import lru_cache
class Graph(bgl.Graph):
__getstate_manages_dict__ = 1
"""So Boost.python knows we manage the object's dict.... |
"""This file contains all functions related to preprocessing."""
# pylint: disable=import-error
import os
import tqdm
import torch
import torchvision.transforms as transforms
# Data transformation
class DatasetTransformer(torch.utils.data.Dataset):
"""Apply transformation to a torch Dataset
"""
def __in... |
import neural_network_lyapunov.train_utils as train_utils
import unittest
import torch
import numpy as np
def setup_relu(relu_layer_width, params):
assert (isinstance(relu_layer_width, tuple))
dtype = torch.float64
def set_param(linear, param_count):
linear.weight.data = params[param_count:para... |
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import argparse
import schedule
import time
import datetime
import glob
# function to create directories
def create_dir(target_dir):
if not os.path.exists... |
"""
Version 1.0 (20/04/2016) - now supporting versioning.
uses clock, span, T, Class objects for easier time-handling.
Support for parsable output added. Use giveargs=True to add CSV info with
split as its seperator. Semicolon, tab or comma are usually good seperators.
Better code alignment: no line exceeds 8... |
day = '17'
with open(f'2020/data/day_{day}.in', 'r', encoding='utf-8') as f:
content = f.read().strip().split('\n')
def skopiraj(dic):
return {k:v for k, v in dic.items()}
def count_lit(grid):
return sum(v for v in grid.values() if v)
##############################
########## PART 1 ##########
###########... |
# On Python < 3, mind the single spurious PytestWarning:
# <https://github.com/pytest-dev/pytest/issues/4014>
from json import JSONDecoder, JSONEncoder
from pytest import raises, warns
try:
# For Python < 3; need the pure-Python version in order to subclass it
from StringIO import StringIO as _StringIO
except Imp... |
#!/usr/bin/env python
# coding: utf-8
# In[20]:
import webbrowser
import platform
import requests
from bs4 import BeautifulSoup
import re
from SaraModules import SaraSpeak
from SaraModules import SaraListen
import time
# MacOS
chrome_path = 'open -a /Applications/Google\ Chrome.app %s'
# Windows
# chrome_path = 'C:/Pr... |
import json
import random
import numpy as np
from tqdm import tqdm
from pathlib import Path
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn')
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.utils import save_image
from to... |
import logging
import json
import re
logger = logging.getLogger(__name__)
LIC_SERVER_STR = "License Server Location"
DUT_HOSTNAME_STR = "DUT Hostname"
ETH_INTF_STR = "Ethernet Interface"
IP_ADDR_ANVL_STR = "IP ANVL Address"
IP_ADDR_DUT_STR = "IP DUT Address"
IP_SUBNET_STR = "IP Subnet Mask"
IP_FST_UNUSED_NET_STR = "I... |
#!/usr/bin/env python3
import hashlib
import os
import sys
import time
import traceback
from collections import defaultdict
from jinja2 import Environment, FileSystemLoader
from watchdog.events import FileModifiedEvent, DirModifiedEvent
from watchdog.observers import Observer
from models import *
from records import... |
OLIVETTI_SHAPE = (64, 64)
def plot_olivetti_components(plt, images, title='Components'):
"""
Parameters
----------
images : list of np.array
"""
gallery_row = 2
gallery_col = 3
image_shape = OLIVETTI_SHAPE
plt.figure(figsize=(2. * gallery_col, 2.26 * gallery_row))
plt.suptitle(title, size=16)
for... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.modules.module import _addindent
from torch.utils.data import Dataset
import numpy as np
from collections import Counter
import pdb
import matplotlib.pyplot as plt
import os
from torch.autogr... |
#!/usr/bin/env python3
from contextlib import suppress
from functools import partial
import json
import logging
import signal
import sys
from blessed import Terminal
from . import style
from .lineinput import LineInput
from .nodeview import NodeView
from .utils import debug_time, signal_handler
__version__ = "0.1"
... |
from os import environ, path
import boto3
import time
# Credentials for testing outside of lambda function
# environ['AWS_SHARED_CREDENTIALS_FILE'] = path.join(path.dirname(__file__), "..", ".aws/credentials")
# environ['AWS_CONFIG_FILE'] = path.join(path.dirname(__file__), "..", ".aws/config")
APP_ID = "YOUR-APP-ID"... |
import random
import functools
from lib.resources import Coal, Oil, Garbage, Nuclear
@functools.total_ordering
class Player:
def __init__(self, pid, color):
self.pid = pid
self.color = color
self.active = False
self.cash = 50
self.auction_rights = True # Cleared each t... |
import os
import tempfile
import unittest
from ufotest._testing import UfotestTestMixin
from ufotest.plugin import PluginManager
from ufotest.hooks import Action, Filter
class TestPluginManager(unittest.TestCase):
def test_construction_works(self):
pm = PluginManager()
self.assertIsInstance(pm, ... |
# 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 agreed to in writing, ... |
from typing import NamedTuple, List, Tuple
import numpy as np
import tensorflow as tf
from tensorflow import keras
import vae_loss
class EncoderConfig(NamedTuple):
"""NamedTuple for configuring a Conv2D layer in an encoder.
Fields:
filter: num filters in layer
kernel_size: kernel size in la... |
"""
Custom model fields to link to CMS content.
"""
from collections import defaultdict
from django.core.exceptions import ValidationError
from django.db import models
from any_urlfield.models.values import AnyUrlValue
from any_urlfield.registry import UrlTypeRegistry
from any_urlfield.validators import ExtendedURLVa... |
import os
import pandas as pd
import numpy as np
from itertools import chain
from pmaf.internal._extensions._cpython._pmafc_extension._helper import (
make_sequence_record_tuple,
)
from pmaf.internal.io._seq import SequenceIO
from typing import Generator, Tuple, Union
def read_qiime_taxonomy_map(taxonomy_tsv_fp: ... |
"""Sensor for the Bitvavo integration."""
import logging
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import BitvavoDataUpdateCoordinator
from .const import (
ASSET_VALUE_BASE... |
"""
SC101 Baby Names Project
Adapted from <NAME>'s Baby Names assignment by
<NAME>.
NAME: <NAME>
This program creates the GUI for Ethan Huang's Baby Names project.
The data used in this project is the Top 1000 baby's name from 1990 to 2010
collected from http://www.ssa.gov/OACT/babynames.
Each name shown on the can... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance ... |
import csv
import json
import logging
import os
import re
from collections import OrderedDict
from io import BytesIO, StringIO
from zipfile import ZipFile
from urllib.parse import urljoin
import json_merge_patch
import requests
from ocdsextensionregistry import ExtensionRegistry
from ocdsdocumentationsupport.models i... |
"""
CS141 Assignment2_Shortpath
Author : <NAME>
UC Riverside, Nov. 30 2016
"""
#!/usr/bin/python
import sys
import re
import time
import os
graphRE=re.compile("(\\d+)\\s(\\d+)")
edgeRE=re.compile("(\\d+)\\s(\\d+)\\s(\\d+)")
vertices=[]
edges=[]
#the format of out put is Trace, xnn means the lenths
# 0 1 ... |
import os
import sys
from collections import defaultdict
from random import choice, uniform
from math import radians
from tempfile import gettempdir
from operator import itemgetter
from datetime import datetime
import bpy
import mathutils
# Update Blender's Python import path
sys.path.append(os.path.dirname(__file__)... |
from django import forms
from .models import *
class SearchForm(forms.Form):
form_residence_options = [('all', 'All')] + Domicile.residence_options
residence_type = forms.ChoiceField(
label="Residence type", choices=form_residence_options, required=False)
pet_friendly = forms.BooleanField(label="A... |
from flask import Flask, make_response, render_template, session, url_for, request, redirect
from datetime import datetime
from collections import defaultdict
import os
import uuid
import json
from gcos import vignette, score_test
from mvs import get_shuffled_vignette, vignette as mvs_vignette
from experiment import g... |
from __future__ import division # only for Python 2
import numpy as np
from sklearn import datasets
from sklearn import svm
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.model_selection import train_test_split as tts
from sklearn.metrics import a... |
#!/usr/bin/python
# coding: utf-8 -*-
# (c) 2019, T-Systems International
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
import time
from queue import Queue
from data_sender import send
import argparse
from threading import Thread, Event
import cv2
import numpy as np
from redis import Redis
import pickle
import torch
from models import TSN
from baseline_rpc_rgb import make_ucf, make_infer, make_hmdb
from sklearn.metrics import confusion_... |
import pytest
import uuid
from gaea.rbmq import RBMQPublisher
from gaea.rbmq.utils.tests import MockRBMQConnectionManager
from gaea.models.utils.test import IDS
def test_get_hives(auth_token, test_app):
response = test_app.get("/hive")
assert response.status_code == 401
response = test_app.get("/hive", ... |
"""Azely's object module (mid-level API).
This module mainly provides ``Object`` class for information of an astronomical
object (object information, hereafter) and ``get_object`` function to search for
object information as an instance of ``Object`` class.
The ``Object`` class is defined as
``Object(name: str, frame... |
from LPfunctions import *
from LPsolver import lp
from games.price_of_anarchy import res_poa, res_opt_f, worst_game
from kroundempty import kroundLP
from prettytable import PrettyTable
import matplotlib.pyplot as plt
def pobUpperWithf(w, f):
def uppart(N):
part = [()]*round((N+1)*(N+2)/2)
c = 0
... |
# -*- coding: utf-8 -*-
from . import settings, config
from . import install
from .oset import OrderedSet
from .adict import AttrDict
from .package import Package, PKG_STATUS_STR, PKG_STATUS_NAMES
from .utils import print_graph, print_array
from .output import ( info as _,
warn as _w,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.