content stringlengths 5 1.05M |
|---|
import oneflow as flow
from otrans.data import EOS, PAD
class Recognizer:
def __init__(self, model, idx2unit=None, lm=None, lm_weight=None, ngpu=1):
self.ngpu = ngpu
self.model = model
self.model.eval()
if self.ngpu > 0:
self.model.cuda()
self.lm = lm
... |
import pandas as pd
if __name__ == '__main__':
website = 'https://www.peakbagger.com/'
links = pd.read_csv('raw_data/links.csv')
links['full_link'] = website + links['link']
full_links = links[['Mountain', 'full_link']]
full_links = full_links.rename(columns={'full_link': 'link'})
full_links.t... |
""" Simulation configuration for non-rl centralized experiments.
A guiding tool for preparing these configurations can be found in:
https://github.com/flow-project/flow/tree/master/tutorials
or in the directory:
flow/tutorials.
A heavy emphasis on:
1. tutorial 1 (https://github.com/flow-project/flow/blob/mas... |
from random import randint
class CurrentAcc:
def validate(self, name, accnumber):
self.name = name
self.accnumber = accnumber
def balance(self, balance):
self.balance = balance
def withdraw(self, amount):
self.amount = amount
def deposit(self, amount):
... |
"""Provided Cluster class for simulation"""
import json
import cerberus
import numpy as np
from bson import json_util
from aries.core import utils
from aries.simulation import simulation_utils
# Schema for cluster validation
cluster_schema = {
'cluster_agents': {'type': 'list', 'schema': {'type': 'string'}},
... |
# import modules
from bot.bot import Bot
import bot.constants as constants
# import discord.py api wrapper
import discord
from discord.ext import commands, tasks
# import python utility libraries
import os
import sys
from datetime import datetime
from bot import constants
# Import the configuration
try:
from co... |
import numpy as np
import pandas as pd
from pydantic import BaseModel, Field, validator
from scipy import stats
from typing import Union, Callable, List
class ProbVar(BaseModel):
name: str
dist: str = Field('norm')
kw : dict = Field({'loc':0,'scale':1})
factor: float = Field(1.0)
constant: float = ... |
# Copyright 2020 The Kubeflow Authors
#
# 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... |
"""
Module to set up run time parameters for Clawpack.
The values set in the function setrun are then written out to data files
that will be read in by the Fortran code.
"""
import os
from pyclaw import data
from math import pi
def setrun(claw_pkg='classic'):
"""
Define the parameters used for ... |
class Quest:
def __init__(self, dbRow):
self.id = dbRow[0]
self.name = dbRow[1]
self.description = dbRow[2]
self.objective = dbRow[3]
self.questType = dbRow[4]
self.category = dbRow[5]
self.location = dbRow[6]
self.stars = dbRow[7]
self.zenny = dbRow[8]
def __repr__(self):
return f"{self.__dict... |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Matthias Urlichs <matthias@urlichs.de>
# Based on work Copyright (c) 2018 Steven P. Goldsmith
"""
libgpiod CFFI interface
-------------
This is a stripped-down version which doesn't do "bulk" access (no point IMHO)
and doesn't implement an event loop (that's Trio's job).
"... |
from streamlink.plugin.api.validate._exception import ValidationError # noqa: F401
# noinspection PyPep8Naming,PyShadowingBuiltins
from streamlink.plugin.api.validate._schemas import ( # noqa: I101, F401
SchemaContainer,
AllSchema as all,
AnySchema as any,
TransformSchema as transform,
OptionalSch... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
estimate_gradient_norm.py
A multithreaded gradient norm sampler
Copyright (C) 2017-2018, IBM Corp.
Copyright (C) 2017, Lily Weng <twweng@mit.edu>
and Huan Zhang <ecezhang@ucdavis.edu>
This program is licenced under the Apache 2.0 licence,
contained... |
import dash
import dash_html_components as html
import dash_core_components as dcc
import plotly.express as px
from dash.dependencies import Input, Output
from eda import calculate_basic_statistics
def show_dashboard(data):
app = dash.Dash('Product Reviews')
nr_of_all_reviews = calculate_basic_statistics(da... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
Pytorch modules
some classes are modified from HuggingFace
(https://github.com/huggingface/transformers)
"""
import copy
import json
import logging
from io import open
import torch
from torch import nn
from apex.normalization.fused_layer_norm im... |
class Solution:
# @param A : list of integers
# @param B : list of integers
# @return an integer
def mice(self, A, B):
mice = sorted(A)
holes = sorted(B)
return max([abs(a-b) for a, b in zip(mice, holes)]) |
#
# Copyright 2017 Luma Pictures
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Tradem... |
# File: Bowling.py
# Description: Calculates the score of a bowling match
# Student's Name: Minh-Tri Ho
# Student's UT EID: mh47723
# Course Name: CS 313E
# Unique Number: 50940
#
# Date Created: 01/29/16
# Date Last Modified: 02/02/16
#Shows the upper part of the scoring
def printHeader():
pr... |
import sys
from PyQt5.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyStock")
self.setGeometry(300, 300, 300, 400)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app... |
import re
from django import template
register = template.Library()
template.base.tag_re = re.compile(template.base.tag_re.pattern, re.DOTALL)
'''
Usage:
------
{% stash 'contact_link' %}
<a href='/v2/contacts/{{ contact_id }}'>{{ contact_name }}</a>
{% endstash %}
{% stash_apply 'contact_link'
... |
import torch
from torch import nn, Tensor
from typing import Union, Tuple, List, Iterable, Dict
from .BatchHardTripletLoss import BatchHardTripletLoss
class BatchHardSoftMarginTripletLoss(BatchHardTripletLoss):
def __init__(self, sentence_embedder):
super(BatchHardSoftMarginTripletLoss, self).__init__(sen... |
import tensorflow as tf
import numpy as np
from transformer import Transformer
from preprocess import DataPreprocesser
from vqa import VQA
from vqa_iter import VQAIter
from tokenizer import MyTokenizer
from encoder import Encoder
from decoder import Decoder
import tqdm
from loss import loss_cosine_similarity
from custo... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-10-14 21:56
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('logistics', '0012_shipment_unique_id'),
]
operatio... |
import os
import sys
import csv
import pysftp
from constants import *
def downloadeFile(fileId, contentType):
FORMAT = ""
if contentType == "image":
FORMAT = IMAGE_FORMAT
elif contentType == "video":
FORMAT = VIDEO_FORMAT
try:
s = pysftp.Connection(SERVER, username=MY_USER, pa... |
# Provision users/groups via direct invocation of the Databricks SCIM API
# given user/group config (may be exported from AAD)
import requests, json, logging
from requests.exceptions import HTTPError
log = logging.getLogger()
USERS_ENDPOINT = '/api/2.0/preview/scim/v2/Users'
GROUPS_ENDPOINT = '/api/2.0/preview/scim/... |
import rospy
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image, CompressedImage
class ImageReceiverROS:
def __init__(self, topic_name):
self.bridge = CvBridge()
self.image_sub = rospy.Subscriber(topic_name, Image, self.callback, queue_size=1)
self.cv_image =... |
import uuid
import os
from flask_pymongo import PyMongo, wrappers
from database import mongo
from util import sanitize_input
from models.user import User
if os.path.exists(".installed"):
raise "webdock is installed"
print("Webdock installation")
username = sanitize_input(input("username: "))
password = sanitize... |
"""
Copyright 2020 ETH Zurich, Secure, Reliable, and Intelligent Systems Lab
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 requi... |
"""
Simple cubic packing(scp) simulator
scp is the simplest packing structure. Each sphere is
coordinated by max. 6 neighbouring spheres.
Volume of a unit cell = 2 * (radius ^ 3)
No. of spheres in one unit cell = 1
This script/module calculates maximum no. of spheres added to a cuboid with
... |
import math
import numpy as np
from astropy.coordinates import SkyCoord
from ..constant import ALPHA_NGP, DELTA_NGP, L_NCP, AU, tropical_year
def parse_pairwise(arg):
"""Parse value with error"""
if (isinstance(arg, list) or isinstance(arg, tuple)) and \
len(arg)==2:
return arg
else:
... |
from typing import List
class Solution:
"""
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
"""
@staticmethod
def find_median_sorted_arrays(nums1_list: List[int], nums2_list: List[int]) -> float:
nums1_list.extend(nums2_list)
... |
import gdb, socket, cPickle, os, time
CWD = os.path.abspath(os.path.dirname(__file__))
sys.path.append(CWD)
from python_gdb_common import *
#import gdb_printers
class GdbDriver:
def __init__(self):
# We register some handlers for events
gdb.events.stop.connect (self.stopEvent)
# gdb.ev... |
import json # we need to use the JSON package to load the data, since the data is stored in JSON format
from data_process import generate_data
def read_data():
'''Open the original json file with the data'''
# popularity_score : a popularity score for this comment (based on the number of upvotes) (type: floa... |
# --------------------------------------------------------
# mcan-vqa (Deep Modular Co-Attention Networks)
# Licensed under The MIT License [see LICENSE for details]
# Written by Yuhao Cui https://github.com/cuiyuhao1996
# --------------------------------------------------------
from cfgs.path_cfgs import PATH
# from ... |
FreeSerifItalic9pt7bBitmaps = [
0x11, 0x12, 0x22, 0x24, 0x40, 0x0C, 0xDE, 0xE5, 0x40, 0x04, 0x82, 0x20,
0x98, 0x24, 0x7F, 0xC4, 0x82, 0x23, 0xFC, 0x24, 0x11, 0x04, 0x83, 0x20,
0x1C, 0x1B, 0x99, 0x4D, 0x26, 0x81, 0xC0, 0x70, 0x1C, 0x13, 0x49, 0xA4,
0xDA, 0xC7, 0xC1, 0x00, 0x80, 0x1C, 0x61, 0xCF, 0x0E, 0x... |
import asyncio
import asyncpg
from config import DB_BIND
QUERIES = open('migrate.sql', 'r').read()
def log(connection, message):
print(message)
async def main():
db = await asyncpg.connect(DB_BIND)
db.add_log_listener(log)
async with db.transaction():
await db.execute(QUERIES)
# populate facts if empty... |
'''
Creating the data in this format :
train_data = [
{
'context': "This tweet sentiment extraction challenge is great",
'qas': [
{
'id': "00001",
'question': "positive",
'answers': [
{
'text': ... |
from typing import Sequence, Tuple
from sympy.physics.units import Dimension, DimensionSystem
from sympy.physics.units.systems.si import dimsys_default
def extend(*args: Tuple[str, str, Dimension], dimsys: DimensionSystem = None) -> Tuple[DimensionSystem, Sequence[Dimension]]:
'''Extends a dimension system by th... |
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import numpy as np
import random
class TenArmedBanditGaussianRewardEnv(gym.Env):
metadata = {'render.modes': ['human']}
def __init__(self, seed=42):
self._seed(seed)
self.num_bandits = 10
# each reward distri... |
from pyrete.core.nodes import (
ReteGraph,
)
from pyrete.core.engine import (
RuleEngine,
)
from pyrete.core.data_layer import (
DataLayer,
)
from pyrete.core.variable_processor import (
VariableProcessor,
)
rule = {
'key': 'sample_rule',
'description': 'A sample rule',
'collections': [
... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from setup... |
# -*- coding: utf-8 -*-
import os
import logging
import requests
from wagtail.core import signals as wtcsig # type: ignore[import]
logger = logging.getLogger(__name__)
def trigger_netlify_build_hook(sender, **kwargs):
"""Tigger Netlify build hook."""
instance = kwargs['instance']
logger.info(
... |
import pickle
classifier_f = open("naivebayes.pickle", "rb")
classifier = pickle.load(classifier_f)
classifier_f.close() |
from flask import Flask, request, redirect, render_template, send_file
from PrivateLib.PEKS.Othertools.utils import base64_to_byte, byte_to_base64
from werkzeug.datastructures import FileStorage
from PrivateLib.Receiver import *
from PrivateLib.Sender import *
from PrivateLib.Parser import *
import os, hashlib, request... |
import re
from ..schema import types
from .external_documentation import ExternalDocumentation
from .paths import Paths
from .info import Info
from .tag import Tag
from .server import Server
from .components import Components
from .extensions import SpecificationExtensions
OPENAPI_VERSION = '3.0.1'
OpenApi = type... |
import os
import shutil
import random
import numpy as np
import cv2
import json
from detectron2.structures import BoxMode
"""
Setup directories and {train, val, test} splits according to a given configuration.
Also create a meta_info.json file un each subdirectories contains information
relevant to detec... |
from bs4 import BeautifulSoup
from bs4 import NavigableString
import requests
import json
import datetime
import re
monsterHolder = {}
monsterHolder['name'] = 'Pathfinder 2.0 monster list'
monsterHolder['date'] = datetime.date.today().strftime("%B %d, %Y")
attackEle = set(("Critical Success", "Success", "Failure", "E... |
# -*- encoding: utf-8 -*-
# django apps
from django.db import models
class CardStatus(models.Model):
''' 银行卡的状态 '''
name = models.CharField(max_length=16, verbose_name='名称')
remark = models.TextField(blank=True, verbose_name='备注')
def __str__(self):
return self.name
class CardOperateType(... |
import unittest
import sys
import os
sys.path.append(os.path.dirname(os.getcwd()))
import cjkstr
class TestCJKStr(unittest.TestCase):
def test_count_cjk_chars(self):
self.assertEqual(cjkstr.count_cjk_chars("hello"), 0)
self.assertEqual(cjkstr.count_cjk_chars("測試一下"), 4)
self.assertEqual(cjk... |
class persona ():
def __init__ (self, nombre,apellido,cedula,telefono,direccion):
self.nombre=nombre
self.apellido=apellido
self.cedula=cedula
self.telefono=telefono
self.direccion=direccion
def __repr__(self):
return "nombre: "+self.nombre+" apellido: "+self,ap... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-03 15:59
from __future__ import unicode_literals
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('markets3', '0005_auto_20160803_1024'),
]
operations = [
... |
from typing import List
def transform_to_string(list: List[List[str]]) -> str:
return ';'.join([','.join([str(x) for x in sorted(sublist)]) for sublist in list]) |
import argparse
from pprint import pprint
import platform
def parse_args(version):
'''
Parse arguments.
'''
# Basic argument parsing.
parser = argparse.ArgumentParser(
description='EDAPI: Elite Dangerous API Tool',
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
#... |
# Copyright (C) [2022] by Cambricon, Inc.
#
# 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, pu... |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.task.target_restriction_mixins import (
DeprecatedSkipAndDeprecatedTransitiveGoalOptionsRegistrar,
HasSkipAndTransitiveGoalOptionsMixin,
)
class FmtGoalRegistrar(Deprecate... |
from rest_framework import APIView
class user_list(APIView):
queryset = Users.objects.all()
serializer_class = UsersSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs) |
'''
Storage for common doc strings and templates shared in non-related classes and methods.
'''
class DOC_TEMPLATE:
#---------------------------------------------------------------------------
# functions
to_html = '''
Return an HTML table representation of this {class_name} using standard TABLE, TR,... |
import rospy
from rospy.exceptions import ROSInterruptException
def handle_shutdown_exception(func):
def wrapped(*args, **kwargs):
try:
return func(*args, **kwargs)
except ROSInterruptException as e:
if str(e) == 'rospy shutdown':
rospy.logwarn('Service faile... |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring,unused-import,reimported
import json
import pytest # type: ignore
import json_schema_tangle_weave.cli as cli
def test_main_ok_json():
job = ['name_of_schema.json']
assert cli.main(job) is 0
def test_main_ok_json_md():
job = ['name_of_prose.j... |
from jeri.core.backends.backend import Backend
import re
import requests
def _get(url, params=None):
response = requests.get(url, params=params)
if response.status_code != 200:
raise RuntimeError('API call failed')
return response.json()
def _get_all(url, offset=0):
parameters = {'offset': o... |
#!/usr/bin/python
###########################################################################
#
# Copyright 2019 Dell, 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.... |
import subprocess
import pyautogui
import time
repeattime = 20
i = 0
subprocess.call([r"BROWSER_PATH"]) # browser launching
time.sleep(5)
while(i <= repeattime):
pyautogui.click(819, 58) # click on url field
pyautogui.hotkey("ctrl", "v")# past the target link from clipboard
pyautogui.press("enter"... |
#!/usr/bin/python3
# coding: utf-8
import random
import sys
import string
def chooseWord():
word='swordfish'
return word
def displayWord(word, letters):
"""
Fonction permettant d'afficher le mot word
en n'affichant que les lettres contenues dans
le tableau letters
Renvoit True si le mot ... |
'''
Worldbank schema
=================
Schema for Worldbank sociodemographic data. Excuse the verbose
variable names, but the alternative would have been raw codes like
'NYGDPMKTPSAKD', so I opted for an auto-generated human-readable schema.
'''
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.... |
from django.contrib.postgres.aggregates.general import ArrayAgg, BoolOr
from django.contrib.postgres.search import SearchRank
from django.db.models import (
Exists,
F,
IntegerField,
Q,
Value,
Case,
When,
BooleanField,
OuterRef,
FilteredRelation,
)
from django.db.models import Que... |
class Environment(object):
def __init__(self, base_url):
self.base_url = base_url
|
import logging
from ..job import Job
from ..types import QueueName, WorkerNumber, SysExcInfoType
logger = logging.getLogger(__name__)
class LoggingMiddleware:
def process_job(self, job: Job, queue: QueueName, worker_num: WorkerNumber) -> None:
logger.info("Running job {}".format(job))
def process_r... |
'''
Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50.
'''
#minha resolução
for par in range(2,51,2):
print(par)
print('Fim!')
#resolução do curso
'''A resolução ficou parecida com a minha.'''
|
from django.test import TestCase
from django.utils import timezone
from django.core import mail
from mock import patch
from bluebottle.test.factory_models.accounts import BlueBottleUserFactory
from bluebottle.test.models import TestBaseUser
from bluebottle.test.factory_models.tasks import TaskFactory, TaskMemberFacto... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 17 17:37:48 2019
@author: salim
@Practica
"""
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt #para dibujos
#-------------------------- 1- Connectarse al repertorio-------------------------------------------------... |
"""
Constants for DCA
"""
# App imports.
from dca.utils import default
DCA_DIR = default('DCA_DIR', 'dca_dir')
DCA_PORT = default('DCA_PORT', '50051')
DCA_SUFFIX = default('DCA_SUFFIX', 'dca')
DCA_CUSTOM = default('DCA_CUSTOM', 'dca_custom')
DCA_AUTO_PACKAGE = default('DCA_AUTO_PACKAGE', 'auto_dca')
# Derived cons... |
#!/usr/bin/env python3
import mistune
def parse_markdown(filename):
""" Takes a .md file and returns a parsed version in HTML.
Parses a markdown file using mistune, returns a string which
contains the parsed information in HTML.
Args:
filename: the file to be parse, must... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 29 23:01:19 2020
@author: GÜRAY
"""
##################################################
## ## ## ## ### ## ## ### ##
#### #### ### ## ## ## ## ## ### ## ### ## ### ##
#### #### ### ## ### # # ## ### ## ### ## ### ##
#### #### ### ## ## ##... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import *
from django import forms
from ckeditor.widgets import CKEditorWidget
from django.core.mail import send_mail
from django.core.mail import EmailMultiAlternatives
from cambiaahora.utils import *
class ResultadoInline(admin.TabularInline):
... |
import itertools
import rpy2.rlike.indexing as rli
class OrdDict(dict):
""" Implements the Ordered Dict API defined in PEP 372.
When `odict` becomes part of collections, this class
should inherit from it rather than from `dict`.
This class differs a little from the Ordered Dict
proposed in PEP 37... |
import sys
import matplotlib.pyplot as plt
import torch
sys.path.append("..")
from pfhedge.instruments import BrownianStock
from pfhedge.instruments import EuropeanOption
from pfhedge.nn import BlackScholes
if __name__ == "__main__":
options_list = []
strikes_list = []
for call in (True, False):
... |
from typing import List
from math import gcd
from fractions import Fraction
"""
example matrix:
[
[0, 1, 0, 0, 0, 1],
[4, 0, 0, 3, 2, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
]
"""
def transform_matrix(m: List[List]):
"""
example matrix becomes... |
"""
Class for reading pre-processed OpenFOAM data in the PyTorch tensor format
Alternatively once can use foamReader for directly readin OpenFOAM output files.
However the latter is slower, thus pre-processing is encouraged.
===
Distributed by: Notre Dame CICS (MIT Liscense)
- Associated publication:
url: https://www.s... |
from basis_modules.helpers.testing import TestImporter
from basis_modules.modules import square
test_payments = TestImporter(
function_key="square.import_payments",
module=square,
# params={},
params_from_env={"access_token": "TEST_SQUARE_ACCESS_TOKEN"},
expected_records_cnt=100,
expected_recor... |
import unittest
import pandas as pd
import os
import pytest
import numpy as np
from pandas.testing import assert_frame_equal
import src.join_df as join_df
class Test_join_df(unittest.TestCase):
def test_main(self):
emotion = pd.read_csv("test/csv_test/join_emotion_test.csv")
characters = pd.read... |
# Internal libraries
import os
import itertools
# Internal modules
from contact import Contact
from ticket import Ticket
# External libraries
from pymongo import MongoClient, errors
class Database(object):
"""docstring for Database."""
def __init__(self):
self.client = MongoClient(os.getenv('DB_HOST... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 applicable law o... |
from tractseg.config.PeakRegHP import HP as PeakRegHP
class HP(PeakRegHP):
DATASET = "HCP_32g"
RESOLUTION = "2.5mm"
FEATURES_FILENAME = "32g_25mm_peaks" |
from aiogram.dispatcher.filters.state import StatesGroup, State
class CheckoutState(StatesGroup):
check_cart = State()
name = State()
phone = State()
address = State()
confirm = State() |
# -*- coding: utf-8 -*-
import fileinput
from lxml import etree
import os
from geodata.address_formatting.formatter import AddressFormatter
#class AddressFormatter(object):
# CATEGORY = 'category'
# NEAR = 'near'
# ATTENTION = 'attention'
# CARE_OF = 'care_of'
# HOUSE = 'house'
# HOUSE_NUMBER = 'house_number'
# PO_... |
# 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 a... |
import json
import requests
from loguru import logger
import time
import re
import execjs
import base64
import os
import pandas as pd
from urllib.parse import urljoin
import urllib.parse
import random
# 随机延时 0~y 秒
def delay_0_y_s(random_delay_num):
y = float(random_delay_num)
time.sleep(random.random() * y)
... |
# __all__ = [
# "ClinicalData",
# "ClinicalYesNoEnum",
# "DiseaseStageEnum",
# "DiseaseGradeEnum",
# "EcogPsEnum",
# "EthnicityEnum",
# "GenderEnum",
# "ModAnnArborEnum",
# "MostRecentTreatmentEnum",
# "PriorTherapyTypeEnum",
# "RaceEnum",
# "RecentTreatmentResponseEnum",... |
import pytest
from pyomrx.utils.cv2_utils import *
from pyomrx.core.circle import Circle
@pytest.fixture
def empty_circle(res_folder):
image_path = str(Path(res_folder) / 'empty_circle.png')
image = load_and_check_image(image_path)
return Circle(image, 6)
def test_empty_circle_is_not_filled(empty_circle... |
from typing import List, Optional, Iterable, Any
class SerializerFieldGenerator:
# Default django serializer field names.
UUID_SERIALIZER_FIELD_NAME = 'serializers.UUIDField'
DATE_SERIALIZER_FIELD_NAME = 'serializers.DateField'
DATETIME_SERIALIZER_FIELD_NAME = 'serializers.DateTimeField'
FOREIGN_K... |
import json
from dataclasses import dataclass
from typing import Optional
from konduto.api.resources.konduto_order_status import KondutoOrderStatus
@dataclass
class KondutoOrderStatusRequest:
status: KondutoOrderStatus
comments: Optional[str] = None
@property
def json(self) -> str:
return js... |
import re
import json
import logging
from cassandra.cluster import Cluster
from flask import Flask, render_template, url_for, request, redirect, session, Response, jsonify
app = Flask(__name__)
app.secret_key = 'walnutfish774'
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == "POST... |
# 双向链表求解
class DlinkedNode():
def __init__(self):
self.key = 0
self.value = 0
self.next = None
self.prev = None
class LRUCache():
def __init__(self, capacity: int):
self.capacity = capacity
self.size = 0
self.cache = {}
self.head = DlinkedNode()... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. 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... |
"""Module that creates and initialises application."""
import logging
import os
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_login import LoginManager
from flask_session import Session
from flask_migrate import Migrate
# from flask_paranoid import Paranoid
fro... |
import math
from . import _singleton_music_analyzer
name = "Music Expand"
start_string = name + " started!"
description = "Changes color with music"
schema = {}
schema.update(_singleton_music_analyzer.music_vis_schema)
def update(lights, step, state):
app = state[_singleton_music_analyzer.MUSIC_VIS_FIELD]
... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from app.views.home_views import home_page
from app.views.notes_view import create_note, delete_note, edit_note, details_note
from app.views.profile_views import profile_view, profi... |
from django.test import TestCase
from nose.tools import *
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from opinions.forms import OpinionStatementForm
from opinions.models import Opinion
from opinions.models import StatementRevision
from opinions.models import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.