content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import io
import math
import skbio
from scipy.spatial import distance
from scipy.spatial import ConvexHull
import pandas as pd
import numpy as np
from skbio import TreeNode
NUM_TRI = 100
VERTS_PER_TRI = 3
ELEMENTS_PER_VERT = 5
(R_INDEX, G_INDEX, B_INDEX) = (0, 1, 2)
(R_OFFSET, G_OFFSET, B_OFFSET) = (2, 3, 4)
def in... | python |
from kimonet.system.generators import regular_system, crystal_system
from kimonet.analysis import visualize_system, TrajectoryAnalysis
from kimonet.system.molecule import Molecule
from kimonet import system_test_info
from kimonet.core.processes.couplings import forster_coupling
from kimonet.core.processes.decays import... | python |
import numpy as np
import pytest
from quara.loss_function.loss_function import LossFunction, LossFunctionOption
class TestLossFunctionOption:
def test_access_mode_weight(self):
loss_option = LossFunctionOption()
assert loss_option.mode_weight == None
loss_option = LossFunction... | python |
import os
import io
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
def get_readme():
path = os.path.join(here, 'README.md')
with io.open(path, encoding='utf-8') as f:
return '\n' + f.read()
setup(
name='ndc_parser',
version='0.1',
description='NDC Parser',
... | python |
import unittest
import torch
from fn import F
from fn.op import apply
from tensorneko.layer import Linear
from torch.nn import Linear as PtLinear, LeakyReLU, BatchNorm1d, Tanh
class TestLinear(unittest.TestCase):
@property
def batch(self):
return 4
@property
def in_neurons(self):
r... | python |
# -*- coding: utf-8 -*-
# Copyright 2016, RadsiantBlue Technologies, 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... | python |
def max_val(t):
"""
t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t
"""
def find_all_int(data):
int_list = []
for item in data:
if isinstance(item, l... | python |
from __future__ import absolute_import
# noinspection PyUnresolvedReferences
from .ABuPickStockExecute import do_pick_stock_work
# noinspection PyUnresolvedReferences
from .ABuPickTimeExecute import do_symbols_with_same_factors, do_symbols_with_diff_factors
# noinspection all
from . import ABuPickTimeWorker as pick_ti... | python |
#!/usr/bin/env python2.7
# license removed for brevity
import rospy
import numpy as np
import json
import time
from std_msgs.msg import String
from std_msgs.msg import Bool
from rospy.numpy_msg import numpy_msg
from feedback_cclfd.srv import RequestFeedback
from feedback_cclfd.srv import PerformDemonstration
from fee... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016-2017 China Telecommunication Co., Ltd.
#
# 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/lice... | python |
# Test case that runs in continuous integration to ensure that PTest isn't broken.
from .base import SingleSatOnlyCase
from .utils import Enums, TestCaseFailure
import os
class CICase(SingleSatOnlyCase):
def run_case_singlesat(self):
self.sim.cycle_no = int(self.sim.flight_controller.read_state("pan.cycle_... | python |
from __future__ import division
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import normal_init
from mmcv.cnn import constant_init
from mmdet.core import (PointGenerator, multi_apply, multiclass_rnms,
images_to_levels, unmap)
from mmdet.core... | python |
"""
Django settings for sentry_django_example project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""... | python |
""" calc.py - simple code to show how to execute testing
"""
def sum(a: float, b: float) -> float:
"""sum adds two numbers
Args:
a (float): First number
b (float): Second number
Returns:
float: sum of a and b
>>> sum(2,3)
5
"""
return a+b... | python |
#!/usr/bin/env python
"""
File metadata consistency scanner.
Python requirements: Python 2.7, :mod:`psycopg2`, Enstore modules.
"""
# Python imports
from __future__ import division, print_function, unicode_literals
import atexit
import ConfigParser
import copy
import ctypes
import datetime
import errn... | python |
# SPDX-FileCopyrightText: 2019-2021 REFITT Team
# SPDX-License-Identifier: Apache-2.0
"""Integration tests for forecast interface."""
# type annotations
# standard libs
# external libs
import pytest
# internal libs
from refitt.data.forecast import Forecast
from refitt.database.model import Observation as Observat... | python |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,'home.html',{'name':'Smit'})
def add(request):
val1 = request.POST['num1']
val2 = request.POST['num2']
return render(request,'result.html',{'result_add':int(val... | python |
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import json
import tensorflow as tf
from utils import queuer
def decoding(sprobs, samples, params, mask=None):
"""Generate decoded sequence from seqs"""
if mask is None:
... | python |
# --------------------------------------------------------------------------- #
# aionextid.py #
# #
# Copyright © 2015-2022, Rajiv Bakulesh Shah, original author. #
... | python |
import os
import sys
import logging
import re
from django.core.exceptions import ImproperlyConfigured
from pathlib import Path # python3 only
logger = logging.getLogger(__name__)
def dotenv_values(dotenv_path):
lines = []
try:
with open(dotenv_path) as fp:
lines = fp.read().splitlines()
... | python |
"""
Tools for asking the ESP about any alarms that have been raised,
and telling the user about them if so.
The top alarmbar shows little QPushButtons for each alarm that is currently active.
If the user clicks a button, they are shown the message text and a "snooze" button
for that alarm.
There is a single physical ... | python |
"""
atpthings.util.dictionary
-------------------------
"""
def getKeys(dictionary: dict, keys: list) -> dict:
"""Get keys from dictionary.
Parameters
----------
dictionary : dict
Dictionary.
keys : list
List of keys wonted to be extracted.
Returns
-------
dict
... | python |
import wx
from html import escape
import sys
import Model
import Utils
class Commentary( wx.Panel ):
def __init__( self, parent, id = wx.ID_ANY ):
super().__init__(parent, id, style=wx.BORDER_SUNKEN)
self.SetDoubleBuffered(True)
self.SetBackgroundColour( wx.WHITE )
self.hbs = wx.BoxSizer(wx.HORIZONTAL)
... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<username>[\w.@+-]+)/$', views.UserDetailView.as_view(), name='detail'),
]
| python |
import torch
import numpy as np
from torch import nn
import torch.nn.functional as F
from . import *
class GlowLevel(nn.Module):
def __init__(self, in_channel, filters=512, n_levels=1, n_steps=2):
'''
Iniitialized Glow Layer
Parameters
----------
in_channel : int
number of ... | python |
from collections import defaultdict
from glypy.io import iupac, glycoct
from glypy.structure.glycan_composition import HashableGlycanComposition, FrozenGlycanComposition
from glypy.enzyme import (
make_n_glycan_pathway, make_mucin_type_o_glycan_pathway,
MultiprocessingGlycome, Glycosylase, Glycosyltransferase,... | python |
"""Define the setup function using setup.cfg."""
from setuptools import setup
setup()
| python |
"""
====================
einsteinpy_geodesics
====================
Julia wrapper for Geodesics
"""
__version__ = "0.2.dev0"
from .geodesics_wrapper import solveSystem
| python |
from leek.api.routes.api_v1 import api_v1_blueprint
from leek.api.routes.manage import manage_bp
from leek.api.routes.users import users_bp
from leek.api.routes.applications import applications_bp
from leek.api.routes.events import events_bp
from leek.api.routes.search import search_bp
from leek.api.routes.agent import... | python |
from __future__ import division
from __future__ import absolute_import
import pycuda.driver as drv
import pycuda.gpuarray as gpuarray
import atexit
STREAM_POOL = []
def get_stream():
if STREAM_POOL:
return STREAM_POOL.pop()
else:
return drv.Stream()
class AsyncInnerProduct:
def __init... | python |
from setuptools import setup,find_packages
import os
pathroot = os.path.split(os.path.realpath(__file__))[0]
setup(
name='sqrt_std',
version='0.1.0',
packages = find_packages(),
entry_points = {
'console_scripts': ['sqrt_std=lib.sqrt_std:main'],
}
) | python |
from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
from tests import pyunit_utils
import h2o
def h2ocluster_status():
"""
Python API test: h2o.cluster_status()
Deprecated, use h2o.cluster().show_status(True)
"""
ret = h2o.cluster_status() # no return type
assert ... | python |
#Main 'run through' of the program. This is run periodically
#to update the state of the file to match what has happened on
#Qualtrics, as well as to send out new surveys in accordance
#with how many have expired or been completed
import urllib
import config
import quapi
import parsers
import helpers
import filemanag... | python |
"""HTML Template Generator
Intended to parse HTML code and emit Python code compatible with Python
Templates.
TODO
- Change tag calls to pass void=True
Open Questions
1. How to merge the generic structure of parsed HTML with existing classes like
HTMLTemplate? For example: the <head> and <body> tags should be m... | python |
import dash
import dash_bootstrap_components as dbc
from apps.monitor import Monitor
from apps.controller import Controller
from apps.navbar import navbar
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=[
dbc.themes.BOOTSTRAP, 'asse... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.PosDishGroupModel import PosDishGroupModel
class KoubeiCateringPosDishgroupSyncModel(object):
def __init__(self):
self._pos_dish_group_model = None
@property
... | python |
with open("file.txt") as f:
something(f)
| python |
#!/app/ansible2/bin/python
# -* coding: utf-8 -*-
DOCUMENTATION = '''
---
author: Arthur Reyes
module: pyvim_facts
description:
- This module gathers and correlates a larger number of useful facts
from a specified guest on VMWare vSphere.
version_added: "0.1"
requirements:
- pyVim
notes:
- This module disab... | python |
from bk_db_tools.xlsx_data_replace import XlsxDataReplace
class SOther(XlsxDataReplace):
dataSets = [
{
'sheetName':'s_player_unit',
'firstColumn':1,
'firstRow':2,
'sql':
"""
select *
from (
select pu.unit_i... | python |
import os
import h5py
import numpy as np
type_to_id = {'worse':[0,0,1], 'okay':[0,1,0], 'better':[1,0,0]}
dirs = ['can',
'lift',
'square',
'transport']
for env in dirs:
path = "datasets/" + env + "/mh"
old = path + "/low_dim.hdf5"
new = path + "/low_dim_fewer_better.hdf5"
os.sys... | python |
import sys
from pathlib import Path
path = str(Path(__file__).parents[1].resolve())
sys.path.append(path)
from datasets import load_dataset
from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor
import soundfile as sf
import torch
from jiwer import wer
import numpy as np
from sonorus.speech.lm import (
Fairs... | python |
from __future__ import unicode_literals
import logging
from django import template
from ..utils import get_seo_model
from ..models import SeoUrl
logger = logging.getLogger(__name__)
register = template.Library()
class SeoDataNode(template.Node):
def __init__(self, variable_name):
self.variable_name =... | python |
from setuptools import setup, find_packages
packages = find_packages()
setup(name = 'cddm_experiment',
version = "1.0.0",
description = 'Tools for cross-differential dynamic microscopy experiment',
author = 'Andrej Petelin',
author_email = 'andrej.petelin@gmail.com',
url="https://github.... | python |
class MyClass:
pass
obj = MyClass() # creating a MyClass Object
print(obj) | python |
def is_palindrome(input_string):
"""Check if a string is a palindrome
irrespective of capitalisation
Returns:
True if string is a palindrome
e.g
>>> is_palindrome("kayak")
OUTPUT : True
False if string is not a palindrome
e.g
>>> is_palindro... | python |
from izihawa_utils.text import camel_to_snake
def test_camel_to_snake():
assert camel_to_snake('CamelCase') == 'camel_case'
assert camel_to_snake('camelCase') == 'camel_case'
assert camel_to_snake('camelCase camel123Case') == 'camel_case camel123_case'
assert camel_to_snake('camelCase\ncamelCase') == ... | python |
from flask import Blueprint, request
from kaos_backend.controllers.notebook import NotebookController
from kaos_backend.util.flask import jsonify
from kaos_model.api import Response
def build_notebook_blueprint(controller: NotebookController):
blueprint = Blueprint('notebook', __name__)
@blueprint.route("/... | python |
#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
# setup.py
from setuptools import setup
DESCRIPTION = "See ./README.md"
LONG_DESCRIPTION = DESCRIPTION
setup(
author="Dan'",
author_email="dan@home",
name="mfm",
version="0.0.0",
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
... | python |
# Copyright 2020 University of New South Wales, University of Sydney, Ingham Institute
# 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
# Unle... | python |
"""Overview plots of transcet"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress
from os.path import join
from src import sonic_layer_depth
plt.ion()
bbox = dict(boxstyle='round', fc='w')
savedir = 'reports/jasa/figures'
c_fields = np.load('data/processed/inputed_decomp.npz')
... | python |
import time
from datetime import datetime, timedelta
import funcy
from unittest import mock
import asyncio
from octoprint.events import EventManager
async def wait_untill(
condition,
poll_period=timedelta(seconds=1),
timeout=timedelta(seconds=10),
condition_name="no_name",
time=time.time,
*con... | python |
from subsystems.drivesubsystem import DriveSubsystem
import commands2
import wpilib
#time in seconds
ticksDistance = 0
class rotateArm(commands2.CommandBase):
def __init__(self, power: float, distance: float) -> None:
super().__init__()
self.power = power
self.distance = distance
d... | python |
#
# Copyright 2017 the original author or 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... | python |
#! /usr/bin/env python3
import numpy as np
from PIL import Image
def load_raw(f, w=3280, h=3280):
# Metadata: width, height
# Metadata: pixelPacking
arr = np.fromfile(f, np.uint8, w*h*3//2).reshape((h,w//2,3)).astype('H')
# Image is big endian 12 bit 2d array, bayered.
# This is detailed in the TX... | python |
ANSI_COLOURS = [
'grey',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'white'
]
for i, name in enumerate(ANSI_COLOURS):
globals()[name] = str(30 + i)
globals()['intense_' + name] = str(30 + i) + ';1'
def get_colours():
cs = ['cyan', 'yellow', 'green', 'magenta', 'r... | python |
#######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
################################... | python |
import itertools
def flatten(*arg):
return [item for sublist in arg for item in sublist]
def intersection(*args):
result = set(args[0])
for i in range(1, len(args)):
result = result.intersection(set(args[i]))
return result
def is_unique(*item_lists):
all_items = flatten(*item_lists)
... | python |
import torch
import torch.nn as nn
from torch.autograd import Function
class GdnFunction(Function):
@staticmethod
def forward(ctx, x, gamma, beta):
ctx.save_for_backward(x, gamma, beta)
n, c, h, w = list(x.size())
tx = x.permute(0, 2, 3, 1).contiguous()
tx = tx.view(-1, c)
... | python |
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2022 Beartype authors.
# See "LICENSE" for further details.
'''
**Callable creation utility unit tests.**
This submodule unit tests the public API of the private
:mod:`beartype._util.utilfunc.ut... | python |
from os import *
import traceback
import sys
if len(sys.argv) != 2:
print("Utilisation: %s fichier"%(sys.argv[0]))
exit(0)
SIZE=256
try:
f=open(sys.argv[1], O_RDONLY)
bs = read(f, SIZE)
while len(bs) > 0:
write(sys.stdout.fileno(), bs)
bs = read(f, SIZE)
close(f)
except OSEr... | python |
from falcor import *
def render_graph_DefaultRenderGraph():
g = RenderGraph('DefaultRenderGraph')
loadRenderPassLibrary('BSDFViewer.dll')
loadRenderPassLibrary('AccumulatePass.dll')
loadRenderPassLibrary('TemporalDelayPass.dll')
loadRenderPassLibrary('Antialiasing.dll')
loadRenderPassLibrary('B... | python |
import histogram_dct as hd
import pandas as pd
# load data
data = pd.read_excel(r'Example\distributions.xlsx')
# uniform distribution:
hd.histogram_dct(data['unf'], bin=12.5, name='uniform distribution')
# normal distribution:
hd.histogram_dct(data['nrm'], bin=4, name='normal distribution')
# exp distri... | python |
""" Python Character Mapping Codec generated from '8859-2.TXT' with gencodec.py.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,erro... | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Flip(nn.Module):
"""
Flip indices transformation.
Example:
>>> f = stribor.Flip()
>>> x = torch.tensor([[1, 2], [3, 4]])
>>> f(x)[0]
tensor([[2, 1],
[4, 3]])
>>> f = stribor.Flip([0, 1])
>>> f(x)[0... | python |
# ••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••
# Copyright (c) 2018, S.J.M. Steffann. This software is licensed under the BSD
# 3-Clause License. Please see the LICENSE file in the project root directory.
# •••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••••... | python |
from typing import Dict, Optional
from fastapi import APIRouter, Depends, HTTPException
from src.api.serializers import UserIn, UserOut, UsersOut
from src.services.auth import get_current_user, get_user_login_from_token
from src.services.users import (
create_user,
get_user_by_id,
get_user_by_login,
se... | python |
import maestro
import time
import numpy as np
import scipy as sp
import scipy.interpolate
import sys
a1 = 0.1
a2 = 0.26
# In degrees from straight config
ee_pos_list = [
np.array([0.12, 0.17]),
#np.array([0.12, 0]),
#np.array([0.14, 0]),
np.array([0.325, 0.12]),
np.array([0.12, 0.17]... | python |
import cv2
import numpy as np
#####################################
#adjust as per ratio required
widthImg = 640
heightImg = 480
#####################################
cap = cv2.VideoCapture(0)
cap.set(3, widthImg)
cap.set(4, heightImg)
cap.set(10, 150) #id: 10, represents brigthness => adjust as required based on set... | python |
import django_tables2 as tables
from net.models import Connection
from utils.tables import BaseTable, ButtonsColumn, SelectColumn
class ConnectionTable(BaseTable):
pk = SelectColumn()
ipv6_address = tables.Column(linkify=True, verbose_name="IPv6")
ipv4_address = tables.Column(linkify=True, verbose_name="... | python |
import os
import json
from .constants import CUST_ATTR_GROUP
def default_custom_attributes_definition():
json_file_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"custom_attributes.json"
)
with open(json_file_path, "r") as json_stream:
data = json.load(json_strea... | python |
# Copyright 2021 Google LLC
#
# 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 law or agreed to in writing, ... | python |
from flask_restplus import Api
from jsonschema import FormatChecker
import logging
log = logging.getLogger(__name__)
# Instantiate a Flask-RESTPlus API
api = Api(version='1.0', title='iter8 analytics REST API',
description='API to perform analytics to support canary releases '
'and A/B tests',
... | python |
import sys
def subst(s, ls):
if s == "":
return ""
for j in xrange(0, len(ls), 2):
i = s.find(ls[j])
if i != -1:
return subst(s[:i], ls) + ls[j + 1] + subst(s[i + len(ls[j]) :], ls)
return s
test_cases = open(sys.argv[1], "r")
for test in test_cases:
s, sub = tes... | python |
from rest_framework import serializers
from daiquiri.metadata.models import Column
class ColumnSerializer(serializers.ModelSerializer):
class Meta:
model = Column
fields = (
'id',
'order',
'name',
'description',
'unit',
'ucd... | python |
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.views.generic import ListView, DetailView, CreateView
from django.views.generic.edit import FormView, UpdateView
from django.contrib.auth import login, authenticate
... | python |
"""
Unit tests for PDF class
"""
import numpy as np
import unittest
import qp
class EvalFuncsTestCase(unittest.TestCase):
""" Tests of evaluations and interpolation functions """
def setUp(self):
"""
Make any objects that are used in multiple tests.
"""
self.xpts = np.linspace... | python |
import itsdangerous, json, atexit, traceback, logging
from flask import redirect, render_template, url_for, abort, \
flash, request
from flask_login import login_user, logout_user, current_user, login_required
from flask_mail import Message
from flask_admin import Admin, AdminIndexView, expose
from flask_admin.con... | python |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
# Updates by Pablo Palafox 2021
import torch.nn as nn
import torch
import torch.nn.functional as F
import kornia
from utils import embedder
from utils import geometry_utils
class PoseDecoder(nn.Module):
def __init__(
self,
... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-08-03 06:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hacker', '0017_auto_20180803_0633'),
]
operations = [
migrations.AddField(
... | python |
import re
from bottle import route, run, template
# shamelessly stolen from https://www.w3schools.com/howto/howto_js_sort_table.asp
js = """
<script>
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("tbl");
switching = true;
dir =... | python |
#!/usr/bin/python3
import alley_oop
| python |
import glob
import json
import os
import argparse
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from sklearn.preprocessing import MinMaxScaler
POSE_BODY_25_PAIRS_RENDER_GPU = \
[1, 8, 1, 2, 1, 5, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9, 9, 10, 10, 11,
8, 12, 12, 13, 13, 14, 1, 0, 0, 15, 15, 17, 0, 16, 1... | python |
from flask import render_template,redirect,session,request, flash
from flask_app import app
from ..models import user, bag
@app.route("/bag/create")
def new_bag():
if 'user_id' not in session:
return redirect('/')
data = {
"id":session['user_id']
}
return render_template("add_bag.html",... | python |
import os
import zipfile
from arelle.CntlrCmdLine import parseAndRun
# from https://specifications.xbrl.org/work-product-index-registries-units-registry-1.0.html
REGISTRY_CONFORMANCE_SUITE = 'tests/resources/conformance_suites/utr/registry/utr-conf-cr-2013-05-17.zip/utr-conf-cr-2013-05-17/2013-05-17'
STRUCTURE_CONFOR... | python |
import os
import torch as torch
import numpy as np
from io import BytesIO
import scipy.misc
#import tensorflow as tf
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolder
from torch.autograd import Variable
from matplotlib imp... | python |
import logging
from datetime import datetime, timezone
from brownie import chain
from yearn.historical_helper import export_historical, time_tracking
from yearn.networks import Network
from yearn.treasury.treasury import StrategistMultisig
from yearn.utils import closest_block_after_timestamp
logger = logging.getLogg... | python |
def write_fbk(file_name, feat_path):
with open(file_name, 'r') as f:
lines = f.readlines()
for lin_num, x in enumerate(lines):
audio_name = x.split("/wav/")[1].split(".")[0]
feat_name = ''.join([feat_path, audio_name, '.fbk'])
lines[lin_num] = ''.join([x.strip(),... | python |
import torch
import torch.nn as nn
import numpy as np
from skimage.morphology import label
class Dice(nn.Module):
"""The Dice score.
"""
def __init__(self):
super().__init__()
def forward(self, output, target):
"""
Args:
output (torch.Tensor) (N, C, *): The model o... | python |
import sort_for_vexflow
import pretty_midi
def notation(orchestra, inst, tech, dyn, note, tgt, onoff, microtone,masking_order_idx):
annotations=[]
orchestration_slice=[]
tgts=[]
for i in range(len(inst)):
# Check that you input proper values:
if tech[i] in list(orchestra[inst[i]].keys()... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-06-18 07:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('disturbance', '0005_auto_20180618_1123'),
]
operations = [
migrations.RemoveField(
... | python |
def shared_function(x, sep=':'):
return sep.join(['got', x]) | python |
from cleaner_console import Console
if __name__ == '__main__':
Console() | python |
from node import constants
def shout(data):
data['type'] = 'shout'
return data
def proto_page(uri, pubkey, guid, text, signature, nickname, PGPPubKey, email,
bitmessage, arbiter, notary, notary_description, notary_fee,
arbiter_description, sin, homepage, avatar_url):
data =... | python |
# -*- coding: utf-8 -*- #
# Copyright 2018 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 requir... | python |
# -*- coding: utf-8 -*-
"""
controlbeast.utils.loader
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2013 by the ControlBeast team, see AUTHORS.
:license: ISC, see LICENSE for details.
"""
import importlib
import os
import re
def __filter_members(item):
"""
Filter function to detect classes... | python |
# Generated by Django 3.2.4 on 2021-06-14 12:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('main_app', '0... | python |
from __future__ import annotations
from typing import (
Any,
Dict,
Iterator,
Mapping,
MutableMapping,
Optional,
Tuple,
TypeVar,
)
from apiwrappers import utils
VT = TypeVar("VT")
class NoValue:
__slots__: Tuple[str, ...] = tuple()
def __repr__(self):
return f"{self.... | python |
# -*- coding: utf-8 -*-from setuptools import setup, find_packages
from baseapp import get_version
setup(
name='feincms_baseapp',
version=get_version(),
description='This is a base app and contenttype for Feincms.',
author='',
author_email='',
url='https://github.com/',
packages=find_package... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/6/24 20:55
# @Author : ganliang
# @File : doctest_test.py
# @Desc : doctest测试 执行模块测试
import doctest
import src.deco
if __name__ == "__main__":
doctest.testmod(src.deco)
| python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumby/flask-thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2015 thumby.io dev@thumby.io
class FlaskThumbor:
__name__ = "FlaskThumbor"
def __init__(self,... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.