content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
x = [0.0, 3.0, 5.0, 2.5, 3.7] #define array
print(type(x))
x.pop(2) #remove third element
print(x)
x.remove(2.5) #remove element equal to 2.5
print(x)
x.append(1.2) #add an element at the end
print(x)
y = x.co... | python |
import datetime
import itertools
import functools
import io
import os
import pathlib
import string
import tqdm
import pytz
import requests
import apiclient.http
import fuzzywuzzy.fuzz
from .info import Conference, ConferenceInfoSource, Session
from apiclient.discovery import build
from google_auth_oauthlib.flow impo... | python |
from microbit import display
from microbit import Image
from KitronikClipDetector import Detector
sensor = Detector()
while True:
if sensor.readDigitalSensor("P2", "Dark") is True:
display.show(Image.HAPPY)
else:
display.show(Image.SAD) | python |
"""Urls for the Zinnia entries short link"""
from django.conf.urls import url
from django.conf.urls import patterns
from zinnia.views.shortlink import EntryShortLink
urlpatterns = patterns(
'',
url(r'^(?P<pk>\d+)/$',
EntryShortLink.as_view(),
name='zinnia_entry_shortlink'),
)
| python |
'''
SOLED
Scrapy settings
For simplicity, this file contains only settings considered important or
commonly used. You can find more settings consulting the documentation:
http://doc.scrapy.org/en/latest/topics/settings.html
http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
http://s... | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | python |
# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... | python |
# required for test discovery | python |
# Copyright 2021 Victor I. Afolabi
#
# 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 wri... | python |
# Created By: Virgil Dupras
# Created On: 2009-04-23
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licens... | python |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import unittest
from nltk.classify.naivebayes import NaiveBayesClassifier
class NaiveBayesClassifierTest(unittest.TestCase):
def test_simple(self):
training_features = [
({'nice': True, 'good': True}, 'positive')... | python |
# -*- coding: utf-8 -*-
import os
from youtube_title_parse import get_artist_title
class MetaTestSequence(type):
def __new__(mcs, name, bases, attrs):
def should_skip(test_params):
if not test_params:
return False
if "skip" in test_params and test_params["skip"] is ... | python |
# -*- coding: utf-8 -*-
import pickle
import numpy as np
import pandas as pd
import pystan
import os, sys
import stan_utility
import patsy
import arviz as az
GLMEdata = pd.read_csv('GLMEdata.csv')
GLMEdata = GLMEdata[GLMEdata.exp == 1]
GLME = stan_utility.compile_model('GLME.stan', model_name="GLME")
fixeff_form = "... | python |
from django.db import models
# Create your models here.
MALE = 'M'
FEMALE = 'F'
UNKNOWN = 'U'
GENDER_CHOICES = (
(MALE, 'Male'),
(FEMALE, 'Female'),
(UNKNOWN, 'Unknown'))
class AdmissionsByGender(models.Model):
PRIMARY = 'P'
SECONDARY = 'S'
DIAGNOSIS_CHOICES = (
(PRIMARY, 'Primary'),... | python |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Project : stock_quant
# @Date : 2022/1/18 23:29
# @Author : Adolf
# @File : info_push.py
# @Function:
import json
import requests
import logging
def post_msg_to_dingtalk(title="", msg="", token="", at=None, type="text"):
if at is None:
at = []
ur... | python |
import unittest
import json
from mock import patch
from provider.utils import unicode_encode
from provider.execution_context import S3Session
from tests.activity.classes_mock import FakeS3Connection
from tests import settings_mock
class TestS3Session(unittest.TestCase):
@patch("provider.execution_context.S3Sessio... | python |
import pyopencl as cl
import numpy as np
np.set_printoptions(linewidth=128)
BOARD_SIZE = 10
SHIP_SIZES = [5,4,3,3,2]
STATE_MISS = 0
STATE_HIT = 1
STATE_UNKNOWN = 2
def bool2IntArray(boolArray):
ret = []
for array in boolArray:
ret.append(np.packbits(array))
return ret
def int2BoolArray(boolArray):
ret = []
... | python |
from sklearn.metrics import mean_absolute_percentage_error as mape
from sklearn.metrics import r2_score
def mean_absolute_percentage_error(actual, forecast) -> float:
"""
calculate mean absolute percentage error (MAPE)
:param actual: actual values
:param forecast: forecast (prediction) values
:ret... | python |
################################################################################
# #
# RUN ALL TESTS AND CHECK FOR ACCURACY #
# ... | python |
from typing import Any, Dict
import numpy
import scipy.special
from mlxtk.util import memoize
@memoize
def binom(n: int, k: int) -> int:
return int(scipy.special.binom(n, k))
# @jit
def build_number_state_table_bosonic(N: int, m: int) -> numpy.ndarray:
number_of_states = binom(N + m - 1, m - 1)
number... | python |
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
import os
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
import numpy as np
import nltk
from nltk.corpus import stopwords
nltk.download('punkt')
stop_words = set(stopwords.w... | python |
import torch.nn as nn
from .torch_helpers import NamedTensor
class Module(nn.Module):
def register_parameter(self, name, tensor):
if isinstance(tensor, NamedTensor):
param = nn.Parameter(tensor.values)
super(Module, self).register_parameter(
"_" + name + "_named", p... | python |
import json
from django.core.urlresolvers import reverse, NoReverseMatch
from django.contrib.admin.templatetags.admin_static import static
from django.template import Template, Context
from django.utils.encoding import force_text
from django.template.loader import get_template
from django.forms.models import BaseModel... | python |
import ray
import torch
from models import Model
import numpy as np
import random
from atari_wrappers import make_atari, wrap_deepmind
@ray.remote
class Player:
def __init__(self, checkpoint, replay_buffer, share_storage, test_mode):
self.game = make_atari(checkpoint["game"]+"NoFrameskip-v4")
self... | python |
# Generated by Django 3.0.9 on 2020-08-17 14:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('filer', '0011_auto_20190418_0137'),
]
operations = [
migrations.AddField(
model_name='file',
name='description_en',
... | python |
import unittest
import test, app
import nltk
from nltk.tokenize import word_tokenize
import json
class TestGetRAD(unittest.TestCase):
def test_word_classifier(self):
keyword = 'I coughed a lot and vomited. I also have a headache.'
words = word_tokenize(keyword)
# returns tag name of part ... | python |
from __future__ import print_function, division
from argparse import ArgumentParser
from sys import exc_info
from time import ctime
from datetime import datetime
from decimal import Decimal
from traceback import print_tb
from random import randint
from tqdm import trange
from .api import TradewaveAPI
from .data impo... | python |
import copy
import floppyforms as forms
from crispy_forms.bootstrap import Tab, TabHolder
from crispy_forms.layout import HTML, Field, Fieldset, Layout
from django import forms as django_forms
from django.forms.models import modelform_factory
from django.utils.text import slugify
from django.utils.translation import ... | python |
#! /usr/bin/env python3
# Copyright 2022 Tier IV, 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 la... | python |
from setuptools import setup
setup(
name='django-subquery',
version='1.0.4',
description='SubQuery support in Django < 1.11',
url='https://github.com/schinckel/django-subquery/',
author='Matthew Schinckel',
author_email='matt@schinckel.net',
packages=['django_subquery']
)
| python |
from easygraphics import *
x = 0
y = 0
def draw_compositon(x, y, mode, alpha_value):
set_background_color(Color.TRANSPARENT)
set_font_size(18)
set_line_width(3)
set_color("black")
set_composition_mode(CompositionMode.SOURCE)
draw_rect_text(x, y + 175, 200, 25, mode)
set_fill_color(to_alph... | python |
#!/usr/bin/python3
import tensorflow as tf
import numpy as np
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
class Addressing(Model):
def __init__(self, memory_locations=128, memory_vector_size=20, maximum_shifts=3, reading=True):
super(Addressing, self).__init__()
... | python |
# grep a csv file for an expression and copy the csv header into the output
import os
import sys
from misc import *
if len(sys.argv) < 3:
err("usage: csv_grep [pattern] [input csv file]")
pattern, filename = sys.argv[1], sys.argv[2]
grep_file = filename + "_grep" # grep results go here
a = os.system("grep " + pat... | python |
import glob
import os
import numpy as np
import pandas as pd
from common.paths import POWER_FC, ADHD, PLS_WEIGHTS, RIDGE_WEIGHTS, BIOBANK_LABELS
from common.power_atlas import to_power_fc_vector, get_power_fc_vector_labels
from common.wisc import WISC_LEVEL
def get_data(wisc_level=5, label_path=ADHD):
"""
G... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
s = input("Введите строку:")
count = 0
vowels = {'е', 'ы', 'а', 'о', 'э', 'я', 'и', 'ю'}
for letter in s:
if letter in vowels:
count += 1
print("Количество гласных равно:")
print(count)
| python |
try:
from sshtunnel import SSHTunnelForwarder
except ImportError:
from sshtunnel.sshtunnel import SSHTunnelForwarder
from cm_api.api_client import ApiResource, ApiException
from cm_api.endpoints.services import ApiService, ApiServiceSetupInfo
import paramiko
import json
import yaml
import requests
import subpro... | python |
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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 ... | python |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... | python |
from abc import ABCMeta, abstractmethod
from copy import deepcopy
import attr
from utensor_cgen.utils import MUST_OVERWRITEN
class Morphism(object):
__metaclass__ = ABCMeta
@abstractmethod
def apply(self, from_op):
raise RuntimeError('abstract transform invoked')
@attr.s
class TypedMorphism(Morphism):
... | python |
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
from essmc2.utils.registry import Registry
HOOKS = Registry("HOOKS")
| python |
## Yoni Schirris. 06/10/2020
## Exact copy of main.py (now main_unsupervised.py)
## Idea is to keep functionality of both supervised and unsupervised in here, with some switches that change only minor
## things to switch between supervised and unsupervised learning.
## Thus, in the end, we should again have a single "m... | python |
"""
Deuce Valere - Tests - API - System - Manager
"""
import datetime
import unittest
from deuceclient.tests import *
from deucevalere.api.system import *
class DeuceValereApiSystemManagerTest(unittest.TestCase):
def setUp(self):
super().setUp()
def tearDown(self):
super().tearDown()
... | python |
# sum_of_multiplications([(1, 2), (5, 10)]) should return 52
# because (1 * 2 + 5 * 10) is 52
def sum_of_multiplications(l):
sum = 0
for value1, value2 in l:
sum += value1 * value2
return sum
if __name__ == '__main__':
print(sum_of_multiplications([(1, 2), (5, 10)])) | python |
"""
This is the plugin code for threshold segmentation(binary) of rectilinear grid.
This plugin is designed to segment a grid such that cells with magnitude greater than the threshold value are
labelled as 1, otherwise labelled as 0. This provides the ground truth results for
such a fluid segmentation.
Accepted input d... | python |
"""
对Kaiming He新提出的MAE的简要实现
"""
# ----------------------------------------------------------------
# borrowed from https://github.com/IcarusWizard/MAE.git
# ----------------------------------------------------------------
import numpy as np, torch
import torch.nn as nn
from .transformer import Encoder
def random_ind... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('barsystem', '0037_auto_20150721_1500'),
]
operations = [
migrations.RenameField(
model_name='product',
... | python |
import unittest
from unittest.mock import Mock, MagicMock
import math
import shapely as sh
import shapely.geometry
import numpy as np
import numpy.testing
import shart
from shart.box import *
class TestMain(unittest.TestCase):
def test_attribute(self):
g = Group.rect(0, 0, 100, 100)
self.asse... | python |
#! /Users/bin/env Python
# Modified version of get_disease.py from ClinGen/LoadData. Creates JSON file
# with all Orphanet data for (initial) load into the server. Run this script
# before using this one:
# obtain_external_data_files.py -s orphanet
import json
from uuid import uuid4
from xml.etree import ElementTre... | python |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... | python |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Bunch of fixtures to be used across the tests."""
import pytest
@pytest.fixture(scope="function")
def hello_world(request):
"""Create a test fixture."""
hw = "Hello World!"
def tear_down():
# clean up here
pass
request.addfinalizer(t... | python |
from __future__ import absolute_import
from datetime import timedelta
from celery.schedules import crontab
from .celery import app
from django.conf import settings
RESULT_BACKEND = 'django-db'
# Mitigate deprecation error:
# The 'BROKER_URL' setting is deprecated and scheduled for removal in
# version 6.0.0. ... | python |
'''
Author : @amitrajitbose
Problem : Codechef IPCTRAIN
Approach : Greedy
'''
t=int(input())
for _ in range(t):
finalAnswer=0
n,day=[int(x) for x in input().strip().split()]
valf=[int(i) for i in range(day+1)]
dt=[]
si=[]
for i in range(n):
d,t,s=[int(x) for x in input().strip().split()]
... | python |
import numpy as np
from numpy.core.defchararray import isupper
def printMatrix(mat):
out = ""
for idxi, i in enumerate(mat):
for idxj, j in enumerate(i):
out += f"{mat[idxi][idxj]} "
out += "\n"
print(out)
def printCoordMatrix(mat):
mat = np.flip(mat, 1)
out = ""
fo... | python |
"""This module will contain class Sort and its related methods."""
class Sort(object):
"""
"""
def __init__(self, iterable=None):
if iterable is None:
iterable = []
if type(iterable) is not list:
raise TypeError('Input is not a list.')
self.len = len(itera... | python |
while True:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid value, enter an integer")
continue
except:
print("Something went wrong")
continue
if age < 0 or age > 499:
print("Age not within valid range")
continue
else... | python |
from itertools import product
import epimargin.plots as plt
import numpy as np
import pandas as pd
import seaborn as sns
from epimargin.estimators import analytical_MPVS
from epimargin.models import SIR
from epimargin.policy import PrioritizedAssignment, RandomVaccineAssignment, VaccinationPolicy
from studies.age_stru... | python |
# coding=utf-8
import camera_app
import logging
logger = logging.getLogger(__name__)
logging.getLogger().setLevel(logging.INFO)
if __name__ == '__main__':
camera_app.start()
| python |
from flask import Blueprint, session, render_template, request, jsonify, Response, abort, current_app, flash, Flask, send_from_directory
from jinja2 import TemplateNotFound
from functools import wraps
from sqlalchemy import or_, and_
from sqlalchemy.orm.exc import NoResultFound
from psiturk.psiturk_config import Psit... | python |
import pandas as pd
import torch
class DataManager:
def __init__(self, data, labels, folds):
self.raw_data = data
self.data = self.chunks(data, folds)
self.labels = self.chunks(labels, folds)
self.folds = folds
self.index = 0
def chunks(self, seq, n):
av... | python |
from datetime import datetime, timedelta
import requests
import collectd
class BorgBaseService:
def __init__(self):
self.endpoint = "https://api.borgbase.com/graphql"
self.api_key = None
self.next_request_time = None
self.cached_response = None
def dispatch(self, repo, value... | python |
import logging
import os
from telegram.ext import Updater
from db_wrapper import DBWrapper
from handlers.admins import AdminsHandler
from handlers.all import AllHandler
TOKEN = os.environ.get("TOKEN")
LOG_LEVEL = os.environ.get("LOG_LEVEL")
DB_FILE = os.environ.get("DB_FILE")
logging.basicConfig(format='%(asctime)s... | python |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,FileField,SubmitField
from wtforms.validators import Required
class CommentForm(FlaskForm):
title = StringField('Comment title',validators= [Required()])
comment = TextAreaField('Comment review')
submit = SubmitField('submit')
... | python |
# Implement the Linear Reciprocal Maximization problem
import gurobipy as gp
import numpy as np
from gurobipy import *
id = 903515184
# Invoke Gurobi to solve the SOCP
def solve_socp(id, m=400, n=50):
gm = gp.Model("reciprocal")
A, b = get_data(id, m, n)
# print(A.shape, b.shape) # (400, 50... | python |
from ..api_base import ApiBase
class CorporateCreditCardExpenses(ApiBase):
"""Class for BankTransactions APIs."""
GET_CORPORATE_CREDIT_CARD_EXPENSES = '/api/tpa/v1/corporate_credit_card_expenses'
GET_CORPORATE_CREDIT_CARD_EXPENSES_COUNT = '/api/tpa/v1/corporate_credit_card_expenses/count'
def get(se... | python |
import prata
import time
import timeit
import numpy as np
import sys
import random
import string
B = 1
KB = 1000
MB = 1000000
END = []
def getString(s):
#''.join(random.choice(string.ascii_letters) for x in range(int(real)))
real = 1 if (s-49) < 1 else s-49
return "1"*real
TIMES = 5
SLEEP = 2
NUMBER = ... | python |
# -*- coding: utf-8 -*-
"""
This file is used for indexing FedWeb2013.
@author: Shuo Zhang
"""
import os
import tarfile
from bs4 import BeautifulSoup
from Elastic import Elastic
def fedweb13_index(index_name,output_file):
elastic = Elastic(index_name)
mappings = {
# "id": Elastic.notanalyzed_field()... | python |
import ast
import re
import shutil
import sys
import urllib.parse
import urllib.request
from pathlib import Path
def download_build(branch_url: str, build: str, reg_exr: re, directory: Path):
build_url = branch_url + build + "/"
build_api_url = build_url + "api/python"
artifacts = ast.literal_eval(urllib.... | python |
from tests.test_helper import *
from braintree.test.credit_card_numbers import CreditCardNumbers
from datetime import datetime
from datetime import date
from braintree.authorization_adjustment import AuthorizationAdjustment
from unittest.mock import MagicMock
class TestTransaction(unittest.TestCase):
@raises_with_... | python |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Promise
from .models import Family
from .models import User
admin.site.register(Promise)
admin.site.register(Family)
admin.site.register(User, UserAdmin)
| python |
"""
Pylot
model.py
You may place your models here.
"""
from active_sqlalchemy import SQLAlchemy
import pylot.component.model
from . import get_config
config = get_config()
db = SQLAlchemy(config.DATABASE_URI)
# User Struct.
UserStruct = pylot.component.model.user_struct(db)
# Post Struct
PostStruct = pylot.compo... | python |
from typing import List, Tuple
import logging
from .track import Track
from vcap import DetectionNode
from vcap_utils import iou_cost_matrix, linear_assignment
MATCH_FUNC_OUTPUT = Tuple[
List[Tuple[DetectionNode, Track]],
List[Track],
List[DetectionNode]]
class Tracker:
def __init__(self, min_iou, ... | python |
def reverseArray(arr, start, end):
while start < end:
if arr[start] != arr[end]:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return arr
def reverseArrayInRecursive(arr, start, end):
if start >= end:
return arr
arr[start], arr[end] = arr[e... | python |
# Copyright 1999-2020 Alibaba Group Holding 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | python |
import pytest
from mock import patch
from uds.can.consecutive_frame import CanConsecutiveFrameHandler, \
InconsistentArgumentsError, CanDlcHandler, DEFAULT_FILLER_BYTE
from uds.can import CanAddressingFormat
class TestCanConsecutiveFrameHandler:
"""Unit tests for `CanConsecutiveFrameHandler` class."""
S... | python |
foo = input("Treat? ")
if foo == "Pastry":
print("Buttery flaky goodness")
elif foo == "Cake":
print("A light and fluffy classic")
elif foo == "Cookie":
print("Warm and crispy on the edges")
else:
print("We do not sell that. It sounds yum!")
foo = int(input("Wind speed? "))
if foo < ... | python |
from .sender import *
from .receiver import *
| python |
import pytest
from pre_commit.main import main as pre_commit
from versort import get_sorter
def test_style():
"""Just run pre-commit and see what happens."""
pre_commit(("run", "--all-files", "--show-diff-on-failure", "--color=always"))
def test_unknown_sorter():
"""See there's a valid error when a sor... | python |
# -*- coding: utf-8 -*-
# (Deprecated) The old version of similarity calculation. Will be removed in upcoming update.
from func.utils import Database
from func.model import Model
from pyspark.sql.functions import column
import pickle
import time
def prefilter(db, test):
app_query = 'SELECT * FROM app WHERE... | python |
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework.exceptions import NotFound
from allauth.account.models import EmailAddress
from users.models import User
from organizations_ext.model... | python |
from doodledashboard.component import NotificationCreator
from doodledashboard.notifications.notification import Notification
from doodledashboard.notifications.outputs import TextNotificationOutput
class TextInMessage(Notification):
"""Creates a notification containing the text of the last message"""
def cr... | python |
from .util import generate_evenly_spaced_data_set
def pagie_func1(x, y):
return 1.0 / x ** (-4) + 1.0 / y ** (-4)
def generate_pagie1():
train = generate_evenly_spaced_data_set(pagie_func1, 0.4, (-5, 5))
test = generate_evenly_spaced_data_set(pagie_func1, 0.4, (-5, 5))
return train, test
all_probl... | python |
# mc_bot.py
# Source: https://github.com/DrGFreeman/mc-to-discord
#
# MIT License
#
# Copyright (c) 2018 Julien de la Bruere-Terreault <drgfreeman@tuta.io>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# i... | python |
"""Setup module for NI Veristand."""
from os.path import dirname
from os.path import join
from setuptools import find_packages
from setuptools import setup
pypi_name = 'niveristand'
def get_version(name):
"""Calculate a version number."""
import os
version = None
script_dir = os.path.dirname(os.path... | python |
# -*- coding: utf-8 -*-
from brewtils.models import Operation
from beer_garden.api.http.base_handler import BaseHandler
class NamespaceListAPI(BaseHandler):
async def get(self):
"""
---
summary: Get a list of all namespaces known to this garden
responses:
200:
... | python |
from PIL import Image
import numpy
from .base import Base
from .loss_func import psnr_np, mse_np
from utils import Loader, Keeper
class BaseInterpolation(Base):
_scale_type = None
_scale_factor = 4
def model(self):
return None
def serialize(self):
pass
def unserialize(self):
... | python |
#Archivo para rutas USER
#Este modulo permite definir subrutas o rutas por separado, response es para respuestas HTTP
from fastapi import APIRouter, Response, status
#Esto solo me dice a donde conectarme, no hay un schema
from config.db import conn
#Aquí traemos el schema
from models.order_details import order_de... | python |
"""
Definitions of various hard coded constants.
Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.net).
"""
# Pyro version
VERSION = "4.30"
# standard object name for the Daemon object
DAEMON_NAME = "Pyro.Daemon"
# standard name for the Name server itself
NAMESERVER_NAME = "Py... | python |
import logging
import bson
import hashlib
import base58
def doc2CID (inp):
try:
# JSON OBJ to BSON encode
bson_ = bson.dumps(inp)
# SHA-256 Double Hashing
hash_ = hashlib.sha256(bson_)
hash_ = hashlib.sha256(hash_.digest())
# Convert to Base-58 string
b58c_ ... | python |
# Supported clients
from .supported_search_clients import SupportedSearchClients
# Utility function
from .download_images import download_image, download_all_images
# Search API Clients
from .search_api_client import SearchAPIClient
from .google_cse_client import GoogleCustomSearchEngineClient
from .bing_image_search... | python |
from quantumdl.models.quantummodel import *
from quantumdl.core.engine import * | python |
import datetime
from django.utils.timezone import utc
from rest_framework.authentication import TokenAuthentication
from rest_framework import exceptions
from django.utils.six import text_type
import base64
import binascii
from django.contrib.auth import get_user_model
from django.middleware.csrf import CsrfViewMiddlew... | python |
from __future__ import annotations
from unittest import TestCase
from tests.classes.simple_order import SimpleOrder
from tests.classes.simple_project import SimpleProject
from tests.classes.simple_chart import SimpleChart
from tests.classes.simple_setting import SimpleSetting
from tests.classes.author import Author
fro... | python |
# -*- coding: utf-8 -*-
from flask import render_template, request, redirect, url_for, abort
from fcsite import check_forced_registration_blueprint
from fcsite.models import bbs
from fcsite.auth import requires_login
from fcsite.utils import pagination, logi
mod = check_forced_registration_blueprint('bbs', __name__, ... | python |
# Copyright 2014: Mirantis 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 b... | python |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
... | python |
# Author: Calebe Elias Ribeiro Brim
# Last Update: 03/06/2018
import numpy as np
def bitsToBytes(values):
'''
Generate relative bits integers
Usage:
bitsToBytes(array.shape(1,10)) => array.shape(1,1)
bitsToBytes(array.shape(2,10)) => array.shape(2,1)
'''
ln = val... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'KeyWizard.ui'
#
# Created by: PyQt5 UI code generator 5.14.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_KeyWizard(object):
def setupUi(self, KeyWizard):
KeyWiz... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pygame import *
import os
PLATFORM_WIDTH = 32
PLATFORM_HEIGHT = 32
PLATFORM_COLOR = "#FF6262"
ICON_DIR = os.path.dirname(__file__) # Полный путь к каталогу с файлами
class Platform(sprite.Sprite):
def __init__(self, x, y):
sprite.Sprite.__init__(self)
... | python |
import sys
import os
from setuptools import setup
"""
Use pandoc to convert README.md to README.rst before uploading
$ pandoc README.md -o README.rst
"""
if "publish" in sys.argv:
os.system("python setup.py sdist upload")
os.system("python setup.py bdist_wheel upload")
sys.exit()
setup(
name="pipr... | python |
"""Module for working with transcripts, creating transcript DBs and reading from transcript DB"""
from __future__ import division
import gzip
from operator import itemgetter
import pysam
import datetime
import os
class Transcript(object):
"""Class for a single transcript"""
def __init__(self, id=None, vers... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.