content stringlengths 5 1.05M |
|---|
# (C) Copyright 2010-2020 Enthought, Inc., Austin, TX
# All rights reserved.
import unittest
from traits.testing.unittest_tools import UnittestTools
from force_bdss.api import KPISpecification
from force_bdss.tests.probe_classes.mco import ProbeMCOFactory
from force_wfmanager.ui.setup.mco.base_mco_options_model_v... |
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
"""
Implementation of flags command
"""
import os
from .base import Base
from ..context import bugzilla_instance
from ..bugzilla import BugzillaError
from .. import ui
class Command(Base):
"""Flags operations: add/remove/set"""
def register(self, subpar... |
from typing import Union, List, Optional
from pyspark.sql.types import (
StructType,
StructField,
StringType,
ArrayType,
DateType,
BooleanType,
DataType,
TimestampType,
)
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class Activit... |
# -*- coding: utf-8 -*-
from .models import ConferenceModerator
def list_conference_moderator(user):
qs = ConferenceModerator.objects.filter(moderator=user)
return qs.all()
|
from __future__ import annotations
import matplotlib as mpl
# https://stackoverflow.com/a/26853961/353337
def _merge(dict1, dict2):
"""Merge two dicts, dict2 takes precedence."""
return {**dict1, **dict2}
def duftify(style: dict, bar: bool = False) -> dict:
try:
grid_color = style["grid.color"]... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Generate elev2D.th for a Bay-Delta SCHSIM model using tides at
Point Reyes and Monterey.
2015-06-16: Customized
"""
import sys
import pandas as pd
from netCDF4 import Dataset
import gdal
from schimpy.separate_species import separate_species
from schimpy.schism_mesh i... |
from sklearn.model_selection import train_test_split
from lifelines import CoxPHFitter
import matplotlib.pyplot as plt
import streamlit as st
class Model:
def __init__(self, data):
self.data = data
def coxPH(self):
train_features = ['gender_Female', 'Partner_Yes', 'Dependents_Yes', 'PhoneServ... |
num = (int(input('Digite um numero')),
int(input('Digite outro numero')),
int(input('Digite mais um numero')),
int(input('Digite ultimo numero')))
print(f'Vc Digitou os numeros {num}')
print(f'o numero 9 apareceu {num.count(9)} vezes')
if 3 in num:
print(f'o valor 3 apareceu na {num.index(3) +... |
import graph_preprocessing as gp
import time
import random
import json
import os
from numba import jit, cuda
# graph = {
# 1: [8, 3, 7],
# 2: [7],
# 3: [1, 5],
# 4: [5, 8],
# 5: [4,3],
# 6: [7],
# 7: [1, 2, 6],
# 8: [1, 4]
# }
# hospital = [8,6, 2, 7]
start = time.time()
graph_reader = ... |
#This program demonstrates usage of 'With' statement from Lesson 6
with open("E:\SelfStudy\Python\PyMegaCourse\example3.txt","a+") as file:
#file.seek(0)
content=file.read()
file.write("\nTest 8")
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for the control service REST API.
"""
import socket
from contextlib import closing
from uuid import uuid4
from pyrsistent import thaw, pmap
from twisted.trial.unittest import TestCase
from twisted.internet.defer import gatherResults
from treq ... |
#!/usr/bin/env python
##########################################################################
# frontends/swig_python/RemoteThrill.py
#
# Part of Project Thrill - http://project-thrill.org
#
# Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
#
# All rights reserved. Published under the BSD-2 license in the LICENSE... |
import skimage.io as io
import skimage.transform as skt
import numpy as np
from PIL import Image
from src.models.class_patcher import patcher
from src.utils.imgproc import *
class patcher(patcher):
def __init__(self, body='./body/body_milk.png', **options):
super().__init__('ミルク', body=body, pantie_positi... |
"""93. Restore IP Addresses"""
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
## Practice:
""" DFS Backtrack string, iterate through first 3 eles for each
string. """
self.res = []
self.dfs(0, ... |
'''
- Leetcode problem: 25
- Difficulty: Hard
- Brief problem description:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out... |
import json
import os
from transfacils import models
from transfacils.helpers.get_trans_api_data import line_data_generator, \
get_line_data
def initialize_lines_db(filename: str = "initial_data.json"):
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
with open(os.path.join(base_dir... |
"""
Performance-related tests to make sure we don't use more memory than we should.
For now this is just for SpectralCube, not DaskSpectralCube.
"""
from __future__ import print_function, absolute_import, division
import numpy as np
import pytest
import tempfile
import sys
try:
import tracemalloc
tracemall... |
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %% [markdown]
# # Covid Plots
#
# I wanted to test out using jupyter notebook to show off some plotly graphs. So here goes.
# %%
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import plotly.graph_objects as ... |
# 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! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import logging
from logging import config as config_log
from colorlog import ColoredFormatter
from DeviceManager.conf import CONFIG
from DeviceManager.utils import HTTPRequestError
class Log:
def __init__(self, LOG_LEVEL = CONFIG.log_level,
LOG_FORMAT = "[%(log_color)s%(asctime)-8s%(reset)s] |%(log_colo... |
import os
import re
import time
from contextlib import closing
import psycopg2
from confluent_kafka import Consumer
DSN_TEMPLATE = os.environ.get("CDC_POSTGRES_DSN_TEMPLATE", "postgres:///{database}")
DATABASE_NAME = "test_db"
def _wait_for_slot() -> None:
with closing(
psycopg2.connect(DSN_TEMPLATE.for... |
from yapsy.IPlugin import IPlugin
from yapsy.PluginManager import PluginManagerSingleton
from flask.ext.admin import BaseView, expose
from flask import render_template
import logging, inspect
class PluginObj(IPlugin, BaseView):
def __init__(self, **kwargs):
IPlugin.__init__(self)
Base... |
# Uses python3
n = int(input())
if n == 1:
print(1)
print(1)
quit()
W = n
prizes = []
for i in range(1, n):
if W>2*i:
prizes.append(i)
W -= i
else:
prizes.append(W)
break
print(len(prizes))
print(' '.join([str(i) for i in prizes])) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020 Huawei Device 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/licenses/LICENSE-2.0
... |
import torch
import numpy as np
import open3d as o3d
class FPFH_RANSAC(torch.nn.Module):
def __init__(self, voxel_size, max_dist, max_iter, max_val):
super().__init__()
self.voxel_size = voxel_size
self.max_iter = max_iter
self.max_val = max_val
self.max_dist = max_dist
... |
from __future__ import print_function
import os
import sys
from documentcloud import DocumentCloud
print("Enter your Document Cloud Credentials")
sys.stdout.write("Username: ")
username = raw_input().strip()
sys.stdout.write("Password: ")
password = raw_input().strip()
base_uri = "https://sourceafrica.net/api/"
clie... |
import os
import sys
import resource
import subprocess
import argparse
import logging
import itertools
import collections
import json
import numpy as np
import pdb
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def make_expts(b_fq_toc, b_compbined_alleles, b_r1, b_r2, bulk_toc, G_ij, se... |
## Script (Python) "guard_cancelled_object"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
workflow = context.portal_workflow
# Note: Also used by profiles/default/types/AnalysisRequest.xml
# Can't do anything to the o... |
import torch
# "long" and "short" denote longer and shorter samples
class PixelShuffle1D(torch.nn.Module):
"""
1D pixel shuffler. https://arxiv.org/pdf/1609.05158.pdf
Upscales sample length, downscales channel length
"short" is input, "long" is output
"""
def __init__(self, upscale_factor):
... |
import random
import emoji
def nick_generator():
nicks = [
'Васёк',
'Геракл',
'Фетида',
'Зевс',
'Врач',
'Вкусняшка',
'Л0ЛЬК0'
]
return random.choice(nicks)
def switch_chars(txt):
symbols = 'qwertyuiopasdfghjklzxcvbnm'
symbols += 'йёцукенгшщзх... |
import datetime
import json
import numpy as np
import pandas as pd
import requests
import xarray as xr
from utils import divide_chunks, get_indices_not_done, \
get_site_codes, append_to_csv_column_wise, load_s3_zarr_store,\
convert_df_to_dataset
def get_all_streamflow_data(output_file, sites_file, huc2=None... |
import numpy as np
from mygrad import log, log1p, log2, log10
from tests.wrappers.uber import backprop_test_factory, fwdprop_test_factory
@fwdprop_test_factory(
mygrad_func=log, true_func=np.log, index_to_bnds={0: (1e-5, 100)}, num_arrays=1
)
def test_log_fwd():
pass
@backprop_test_factory(
mygrad_func... |
from pyspark.sql import SparkSession
spark = SparkSession\
.builder\
.appName("SparkApp")\
.master("spark://VN-L2041.hcg.homecredit.net:7077")\
.getOrCreate()
df1 = spark.range(2, 10000000, 2)
df2 = spark.range(2, 10000000, 4)
step1 = df1.repartition(5)
step12 = df2.repartition(6)
step... |
import asyncio
import logging
import time
import math
from aiohttp import ClientConnectionError
from asyncio.queues import QueueEmpty
from .utils import Throttler
from botocore.exceptions import ClientError
from .base import Base
from . import exceptions
from .processors import JsonProcessor
log = logging.getLogger... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 3 10:57:50 2019
@author: ngritti
"""
from PyQt5.QtCore import Qt
from PyQt5 import QtCore
from PyQt5.QtWidgets import (QApplication, QVBoxLayout, QDialog,
QGridLayout, QLabel, QPushButton,
QWidget, QSizePolicy, QSpinBox, QDoubleSpin... |
"""
* Primitives 3D.
*
* Placing mathematically 3D objects in synthetic space.
* The lights() method reveals their imagined dimension.
* The box() and sphere() functions each have one parameter
* which is used to specify their size. These shapes are
* positioned using the translate() function.
"""
size(640,... |
class Goal(object):
def __init__(self, goalTuple):
super().__init__()
self._GoalID = goalTuple[0]
self._ProjectID = goalTuple[1]
self._ProjectTargetWeight = goalTuple[2]
def getGoalID(self):
return self._GoalID
def getProjectID(self):
return self._ProjectID... |
from exchanges import helpers
from exchanges import bitfinex
from exchanges import bitstamp
from exchanges import okcoin
from exchanges import cex
from exchanges import btce
from time import sleep
from datetime import datetime
import csv
# PREPARE OUTPUT FILE
# tell computer where to put CSV
filename = datetime.now(... |
import numpy
def bad_reward(dead, water_amount):
if water_amount > 0 and not dead:
return 1
return 0
def good_reward(old_moisture, new_moisture):
# gaussian function
old_moisture_reward = numpy.exp(-numpy.power(old_moisture - 0.5, 2.) / (2 * numpy.power(0.25, 2.)))
new_moisture_reward = ... |
while True:
user = input('Criptografar(1) Descriptografar(2) cancelar(0):')
if user == '0':break
mensagem = input("sua mensagem: ").lower().replace(' ','')
senha = input("sua senha: ").lower().replace(' ','')
crip = ''
alpha = 'abcdefghijklmnopqrstuvwxyz'
while len(mensagem) > len(senha): senha+=... |
# Generated by Django 3.1.4 on 2021-01-30 22:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("person", "0024_date_migration_information_target_group"),
]
operations = [
migrations.RemoveField(
model_name="speakerinformation",
... |
# -*- coding: utf-8 -*-
u"""
Created on 2015-7-13
@author: cheng.li
"""
from PyFin.tests.DateUtilities.testCalendar import TestCalendar
from PyFin.tests.DateUtilities.testDate import TestDate
from PyFin.tests.DateUtilities.testPeriod import TestPeriod
from PyFin.tests.DateUtilities.testSchedule import TestSchedule
fr... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 4 18:14:29 2016
@author: becker
"""
import numpy as np
import scipy.linalg as linalg
import scipy.sparse as sparse
try:
from simfempy.meshes.simplexmesh import SimplexMesh
except ModuleNotFoundError:
from simfempy.meshes.simplexmesh import SimplexMesh
import sim... |
import lc_data_access
import time
lc_access = lc_data_access.LC_Access()
# TODO:
# > Deal with the async aspect if there are too many calls.
# > Cleanup this file for testing.
# > link to the problem on the !get command.
# > don't count duplicates.
# > update recap command to say something if there aren't any users.... |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... |
import re
import socketserver
# 自定义处理函数
class MyHandler(socketserver.BaseRequestHandler):
def handle(self):
"""自定义处理方法"""
data = self.request.recv(2048)
if data:
header, other = data.decode("utf-8").split("\r\n", 1)
self.set_request_headers(other) # 把请求头组装成字典
... |
#!/share/software/user/open/python/3.6.1/bin/python3
from src.ModelDriver import *
## MODIFY THESE PARAMS FOR SPECIFIC RUN ###
X_train = "/oak/stanford/groups/aboettig/Aparna/NNreviews/TestRobustness/jitterData/train_5.23.18_JitterRad-40.0_jitterPerc-0.5_xyz.txt"
Y_train = "/oak/stanford/groups/aboettig/Aparna/NNproje... |
# -*- coding: utf-8 -*-
'''
Provide authentication using a Slack token
Slack auth can be defined like any other eauth module:
.. code-block:: yaml
external_auth:
slack:
fred:
- .*
- '@runner'
'''
# Import python libs
from __future__ import absolute_import, print_function, unic... |
"""Refresh cog."""
from discord.ext import commands, tasks
from bot import google
class Refresh(commands.Cog, command_attrs={"hidden": True}):
"""All the miscellaneous commands."""
def __init__(self, bot):
self.bot = bot
self.refresh_loop.start()
@staticmethod
async def run_refresh... |
from cyaron import *
CASES = 10
for t in range(1, CASES + 1):
io = IO(f"{t}.in")
# ==============================
n = 100
k = randint(0, int(1e12)) if t <= 5 else int(1e12)
io.input_writeln(n, k)
for i in range(n):
io.input_writeln(
*(randint(-1000 if t <= 7 else 0, 1000) f... |
""" Convert img-list to tensorflow TFRecord format """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import numpy as np
import pandas as pd
import argparse
import cv2
import json
from natsort import natsorted
from tqdm import tqdm
from... |
from rjgtoys.cli import Command
class GreeterBase(Command):
DEFAULT_NAME = "you"
def _arg_name(self, p):
p.add_argument(
'--name',
type=str,
help="Name of the person to greet",
default=self.DEFAULT_NAME
)
def run(self, args):
prin... |
from rest_framework import exceptions, serializers
from api.v2.serializers.summaries import StatusTypeSummarySerializer
from core.models import StatusType
class StatusTypeRelatedField(serializers.RelatedField):
def get_queryset(self):
return StatusType.objects.all()
def to_representation(self, statu... |
from test_all_fixers import lib3to2FixerTestCase
class Test_printfunction(lib3to2FixerTestCase):
fixer = u"printfunction"
def test_generic(self):
b = u"""print()"""
a = u"""from __future__ import print_function\nprint()"""
self.check(b, a)
def test_literal(self):
b = u"""... |
from django import forms
from utils.api.client import MarketAccessAPIClient
from utils.forms import (
ChoiceFieldWithHelpText,
ClearableMixin,
DayMonthYearField,
MultipleChoiceFieldWithHelpText,
YesNoBooleanField,
YesNoDontKnowBooleanField,
)
from .mixins import APIFormMixin
class UpdateComm... |
# Copyright (c) 2020 PaddlePaddle Authors. 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 appli... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 19 13:21:23 2017
@author: James Jiang
"""
all_lines = [line.rstrip('\n') for line in open('Data.txt')]
all_lines_chars = []
for i in range(len(all_lines)):
chars = [j for j in all_lines[i]]
all_lines_chars.append(chars)
index_list = 0
index_all = 0
for i i... |
from django.db import models
from django.urls import reverse
import datetime
from .genre import Genre
from .category import Categorie
class Artist(models.Model):
name = models.CharField(max_length=100)
known_as = models.CharField(max_length=60)
genre = models.ManyToManyField(Genre)
categorie = models.F... |
import setuptools
from commandintegrator import __version__ as version
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="commandintegrator",
version=version,
author="Simon Olofsson",
author_email="dotchetter@protonmail.ch",
description="A framework and API... |
from thingsboard_gateway.connectors.converter import Converter, abstractmethod, log
class MPlcConverter(Converter):
@abstractmethod
def convert(self, config, data):
pass
|
# -*- coding: utf-8 -*-
from jsonlint.i18n import DummyTranslations
from jsonlint.validators import ValidationError, StopValidation
class DummyField(object):
_translations = DummyTranslations()
def __init__(self, data, errors=(), raw_data=None):
self.data = data
self.errors = list(errors)
... |
import datetime
import posixpath
import pytz
from pylons import request
from pylons import app_globals as g
from pylons import tmpl_context as c
from pylons.controllers.util import abort
from r2.config import feature
from r2.controllers import add_controller
from r2.controllers.reddit_base import RedditController
fro... |
""" Download views for editorial app. """
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect, get_object_or_404
from django.conf import settings
from django.core.mail import send_mail
from django.http import HttpResponse
from django.utils import timezo... |
from multiprocessing import Pool
class Collection:
"""
Helper to provide a natural Functional Programming approach in Python.
"""
def __init__(self, val):
self.val = val
def apply(self, f):
return Collection(f(self.val))
def filter(self, f):
return Collection(filt... |
import math
from lib.preset import Preset
from lib.color_fade import Rainbow
from lib.basic_tickers import fade, offset, speed
from lib.parameters import FloatParameter
class RadialRainbow(Preset):
"""
demonstrates scene attributes by assigning a color rainbow
to fixtures based on their radial position i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A demonstration of simulating open system dynamics by sampling
over randomized pure state trajectories.
This simulates the dynamics of an edge-driven XXZ chain,
which has an analytic solution for lam = 1.0, eps = 2.0.
See: T. Prosen, Phys. Rev. Lett. 107, 137201 (2011... |
import numpy as np
from seizures.features.FeatureExtractBase import FeatureExtractBase
from seizures.data.Instance import Instance
import numpy as np
from numpy import unwrap, angle
from scipy.signal import hilbert
from matplotlib import pyplot as plt
class PLVFeatures(FeatureExtractBase):
"""
Class ... |
from week_zero.swapper import swapper
from week_zero.matrix import matrix1
from week_zero.design import design
from week_zero.funcy import monkey
from week_one.week_one import fibonacci
from week_one.week_one import for_loopy, while_loopy, recursive_loopy
from main import my_info
from week_two.factor import normal_fact... |
# Alex Hancock, UCSC CGL
# Luigi Monitor
import json
import boto
from boto.s3.key import Key
from sqlalchemy import MetaData, Table, Column, String, Float, create_engine
unique_job = 'spawnFlop_SRR1988343_demo__consonance_jobs__0992701f6f'
sample_id = 'DTB-116_Baseline_1'
topfolder = 'UCSF_SU2C_WCDT_DTB-116_DTB-116_... |
import sys
import SelectiveRepeat
import StopAndWait
import GoBackN
def print_usage():
print("""\nUsage: main.py option config-file-name\n
option:\n-st:\tstop and wait\n-sr:\tselective repeat\n-go:\tgo back N\n""")
if len(sys.argv) < 3:
print_usage()
elif len(sys.argv) == 3:
method = sys.argv[1]
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import warnings
import os
import io
import re
try:
from setuptools import setup
from setuptools.command.install import install
setup
except ImportError:
from distutils.core import setup
setup
# Get the long description from the README
def readme():
with open(... |
from openpnm.algorithms import TransientReactiveTransport, FickianDiffusion
from openpnm.utils import logging, Docorator
logger = logging.getLogger(__name__)
docstr = Docorator()
class TransientFickianDiffusion(TransientReactiveTransport, FickianDiffusion):
r"""
A class to simulate transient diffusion with re... |
from typing import Optional, Union
from datetime import date, time
from .reserve import Reserve, ReserveSetType
from .user import User
class Supboard(Reserve):
"""Supboard reservation data class
Attributes:
is_complete:
A boolean attribute indicates that reservation is complete or not.
... |
name = "declutter" |
#!/usr/bin/python3
def only_diff_elements(set_1, set_2):
return (set_1 ^ set_2)
|
from emf.fields import enviro as env
for i in range(1,4):
fn1 = 'enviro-files/Envsmpl' + str(i) + '.o01'
fn2 = 'enviro-files/Envsmpl' + str(i) + '.o02'
env.compare_o01_o02(fn1, fn2, path='o0-comparison')
|
import requests
import logging
from shotgun_api3 import Shotgun
from sgsession import Session
import json
log = logging.getLogger(__name__)
SLACK_CHANNEL = SLACK_CHANNEL
SLACK_TOKEN = SLACK_TOKEN
def callback(event):
sg = Session()
print event['entity']
if event['project']['id'] != 74:
return "ch... |
def response_decider():
"""
This will execute commands or reply base on user input
Returns:
Nothing
"""
# Begin Application
print(INTRO)
# User Input Analyzer
while True:
# Get user input
user_input = input("User: ")
if user_input.lower()... |
import dgl
import torch
import torch.nn as nn
from data.molecules import MoleculeDataset
from data.QM9 import QM9Dataset
from data.SBMs import SBMsDataset
from data.TSP import TSPDataset
from data.superpixels import SuperPixDataset
from data.cora import CoraDataset
from models.networks import *
from utils.utils import ... |
# based on https://gist.github.com/wshanshan/c825efca4501a491447056849dd207d6
# Ported for ProjectAlf by Alfiananda P.A
import os
import random
import numpy as np
from colour import Color
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from PIL import Image, ImageDraw, ImageFont
f... |
import argparse
import gym
from .agents import HumanPlayer, RandomPlayer, SelfPlayRLAgent
parser = argparse.ArgumentParser("Play Connect-Four between two players")
parser.add_argument("--p1", choices=['self_play', 'random', 'human'], default='self_play')
parser.add_argument("--p2", choices=['self_play', 'random', 'h... |
# Delete a video using its video ID
import apivideo
from apivideo.apis import VideosApi
from apivideo.exceptions import ApiAuthException
api_key = "your api key here"
client = apivideo.AuthenticatedApiClient(api_key)
# If you'd rather use the sandbox environment:
# client = apivideo.AuthenticatedApiClient(api_key, p... |
from api import db, bcrypt, UserModel
import datetime
class Administration():
@staticmethod
def create_admin_user(name, login, password):
Administration.delete_user(login)
user = UserModel(name, login, password, timestamp = datetime.datetime.now())
try:
result = db.session.add(user)
db.sess... |
def break_words(stuff):
"""this function will break up words for us.
Args:
stuff ([string]): [the string to break]
"""
words = stuff.split(' ')
return words
def sort_words(words):
"""this function will sort words
Args:
words ([string]): [the string to sort]
"""
re... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 Graz University of Technology.
#
# invenio-records-lom is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Marshmallow schema for validating and serializing LOM JSONs."""
from flask import... |
import re
from pathlib import Path
from random import random
import torch
from more_itertools import flatten
from torch import nn
from torch.utils.data import Dataset
from torchvision import transforms
from util import dose2locs, loc2dose
class ImageDataset(Dataset):
def __init__(self, folder, image_size, trans... |
import requests
def call_api(city_name):
url = "http://api.openweathermap.org/data/2.5/weather"
api_key = "d14f9d7cc8a0c8af189d902e396458ea"
params = {"appid" : api_key, "q" : city_name, "units" : "metric"}
response = requests.get(url, params = params)
response_in_json = response.json()
weather_result = ... |
# -*- coding: utf-8 -*-
""" Code is generated by ucloud-model, DO NOT EDIT IT. """
from ucloud.core.client import Client
from ucloud.services.uhub.schemas import apis
class UHubClient(Client):
def __init__(self, config, transport=None, middleware=None, logger=None):
super(UHubClient, self).__init__(confi... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
from typing import Any, List
from ..problem import ProblemPredicate, ProblemType
from .base import Field, NonNullMixin
class BoolField(NonNullMixin, Field):
def validate(self, value: Any) -> List[ProblemPredicate]:
problems = super().validate(value)
if problems:
return problems
... |
import datetime, time
from io import StringIO
import typing
import aiohttp
from aiohttp.client import ClientSession
import discord
from discord import message
from discord import file
from discord.components import SelectOption
from discord.enums import DefaultAvatar
from discord.ext import commands
from discord.ext.co... |
"""Annotate with UCSC Genome Browser or other sql RefGene database."""
__author__ = "Martin Haagmans (https://github.com/zaag)"
__license__ = "MIT"
import os
import pymysql
import pybedtools
class Annotation:
"""Annotate gene or region with RefGene.
Method to query genomic intervals returns list of genena... |
import math
def add_vectors(vector1, vector2):
#Note the vectors are tuple (angle, magnitude)
x = math.sin(vector1[0]) * vector1[1] + math.sin(vector2[0]) * vector2[1]
y = math.cos(vector1[0]) * vector1[1] + math.cos(vector2[0]) * vector2[1]
mag = math.hypot(x, y)
angle = (math.pi/2) - math.atan2(y, x)
return (a... |
"""
Generalized extreme value distribution
--------------------------------------
Note that the parameter xi used here has the opposite sign
of the corresponding shape parameter in `scipy.stats.genextreme`.
"""
import mpmath
__all__ = ['pdf', 'logpdf', 'cdf', 'sf', 'mean', 'var']
def pdf(x, xi, mu=0, sigma=1):
... |
from __future__ import unicode_literals
from .models import ec2_backends
from ..core.models import MockAWS
ec2_backend = ec2_backends['us-east-1']
def mock_ec2(func=None):
if func:
return MockAWS(ec2_backends)(func)
else:
return MockAWS(ec2_backends)
|
class Vector2D:
def __init__(self, vec: List[List[int]]):
self.vec = []
self.i = 0
for A in vec:
self.vec += A
def next(self) -> int:
ans = self.vec[self.i]
self.i += 1
return ans
def hasNext(self) -> bool:
return self.i < len(self.vec)
|
import os
serve_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "serve"))
serve = {"__mpld3": serve_path}
scripts = [
"/__mpld3/d3.placeholder.js", # will load faster for mpld3
"/__mpld3/d3.v5.min.js",
# "/__mpld3/mpld3.v0.5.7.js",
"/__mpld3/mpld3.v0.5.7.min.js",
"/__mpld3/vue-mpld... |
# from python
from pathlib import Path
from typing import Union
import textwrap
# from pypi
from bokeh.embed import autoload_static
import bokeh.plotting
import bokeh.resources
import holoviews
PathType = Union[str, Path]
class EmbedBokeh:
"""Embed a bokeh figure
Args:
plot: a hvplot to embed
fold... |
from logging import Filter, LogRecord
from typing import Union
from pydantic import BaseModel
class GetData(BaseModel):
"""BaseModel that handles input data for the API which is treated as members for the class ``GetData``.
>>> GetData
See Also:
- ``command``: Offline command sent via API which... |
import requests
from requests.exceptions import HTTPError
import pprint
def get_json_dict(url: str) -> dict:
try:
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:86.0) Gecko/20100101 Firefox/86.0",
"Accept": "application/json, text/plain, */*",
"Accept-L... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.