text stringlengths 3.07k 12.6k |
|---|
import numpy as np
from PIL import Image, ImageOps, ImageFilter
import random
import torch
from torchvision import transforms
import cv2
def crop(img, mask, size):
# padding height or width if smaller than cropping size
w, h = img.size
padw = size - w if w < size else 0
padh = size - h if h < size els... |
import logging
from datetime import datetime, timedelta
from textwrap import shorten
import rumps
from humanfriendly import format_timespan
from noko import Noko
from timeular import Zei
from config import NOKO_TOKEN, ORIENTATION_MAPPING
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(thread... |
# coding: utf-8
# main.py the api core
# Created by S4n1x-d4rk3r
from bs4 import BeautifulSoup
from flask import Flask, jsonify, request
import requests, sqlite3
from hashlib import md5
from datetime import datetime
import time
conn = sqlite3.connect('./flashit.db')
c = conn.cursor()
c.execute('create table if not ex... |
# Get prediction tag from our trained model: detect all images in a directory (no face detection)
"""
Evaluates a folder of video files or a single file with a xception binary
classification network.
Usage:
python detect_from_video.py
-i <folder with video files or path to video file>
-m <path to model file>
... |
import os
import os.path
import re
import codecs
import fnmatch
import logging
import itertools
from .utils import (PageNotFoundError, NamespaceNotFoundError,
split_page_url)
META_ENDPOINT = '_meta'
logger = logging.getLogger(__name__)
valid_filename_pattern = re.compile('^[\w \.\-\(\)\[\]\\/]+$... |
#!/usr/bin/env python3
# Copyright 2022 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import os
import sys
import json
import subprocess
import tempfile
from dataclasses import dataclass
from typing import... |
from discord.ext import commands
from __main__ import send_cmd_help
from .utils.dataIO import dataIO
import datetime
import discord
import os
try:
import psutil
except:
psutil = False
class Statistics:
"""
Statistics
"""
def __init__(self, bot):
self.bot = bot
def redapi_hook(se... |
"""Dataset loader"""
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.utils.class_weight import compute_class_weight
import tensorflow as tf
from tensorflow.keras.datasets import cifar10, cifar100
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import glob
from o... |
"""
File: babygraphics.py
Name: <NAME>
-----------------
SC101 Baby Names Project
Adapted from <NAME>'s Baby Names assignment by
<NAME>.
-----------------
This file will create a canvas and enable user to
use the program to search for babes' names' ranks
over decades.
Once the user search a name, the corresponding rank... |
#! /usr/bin/env python
# by caozj
# 20 Dec 2017
# 10:34:35 AM
import os
import sys
import argparse
import time
import numpy as np
import scipy.stats
import Cell_BLAST as cb
import utils
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
def parse_args():
parser = argparse.ArgumentParser()
# I/O
parser.add_argu... |
#Libraries required
import json
import requests
from flask import Flask, jsonify, request
import datetime
from urllib.parse import urlparse
import hashlib
from uuid import uuid4
##########################
## creating the BLOCKCHAIN ###
##########################
class BLOCKCHAIN:
def __init__(self):
self.c... |
from flask import copy_current_request_context
from flask_socketio import emit, disconnect, join_room
from flask_login import current_user
from app import socketio,db
from app.models import Post, Game, Chapter, Scene
from app.game.roll_parser import roll_msg
# ---- Helper Functions ----
def _pyobj_to_obj_list(object... |
import argparse
import numpy as np
import random
from itertools import count
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
import matplotlib
from matplotlib.pylab import plt
from kalah.kalahboard import KalahBoard
from kala... |
import json
import os
import re
import threading
import js2py
import requests
from bs4 import BeautifulSoup as soup
class PornhubVideo(object):
__link = 'https://www.pornhub.com'
def __init__(self, url_or_viewkey, ifGetInfo=False):
if 'http' in url_or_viewkey:
self.__pageUrl = url_or_vi... |
import configparser
import cv2
import numpy as np
import time
from matplotlib import pyplot as plt
HORIZONTAL_MAX_DIFF = 20
KEY_ESCAPE = 27
COLOR_ORANGE = (0,128,255)
COLOR_MAGENTA = (255,0,255)
COLOR_GREEN = (0,255,0)
COLOR_RED = (0,0,255)
COLOR_BLUE = (255,0,0)
# Read local file `config.ini`
config = configparser.C... |
import os
import re
import logging
from datetime import datetime
from dateutil import tz
from todoist.api import TodoistAPI
from todoist.managers.notes import NotesManager
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
TODOIST_DATE_FORMAT = "%Y-%m-%d"
def get_token():
token = os.getenv('TODO... |
# coding: utf-8
import numpy as np
from matplotlib.gridspec import GridSpec
# from matplotlib.patches import Rectangle
def nonzero_intervals(vec, gap=1):
edges, = np.nonzero(np.diff((vec==0)*1))
edges += 1
if vec[0] != 0:
edge_vec = [[0], edges]
else:
edges[0] = 0
edge_vec =... |
import logging
import socket
import boto3
import time
from string import Template
from botocore.exceptions import ClientError
from psutil import virtual_memory
from ec2_metadata import EC2Metadata
import multiprocessing
logger = logging.getLogger("configbutler")
class UnsafeSubstitution(Exception):
def __init... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
__author__ = "bibow"
import json, traceback, logging
from graphene import (
Field,
ObjectType,
Schema,
Mutation,
Boolean,
String,
DateTime,
Int,
List,
)
from silvaengine_utility import Utility
from data... |
#
# Copyright 2019 <NAME>, <NAME>, <NAME>
#
# 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... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import sys
#sys.path.append('/home-link/qeana10/bin/PyVCF-0.6.0')
import csv
#import vcf
from collections import defaultdict
def extractXLSdata(xlsFilename):
xlsFile = open(xlsFilename, 'r')
csvreader = csv.DictReader(xlsFile, delimiter='\t')
resultsDict = defaultdict(list)
for row in csvreader... |
"""
Image Downloader
Downloads image from website and label them manually during saving
By: Xiaochi(George)Li/Mar.2020
"""
from typing import Dict, List
import urllib.request
from bs4 import BeautifulSoup
import re
import requests
import os
from tqdm.auto import tqdm
import cv2 as cv
import numpy as np
website = "htt... |
#coding: utf-8
from core.classifier import * #classifier class
import core.xyz as xyz #coorddb class (holds the data)
import math
#sklearn module - does the classification
from sklearn import svm
from sklearn import linear_model
from sklearn import preprocessing
class SVM_G (svm.SVC):
def __init__(self, en... |
# -*- mode: python; tab-width: 4; indent-tabs-mode: t; python-indent: 4 -*-
from kctllib.kdatabase import *
from kctllib.kparams import *
from kctllib.kkeys import *
# kpython
from kreadline import Command
from misc import *
class LsKeysCommand(Command):
Name = "lskeys"
Syntax = ""
Help = "List all keys in datab... |
"""
Helper functions specifically for the
profile asimilation coupled with Obs study
"""
import os, sys
import numpy as np
import pandas as pd
import xarray
from scipy.interpolate import interp1d
# manually add a2e-mmc repos to PYTHONPATH if needed
module_path = os.path.join(os.environ['HOME'],'tools','a2e-mmc')
if mo... |
import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
N = 80
X = np.arange(-3.9, 4 + 1e-10, 0.1)
REPS = 1000
A = 2
B = 2
def lad(smp_x, smp_y):
def med(smp):
return (smp[N // 2 - 1] + smp[N // 2]) / 2 if N % 2 == 0 else smp[(N - 1) // 2]
def ... |
"""Utility methods for computing the performance metrics."""
from matching import Matching
from rectangle import Rectangle
def safe_divide(numerator, denominator):
"""Computes the safe division to avoid the divide by zero problem."""
if denominator == 0:
return 0
return numerator / denominator
def compute... |
# ex: set sts=4 ts=4 sw=4 noet:
# -*- coding: utf-8 -*-
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##... |
#
# SPDX-License-Identifier: Apache-2.0
#
# Copyright 2020 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
import numpy as np
import pytest
import xarray as xr
from numpy.testing import assert_array_equal
from openeo_driver.save_result import AggregatePolygonResult
from shapely.geometry import GeometryCollection, Polygon
from openeo.metadata import CollectionMetadata
def test_aggregate_polygon_result_basic(tmp_path):
... |
__all__ = ['upwindFirstENO3bHelper']
import copy
import logging
import cupy as cp
import numpy as np
from LevelSetPy.Utilities import *
logger = logging.getLogger(__name__)
def upwindFirstENO3bHelper(grid, gdata, dim, direction):
"""
upwindFirstENO3bHelper: helper function for upwindFirstENO3b.
Returns... |
import abc
import json
from transformers import GPT2Tokenizer
from .core import GPT
class BasePrompt(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def text(self):
raise NotImplementedError
def tokens(self, *args, **kwargs):
if not args or kwargs:
text = self.text... |
"""Utilities for API authorization."""
import json
import casbin
import casbin_sqlalchemy_adapter
from functools import wraps
from six.moves.urllib.request import urlopen
from jose import jwt
from flask import request, _request_ctx_stack
from flask_cors import cross_origin
from server import app, api
# CASBIN Set... |
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
sns.set_style({'font.sans-serif':['simhei','Arial']})
def price_comparation():
shanghai = pd.read_csv('sh.csv')# 将已有数据导进来
shanghai.dropna(inpl... |
#! /usr/bin/python
import os
import sys
import json
import luigi
import numpy as np
import nifty.tools as nt
import cluster_tools.utils.volume_utils as vu
import cluster_tools.utils.function_utils as fu
from cluster_tools.cluster_tasks import SlurmTask, LocalTask, LSFTask
class BackgroundSizeFilterBase(luigi.Task)... |
# @Author: <NAME> <xuan>
# @Date: 2019-12-22, 12:19:37
# @Last modified by: xuan
# @Last modified time: 2019-12-22, 1:34:14
from common import *
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def l2_norm(input, axis=1):
... |
# Copyright (c) 2010 <NAME>
# Copyright (c) 2010-2011 dequis
# Copyright (c) 2010, 2012 roger
# Copyright (c) 2011 <NAME>
# Copyright (c) 2011-2012, 2014 <NAME>
# Copyright (c) 2012 dmpayton
# Copyright (c) 2012-2013 <NAME>
# Copyright (c) 2013 hbc
# Copyright (c) 2013 <NAME>
# Copyright (c) 2014 <NAME>
#
# Permission ... |
#province.py
import functools
from flask import Blueprint, render_template, request, session, jsonify
from werkzeug.exceptions import abort
from werkzeug.utils import redirect
from app import models,utils,service
from app.services import testing_service
province = Blueprint('province',__name__)
def admin_required(f... |
# Hamiltonian Neural Networks | 2019
# <NAME>, <NAME>, <NAME>
import numpy as np
import gym
import scipy, scipy.misc
import os, sys
sys.path.append(os.path.join(os.path.dirname("__file__"), '..'))
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
from ..utils import to_pickle, from_pickle
def g... |
import shlex, sys
# Table to reference command name to opcode
opcode_table = {
"ld" : "00000",
"ldi" : "00001",
"st" : "00010",
"ldr" : "ERROR",
"str" : "ERROR",
"add" : "00011",
"sub" : "00100",
"and" : "00101",
"or" : "00110",
"shr" : "00111",
"shra" : "01000",
... |
import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from pattern.web import Crawler, DEPTH, BREADTH, FIFO, LIFO
# This example demonstrates how to use the Crawler class for web crawling.
# --------------------------------------------------------------------------------------------... |
# coding=utf-8
from setproctitle import setproctitle
from utils import SensorConsumerBase
import datetime
import os
import sys
import json
class FridgeInside(SensorConsumerBase):
THRESHOLD_CONFIG = {
"fridge_temperature2": {
"notification": "fridge-temperature",
"message": "Jääkaa... |
from web_interface import persistents
import os
import pickle
from random import randint
from random import shuffle
import numpy as np
import tensorflow as tf
import lymph.utils.StackedAutoEncoder as SAE
def classification_service(train_folder: str, test_folder: str):
return _train(train_folder, test_folder)
de... |
"""
Generator of documentation from the Pydoc-strings.
"""
import re
import inspect
import types
import enum
def prettify(text):
pattern = re.compile(r"\`[A-Za-z._\(\)]+\`")
p = 0
new_text = ''
for m in pattern.finditer(text):
s, e = m.span()
new_text += text[p:s]
new_text +=... |
#! /usr/bin/env python
# encoding: UTF-8
# <NAME>
# <NAME> 2008
import re
import Task, Utils, Logs
from TaskGen import extension, taskgen, feature, after
from Configure import conf
import preproc
"""
Welcome in the hell of adding tasks dynamically
swig interface files may be created at runtime, the module name may b... |
# TODO: Missing script docstring. How should this script be run? What is this for?
# -------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license in... |
import inspect
import sys
import time
import discord
from helpers.embed_builder import EmbedBuilder
from helpers.misc_functions import (author_is_mod, is_integer,
is_valid_duration, parse_duration)
from commands.base import Command
class UnBanCommand(Command):
def __init__(se... |
import numpy as np
import cv2
from renderer import plot_sdf
SHAPE_PATH = '../shapes/shape/'
SHAPE_IMAGE_PATH = '../shapes/shape_images/'
TRAIN_DATA_PATH = '../datasets/train/'
VAL_DATA_PATH = '../datasets/val/'
SAMPLED_IMAGE_PATH = '../datasets/sampled_images/'
HEATMAP_PATH = '../results/true_heatmaps/'
CANVAS_SIZE =... |
import logging
from dataclasses import dataclass
from sylo.definitions import (
TIMER_DEFAULTS,
CONFIG_FILE_LOCATION,
SQLITE_DB,
)
from sylo.utils import check_for_file, mins_to_secs, get_today
import tomli
import sqlite3
logger = logging.getLogger(__name__)
@dataclass
class Rest:
mins: int = TIMER_... |
"""
Plotting reduction sizes
"""
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
RESULTS_FOLDER = os.path.join(os.path.dirname(__file__), "..", "timings")
DELTAS = [0, 0.01, 0.05, 0.1]
def load_times():
return pd.concat([pd.read_csv(os.path.join(RESULTS_FOLDER, fname), index... |
#!/usr/bin/env python
from __future__ import (absolute_import, division, print_function,
unicode_literals, generators, nested_scopes, with_statement)
from builtins import (bytes, dict, int, list, object, range, str, ascii,
chr, hex, input, next, oct, open, pow, round, super, filter, map, zip)
# The above imports... |
from pathlib import Path
from fastai2.learner import load_learner
from subprocess import run, PIPE
import sys
import json
from ml.vector_processing import (
unify,
sparsify,
intersection,
shapely_to_geojson,
)
from ml.raster_processing import (
inference_to_poly,
merge_chips,
inference_to_ge... |
import math
import pygame as pg
from OpenGL.GL import *
from OpenGL.GLU import *
def mouseMotion(dx, dy):
global rot
dx /= 8
dy /= 8
rot[0] += dy
rot[1] += dx
if rot[0] > 90:
rot[0] = 90
elif rot[0] < -90:
rot[0] = -90
def updatePosition():
global p... |
import json
import logging
import math
from copy import deepcopy
import numpy as np
from qcelemental.models import AtomicInput, AtomicResult, Molecule
from qcelemental.util.serialization import json_dumps
from . import history
from .exceptions import OptError
class ComputeWrapper:
"""An implementation of MolSSI... |
import re
import os
import tools.naming_files_folders as naming
from project_root import *
import pickle as pk
import numpy as np
import pandas as pd
from tools.parsetxt import __try_load_cpp
author_2_pickle_loc = {
x: proot(x, 'pickles_txt') for x in naming.authors
}
author_2_workspace_loc = {
x: proot(x, 'pi... |
import re
from .exceptions import ClassValidationException
class Tokenizer:
"""
base tokenizer
"""
@classmethod
def tokenize(cls, input_str):
pass
class ClassTokenizer(Tokenizer):
"""
class tokenizer
creates tokens for all class components
"""
@classmethod
def ... |
# coding: utf-8
"""
Interface for isCAN from Thorsis Technologies GmbH, former ifak system GmbH.
"""
from __future__ import absolute_import, division
import ctypes
import time
import logging
from can import CanError, BusABC, Message
logger = logging.getLogger(__name__)
CanData = ctypes.c_ubyte * 8
class Message... |
# Import external modules
from collections import Counter
import hashlib
import logging
import random
import re
import sys
# Import app modules
from configAutocomplete import const as conf
# Assumes that keys are integers, but may return float between keys
def medianKey( keyToCount ):
if keyToCount is None: ret... |
##
# author: <NAME>
# email: <EMAIL>
#
# Chsmartbulb controler
# Similar to this one: https://github.com/pfalcon/Chsmartbulb-led-bulb-speaker,
# but I change some socket value and it work!
# The code can control the bulb with "ilight pro" app can control.
# Only can control the color, the color or white/yellow mode.
#
... |
import os
import sys
import numpy as np
# Root directory of the project
from PIL import Image
ROOT_DIR = os.path.abspath(".")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
sys.path.append("/content/backlash") # To find local version of the library on Google Colab
from mrcnn i... |
import logging
from typing import Dict, Optional
from python_hosts import Hosts
from semver import VersionInfo
from tabulate import tabulate
from daktari.check import Check, CheckResult
from daktari.command_utils import get_stdout
from daktari.os import OS, check_env_var_exists, get_env_var_value
from daktari.version... |
import json
import os
import boto3
import zipfile
import csv
import datetime
import urllib
accountnumber = os.environ['accountnumber']
bucketname = os.environ['bucketname']
snstopic = os.environ['snstopic']
dayintervalStart = os.environ['dayintervalStart']
dayintervalEnd = os.environ['dayintervalEnd']
'''
Here is the... |
"""Tools to extract (but not create) pdf annotations."""
from __future__ import annotations
import json
import logging
import os
from collections import defaultdict
from typing import Any, Dict, List, Optional, Union
from PyPDF2.generic import ByteStringObject, IndirectObject
from PyPDF2.pdf import PageObject
from p... |
import numpy as np
import pandas as pd
from lyrics_api import *
import requests
from bs4 import BeautifulSoup
import urllib
import urllib.request
from googletrans import Translator
from tensorflow import keras
import vectorize_data
# Declaring global variables
# This method is to allow to call from other python fi... |
import numpy as np
import load_mnist
TAKE = 30000
def train_test_split():
train_img = load_mnist.read_idx('train-img.data')[:TAKE]
train_labels = load_mnist.read_idx('train-labels.data')[:TAKE]
test_img = load_mnist.read_idx('test-img.data')
test_labels = load_mnist.read_idx('test-labels.data')
train_img... |
import itertools
import os
import matplotlib as mpl
# mpl.use('Agg') # back-end to run without X server
import matplotlib.pyplot as plt
import math
import sympy.ntheory as nt
import rsabias.core.features as features
class State:
def __init__(self, fig, ax, cols, rows):
self.fig = fig
self.ax = ... |
""" ksconf.builder.steps: Collection of reusable build steps for reuse in your build script.
"""
from __future__ import absolute_import, unicode_literals
import re
import sys
from shutil import copy2, rmtree
from ksconf.builder import QUIET, VERBOSE, BuildStep
if sys.version_info < (3, 6):
# Allow these stdlib ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Tortenproblem
https://www.programmieraufgaben.ch/aufgabe/das-tortenproblem/8ijpjc7u
"""
# Programmieraufgabe:
# k Kinder erhalten t Torten.
#
# Die Torten sind alle gleich groß, haben aber verschiedene
# Geschmacksrichtungen. Die Torten werden zunächst je... |
import argparse
import os.path
import pathlib
import random
import numpy as np
import tensorflow as tf
from tensorflow.keras.mixed_precision import experimental as prec
import la_mbda.env_wrappers as env_wrappers
import la_mbda.utils as utils
def define_config():
return {
# LAMBDA
'horizon': 15,... |
"""
Copyright (c) <NAME> and <NAME>
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import numpy as np
class BoundingBox(object):
"""BoundingBox class
"""
def __init__(self, bbox, dtype=np.int):
if isinstance(bbox, Boundi... |
# Copyright 2019 <NAME>
# See LICENSE for details
import functools
from dataclasses import dataclass
from enum import Enum
from typing import Tuple, Dict, Union
from FIT.base_types import BaseType, UnsignedInt8, UnsignedInt16, UnsignedInt32
class Architecture(Enum):
LittleEndian = UnsignedInt8(0)
BigEndia... |
import os
import re
import sys
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from distutils.version import LooseVersion
import subprocess
__pkg_name__ = 'pepper'
__author__ = '<NAME>'
__description__ = 'RNN based genome inference tool.'
class CMakeExtension(Extension):
... |
# Get MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# Create session
import tensorflow as tf
# Placeholder to store our images
x = tf.placeholder(tf.float32, [None, 784])
# Placeholder to store our labels
y_ = tf.placeholder(tf.floa... |
from torch import nn
import torch.nn.functional as F
import numpy as np
from PIL import Image
import os
import shutil
from config import cfg
import pdb
import math
def weights_normal_init(*models):
for model in models:
dev=0.01
if isinstance(model, list):
for m in model:
... |
#!/usr/bin/python3
import tkinter as tk
import tkinter.filedialog as filedialog
from tkinter import ttk
from collections import deque
from multiprocessing import Process, Queue, freeze_support
from threading import Thread
#from tqdm import tqdm
import os
import signal
multi_queue = Queue()
DELAY_PROGRESS = 50
DELAY_C... |
# https://deeplearningcourses.com/c/support-vector-machines-in-python
# https://www.udemy.com/support-vector-machines-in-python
from __future__ import print_function, division
from builtins import range
# Note: you may need to update your version of future
# sudo pip install -U future
import numpy as np
import pandas ... |
"""
SQL expressions module
"""
from abc import abstractmethod
class ExprABC:
""" Expression Abstract class """
def op(self, *args): # 1st: op, 2nd: y (optional)
""" Get unary or binary expression """
if len(args) > 2:
raise RuntimeError('Too many arguments.')
if len(a... |
from django import forms
from django.forms import ModelForm
from django.utils.translation import ugettext as _
from django.utils.html import escape
from recursos.models import *
# Usuarios
class LoginForm (forms.Form):
name = forms.CharField (label = 'Nombre de usuario',
max_length = 30,
require... |
# -*- encoding:utf-8 -*-
import pytest
from hippy.objspace import getspace
from .test_interpreter import BaseTestInterpreter
from hippy.locale import rsetlocale, strcoll_u
from rpython.rlib.rlocale import LC_CTYPE, LC_COLLATE, LocaleError
def has_locales(*locales):
"""Check if te locales are available on the syst... |
#!/usr/bin/env python3
#
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
from torch.distributions import Distribution
import torch
from copy import deepcopy
from typing import TypeVar, Callable, Union, Tuple
from torch.nn import Module, Parameter
from abc import ABC
from functools import lru_cache
from .state import NewState
from ..distributions import DistributionWrapper
from ..typing impo... |
# !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) <NAME>, 2021
# All rights reserved
# @Author: '<NAME> <<EMAIL>>'
# @Time: '7/2/21 10:22 AM'
# sys
import functools
import time
import typing as t
from inspect import isgenerator
# 3p
import grpc
from grpc.experimental import wrap_server_method_handler
from p... |
import unittest
import sys
from os.path import dirname, abspath
import numpy as np
from scipy.stats import spearmanr, pearsonr
from halla.utils import stats
from utils import compare_numpy_array
class TestStatsUtils(unittest.TestCase):
'''Tests the p-value permutation test function; extreme cases
'''
def ... |
import re
from django.conf import settings
from evennia.utils.ansi import strip_ansi
from evennia.utils.utils import make_iter, to_str, wrap
def capitalize(text):
#allow ellipses to force lower case.
if not "..." in text[0:4]:
list_text = text
if text.startswith("|"):
list_text = te... |
class MR_FDUM(nn.Module):
def __init__(self):
super(MR_FDUM, self).__init__()
self.avgpool = paddle.nn.AdaptiveAvgPool2D(1)
self.maxpool = paddle.nn.AdaptiveMaxPool2D(1)
self.avg_bn = nn.BatchNorm2D(2048)
self.max_bn = nn.BatchNorm2D(2048)
self.relu = nn.ReLU()
... |
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.core.files.images import get_image_dimensions
from .models import Academy
class AboutAcadem... |
import asyncio
import time
import typing as t
from datetime import datetime
import discord
import youtube_dl
import os
import aiohttp
from discord.ext import commands
LYRICS_URL = "https://some-random-api.ml/lyrics?title="
# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambd... |
"""Fancy traceback formatting
We have yet to decide which of these we'll do:
1. Mokeypatch the stdlib traceback module to improve traceback formatting
everywhere.
2. Provide routines other library authors can call to print nice tracebacks.
"""
# print_exception (which is what Django uses for runserver output) and... |
import json
from abc import ABC
from typing import List
class PetConfig(ABC):
"""Abstract class for a PET configuration that can be saved to and loaded from a json file."""
def __repr__(self):
return repr(self.__dict__)
def save(self, path: str):
"""Save this config to a file."""
... |
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
from functools import partial
from migen import *
from util import *
from third_party import wishbone as wb
from bus.wishbone_utils import *
"""
Tri-bus structure:
1. Memory bus (crossbar)
- Memories / Cache
- All controllers
2. Peripheral bus (shared)
- Low-performance peripherals
... |
import socket
import errno
import sys
import tkinter as tk
import threading
PORT = 1234
DEBUG_MODE = True
HEADER_LENGTH = 10
ENCODING = "UTF-8"
WIDTH = 325
HEIGHT = 500
THEME_COLOR = "#0D1216"
class ChatClient:
def __init__(self, port, name='Unknown'):
self.port = port
self.name = name
se... |
""" -*- coding: utf-8 -*-
docs/examples.py
Extensive examples for FileAsObj
"""
from fileasobj import FileAsObj
def example_read_exists():
"""
Reading a file that already exists.
This will raise an exception if the file does not exist.
"""
my_file = FileAsObj('/tmp/example_file.txt')
def exampl... |
import py
import sys
callcapture = py.io.StdCapture.call
def setup_module(mod):
mod.tempdir = py.test.ensuretemp("py.log-test")
mod.logstate = py.log._getstate()
def teardown_module(mod):
py.log._setstate(mod.logstate)
class TestLogProducer:
def setup_method(self, meth):
self.state = p... |
'''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:Companion
[1] <NAME>, <NAME>, <NAME>, <NAME>
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import encoder # getting the encoder from the train... |
from skimage.feature import greycoprops,greycomatrix
import matplotlib.image as mpimg
import pandas as pd
import numpy as np
import glob
import SimpleITK as sitk
import scipy.misc as sci
# Returns all column names with patch NO., distance and angles
def getGLCMColumnNames(patch=[1,2,3,4,5],distances = [1,3,5],angles=[... |
from keras.applications.xception import Xception, preprocess_input
from keras.models import load_model
from keras.preprocessing.image import img_to_array
from keras.applications.resnet50 import ResNet50
from keras.applications import imagenet_utils
from dataclasses import dataclass
from typing import List
from core im... |
import imp
import unittest
try:
from StringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
from docutils.readers import standalone
from docutils.core import Publisher, default_description, \
default_usage
from types import ModuleType
#rst2odp = ModuleType('rst2odp')
#exec open('... |
import os
import math
import time
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim.lr_scheduler import StepLR
import numpy as np
import config
import scipy as sp
import scipy.stats
from task_generator import TaskGenerator,split_fine_grained_dataset,mini_imagenet_folder... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.