content stringlengths 5 1.05M |
|---|
"""Unit tests for the `cf_predict` package."""
|
import torch
import argparse
from Transformer import Transformer
parser = argparse.ArgumentParser(description='Test transformer')
parser.add_argument('--src_len', '-s', type=int, default=5, help='the source sequence length')
parser.add_argument('--batch_size', '-bs', type=int, default=2, help='batch size')
parser.add... |
import FWCore.ParameterSet.Config as cms
#
#
#------------------
#Preshower clustering:
#------------------
from RecoEcal.EgammaClusterProducers.multi5x5SuperClustersWithPreshower_cfi import *
# producer for endcap SuperClusters including preshower energy
from RecoEcal.EgammaClusterProducers.correctedMulti5x5SuperClus... |
# Process PET from worldclim temperature
# Peter Uhe
# 25/3/2019
#
# This script uses python3, set up using conda environment gdal_env2
import os,sys,glob
import gdal
import numpy as np
import datetime,calendar
import netCDF4
sys.path.append('/home/pu17449/gitsrc/PyETo')
import pyeto
inpath = '/home/pu17449/data2/wo... |
"""
Created on Wed Nov 7 13:06:08 2018
@author: david
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures
import pandas as pd
#from astropy.convolution import Gaussian2DKernel... |
import autodisc as ad
from autodisc.gui.gui import DictTableGUI, BaseFrame
import collections
try:
import tkinter as tk
except:
import Tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class StatisticTableGUI(DictTableGUI):
@staticmethod
def... |
from gf.models.account import Account
from time import time
from uuid import uuid4
import multiprocessing as mp
import gf.lib.db.db_utils as db
#db.get_row_by_id("users", uuid4())
#db.get_row_by_id("shit", uuid4())
Account(id=uuid4(), username= "hello", name="John", email="shit").commit()
quit()
init_id = uuid4()
acc ... |
from collections import deque
import json
from kafka import KafkaProducer, KafkaConsumer
from anonymizer import Anonymizer
consumer = KafkaConsumer(bootstrap_servers="localhost:9092", value_deserializer=json.loads)
consumer.subscribe(["unanon"])
producer = KafkaProducer(bootstrap_servers="localhost:9092")
def anony... |
import click
import pprint
@click.command()
@click.argument('type', default='all')
@click.option('--check/--no-check', help="Just check (no changes)", default=False)
@click.option('--update/--no-update', help="Update if exists", default=False)
@click.option('--push/--no-push', help="Push update (when specifed wit... |
import pytest
import yaml
from utils import utils
class TestConvertReiwaToYear:
@pytest.fixture(scope="function")
def data_fixture(self):
return ((1, 2019), (2, 2020), (3, 2021))
def test_convert(self, data_fixture):
for reiwa, actual in data_fixture:
assert utils.convert_re... |
"""
FactSet ESG API
FactSet ESG (powered by FactSet Truvalue Labs) applies machine learning to uncover risks and opportunities from companies' Environmental, Social and Governance (ESG) behavior, which are aggregated and categorized into continuously updated, material ESG scores. The service focuses on company... |
#SPDX-License-Identifier: MIT
from augur.application import Application
from augur.augurplugin import AugurPlugin
from augur import logger
class FacadePlugin(AugurPlugin):
"""
This plugin serves as an example as to how to load plugins into Augur
"""
def __init__(self, augur):
self.__f... |
from .currencies import Currencies
from .rates import Rates
|
import pandas as pd
import numpy as np
import datetime
import time
import requests
from splinter import Browser
from bs4 import BeautifulSoup as bs
from selenium import webdriver
from flask import Flask, render_template
import pymongo
def Scraper():
executable_path = {'executable_path': 'chromedriver.exe'}
... |
import os, matplotlib
class FileSaver:
def save_figure(self, selected_month, plt, charttype):
DIR = (selected_month)
CHECK_FOLDER = os.path.isdir(f"output/{DIR}")
# If folder doesn't exist, then create it.
if not CHECK_FOLDER:
os.makedirs(f"output/{DIR}")
plt.s... |
from django.apps import AppConfig
class books_repoConfig(AppConfig):
name = 'books_repo'
|
import discord
from discord.ext import commands, tasks
import os
import pickle
import config
import asyncio
import typing
import re
import traceback
from enum import Enum
from collections import OrderedDict
import datetime
import pytz
from apiclient import discovery
from google.oauth2 import service_account
class G... |
'''
Created on 16 de nov de 2020
@author: klaus
'''
import jsonlines
from folders import DATA_DIR, SUBMISSIONS_DIR
import os
from os import path
import pandas as pd
import numpy as np
import igraph as ig
from input.read_input import read_item_data, get_mappings, NUM_DOMS
from nn import domain_string_identifier
from n... |
import sys
import torchvision
import torch
from torch.utils.data import Dataset
from .episodic_dataset import EpisodicDataset, FewShotSampler
import json
import os
import numpy as np
import numpy
import cv2
import pickle as pkl
# Inherit order is important, FewShotDataset constructor is prioritary
class EpisodicTiered... |
# Test the difference in computation time between a set of functions that calculate all prime numbers in a given range
import time
import math
import matplotlib.pyplot as plt
# Methods for finding all prime numbers up to max value 'n'
# Slow method using a basic check
def slow_method(n: int) -> list[int]:
results... |
from typing import List, Optional
from fastapi.datastructures import UploadFile
from pydantic.main import BaseModel
from enum import Enum
class TextSpan(BaseModel):
text: str
start: int
end: int
class NamedEntity(TextSpan):
label: str # The (predicted) label of the text span
definition: Optiona... |
import numpy as np
from sklearn.metrics import confusion_matrix
def test_data_index(true_label,pred_label,class_num):
M = 0
C = np.zeros((class_num+1,class_num+1))
c1 = confusion_matrix(true_label, pred_label)
C[0:class_num,0:class_num] = c1
C[0:class_num,class_num] = np.sum(c1,axis=1)
C[class_num,0:class_num] ... |
l=input()
n=len(l)
f=0
prev=0
found=0
for i in range(n-1):
if l[i:i+2]=='AB':
if f==0:
prev=i+1
f=1
else:
continue
elif l[i:i+2]=='BA':
if f==1:
if i!=prev:
found=1
else:
continue
prev=0
f=0
for ... |
"""
A Python library for generating Atom feeds for podcasts.
Uses the specification described at
http://www.atomenabled.org/developers/syndication/
"""
from xml.etree import ElementTree as ET
from xml.dom import minidom
import copy
from datetime import datetime, timedelta
from uuid import UUID
def parse_datetime(dt)... |
from datetime import timedelta
import json
import sys
import click
from humanize import naturaldelta
from . import __version__
from .click_timedelta import TIME_DELTA
from .watson_overtime import watson_overtime
def _build_work_diff_msg(diff: timedelta) -> str:
msg = f"You are {naturaldelta(diff)} "
if diff... |
def dump_locals(lcls):
print('|' + ('='*78) + '|')
print("|Locals:".ljust(79) + '|')
print('|' + ('- -'*(79//3)) + '|')
for (k, v) in lcls.items():
print("| {} => {}".format(k, v).ljust(79) + '|')
print('|' + ('='*78) + '|')
def dump_obj(name, obj):
print('|' + ('='*78) + '|')
pri... |
"""
Settings file
You can set the database settings in here at DATABASES['default']
You can also set the supported languages with SUPPORTED_LANGUAGES
Before you launch the site, you should probably set DATABASE password and the SECRET_KEY to something that
is not in a public git repository...
"""
from random i... |
# From any external file our program counts the number of lines
# thanks to Stackoverflow
# @program 3
# @author unobatbayar
# @date 03-10-2018
num_lines = sum(1 for line in open('out.txt'))
print(num_lines)
|
#!/usr/bin/env python
import requests
import traceback
import sys
from bs4 import BeautifulSoup
import csv
## getHTML
def getHTML():
url = "http://mcc-mnc.com/"
html = ""
try :
r = requests.get(url)
html = r.text.encode("utf-8")
except:
traceback.print_exc()
return htm... |
from user import User
from db import Base, Session
from sqlalchemy import *
from sqlalchemy.orm import relation, sessionmaker
from datetime import datetime, date
from attendee import Attendee
from werkzeug.security import generate_password_hash, check_password_hash
from flask import json
from sqlalchemy import exc
from... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
import random
import time
# Using the Python Device SDK for IoT Hub:
# https://github.com/Azure/azure-iot-sdk-python
# The sample connects to a device-specific MQTT en... |
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, www.privaz.io Valletech AB
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# OpenNebula common documentation
DOCUMENTATION = r'''
options:
api_url:
description:
... |
#!/usr/bin/env python3
import os
from electroncash.util import json_decode
from tkinter import filedialog
from tkinter import *
Tk().withdraw()
wallet = filedialog.askopenfilename(initialdir = "~/.electron-cash/wallets",title = "Select wallet")
coins = os.popen("electron-cash -w "+wallet+" listunspent").read()
coin... |
from unittest import mock
from django.conf import settings
from django.contrib.auth.models import User
from django.test import Client, TestCase
from .models import Lamp
from .views import LampControlForm
class LoginTests(TestCase):
def setUp(self):
self.client = Client()
def test_login_view(self):... |
# -*- coding: utf-8 -*-
# Copyright © 2018 by IBPort. All rights reserved.
# @Author: Neal Wong
# @Email: ibprnd@gmail.com
from setuptools import setup
setup(
name='scrapy_autoproxy',
version='1.0.0',
description='Machine learning proxy picker',
long_description=open('README.rst').read(),... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
def bin_count(x):
return bin(x).count('1')
def logic(n, m, y):
print(2)
print(n, 1)
if n == 0:
print(1)
print(1)
for i in range(m):
print(-1.0, end=' ')
print(-1.0)
return
for idx in range(n):
for binary in range(m):
if idx ... |
import remi.gui as gui
import remi.server
import collections
class DraggableItem(gui.EventSource):
def __init__(self, container, **kwargs):
gui.EventSource.__init__(self)
self.container = container
self.refWidget = None
self.parent = None
self.active = False
self.ori... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'EA.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
... |
from flask_appbuilder.security.sqla.apis.permission import PermissionApi # noqa: F401
from flask_appbuilder.security.sqla.apis.permission_view_menu import ( # noqa: F401
PermissionViewMenuApi,
)
from flask_appbuilder.security.sqla.apis.role import RoleApi # noqa: F401
from flask_appbuilder.security.sqla.apis.use... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2016 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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 c... |
#
# The XBUILD builder.
#
# (c) 2012 The XTK Developers <dev@goXTK.com>
#
import datetime
import os
import stat
import sys
import subprocess
import config
from _cdash import CDash
from _colors import Colors
from _jsfilefinder import JSFileFinder
from _licenser import Licenser
#
#
#
class Builder( object ):
'''
'... |
import logging
from src.backup.datastore.backup_finder import BackupFinder
from src.restore.list.backup_list_restore_service import \
BackupListRestoreRequest, BackupItem, BackupListRestoreService
from src.restore.status.restoration_job_status_service import \
RestorationJobStatusService
class TableRestoreSe... |
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
# 初始化dp[i][j] 当成二维的01背包问题
dp=[[0]*(n+1) for _ in range(m+1)]
for str in strs:
zeroNum = 0
oneNum = 0
#获得每个str下有几个0 和几个1 相当于物品价值
for i in str:
if i ==... |
import sys
assert sys.version_info >= (3,9), "This script requires at least Python 3.9"
world = {
"uuid": "1A507EF7-87D8-4EBA-865E-C5D36673C916",
"name": "YELLOWSTONE",
"creator": "Twine",
"creatorVersion": "2.3.14",
"schemaName": "Harlowe 3 to JSON",
"schemaVersion": "0.0.6",
"createdAtMs": 163121052117... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
# See: https://docs.python.org/2/library/string.html#format-specification-mini-language
import math
def main():
# "{field_name:format_spec}".format(...)
#
# format_spec ::= [[fill]align][sign][#][0... |
import uuid
from yandex_checkout.domain.common.http_verb import HttpVerb
from yandex_checkout.client import ApiClient
from yandex_checkout.domain.request.webhook_request import WebhookRequest
from yandex_checkout.domain.response.webhook_response import WebhookResponse, WebhookList
class Webhook:
base_path = '/w... |
from .cache import LRUCache |
from kasa_device_manager import KasaDeviceManager
if __name__ == "__main__":
kasa_device_manager = KasaDeviceManager()
# Print all the discovered devices out to the console
devices = kasa_device_manager.get_all_devices()
print(devices)
# Toggle a devices power state
# kasa_device_manager.tog... |
import pytest
from dynaconf import LazySettings
from dynaconf.loaders.yaml_loader import load, clean
settings = LazySettings(
NAMESPACE_FOR_DYNACONF='EXAMPLE',
)
YAML = """
# the bellow is just to ensure `,` will not break string YAML
a: "a,b"
example:
password: 99999
host: server.com
port: 8080
service:... |
# cls=20, base yolo5
import torch
import torch.nn as nn
import common as C
from torchsummary import summary
class YOLOV4(nn.Module):
def __init__(self):
super(YOLOV4, self).__init__()
self.input = nn.Sequential(
C.Conv(3, 32, 3, 1, mish_act=True),
)
self.group0 = nn.... |
import onnxruntime as ort
import numpy as np
from onnxruntime_extensions import get_library_path
# python implementation for results check
def compare(x, y):
"""Comparison helper function for multithresholding.
Gets two values and returns 1.0 if x>=y otherwise 0.0."""
if x >= y:
return 1.0
els... |
from itertools import permutations
from pytest import raises
import math
import networkx as nx
from networkx.algorithms.matching import matching_dict_to_set
from networkx.utils import edges_equal
class TestMaxWeightMatching:
"""Unit tests for the
:func:`~networkx.algorithms.matching.max_weight_matching` func... |
from unittest import TestCase
from src import utils
class TestGetLoggerName(TestCase):
def test_get_logger_name(self):
logger_name = utils.get_logger_name(self.__class__)
self.assertEqual("TesGetLogNam", logger_name)
class TestGetProxyPort(TestCase):
def test_get_proxy_port(self):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-08-24 12:46:36
# @Author : LiangJ
import base64
import json
from time import time
import tornado.gen
import tornado.web
from BeautifulSoup import BeautifulSoup
from sqlalchemy.orm.exc import NoResultFound
from tornado.httpclient import HTTP... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 11:27:20 2018
@author: DrLC
"""
import pandas
import math
import nltk
import re
import gzip, pickle
import matplotlib.pyplot as plt
def load_csv(path="test.csv"):
return pandas.read_csv(path, header=None)
def load_class(path="classes.t... |
import time
import struct
import sys
import os
import re
import threading
from functools import partial
import wx
import wx.lib.newevent as NE
from spidriver import SPIDriver
PingEvent, EVT_PING = NE.NewEvent()
def ping_thr(win):
while True:
wx.PostEvent(win, PingEvent())
time.sleep(1)
class He... |
#!/usr/bin/python
"""
To add users and see their passwords
"""
import sqlite3
from passlib.hash import pbkdf2_sha256
conn = sqlite3.connect('DB.db', check_same_thread=False)
c = conn.cursor()
c.execute('''CREATE table if not exists LOGIN(unix real, username TEXT, password TEXT, hash TEXT)''')
print "Opened database... |
import datetime
class BaseQuery(object):
supports_rolling = False
supports_isolated_rolling = False
def __init__(self, query_name, client, vars, log):
self.log = log
self.query_name = query_name
self.client = client
self.vars = vars
self.result = None
self.... |
import tensorflow as tf
hello = tf.constant('Hello, TF!')
mylist = tf.Variable([3.142,3.201,4.019],tf.float16)
mylist_rank = tf.rank(mylist)
myzeros = tf.zeros([2,2,3])
with tf.compat.v1.Session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
print(sess.run(myzeros))
print(sess.run(mylist)... |
# -*- coding: utf-8 -*-
"""
.. module:: NamedOpetope
:synopsis: Implementation of the named approach for opetopes
.. moduleauthor:: Cédric HT
"""
from copy import deepcopy
from typing import ClassVar, Dict, List, Optional, Set, Tuple, Union
from opetopy.common import *
class Variable:
"""
A variable is... |
# -*- coding: utf-8 -*-
from flask import Flask # 引入 flask
from flask import redirect
from flask import render_template
from flask import url_for
from flask_cors import CORS
from config import GlobalVar
app = Flask(__name__, template_folder=GlobalVar.BASE_DIR + '/templates') # 实例化一个flask 对象
CORS(app)
... |
# Copyright 2013 Red Hat, 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... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import re
import os
from urllib.parse import urljoin
from datetime import datetime
from bs4 import BeautifulSoup
from ferenda import util
from ferenda import Do... |
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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 agre... |
# Generated by Django 3.0.5 on 2020-04-19 04:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('spectroscopy', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='spectrophotometer',
name='produc... |
order = [
'artellapipe.tools.outliner.widgets.buttons',
'artellapipe.tools.outliner.widgets.items'
]
|
#!/usr/bin/env python
# Copyright 2020 T-Mobile, USA, Inc.
#
# 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... |
import re
from urllib.parse import urlsplit
from bs4 import BeautifulSoup
from .base_fetcher import BaseFetcher
def clean_text(tag):
text = tag.find("pre").prettify()[5:-6].replace("<br/>", "\n").replace(u'\xa0', ' ')
# print('text', repr(text), repr(tag.find("pre").get_text()))
return text
... |
from mltoolkit.mldp import Pipeline
from mltoolkit.mldp.steps.formatters import PyTorchFormatter
class PyTorchPipeline(Pipeline):
"""
Addresses the issue associated with processes that put PyTorch tensors to a
Queue object must be alive when the main processes gets/requests them from
the Queue. Format... |
import os
import sys
sys.path.append('../../')
from dquant.markets._binance_spot_rest import Binance
from dquant.markets._bitfinex_spot_rest import TradingV1
# from dquant.markets._huobi_spot_rest import HuobiRest
from dquant.markets._okex_spot_rest import OkexSpotRest
from dquant.markets.market import Market
from dqua... |
# Face.py - module for reading and parsing Scintilla.iface file
# Implemented 2000 by Neil Hodgson neilh@scintilla.org
# Released to the public domain.
# Requires Python 2.5 or later
def sanitiseLine(line):
if line[-1:] == '\n': line = line[:-1]
if line.find("##") != -1:
line = line[:line.find("##")]
line = line.... |
from setuptools import setup
from setuptools_rust import RustExtension, Binding
def read(f):
return open(f, encoding='utf-8').read()
setup(
name="PyValico",
version="0.0.2",
author='Simon Knibbs',
license='MIT',
url='https://github.com/s-knibbs/pyvalico',
author_email='simon.knibbs@gmail... |
import matplotlib.pyplot as plt
import numpy as np
import csv
markers = {
'heuristic': { 'timestamps': [], 'repl': [], 'repl_err': [], 'cost': [], 'cost_err': [], 'migr': [], 'migr_err': [], 'drop': [], 'drop_err': [], 'effc': [], 'effc_err': [] },
'optimal': { 'timestamps': [], 'repl': [], 'repl_err': [], 'co... |
# coding: utf-8
'''
===============================================================================
Sitegen
Author: Karlisson M. Bezerra
E-mail: contact@hacktoon.com
URL: https://github.com/hacktoon/sitegen
License: WTFPL - http://sam.zoy.org/wtfpl/COPYING
=============================================================... |
from configuration import configuration, dbName, debugEverythingNeedsRolling
from optionChain import OptionChain
from statistics import median
from tinydb import TinyDB, Query
import datetime
import time
import alert
import support
class Cc:
def __init__(self, asset):
self.asset = asset
def findNew(... |
"""Plotting Module."""
from scphylo.pl._data import heatmap
from scphylo.pl._trees import clonal_tree, dendro_tree, networkx_tree, newick_tree
__all__ = (heatmap, clonal_tree, dendro_tree, networkx_tree, newick_tree)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-03-05 02:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('storehouse', '0002_supplier'),
]
operations = [
migrations.CreateModel(
... |
import json
from pathlib import Path
from types import SimpleNamespace
from typing import NamedTuple, Any, Optional
from flask.testing import FlaskClient
from numpy.testing import assert_almost_equal
from osgeo_utils.auxiliary.base import PathLikeOrStr
test_env = SimpleNamespace()
test_env.root = Path('.')
test_env.... |
#!/usr/bin/python
import smtplib
import subprocess
import urllib2
from email.mime.text import MIMEText
smtp_address="YOUR SMTP LOGIN"
sender="YOUR SMTP LOGIN "
receiver="YOUR EMAIL DESTINATION"
password="YOURU SMTP PASSWORD"
uptime = subprocess.check_output('uptime')
ip_ext = urllib2.urlopen("http://ifconfig.me/i... |
from scipy.stats import norm
import math
def dice_test(stat, alfa, mode_speed):
# add parametrs for normal distribution
if mode_speed == "plt_6":
critical_const = norm.ppf(alfa, loc=0.2700502, scale=math.sqrt(0.0002832429))
p_value = norm.cdf(stat, loc=0.2700502, scale=math.sqrt(0.0002832429))
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from clickhouse_mysql.observable import Observable
class Reader(Observable):
"""Read data from source and notify observers"""
converter = None
event_handlers = {
# called on each WriteRowsEvent
'WriteRowsEvent': [],
# called on each... |
"""
Call two arms equally strong if the heaviest weights they each are able
to lift are equal.
Call two people equally strong if their strongest arms are equally strong
(the strongest arm can be both the right and the left), and so are their
weakest arms.
Given your and your friend's arms' lifting capabilities find o... |
import setuptools
setuptools.setup(
name="confluent_schema_registry_client",
version="1.1.0",
author="Tom Leach",
author_email="tom@gc.com",
description="A simple client Confluent's Avro Schema Registry",
license="MIT",
keywords="confluent schema registry client avro http rest",
url="ht... |
#!/usr/bin/env python2
"""
Dump ranks into a JS file, to be included by index.html.
The JS file contains a global "raw_data" object, with fields:
- contests: list of included contests. Each is an object with:
- name: name of the contest.
- tasks: list of tasks to include in this contest.
- scores: map each use... |
"""Responses provided by the iov42 platform."""
import json
from dataclasses import dataclass
from typing import List
from typing import Union
from ._entity import Identifier
from ._request import Request
@dataclass(frozen=True)
class BaseResponse:
"""Base class for successful platform responses."""
request... |
# -*- coding:utf-8 -*-
__author__ = 'shichao'
import platform
import tensorflow as tf
import numpy as np
import time
def iterator_demo():
'''
python iterator demo
:return:
'''
class numIter: #
def __init__(self, n):
self.n = n
def __iter__(self):
self.x = ... |
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QMessageBox, QFileDialog, QGridLayout, QHBoxLayout, \
QVBoxLayout, QGroupBox, QCheckBox, QPushButton, QAction
from PatchEdit impor... |
import typer
INFO = typer.style("INFO", fg=typer.colors.GREEN) + ": "
HELP = typer.style("HELP", fg=typer.colors.BLUE) + ": "
FAIL = typer.style("FAIL", fg=typer.colors.RED) + ": "
SUCCESS = typer.style("SUCCESS", fg=typer.colors.BLUE) + ": "
typer.echo(f"{INFO} Importing modules, please wait")
import os
im... |
#!/usr/bin/env python3.7
# Copyright 2021 DataStax, Inc.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
import torch
import onnx
from pathlib import Path
import sys
def convert2onnx(model_path,input_size,out_path=None):
if out_path is None:
out_path=Path(model_path).with_suffix('.onnx')
model=torch.load(model_path)
out_path=export2onnx(model,input_size,out_path)
return out_path
... |
from caffe2.python import core
import numpy as np
class ParameterTags(object):
BIAS = 'BIAS'
WEIGHT = 'WEIGHT'
COMPUTED_PARAM = 'COMPUTED_PARAM'
class ParameterInfo(object):
def __init__(
self, param_id, param, key=None, shape=None, length=None,
gra... |
# Criar e modificar arquivos txt
'''
'r' = Usado somente para ler algo
'w' = Usado somente para escrever algo
'r+' = Usado para ler e escrever algo
'a' = Usado para acrescentar algo
'''
numeros = [0, 15, 10, 20, 15, 45]
# Criar um arquivo e colocar as informações da lista numeros dentro dele
with open('numeros.txt... |
"""
Copyright Tiyab KONLAMBIGUE
"""
from gce import client
import logging
import time
from model import job as jobmodel
import configuration
JSON_KEY_FOLDER = configuration.JSON_KEY_FOLDER
# Google instance image project configs
IMAGES_PROJECT = configuration.IMAGES_PROJECT
class instance():
GCE_TERMINATED_STAT... |
import datapackage
from datapackage_pipelines.wrapper import ingest, spew, get_dependency_datapackage_url
dep_prefix = 'dependency://'
parameters, dp, res_iter = ingest()
url = parameters['url']
if url.startswith(dep_prefix):
dependency = url[len(dep_prefix):].strip()
url = get_dependency_datapackage_url(de... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from functools import reduce
import operator
import math
import dolfin as dl
import mshr
def sort_points_in_anti_clockwise_order(coords):
coords=coords.T
center = tuple(map(operator.truediv, reduce(lambda x, y: map(operator.add, x, y), coo... |
from fractions import Fraction
from src.seq import fibonacci, stern_diatomic_seq, fib_seq, stern_brocot
from src.graph import stern_brocot_graph
from itertools import islice
import pytest
def test_returns_first_5_numbers_of_stern_brocot():
assert take(stern_brocot, 5) == [
Fraction(1, 1),
Fraction... |
# Copyright 2020 Thiago Teixeira
#
# 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 writin... |
from datetime import datetime
from importers.e_trac_importer import ETracImporter
from importers.nmea_importer import NMEAImporter
from pepys_import.core.formats import rep_line
def test_nmea_timestamp_parsing():
parse_timestamp = NMEAImporter.parse_timestamp
# Invalid day in date
result = parse_timesta... |
from flask_wtf import FlaskForm
from wtforms import IntegerField
from wtforms import SelectField
from wtforms import SubmitField
from wtforms import StringField
from wtforms import FileField
from wtforms import SelectField
from wtforms import PasswordField
from wtforms.validators import Email, Length, Required
from wtf... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.