content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# # Image Clustering via KMeans
# # Author: Abhishek Gadiraju (abhishek.gadiraju@gmail.com)
# import numpy as np
# import random
# import sys
# #from PIL import Image
# class KMeans:
# def __init__(self, K):
# self.K = K
# self.centroids = [] # list of centroids
# self.clusters = {} # dictionary of... | python |
from datetime import datetime
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
from pydantic import BaseModel
from ..utils import ynab_style_json_dumps
from .entities import AccountEntity, FileMetaDataEntity, PayeeEntity, TransactionEntity
class DiffFile(BaseModel):
startVersion: str #... | python |
from django.db import models
# Create your models here.
class User(models.Model):
uid = models.AutoField(primary_key = True)
first_name = models.CharField(max_length = 30)
last_name = models.CharField(max_length = 30, null= True)
address = models.TextField()
city = models.CharField(max_length = 30)
stat... | python |
# -*- coding: utf-8 -*-
import os
from O365 import Account, Connection, FileSystemTokenBackend
from datetime import datetime as dt
from datetime import timedelta
from conf.conf import CONFIG as conf
from fritzhome import FritzBox
import logging
class Core:
@staticmethod
def get_credentials():
return... | python |
from pymongo import MongoClient
import numpy as np
client = MongoClient("mongodb://localhost:27017")
db = client['test']
cursor = db.inflacao.find()
for document in cursor:
print(document)
def mmq(x, y):
x = np.insert(x, 0, 1, axis=1)
x_t = np.transpose(x)
xt_x = np.dot(x_t, x)
inverse_xt_x = np.lin... | python |
import strongr.core.gateways as gateways
from sqlalchemy import Column, ForeignKey, Integer, String, Enum, DateTime, func
from sqlalchemy.orm import relationship, synonym
from strongr.schedulerdomain.model.vmstate import VmState
Base = gateways.Gateways.sqlalchemy_base()
class Vm(Base):
__tablename__ = 'vms'
... | python |
"""
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value
appears at least twice in the array, and it should return false if every element is distinct.
"""
__author__ = 'Daniel'
from collections import Counter
class Solution:
def containsDuplicate(sel... | python |
from dials.algorithms.shoebox.masker import *
from dials_algorithms_shoebox_ext import *
| python |
# -*- coding: utf-8 -*-
"""
Test script for pyvi/volterra/tools.py
Notes
-----
Developed for Python 3.6
@author: Damien Bouvier (Damien.Bouvier@ircam.fr)
"""
#==============================================================================
# Importations
#================================================================... | python |
from graph import Graph
_SUCCESS = 0
_ERROR = 1
class Analyzer:
"""
Analyzer syntactic for operator grammar
"""
def __init__(self):
"""Init"""
self.graph = Graph()
self.rules = []
self.init = None
self.f={}
self.g={}
def add_rule(self, array):
... | python |
from __future__ import print_function
import boto3
import json
def lambda_handler(event, context):
dynamo = boto3.resource('dynamodb').Table(event['tableName'])
column = event['column']
request = dynamo.scan(AttributesToGet=[column])
# Undefined for no values
if request['Count'] is 0:
... | python |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'mainunJTzN.ui'
##
## Created by: Qt User Interface Compiler version 5.15.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
###############... | python |
from logging import getLogger
from functools import lru_cache
from .funcs import list_to_str, try_draw
from .html import Div
class Boot:
defaults = {}
_class = ""
def __init__(self, *args, **kwargs) -> None:
self.logger = getLogger(self.__class__.__name__)
self.args = args
... | python |
# -*- coding: UTF-8 -*-
# Stock data fetch from website.
from qcinfo import xueqiu as XQ
from qcinfo import qcrepo, gtimg
from qcinfo.log import qcinfo_log
logger = qcinfo_log()
async def company_info_async(code):
'''
上市公司基本信息
:param code: Stock code
:return:
'''
return await XQ.company_info_a... | python |
# -*- coding: utf-8 -*-
"""Delayed evaluation.
Inspired by Racket's promises and `macropy.quick_lambda.lazy`.
See:
https://docs.racket-lang.org/reference/Delayed_Evaluation.html
https://macropy3.readthedocs.io/en/latest/lazy.html
"""
__all__ = ["delay", "force"]
from mcpyrate.multiphase import macros, phase... | python |
# Generated by Django 2.2.6 on 2020-03-18 13:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tasks", "0004_task_reference"),
]
operations = [
migrations.RemoveField(model_name="task", name="estimated_duration",),
migrations.A... | python |
import pickle
import numpy as np
import os
#Count # of pts in every detected object
fname_detected="./detected.txt"
fname_undetected="./undetected.txt"
#a,b=os.path.splitext(filename)
with open(fname_detected , 'rb') as f:
detected = f.readlines()
with open(fname_undetected , 'rb') as f:
undetected = f.readli... | python |
class Reader:
def __init__(self, stream, sep=None, buf_size=1024 * 4):
self.stream = stream
self.sep = sep
self.buf_size = buf_size
self.__buffer = None
self.__eof = False
def __iter__(self):
return self
def __next__(self):
if not self.__buffer:
... | python |
# main.py
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
USERNAME = "ACCOUNT_USER"
PASSWORD = "ACCOUNT_PASS"
URL = "https://www.netflix.com/browse/my-list"
REGEX = r"https://www.netflix.com/watch/(.*?)\?tctx"
def login(browser):
print(browser.current_url)
try:
... | python |
file = open('file_example.txt', 'r')
contents = file.read()
file.close()
print(contents)
| python |
# 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 unde... | python |
# coding=utf-8
from __future__ import unicode_literals
from .consumer import OAuth1ConsumerBlueprint, OAuth2ConsumerBlueprint
__version__ = "0.13.0"
| python |
import paho.mqtt.publish as publish
publish.single("yuyao/server", "payload", hostname="0.0.0.0")
| python |
from graphics import *
import random
import pyautogui
mouseX, mouseY = pyautogui.position()
def scene(x,y):
win = GraphWin("Scene", x, y)
win.setBackground('skyblue')
#layer 1
sun = Circle(Point(win.getWidth()*0.8,win.getHeight()*0.2), win.getHeight()*0.1)
sun.setFill('yellow')
s... | python |
"""
This file is the entry point for the maggport package
Example:
maggport --host <host> --port <port> --db <db> --collection <collection> --pipeline_path <pipeline_path> --out <out>
"""
import ast
import json
import time
from typing import Any
import click
import pymongo
from maggport import exports, logger, v... | python |
import numpy as np
import multiprocessing as mp
from abc import ABCMeta, abstractmethod
from warnings import warn
from .. import Bandstructure
from .. import Parameters
class System(metaclass=ABCMeta):
"""Abstract class for the implementation of a specific model system. Child classes need to
implement ``tunn... | python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# vim:set shiftwidth=2 tabstop=2 expandtab textwidth=79:
import asyncio
import cgi
import logging
import os
import random
import re
import string
import time
import urllib
import urllib.parse
from collections import namedtuple
import aiohttp
import async_timeout
import reques... | python |
from django import forms
from django.utils.translation import gettext_lazy
from dfirtrack_main.models import Analysisstatus, Case, Company, Domain, Dnsname, Location, Os, Reason, Serviceprovider, System, Systemstatus, Systemtype, Tag
class SystemImporterFileCsvConfigbasedForm(forms.Form):
# file upload field (var... | python |
import pytest
from pytest_mock import MockerFixture
from pystratis.api.notifications import Notifications
from pystratis.core.networks import StraxMain, CirrusMain
def test_all_strax_endpoints_implemented(strax_swagger_json):
paths = [key.lower() for key in strax_swagger_json['paths']]
for endpoint in paths:
... | python |
"""
detail
~~~~~~
Parse an OSM XML file, validating the data, and producing a stream of rich
data objects. Designed for debugging and understanding the data. Practical
applications should use one of the faster, more streamlined processing modules.
"""
from .utils import saxgen as _saxgen
import datetime as _datetim... | python |
from django.conf import settings
__all__ = ['lazy_register']
def lazy_register(register):
if "compressor" in settings.INSTALLED_APPS:
@register.tag
def compress(parser, token):
from compressor.templatetags.compress import compress
return compress(parser, token)
else:
try:
@reg... | python |
from ....graph import (
Graph,
Edge,
)
class MSTPrim():
def __call__(
self,
g: Graph,
) -> Graph:
import heapq
n = g.size
new_g = Graph.from_size(n)
visited = [False] * n
inf = 1 << 60
weight = [inf] * n
hq = [(0, -1, 0)]
while hq:
wu, pre, u = heapq.heappop(hq)
... | python |
import numpy as np
import sklearn as sk
import csv
# default values for options
options = {}
options['train_log_dir'] = 'logs'
options['output_dir'] = 'output'
options['training_file'] = '../data/uniform.pickle'
options['noise_dims'] = 62
options['latent_dims'] = 2
options['batch_size'] = 128
options['gen_lr'] = 1e-3
... | python |
#14) Longest Collatz sequence
#The following iterative sequence is defined for the set of positive integers:
#n → n/2 (n is even)
#n → 3n + 1 (n is odd)
#Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
#It can be seen that this sequence (starting... | python |
__all__ = []
from . import decorators
__all__.extend(decorators.__all__)
from .decorators import *
from . import readers
__all__.extend(readers.__all__)
from .readers import *
from . import menu
__all__.extend(menu.__all__)
from .menu import *
| python |
# ------- 3rd party imports -------
import flask
from flask import Blueprint, render_template, request
your_short_url_blueprint = Blueprint('your_short_url_blueprint', __name__, template_folder='templates')
@your_short_url_blueprint.route('/your_short_url')
def your_short_url():
original_url = request.args['orig... | python |
# coding: utf-8
import os
import sys
import sqlite3
import cfg
from src import logging
def db_init():
try:
if not os.path.isfile(cfg.get_path_to_db()):
logging.Logger('info').info('Database has just been created and is empty')
db_con = sqlite3.connect(cfg.get_path_to_db())
db... | python |
# Copyright 2013-2021 Sebastian Ramacher <sebastian+dev@ramacher.at>
#
# 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, c... | python |
from distutils.core import setup
setup(
name='cvpro',
packages=['cvpro'],
version='1.1.0',
license='MIT',
description='CVPRO - Computer Vision PROfessional - HELPING LIBRARY',
long_description="README.md",
long_description_type="text/markdown",
author='MOHAK BAJAJ',
autho... | python |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.http import HttpResponse
admin.autodiscover()
urlpatterns = [
url(r'^api/v2/', include('fiber.rest_api.urls')),
url(r'^admin/fiber/', include('fib... | python |
# Copyright 2013-2019 Donald Stufft and individual contributors
#
# 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 applicabl... | python |
Age = 20
print Age
| python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: sync_ldap_dimission_user_state_to_cmdb.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _m... | python |
"""empty message
Revision ID: 59608aa9414e
Revises: 91c2bd4689a
Create Date: 2015-09-28 12:36:05.708632
"""
# revision identifiers, used by Alembic.
revision = '59608aa9414e'
down_revision = '91c2bd4689a'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - pl... | python |
"""Properties used to create the Gaphor data models.
The logic for creating and destroying connections between elements is
implemented in Python property classes. These classes are simply instantiated
like this:
class Class(Element): pass
class Comment(Element): pass
Class.comment = association('comment', ... | python |
import asyncio
import collections.abc
import functools
import inspect
from typing import (
Any,
Awaitable,
Callable,
Dict,
Hashable,
Iterator,
Optional,
Set,
Tuple,
Union,
)
import uuid
from aiohttp import web
import aiohttp_session
__version__ = "1.1.1"
DEFAULT_ID_FACTORY = l... | python |
import unittest
__author__ = "Bilal El Uneis"
__since__ = "August 2020"
__email__ = "bilaleluneis@gmail.com"
class A:
def __init__(self) -> None:
pass
@property
def id(self) -> int:
return id(self)
class RefrenceTypeTests(unittest.TestCase):
def test_refrence(self) -> None:
... | python |
#!/usr/bin/env python
# Test driver for basic test
from __future__ import print_function
import sys
import unittest
import time
import os
import math
import rospy
import rospy.client
import rospkg
from sensor_msgs.msg import Image, CompressedImage
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
... | python |
from google_images_search import GoogleImagesSearch
import os
import requests
with open(r".\APIKEY.txt" , 'r') as f:
f_con = f.readlines()
APIKEY, api2 = f_con[0],f_con[1]
gis = GoogleImagesSearch(APIKEY, api2)
class searcher:
def __init__(self,word,imgName):
self.word = word
s... | python |
from django.urls import reverse
from aether.utils.cache import expire_page
def invalidate_cache(sender, instance, created, **kwargs):
expire_page(reverse('gallery:index'))
| python |
from __future__ import unicode_literals
import vmraid
from vmraid import _
session = vmraid.session
def authenticate(user, raise_err = True):
if session.user == 'Guest':
if not vmraid.db.exists('Chat Token', user):
if raise_err:
vmraid.throw(_("Sorry, you're not authorized."))
else:
return False
... | python |
# Copyright (c) 2022 PaddlePaddle 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 appli... | python |
# -*- coding: utf-8 -*-
"""
:author: T8840
:tag: Thinking is a good thing!
:description:
"""
import mitmproxy.http
import json
import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
from utils import get_yaml_data
data = get_yaml... | python |
from argparse import Namespace
import pandas as pd
import game
import argparse
import time
import random
class Play():
def __init__(self):
'''Initiate a new play'''
self.args_keys = []
self.len_gkeys = 0
self.args_read = self._set_parser()
self.arg_d = {}
self.collection = []
self.log = []
self.df =... | python |
# MIT License
#
# Copyright (c) 2021 Soohwan Kim
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, ... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#****************************************************************************************************************************************************
# Copyright 2020 NXP
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifi... | python |
'''
DDS: DDS image loader
'''
__all__ = ('ImageLoaderDDS', )
from kivy.lib.ddsfile import DDSFile
from kivy.logger import Logger
from kivy.core.image import ImageLoaderBase, ImageData, ImageLoader
class ImageLoaderDDS(ImageLoaderBase):
@staticmethod
def extensions():
return ('dds', )
def load(... | python |
# Program to calculate tax band
print('Start')
# Set up 'constants' to be used
BASIC_RATE_THRESHOLD = 12500
HIGHER_RATE_THRESHOLD = 50000
ADDITIONAL_RATE_THRESHOLD = 150000
# Get user input and a number
income_string = input('Please input your income: ')
if income_string.isnumeric():
annual_income = int(income_st... | python |
'''
'''
import os
from keras.applications.resnet50 import ResNet50
BASE_FOLDER = os.path.join(os.environ['HOME'], 'workspace/Maestria/')
KERAS_MODEL_FOLDER = os.environ['HOME']+'/.keras/models/'
MODELS_FOLDER = os.path.join(BASE_FOLDER, 'Model')
TRAIN_PATH = os.path.join(BASE_FOLDER, 'Videos/tf_pascal_voc')
model = ... | python |
"""
Created on Thu Mar 24 22:46:30 2022
@author: csemn
"""
import pandas as pd
dataset = pd.read_csv("diabetes.csv")
#Preparing the Data
x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_si... | python |
from io import BytesIO
from unittest import SkipTest
import av
from .common import Image, MethodLogger, TestCase, fate_png, fate_suite, run_in_sandbox
from .test_encode import assert_rgb_rotate, write_rgb_rotate
class BrokenBuffer(BytesIO):
"""
Buffer which can be "broken" to simulate an I/O error.
"""
... | python |
# Generated by Django 2.0 on 2017-12-14 05:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devices', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='device',
name='type',
field... | python |
#!/usr/bin/env python3
from PIL import Image
from struct import pack
def pre(p):
p = list(p)
p[0] = p[0]*p[3]//255
p[1] = p[1]*p[3]//255
p[2] = p[2]*p[3]//255
return p
def write(i, o, X, Y):
for y in range(Y):
for x in range(X):
p = pre(i.getpixel((x, y)))
o.wri... | python |
from dataclasses import dataclass
from bindings.gmd.topo_curve_type import TopoCurveType
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class TopoCurve(TopoCurveType):
"""gml:TopoCurve represents a homogeneous topological expression, a
sequence of directed edges, which if realised are isomorphic to ... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from collections import namedtuple
from corehq.apps.callcenter.data_source import get_sql_adapters_for_domain
from corehq.apps.reports.analytics.esaccessors import get_form_counts_for_domains
from corehq.apps... | python |
from django.apps import AppConfig
class PointsConfig(AppConfig):
name = 'poznaj.points'
verbose_name = 'Points'
| python |
import os
import uuid
import click
def test_var_name_preservation(runner):
@click.command()
@click.option('--modelFileCamelCase', '-m', type=click.Path())
def cli(modelFileCamelCase):
"""Hello World!"""
click.echo("I EXECUTED w/ a camelCaseVariable!")
result = runner.invoke(cli, ["--... | python |
import seaborn as sns
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
fig_folder = "figure_data/fig3_SEI/"
lb_fs = 12
tl_fs = 10
#e_color =
sns.set_palette("Set1", n_colors=8, desat=.5)
# get the data
dos = pd.read_csv(fig_folder+"dos_interp.txt", sep='\t', skiprows=1, names=["E", "DOS"])... | python |
#!/usr/bin/env python3
"""
Main module for the deployable project.
"""
# Shared imports for bootstrap and normal use
from pathlib import Path # For bootstrap and figuring out paths from args
# Bootstrap to be able to perform absolute imports as standalone code
if __name__ == "__main__":
from absolute_import import... | python |
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from pgweb.util.decorators import cache
import httplib
import urllib
import psycopg2
imp... | python |
# .................................................................................................................
level_dict["regal"] = {
"scheme": "bronze_scheme",
"size": (7,3,9),
"intro": "regal",
"help... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
#######################################
# Script que permite la generación de mapas para las variables de
# temperatura (máxima, mínima y promedio),
# Humedad Relativa (máxima, mínima y promedio),
lluvia, y reflectividad de radar.
# Author: Jorge Mauricio
# Email: jorg... | python |
# Warm-up + cosine Learning Rate scheduler. Based on the formulas from:
#
# "Bag of Tricks for Image Classification with Convolutional ...." paper
#
# Stores LR to plot in the end
import math
import matplotlib.pyplot as plt
import torch.optim as optim
from callbacks.cb import Callbacks # base
class LR_SchedCB_W... | python |
__version_info__ = (1, 7, 2)
__version__ = '.'.join(map(str, __version_info__))
| python |
from typing import TypeVar, Callable, Any
from amino import Either, Boolean, do, Do
from amino.state import State
from amino.boolean import true
from ribosome.nvim.api.data import NvimApi
from ribosome.nvim.io.compute import NvimIOSuspend, NvimIOPure, NvimIOError, NvimIO, NvimIORecover, lift_n_result
from ribosome.nv... | python |
# coding: utf-8
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
from pydocx.openxml.packaging import FootnotesPart, MainDocumentPart
from pydocx.test import DocumentGeneratorTestCase
from pydocx.test.utils import WordprocessingDocumentFactory
class FootnoteTestCase(Documen... | python |
from tkinter import *
def buttonClick():
print("Clicked!")
root=Tk()
f=Frame(root, height=400, width=500)
f.propagate(0)
#f.propagate(1)
f.pack()
b=Button(f, text='Click Here', width=15, height=2, bg='yellow', fg='green', activebackground='blue', activeforeground='red')
#b.bind('<Button-1>',butto... | python |
def redCountours(image):
frame_threshold = cv2.inRange(image, (0, 100, 100), (10, 255, 255))
thresh2 = cv2.inRange(image, (150, 140, 100), (180, 255, 255))
frame_threshold_both = frame_threshold + thresh2
#Dialate Color Threshold Mask after Eroding to Beef Up detected areas for analysis
frame_t... | python |
ORANGE, WHITE = '\033[93m', '\033[0m'
def warning(message):
print("\n " + ORANGE + "Warning: " + WHITE + message + "\n")
class _Options:
def __init__(self):
self.values = tuple() # options with non-Boolean values (strings or numbers)
self.flags = tuple() # Boolean options
self.par... | python |
from django.shortcuts import render, redirect
from LogESP import __version__
# Create your views here.
def index(request):
return render(request, 'index.html', {'version': __version__})
| python |
#!/usr/bin/env python
# coding: utf-8
"""
A rudimentary backward- and forward-compatible script to benchmark pystache.
Usage:
tests/benchmark.py 10000
"""
import sys
from timeit import Timer
try:
import chevron as pystache
print('Using module: chevron')
except (ImportError):
import pystache
print(... | python |
#
# PySNMP MIB module TRAPEZE-NETWORKS-CLIENT-SESSION-TC (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-CLIENT-SESSION-TC
# Produced by pysmi-0.3.4 at Wed May 1 15:27:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using... | python |
'''
f(n) = 3 g(n-1)
''' | python |
__version__ = "v1.0"
__copyright__ = "Copyright 2021"
__license__ = "MIT"
__lab__ = "Adam Cribbs lab"
import time
import pandas as pd
class reader(object):
def __init__(self, ):
pass
def todf(self, seqs, names):
"""
Parameters
----------
seqs
names
... | python |
from glob import iglob
from multiprocessing import Pool
from os import getcwd
from os import path
from os import sep
from sys import platform
from sys import version_info
from tempfile import gettempdir
import pytest
from pytesseract import ALTONotSupported
from pytesseract import get_languages
from pytesseract impor... | python |
import re
from typing import Any
from dragn.dice.die import DieBuilder
def __getattr__(name: str) -> Any:
"""
Module level __getattr__ to automatically create dice when
one a die of non-standard sizes.
"""
m = re.match(r"D(\d+)", name)
if m is None:
raise AttributeError(f"Name {name} ... | python |
'''This script uses OpenCV's haarcascade (face and eye cascade) to detect face
and eyes in a given input image.'''
#Import necessary libraries
import cv2 as cv #wrapper package for openCv bindings
import numpy as np
#Load face cascade and hair cascade from haarcascades folder
face_cascade = cv.CascadeClassifier("haar... | python |
#!/usr/bin/env python
# -*- coding: utf-8
import argparse
import socket
import json
from flask import Flask, render_template, request
from src import osint
def validate_address_port(address, port):
"""
Validate IP address and port
"""
try:
socket.inet_aton(address)
except socket.error:
... | python |
# pylint: disable=invalid-name, unused-variable
"""Schedule for dense operator"""
from __future__ import absolute_import as _abs
import tvm
from tvm.contrib import rocblas
import topi
from ..nn.dense import dense, dense_default
from .. import tag
from .. import generic
@dense.register("rocm")
def dense_rocm(data, weig... | python |
import pytest
from xnd import xnd
import test_scalar as m
def unpack(x):
if isinstance(x, xnd):
return str(x.type), x.value
if isinstance(x, tuple):
return tuple(map(unpack, x))
return x
def assert_equal(x, y):
assert unpack(x) == unpack(y)
def test_scalar_input():
dt = 'int6... | python |
from time import time
import torch
import random
import numpy as np
import os
from pypinyin import lazy_pinyin
import jieba
def time_cost(func):
def wrapper(*arg, **kargs):
t0 = time()
res = func(*arg, **kargs)
t1 = time()
print(f'[{func.__name__}] cost {t1 - t0:.2f}s')
ret... | python |
import unittest
import datafilereader
class TestParents(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.project = datafilereader.construct_project(
datafilereader.SIMPLE_TEST_SUITE_PATH)
cls.directory = cls.project.data
cls.test = datafilereader.get_ct... | python |
import click, os, functools, sys
from carbin import __version__
from carbin.prefix import CarbinPrefix
from carbin.prefix import PackageBuild
import carbin.util as util
aliases = {
'rm': 'remove',
'ls': 'list'
}
class AliasedGroup(click.Group):
def get_command(self, ctx, cmd_name):
rv = click.Gr... | python |
#!/usr/bin/env python
"""
Something like
https://github.com/vs-uulm/nemesys/blob/c03cafdaed3175647d5bc690488742745acbd0eb/src/nemesys_fms.py
adopted to test l2pre with Fomat Match Score (FMS)
"""
# system import
import argparse
from IPython import embed
from time import time
# nemere import
from nemere.validation.di... | python |
import unittest
from code.evallib import recall
class TestRecall(unittest.TestCase):
'''
Recall tests
recall excepts two parameters: two document sets (relevent and retrieved)
It returns the value of: |(relevent INTERSECTION retrieved)| / |relevent|
'''
def test_expected(self):
releve... | python |
from typing import List, Optional
from athenian.api.models.web.base_model_ import Model
from athenian.api.models.web.contributor import Contributor
class Team(Model):
"""Definition of a team of several developers."""
openapi_types = {
"id": int,
"name": str,
"members": List[Contribut... | python |
#!/usr/bin/env python
"""
Module for stats and fitting classes.
Created June 2015
Copyright (C) Damien Farrell
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 ... | python |
from load_data.ILoadUnsupervised import ILoadUnsupervised
from os import listdir
from os.path import join, splitext
#from pims import ImageReader
from PIL import Image
class LoadAnimeFaces(ILoadUnsupervised):
def __init__(self, folderpath="train_data/Folder_Manga_Anime/anime-faces"):
self.folderpath = fold... | python |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
import twitter_scraper as twitter_scraper
import json
import codecs
standard_library.install_aliases()
def main():
def build_list... | python |
from copy import deepcopy
from py_ecc import bls
import build.phase0.spec as spec
from build.phase0.utils.minimal_ssz import signed_root
from build.phase0.spec import (
# constants
EMPTY_SIGNATURE,
# SSZ
AttestationData,
Deposit,
DepositInput,
DepositData,
Eth1Data,
VoluntaryExit,
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.