content stringlengths 5 1.05M |
|---|
from abc import ABCMeta, abstractmethod
from scipy.stats import f_oneway
from scipy.stats import kruskal
from scipy.stats import levene
from scipy.stats import fligner
from scipy.stats import bartlett
from oeda.log import error
from oeda.analysis import Analysis
class NSampleTest(Analysis):
def run(self, data, k... |
from django.urls import path, re_path
from dashboard import views
from daru_wheel.temp_views import spin
# from daruwheel import views as spinview
app_name = "dashboard"
urlpatterns = [
# Matches any html file
re_path(r"^.*\.html", views.pages, name="pages"),
# The home page
path("", views.index, nam... |
# -*- coding: utf-8 -*-
# file: BERT_ASPECT.py
# author: xiangpan <xiangpan.cs@gmail.com>
# Copyright (C) 2019. All Rights Reserved.
import torch
import torch.nn as nn
# TD-BERT
class BERT_ASPECT(nn.Module):
def __init__(self, bert, opt):
super(BERT_ASPECT, self).__init__()
self.bert = bert
... |
"""AR-specific Form helpers."""
from django.forms import ValidationError
from django.forms.fields import CharField, RegexField, Select
from django.utils.translation import gettext_lazy as _
from stdnum.ar import cbu
from stdnum.exceptions import InvalidLength, InvalidChecksum, ValidationError as StdnumValidationError
... |
import matplotlib.pyplot as plt
import re
with open('logs_baseline.txt', 'r') as f:
data = f.read()
train_loss = re.findall(r" loss: (0\.\d+)", data)
val_loss = re.findall(r" val_loss: (0\.\d+)", data)
train_loss = list(map(lambda x : float(x), train_loss))[:48]
val_loss = list(map(lambda x : float(x), val_los... |
# import icevision.models.rcnn.backbones as backbones
from icevision.models.rcnn import backbones
from icevision.models.rcnn.loss_fn import *
from icevision.models.rcnn.mask_rcnn.dataloaders import *
from icevision.models.rcnn.mask_rcnn.model import *
from icevision.models.rcnn.mask_rcnn.prediction import *
from icevi... |
# MQTT-to-Kinesis Bridge
from __future__ import print_function
import json
import argparse
import boto
import paho.mqtt.client as paho
from argparse import RawTextHelpFormatter
from boto.kinesis.exceptions import ResourceNotFoundException
# To preclude inclusion of aws keys into this code, you may temporarily add
#... |
# -*- coding: utf-8 -*-
# Disable while we have Python 2.x compatability
# pylint: disable=useless-object-inheritance
"""Access to the Music Library.
The Music Library is the collection of music stored on your local network.
For access to third party music streaming services, see the
`music_service` module."""
from... |
# coding: utf-8
import sys
from setuptools import setup, find_packages
NAME = "openapi_server"
VERSION = "1.0.0"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = [
"connexion>=2.0.2",
"swagger-ui-bundle>=... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.conf import settings
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding i... |
"""
Class for holding Light Curve Data
"""
from __future__ import absolute_import, print_function, division
from future.utils import with_metaclass
from future.moves.itertools import zip_longest
import abc
from collections import Sequence
import numpy as np
import pandas as pd
from astropy.table import Table
import snc... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: tensorflow_serving/apis/inference.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 _message
from google.protobuf i... |
from flask import Blueprint
api_v1_routes = Blueprint("api_v1", __name__)
from . import users, errors # isort:skip
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from .function_java_script_udf import *
from .get_job import *
from .job import *
from .out... |
# coding:utf-8
import os
import pickle
import getpass
import keyring
from halo import Halo
class UserInfoManager(object):
CORP_ID = "CORP_ID"
USER_ID = "USER_ID"
USER_PASS = "USER_PASS"
MF_SERVICE = "MF_SERVICE"
USER_INFO_PATH = os.environ["HOME"] + "/.local/share/dakoker"
def get(self) -> ha... |
from ACI_functions import *
from pprint import pprint
import xml.etree.ElementTree as et
import xmltodict, json
import smtplib
from email.message import EmailMessage
data = ''
#How many errors do you want it to ignore before it tells you about it.
#This is refrenced as if errors > theshold don't ignore it
... |
from PySide.QtGui import QUndoCommand
class EditCommand(QUndoCommand):
"""
Edit the selected cell
:var __model: QTableModel: Model for command
:var __index: QModelIndex: selected cell
:var __oldValue: string: value before redo command executed
:var __newValue: string: value before undo command... |
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
import numpy as np
from app import app
from scripts.read_data import get_language
layout = dbc.Nav([
dbc.DropdownMenu(
[dbc.DropdownMenuI... |
LANGUAGE = (
('', 'select'),
('sw', 'Swahili'),
('en', 'English'),
)
STATUS = (
('Pending','Pending'),
('Approved','Approved'),
('Discarded', 'Discarded'),
)
MEMBERSHIP = (
('','select'),
('Free', 'Free'),
('Premium', 'Premium'),
) |
from functools import cache
from logging import Logger
from typing import Any, Dict, List, Set, Tuple
import pandas as pd
from the_census._api.interface import ICensusApiFetchService
from the_census._data_transformation.interface import ICensusDataTransformer
from the_census._exceptions import EmptyRepositoryExceptio... |
class ExecutionPolicy:
RUN_ALWAYS = 0
RUN_IF_PREVIOUS_SUCCEED = 1
RUN_IF_PREVIOUS_FAILED = 2
|
from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# Importing the Kratos Library
import KratosMultiphysics
# Import applications
import KratosMultiphysics.MeshMovingApplication as KratosMeshMoving
import KratosMultiphysics.Trilinos... |
#!/usr/bin/env python3
import sys
from collections import Counter
from pprint import pprint
from tqdm import tqdm
from tools.lib.route import Route
from tools.lib.logreader import LogReader
if __name__ == "__main__":
r = Route(sys.argv[1])
cnt_valid: Counter = Counter()
cnt_events: Counter = Counter()
for q... |
import numpy
import cartopy
class topo:
"""
A class to aid in playing with the design of idealized domains
"""
def __init__(self, nj, ni, dlon=1, dlat=1, lon0=0, lat0=0, D=1):
"""
Create a topo object with a mesh of nj*ni cells with depth -D
on a mesg ranging from lon0..lon... |
from .logger import Logger
from .utility import *
from .service import *
from .youtube import *
from .nlp import *
from .main import * |
import importlib
import os
import sys
import urllib.request as urllib2
from pyspark.context import SparkContext
from pyspark.sql import SparkSession
import inspect
class Trompi(object):
_PYTHON_DIR_PATH = "./.dynamic_python_file_directory_from_file_service"
_url = '127.0.0.1:8019'
_base_directory_path = ... |
import pickle
import warnings
from pathlib import Path
import sklearn_crfsuite
from .features import transform, tokens_to_instance, load_data
from .utils import tokenize
class AddressParser:
def __init__(self, use_pretrained=True):
if use_pretrained:
here = Path(__file__).parent.absolute()
... |
#!/usr/bin/env python3
from subprocess import check_output
import argparse
proc = 'sim_server'
command = ['ps', 'x', '-o', 'pid,%cpu,%mem,command', '|', 'grep']
host = ["fisher"]
parser = argparse.ArgumentParser(description='Status of server.')
parser.add_argument("host", nargs=argparse.REMAINDER, help='host, defaul... |
import numpy as np
import torch
from sklearn.decomposition import PCA
from tqdm import tqdm
def fit_pca(X_train, X_test, X_val, n_components):
"""
Fits Principal Component Analysis on training data (first parameter),
and transforms training, validation and test data accordingly.
Parameter... |
from .fromkey import FromKey
from .tokey import ToKey
from .tensorflowscorer import TensorFlowScorer
from .datasettransformer import DatasetTransformer
from .onnxrunner import OnnxRunner
from .datetimesplitter import DateTimeSplitter
from .tokeyimputer import ToKeyImputer
from .tostring import ToString
__all__ = [
... |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
import mock
import pytest
import qitest.conf
test_gtest_one = {
"name": "gtest_one",
"cmd": ["/path/to/test_one", "--gtest_output", "foo.xml"]... |
from math import *
from cmath import rect as from_polar, exp as cexp
from frostsynth import *
from frostsynth.filters.base import *
def decay(source, factor=0.01, gain=1.0, duration=1.0, normalized=True, srate=None):
"""Exponential decay by 'factor' in time 'duration' when fed with a simple impulse."""
srate... |
from PIL import Image
from os import listdir, system
from sys import argv
from time import sleep
system('cls')
path = './beta/img/' + argv[1]
feet = int(argv[2])
ratio = 0.82, 0.57
print(path)
base = Image.open(path)
result = Image.new('RGBA', base.size, (0, 0, 0, 0))
W, H = base.size
print(W, H)
for y in range(H)... |
from torch import nn, optim, as_tensor
from torch.utils.data import Dataset, DataLoader
import torch.nn.functional as F
from torch.optim import lr_scheduler
from torch.nn.init import *
from torchvision import transforms, utils, datasets, models
from models.inception_resnet_v1 import InceptionResnetV1
import cv2
from PI... |
import pytest
import methylize
from pathlib import Path
import pandas as pd
import logging
logging.basicConfig(level=logging.DEBUG)
def test_diff_meth_regions_default():
test_folder = '450k_test'
def run_once():
import methylcheck
g69,meta = methylcheck.load_both('/Volumes/LEGX/SCS/GSE69238/')
... |
"""
Syntax
myTuple = (element1, ...., elementN)
myTupleTwo = tuple( listObject )
"""
newCars = ('Tesla','Abracada','Sopapos')
cars = tuple( ['GT86', 'Impreza','Civic','Gol','Astra','Fusca'] ) |
math_Value = {'joni':5,
'edward' : 8,
'edi' : 7,
'hendrik' : 9}
name = input("Enter the student's name: ")
if name in math_Value:
print("math value" , name , "is",
math_Value [name] )
else:
print("student data not found.")
print("the followi... |
class Solution:
def XXX(self, n: int) -> str:
def go(s):
res = ''
s += '#'
cnt = 1
for i in range(1, len(s)):
if s[i] != s[i - 1]:
res += str(cnt) + s[i - 1]
cnt = 1
else:
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 16:20:14 2020
@author: SethHarden
Nodes in a Subtree
You are given a tree that contains N nodes, each containing an integer u which corresponds to a lowercase character c in the string s using 1-based indexing.
You are required to answer Q queries of type [u, c], wh... |
#pylint: disable=too-many-function-args
#pylint: disable=no-member
""" Kacper Stysinski """
from copy import deepcopy
import pygame
import sys
GREEN = (0, 255, 133)
GRAY = (123, 123, 123)
LIGHT_GRAY = (100, 100, 100)
BLUE = (20, 20, 123)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
def check_pos(grid, row, col, val):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/GuidanceResponse) on 2020-02-03.
# 2020, SMART Health IT.
import sys
from dataclasses import dataclass, field
from typing import ClassVar, Optional, List
from .annotation import Annotation
... |
#CLIENT
import socket
from tictactoe import *
class Client:
def __init__(self):
self.ip = input("Digite o IP do servidor\n")
self.porta = input("Digite uma porta\n")
self.endereco = (self.ip, int(self.porta))
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self... |
'''
This module creates a basic logistic system.
'''
import random
class Location:
'''
Class for locations.
'''
def __init__(self, city:str, postoffice:int):
self.city = city
self.postoffice = postoffice
class Item:
'''
Class for items.
'''
def __init__(self, name:s... |
from infobip.clients import get_number_context_logs
from __init__ import configuration
get_delivery_reports_client = get_number_context_logs(configuration)
response = get_delivery_reports_client.execute({"limit": 1})
print(unicode(response))
|
nome = str(input("Informe o seu nome: "))
idade = int(input("Informe sua idade: "))
salario = float(input("Informe o seu salário: "))
print("-"*40)
print("M para masculino")
print("F para feminino")
print("-"*40)
sexo = str(input("Informe o seu sexo: "))
print("-"*40)
print("solteiro")
print("casado")
print(... |
from django.contrib import admin
from vozila_specials.models import ProjectPost, CommentP, DisLikeP, LikeP
class LikeInline(admin.TabularInline):
model = LikeP
class DisLikeInline(admin.TabularInline):
model = DisLikeP
class SiteAdmin(admin.ModelAdmin):
list_display = ('id', 'owner', 'title', 'date_cr... |
import matplotlib.pyplot as plt
import numpy as np
import mpl_toolkits.axisartist.angle_helper as angle_helper
from mpl_toolkits.axisartist import Subplot
from mpl_toolkits.axisartist import SubplotHost, ParasiteAxesAuxTrans
from mpl_toolkits.axisartist.grid_helper_curvelinear import GridHelperCurveLinear
from matplotl... |
from genetic_optimizer import *
import pdb
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
import itertools
import time
columns = ['Survived', 'Pclass', 'S... |
import matplotlib.pyplot as plt
import numpy as np
from environment.corridor_gridworld import ShortCorridor
class Agent:
def __init__(self, env):
self.env = env
def play(self, number_of_episodes, prob_to_right=0):
reward_cumulate = 0
for _ in range(number_of_episodes):
sel... |
from PyQt4 import Qt, QtCore, QtGui
from taurus.qt.qtgui.resource import getThemeIcon
import panic, fandango
from widgets import iLDAPValidatedWidget
class dacWidget(QtGui.QWidget):
def __init__(self,parent=None,container=None,device=None):
QtGui.QWidget.__init__(self,parent)
self._dacwi = devattr... |
from django.conf.urls import url
from .views import UserAPIView, Login, Logout, Signup
urlpatterns = [
url(r'^list/$', UserAPIView.as_view(), name="User"),
url(r'^signup/$', Signup.as_view(), name='Signup'),
url(r'^retrieve_update_destroy/(?P<pk>[\d]+)/$', UserAPIView.as_view(), name="User APi"),
url(r... |
# Generated by Django 2.2.2 on 2019-09-04 18:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pages', '0006_auto_20190904_2314'),
]
operations = [
migrations.RenameField(
model_name='service',
old_name='image_name',
... |
#-*- coding: utf-8 -*-
""" Сейчас порог (VOLTAGE_THRESHOLD) не рассчитывает
"""
# core
# utils
import json
# Other
import uasio.os_io.io_wrapper as iow
from jarvis.py_dbg_toolkit.doColoredConsole import co
import convertors_simple_data_types.xintyy_type_convertors as tc
import convertors_simple_data_types.float32_c... |
N = int(input())
result = False
for a in range(25):
for b in range(14):
if 4 * a + 7 *b == N:
result = True
print("Yes" if result else "No")
|
"""run diffusion equation to determine selectivity of fluophore,
i.e current and release time series for specific molecule."""
from nanopores.tools.fields import cache
import nanopores
import dolfin
import matplotlib.pyplot as plt
from nanopores.physics.convdiff import ConvectionDiffusion
import forcefields
from eikona... |
import csv
import json
import requests
import operator
import trade_history_downloader
class Order:
def __init__(self, side, symbol, shares, price, date, state):
self.side = side
self.symbol = symbol
self.shares = float(shares)
self.price = float(price)
self.date = date
self.state = state
def pl(self):... |
import os
from libsunnetimport*
import numpy as np
import imageio
import random
import ctypes
import datetime
# create net
net = snNet.Net()
net.addNode("In", snOperator.Input(), "C1") \
.addNode("C1", snOperator.Convolution(10, (3, 3), -1), "C2") \
.addNode("C2",snOperator.Convolution(10,(3, 3), 0), "P1 Crop... |
# -------------------------------------------------------------------------
# This module contains all of the parameters, funcions and classes that
# are used across more than one signal type
# -------------------------------------------------------------------------
from . import common
from . import dcc_control
fro... |
from flask import Flask, render_template, redirect, request
import os
import sqlite3 as sql
port = 5000
app = Flask(__name__, template_folder="contests")
@app.route('/')
def index():
conn = sql.connect("sqlite.db")
conn.row_factory = sql.Row
cur = conn.cursor()
cur.execute("SELECT contest_id, contest_name FROM co... |
import os
import unittest
from datetime import datetime
from unittest.mock import patch
import duolingo
USERNAME = os.environ.get('DUOLINGO_USER', 'ferguslongley')
PASSWORD = os.environ.get('DUOLINGO_PASSWORD')
USERNAME2 = os.environ.get("DUOLINGO_USER_2", "Spaniard")
def _example_word(lang):
"""
Returns an... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Jiyuan Zhou
Enable an agent to follow a hard coded trajectory in the form of
a square with rounded corners using trained straight and circle models.
"""
import argparse
import cProfile
import pstats
import sys
import time
import math
import yaml
import joblib... |
import searchInsertPositions
import unittest
class SearchInsertPositionsCase(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_searchInsertPositions(self):
s = searchInsertPositions.Solution()
for nums, target, sol in [ ([1, 3, 5, 6], 7, ... |
from abc import ABC, abstractmethod
import math
import lru
import numpy as np
import torch
from textattack.goal_function_results.goal_function_result import (
GoalFunctionResultStatus,
)
from textattack.shared import utils, validators
from textattack.shared.utils import batch_model_predict, default_class_repr
c... |
from setuptools import setup
setup(
name='zpylib',
version='0.1dev',
packages=['zpylib'],
license='See LICENSE.txt',
)
|
import ctypes
import os.path
class DeviceUnderTest:
def __init__(self):
dll_name = "simulation.so"
dllabspath = \
os.path.dirname(os.path.abspath(os.path.abspath(__file__))) \
+ os.path.sep + ".." + os.path.sep + ".." \
+ os.path.sep + "Software" + os.path.sep +... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
# Written by Hu Di
import pytest
import os
import subprocess
def pytest_sessionstart(session):
faster_rcnn_working_dic = os.path.join(os.path.dirname(__file__), '../')
subprocess.run(['make'], shell=True, cwd=faster_rcnn_working_dic)
|
import lib.Settings as settings
from lib.Locale import _
from lib.Locale import locCurrency
from lib.Locale import locDate
import os
import math
import threading
import platform
from tkinter import *
from tkinter import messagebox
from lib.Widgets import Frame_
from lib.Widgets import LabelButton_
from lib.Wid... |
import setuptools
with open('README.md') as f:
long_description = f.read()
setuptools.setup(
name='m3u8',
version='0.0.1',
author='WaizungTaam',
author_email='waizungtaam@gmail.com',
license='MIT',
description='Python m3u8 parser',
long_description=long_description,
packages=['m3... |
#!/usr/bin/env python
# file: osversion.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# Created: 2018-04-06 22:34:00 +0200
# Last modified: 2018-08-19T14:18:16+0200
"""Print the __FreeBSD_version. This is also called OSVERSION in scripts."""
from ctypes import CDLL
import s... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# Create Flask application, load configuration, and create
# the SQLAlchemy object
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///network.db'
db = SQLAlchemy(app)
# This is the database model object
class Device(db.Model):
_... |
import cv2
class DisplayDraw(object):
def __init__(self, parent=None):
self.indicator_text_setting = {
'fontFace': cv2.FONT_HERSHEY_SIMPLEX,
'fontScale': 1.0,
'color': (0, 255, 0),
'thickness': 1,
'lineType': cv2.LINE_AA
}
self.las... |
"""Constants for the DLNA DMR component."""
from __future__ import annotations
from collections.abc import Mapping
import logging
from typing import Final
from async_upnp_client.profiles.dlna import PlayMode as _PlayMode
from homeassistant.components.media_player import const as _mp_const
LOGGER = logging.getLogger... |
from setuptools import setup, find_packages
import pathlib
HERE = pathlib.Path(__file__).parent
README = (HERE / "README.md").read_text()
setup(
name = "Physical Quantity calculating",
version = '0.1.0',
description=
'''
In arithmetic operations, the corresponding physic... |
import os
import re
import torch
import numpy as np
import ConfigSpace
from functools import partial, wraps
from pathlib import Path
from torch.autograd import Variable
from ConfigSpace.read_and_write import json as cs_json
from nes.darts.baselearner_train.genotypes import Genotype, PRIMITIVES
only_numeric_fn = lam... |
from iso3166 import countries
TYPE = ('alert', 'update', 'test', 'cancel')
COUNTRY = {y[0]:y[1] for y in sorted(((x.numeric, x.name) for x in countries), key=lambda x: int(x[0]))}
PROVIDER = ('none', )
CATEGORY = (
('geo1', (
'earthquake',
'tsunami',
'sinkhole',
'avalanche',
... |
#-*- coding: UTF-8 -*-
import sys, os, click
from . import browser
learn = browser.Learn()
@click.command(help = 'Download all course files')
def download():
learn.init()
lessons = learn.get_lessons()
for lesson in lessons:
click.echo("Check " + lesson[1])
groups = learn.get_files_id(lesson[0])
for group in... |
#!/usr/bin/env python3
import math
import random
'''
The AutoSortedArray class encapsulates a list and arranges such that
if we add items one by one (using the .append() method), we do not have
to remember to sort the list after populating it-- items are inserted
in sorted order.
A binary search is done to determi... |
"""BackgroundFrame for the App."""
from __future__ import annotations
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import (
QFrame,
QGraphicsDropShadowEffect,
QHBoxLayout,
QWidget,
)
class BackgroundFrame(QFrame):
"""BackgroundFrame for the App."""
def __init__(self, parent: QWidget |... |
from __future__ import annotations
from collections import defaultdict
from typing import Dict, List, Tuple
from .solution import Solution
BagColor = str
SHINY_GOLD = "shiny gold"
class BagsRules:
__slots__ = "_graph"
def __init__(self):
self._graph: Dict[BagColor,
List... |
# Philip Brady
# This is the Weekly Task 6.
# The program takes a positive floating-point
# number as input and outputs an approximation
# of its square root. The function called sqrt
# does this.
# Imported the math module.
import math
# Created a function that takes the value x.
def sqrt(x):
# Used the sqrt fu... |
# Copyright 2009-2017 Ram Rachum.
# This program is distributed under the MIT license.
from python_toolbox.nifty_collections import WeakKeyDefaultDict
from python_toolbox import gc_tools
class WeakreffableObject:
''' '''
def __lt__(self, other):
# Arbitrary sort order for testing.
return id(s... |
from inspect import signature, Signature, Parameter
from typing import Any, _TypedDictMeta, T_co, Union, _GenericAlias
from i2.errors import InputError
COMPLEX_TYPE_MAPPING = {}
JSON_TYPES = [list, str, int, float, dict, bool]
def mk_sub_dict_schema_from_typed_dict(typed_dict):
total = getattr(typed_dict, '__tot... |
"""Support for a Emonitor channel sensor."""
from __future__ import annotations
from aioemonitor.monitor import EmonitorChannel, EmonitorStatus
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.config_entries ... |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
from .qio import (
ParallelTempering,
SimulatedAnnealing,
Tabu,
QuantumMonteCarlo,
PopulationAnnealing,
SubstochasticMonteCarlo,
)
|
from django.db.models.query import RawQuerySet
from django.db.models import sql
from django.core.paginator import Paginator
from rest_framework.pagination import PageNumberPagination
class Pagination(PageNumberPagination):
"""
DRF pagination_class, you use it by saying:
class MyView(GenericAPIView):
... |
# -*- coding: utf8 -*-
from __future__ import print_function, unicode_literals
import json
import logging
from . import BaseParser
logger = logging.getLogger("config")
class JsonParser(BaseParser):
"""
Parse config from json.
"""
def __init__(self, name):
"""
:param name: parser n... |
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
"""Dependencies that linter rules depend on."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def lowrisc_misc_linters_dependencies():
"""Declare... |
"""
"""
# IMPORT modules. Must have unittest, and probably coast.
import coast
from coast import general_utils
import unittest
import numpy as np
import pytz
import datetime
import unit_test_files as files
class test_general_utils(unittest.TestCase):
def test_copy_coast_object(self):
sci = coast.Gridded... |
from allauth.account.forms import SignupForm
from django import forms
from bims.models import Profile
class CustomSignupForm(SignupForm):
first_name = forms.CharField(
max_length=150,
label='First Name',
required=True)
last_name = forms.CharField(
max_length=150,
label=... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from ldshell.helpers import create_socket_address, parse_socket_address
from nubia import... |
from lms_code.analysis.run_bem import bemify, boundary_conditions,\
assemble, constrain, solve, evaluate_surface_disp, set_params,\
create_fault_mesh, create_surface_mesh, pin_ends_constraint,\
apply_jump_constraint
import lms_code.lib.rep2 as rep2
from codim1.core.tools import plot_mesh
import sys
import m... |
# -*- coding: utf-8 -*-
from cradmin_legacy import crapp
from cradmin_legacy.crinstance import reverse_cradmin_url
from devilry.devilry_deadlinemanagement.cradmin_app import ExaminerDeadlineManagementApp
from devilry.devilry_deadlinemanagement.views import deadline_listview
from devilry.devilry_deadlinemanagement.vi... |
# encoding: utf-8
from django.conf.urls import url
from uploader.views import FileListView
from uploader.views import FileCreateView
urlpatterns = [
url(r'^$', FileListView.as_view(), name='list'),
]
|
from flask_wtf import FlaskForm
from wtforms import SubmitField,StringField, IntegerField, RadioField, SelectField
class SearchForm(FlaskForm):
animal_name = StringField('Animal Name')
species = StringField('Species')
# gender = RadioField("Gender",choices=[('M',"Male"),('F',"Female")])
category = SelectField(... |
import Crypto.Util.Counter
from Crypto.Cipher import AES
from math import ceil
from math import log
def to_int(b):
num = 0
for i in range(len(b)):
num |= b[i] << (i * 8)
return num
class AESCTR(object):
def __init__(self, key, iv):
self.__aes = AES.new(
key,
AE... |
import spellchecker
from nltk.stem import PorterStemmer, WordNetLemmatizer
from sacremoses import MosesDetokenizer
from lti_app.caching import caching
from lti_app.core.api import LanguageToolClient
from lti_app.core.text_processing.parser import Parser
from lti_app.helpers import Singleton
class Tools(metaclass=Sin... |
import numpy as np
def get_data(file):
f = open(file, 'r')
data = []
for line in f:
line = line.strip()
data.append(line)
return data
# L = sequence length, P = motif length
def init_EM(L, P):
lmbda = np.random.uniform(0,1,size=(L,))
lmbda = lmbda/np.sum(lmbda) # normalization... |
#!/usr/bin/env python
"""
Contains modules for platform-specific methods.
"""
|
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from python_pachyderm.client.pps import pps_pb2 as client_dot_pps_dot_pps__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
class APIStub(object):
# missing associated documentation comment in .proto fi... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# @fb-only: from . import fb, fbnet_v2 # noqa
# Explicitly expose all registry-based modules
__all__ = [
"fbnet_v2",
# @fb-only: "fb",
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.