content stringlengths 5 1.05M |
|---|
from __future__ import unicode_literals
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Field
from . import models
from django import forms
# from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.conf import settings
from dj... |
# from multiprocessing import Pool
from concurrent.futures import ProcessPoolExecutor as Pool
from datetime import datetime
from logger_tt import logger
from metaDMG.fit.serial import run_single_config
from metaDMG.utils import Configs
def run_workflow(configs: Configs):
parallel_samples = min(configs["paralle... |
from pyramid.events import subscriber
from websauna.system.admin import menu
from websauna.system.admin.events import AdminConstruction
from websauna.system.admin.modeladmin import ModelAdminRoot
from websauna.system.core.traversal import Resource
@subscriber(AdminConstruction)
def contribute_model_admin(event):
... |
from __future__ import print_function
__author__ = 'ragomez'
def fibonacci(n):
x = 0
y = 1
while x <= n:
yield x
x, y = y, x + y
number = int(raw_input('Enter limit of fibonacci sequence:'))
for i in fibonacci(number):
print(i)
|
# -----------------------------------------------------------
# Copyright (C) 2020 NVIDIA Corporation. All rights reserved.
# Nvidia Source Code License-NC
# Code written by Xueting Li.
# -----------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
f... |
import logging
import os
import pickle
import nltk
from src.classifier.german_pos_tagger import ClassifierBasedGermanTagger
from src.util.globals import RESOURCE_DIR
from src.util.log_util import log_setup
log_setup()
log = logging.getLogger(__name__)
corpus_name = 'tiger_release_aug07.corrected.16012013.conll09'
... |
"""ps
Revision ID: 537547987ae9
Revises: f4b53dde4c06
Create Date: 2018-07-16 23:44:50.913299
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '537547987ae9'
down_revision = 'f4b53dde4c06'
branch_labels = None
depends_on = None
def upgrade():
# ### command... |
# Desafio 097 -> Crie um programa que tenha uma função chamada escreva() que receba textos quaisquer
# como parâmetro
# e mostre uma msg com tamanho adaptável (com os ---- do mesmo tamanho)
def escreva(txt):
print('-' * (len(txt)))
print(txt)
print('-' * (len(txt)))
whi... |
"""Renderer za XHTML dokumente koji sadrže samo liste.
Kolokvij 2. veljače 2015. (Puljić)"""
from vepar import *
class T(TipoviTokena):
HTML, HEAD, BODY = '<html>', '<head>', '<body>'
ZHTML, ZHEAD, ZBODY = '</html>', '</head>', '</body>'
OL,ZOL,UL,ZUL,LI,ZLI = '<ol>','</ol>','<ul>','</ul>','<li>','</li>... |
def get_yes_no(message = "") -> str:
'''
Returns a Yes/No response for the user
based on the given string argument.
'''
response = input(message)
while True:
response = response.capitalize()
response = response.strip()
if response == "Yes" or response == "No":
... |
# to treat module namespaces in this directory as a package
# https://docs.python.org/3/tutorial/modules.html#packages |
# Copyright (c) 2017, 2019, Oracle and/or its affiliates.
# Copyright (c) 2013, Pablo Mouzo
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
#
# TITLE :
# AUTHOR :
# PROJECT :
#
# ----------------------------------------------------------------------------
### Docstring and Metadata
"""**DOCSTRING**
"""
__author__ = ""
# __copyr... |
"""
PATH -> É a pasta onde contem as subpastas que contem outras subpastas ou arquivos.\n
testPATH -> Uma pasta de test.\n
createdPATH -> Nome da pasta digitada pelo usuário.
"""
PATH = "/home/farioso/www/file03_git/fluentui-system-icons/assets"
testPATH = "files"
createdPATH = "soSvg"
# Caso não queira importar v... |
from django.utils.translation import gettext as _
from django.contrib.auth import password_validation
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from rest_framework.res... |
from direct.task import Task
from direct.http import WebRequest
from direct.directnotify import DirectNotifyGlobal
import random, string
class webNotifyDebug:
def __init__(self, portNumber = 8888, username = None, password = None):
self.portNumber = portNumber
self.username = username
self... |
from django.apps import AppConfig
class ProbeConfig(AppConfig):
name = 'probe'
|
import cv2
import numpy as np
from glob import glob
from sklearn.model_selection import train_test_split
def return_imgs():
cars = glob('../data/cars_rear_view/vehicles/**/*.png')
non_cars = glob('../data/cars_rear_view/non-vehicles/**/*.png')
return cars, non_cars
def create_dataset(cars, non_cars... |
# [Project YNS] Yonsei Univ. Notification Service, Project KNSF based.
# 0.1.2va, 20.02.02. First launched.
# written by acoustikue(SukJoon Oh), Yonsei University EE
# __ _ __
# ____ __________ __ _______/ /_(_) /____ _____
# / __ `/ ___/ __ \/ / / / ___/ __/ / //_/... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass
from typing import Tuple
from pants.engine.internals.scheduler import Workunit
from pants.engine.rules import collect_rules, rule
from pants.engine.strea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayEbppInstserviceDeductPayModel(object):
def __init__(self):
self._agreement_id = None
self._bill_date = None
self._bill_key = None
self._ededuct_product_code ... |
from src.segmentation.networks.resnetunet.encoder import ResNet
from src.segmentation.networks.resnetunet.decoders import UnetDecoder, PSPDecoder
import importlib
from torch import optim
from typeguard import typechecked
import numpy as np
import pytorch_lightning as pl
import torch
from torch import nn
from torch.opti... |
import inspect
import platform
import httpx
from typing import Dict, Generic, Iterable, Optional, Any, TypeVar, Union, Type
from typing_extensions import TypedDict
import json
from random import random
from ._models import NoneModel, IResponseModel, GenericModel
from abc import ABC, abstractmethod
from pydantic import ... |
from configuration import *
file_name = 'PdfWithAnnotations.pdf'
uploadFile(file_name)
response_annotations = pdf_api.get_document_free_text_annotations(
file_name, folder=temp_folder)
annotation_id = response_annotations.annotations.list[0].id
response = pdf_api.get_free_text_annotation(
file_name, annotati... |
# Generated by Django 2.2rc1 on 2019-04-02 10:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('openbook_categories', '0005_auto_20190327_1945'),
('openbook_categories', '0005_auto_20190330_1554'),
]
operations = [
]
|
# -*- encode: utf-8 -*-
from docx import Document
from docx.shared import Inches
document = Document()
indent = ' '
# section
document.add_heading('Summary', 0)
document.add_paragraph(indent + 'This chapter describes the mechanics of the publication process, which includes choosing a journal, submitting a manusc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import errno
import itertools
import os
import time
from bs4 import BeautifulSoup
import click
import dataset
import funcy as fy
import requests
HTML_DB_FILENAME = 'scraped_html_copy.db'
DATASET = dataset.connect('sqlite:///' + HTML_DB_FILENAME)
TABLE = DATAS... |
from __future__ import print_function
from testconfig import config
from pyvcloud.vcloudair import VCA
class TestVCA:
def __init__(self):
self.vca = None
self.login_to_vcloud()
def login_to_vcloud(self):
"""Login to vCloud"""
username = config['vcloud']['username']
p... |
# Copyright 2020 The TensorFlow 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 applica... |
"""测试Schema用例"""
from marshmallow import Schema, fields
class GrandChildSchema(Schema):
name_3 = fields.Str()
class ChildSchema(Schema):
name_2 = fields.Str()
code_2 = fields.Str()
grand_children = fields.List(fields.Nested(GrandChildSchema))
class ParentSchema(Schema):
name = fields.Str()... |
# 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! ***
from . import _utilities
import typing
# Export this package's modules as members:
from .aws_network_peering import *
from .aws_transit... |
#!/usr/bin/python3
import sys, re
lineRe = re.compile(r'^\((\d), \((\d), (\d), (\d)\)\): \[(.*)\]\s*$')
def main(fileName):
f = open(fileName, 'r')
print('<situations>')
for line in f.readlines():
lineMatch = lineRe.match(line)
if lineMatch:
# Starting at one to make compliant w... |
# Generated by Django 2.1.7 on 2019-03-29 07:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('membership', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='racer',
... |
# Run 'dispycosnode.py' program to start processes to execute computations sent
# by this client, along with this program.
# Distributed computing example where this client sends computation to remote
# dispycos process to run as remote tasks. At any time at most one computation
# task is scheduled at a process, as th... |
from dataclasses import dataclass, field
from math import sin, cos, pi as PI
@dataclass
class AngledVector:
"""This class is used as a storing place for currently being claculated part of koch's curve and as a place for calculating all the angles"""
angle: float = 0
x: float = field(init = False, defaul... |
import os
import math
from torchvision import utils
import torch
import copy
from utils.sample import sample_noises
from utils.losses import loss_hinge_dis, loss_hinge_gen
import time
class GanTrainer(object):
def __init__(self, iteration, dataset, genenerator, discriminator, gen_optimizer, dis_optimizer, output... |
import logging
from time import sleep
from vspk import v6 as vsdk
from vspk.utils import set_log_level
set_log_level(logging.ERROR)
def did_receive_push(data):
""" Receive delegate
"""
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(data)
if __name__ == '__main__':
import sys
... |
#!/usr/bin/env python
# Script that reads .cloginrc credential/configuration file for clogin
__version__ = (1, 0)
from __future__ import with_statement # This isn't required in Python 2.6
from collections import OrderedDict
dot_cloginrc = '.cloginrc'
class LastUpdatedOrderedDict(OrderedDict):
'Store items in the... |
'''
miscellaneous functions
'''
import os
import errno
import time
import math
import gzip
import numpy as np
import pickle as pkl
from PIL import Image
import gym
import matplotlib.pyplot as plt
from utils.learning import logging
from utils.transformers import quaternion_from_matrix, rotation_matrix
''' for rl ge... |
"""
Unit tests for plots.py functions.
"""
import unittest
import matplotlib
import matplotlib.pyplot as plt
from radioactivedecay.plots import (
_parse_nuclide_label,
_parse_decay_mode_label,
_check_fig_axes,
)
class TestFunctions(unittest.TestCase):
"""
Unit tests for plots.py functions.
""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: José Sánchez-Gallego (gallegoj@uw.edu)
# @Date: 2020-07-30
# @Filename: client.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
from __future__ import annotations
import asyncio
import json
import logging
import pathlib
import uui... |
import abc
class MyClass(metaclass= abc.ABCMeta):
def my_set_val(self, value):
self.value = value
def my_get_val(self):
return self.value
@abc.abstractmethod
def print_doc(self):
return
class MyChildClass(MyClass):
def my_set_val(self, value):
if not isinstanc... |
from abc import ABC, abstractmethod
import pandas as pd
from us_pls._download.models import DatafileType
class ITransformationService(ABC):
@abstractmethod
def transform_columns(
self, df: pd.DataFrame, datafile_type: DatafileType
) -> pd.DataFrame:
...
|
import time
import pickle
import graph
import utils
import scipy.io as sio
import networkx as nx
import debias_result as LINE
def fair(name, vanilla, lambda_=0., similarity=None):
# vanilla result
X = vanilla[name]
# load dataset
data = graph.read_pickle(name)
A_train = data['adjacency_train']... |
from typing import List, Optional
import numpy as np
from django.db.models.aggregates import Sum
from scipy import special
from django.core.exceptions import ObjectDoesNotExist
from django.db import IntegrityError, models
from django_pandas.managers import DataFrameManager
from app.support.repetition import calculat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file was part of Flask-Bootstrap and was modified under the terms of
# its BSD License. Copyright (c) 2013, Marc Brinkmann. All rights reserved.
#
# This file was part of Bootstrap-Flask and was modified under the terms of
# its MIT License. Copyright (c) 2018 Grey ... |
CATALOGUE_1 = {
"Hyperbole and a Half": {
"author": "Allie Brosh",
"pages": 369
},
"Rainbow in the Cloud": {
"author": "Maya Angelou",
"pages": 105
},
"Bloody Brilliant Women": {
"author": "Cathy Newman",
"pages": 358
},
}
def get_book_author(cat... |
# histogram is nothing but a discretized probability distribution of the
# data
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
A = pd.read_csv("data_1d.csv",header=None).as_matrix()
x = A[:,0] # x axis is the first column colon : means select everything in that
# dimension
y = A... |
import cherrypy
import datetime
import config
import core.Database
import core.Hardware
import core.WeatherData
import core.WaterSettings
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
class WaterAdmin(object):
db = None # Hold our database connectio... |
import torch
import torch.nn as nn
import pytorch_lightning as pl
import hydra
import random
import wandb
import math
from urllib.parse import urlparse
from typing import List, Dict, Tuple, Optional
from omegaconf import DictConfig, OmegaConf
from hydra.utils import instantiate, to_absolute_path
from pytorch_lightning... |
"""
https://www.programiz.com/dsa/heap-sort
Procedures to follow for Heapsort
---------------------------------
Since the tree satisfies **Max-Heap** property, then the largest item is stored at the root node.
Remove the root element and put at the end of the array (nth position) Put the last item of the tree (heap) a... |
import os, os.path
import random
import sqlite3
import string
import time
import cherrypy
DB_STRING = "url.db"
BASE_HOST_NAME = "http://localhost:8080/"
class ShortUrlGenerator(object):
@cherrypy.expose
def index(self):
return file('index.html')
class ShortUrlWebService(object):
exposed = True
... |
import asyncio
import datetime
from typing import Union
import discord
from discord.ext import commands
from PyDiscordBot.misc import Constants
from PyDiscordBot.utils import MessagingUtils, DataUtils, TimeUtils
class Utils:
def __init__(self, bot: commands.Bot, ctx: commands.Context, to_send: discord.Embed = N... |
import argparse
import logging
import time
import cv2
import numpy as np
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks import get_graph_path, model_wh
logger = logging.getLogger('TfPoseEstimator-Video')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
forma... |
import inspect
import re
class Checker:
@classmethod
def full_check(cls, stream, sep=',', quotechar=None, tests='all'):
"""Perform all the tests on the stream.
Parameters
----------
stream : file object
An file-like object made of characters. It must suport call
... |
from django.conf import settings
import jingo
from nose.tools import eq_
try:
from build import BUILD_ID_CSS, BUILD_ID_JS
except:
BUILD_ID_CSS = BUILD_ID_JS = 'dev'
def setup():
jingo.load_helpers()
def test_js_helper():
"""
Given the js() tag if we return the assets that make up that bundle
... |
#!/usr/bin/env python
#coding:utf-8
# Purpose: compatibility layer
# Created: 01.01.12
# Copyright (C) 2012, Manfred Moitzi
# License: MIT license
from __future__ import unicode_literals, print_function, division
__author__ = "mozman <mozman@gmx.at>"
import sys, zipfile
PY3 = sys.version_info[0] > 2
if PY3:
# di... |
import sys
read = lambda: sys.stdin.readline()
num = dict()
for a in map(int, read().split()):
try:
num[a] += 1
except:
num[a] = 1
if len(num) == 1:
print(10000 + sum(num.keys())*1000)
elif len(num) == 2:
print(1000 + sorted(num, key= lambda x: num[x])[1]*100)
elif len(num) == 3:
p... |
"""
Copyright (c) 2015-2020 Raj Patel(raj454raj@gmail.com), StopStalk
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
... |
import os
import random
import time
import numpy as np
import torch
import torch.distributed as dist
from torch.nn.utils import vector_to_parameters
import torchvision.transforms as T
from pytorl.agents import GorilaDQN_ClientAgent
import pytorl.distributed as rl_dist
from pytorl.envs import make_atari_env
import pytor... |
import godaddy_ddns.ddns
import godaddy_ddns.settings
import argparse
def main():
settings = godaddy_ddns.settings.Settings()
config = settings.get_settings()
# Initiate the parser
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--configure", help="Configure the program", action="st... |
from django.db import models
import requests
from rq import get_current_job
class Task(models.Model):
# A model to save information about an asynchronous task
created_on = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=128)
job_id = models.CharField(max_length=128)
resu... |
#!/usr/local/bin/python
# coding: latin-1
"""
Use cooked_input tables to create a Unicode character picker. This demonstrates how to use cooked input with large,
mult-column table. It also shows how to used commands for table control.
Len Wanger, 2017
"""
import unicodedata
import cooked_input as ci
try:
# Try... |
# Generated by Django 2.2.3 on 2020-06-01 10:00
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='EmployeeDetails',
fields=[
... |
import json
import shelve
import sys
from urllib import request
from os import path
import tempfile
import asyncio
from pathlib import Path
from pyppeteer import launch
with open('styles.css') as f:
css = f.read().replace('\n', '')
Path('db').mkdir(exist_ok=True)
Path('tasks').mkdir(exist_ok=True)... |
import numpy as np
import math
import os
from helper_class2.training_history import TrainingHistory
from helper_class2.enum_def import NetType
from helper_class2.classifier_function import Logistic, SoftMax
from helper_class2.loss_function import LossFunction
from helper_class2.weights_bias import WeightsBias
f... |
import sys
from ... import microbuild
@microbuild.task()
def clean():
"""Clean build directory."""
print "clean"
@microbuild.task(clean)
def html():
"""Generate HTML."""
print "html"
@microbuild.task(clean)
@microbuild.ignore
def images():
"""Prepare images. Should be ignored."""
raise... |
import itertools
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score
import os
def calculate_MAD(y_test, y_pred):
s = 0
for i in range(len(y_test)):
s+=abs(y_test[i]-y_pred[i])
return s/len(y_test)
# This functio... |
"""
IR mocks
"""
from collections import OrderedDict
from copy import deepcopy
from cdd.ast_utils import NoneStr
from cdd.defaults_utils import remove_defaults_from_intermediate_repr
from cdd.pure_utils import deindent, paren_wrap_code
from cdd.tests.mocks.classes import (
class_torch_nn_l1loss_docstring_str,
... |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from mixer.backend.django import mixer
from ..models import *
class TestAnnotationAPI(APITestCase):
def setUp(self):
self.username, self.password = 'user', 'pass'
def create_user(self):
... |
#!/usr/bin/env python
# Copyright 2020-2020 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
import json
from functools import wraps
from typing import Any, Callable, List, Mapping, Optional
import jsonschema # type: ignore
import yaml
from air_flags.flag import Flag
from air_flags.rollout import Rollout
from air_flags.validators import (
SCHEMA_VALIDATOR,
TYPE_JSON,
TYPE_YAML,
VALID_CONFIG_... |
from dogbot.cqsdk.utils import reply
import random
def bark(bot, message):
if '汪' in message.text:
reply(bot, message, random.choice([
"汪!",
"汪汪!",
"汪汪汪!",
"嗷?",
"呜~",
"poi!",
"っぽい!",
"ワン!",
"わん!",
... |
"""
A core class for what CloudMan sees as a file system. This means that it is
aware of it and can thus manipulate it.
"""
import os
import shutil
import commands
import threading
from datetime import datetime
from cm.util import misc
from cm.util import Time
from cm.util.misc import run
from cm.util.misc import nice... |
def my_function():
print("The Function Was Called")
my_function.description = "A silly function"
def second_function():
print("The second was called")
second_function.description = "A sillier function."
def another_function(function):
print("The description:", end=" ")
print(function.description... |
################################################################################
# Constants
################################################################################
RPM_SCALE_FACTOR = 40
INJECTION_TIMING_SCALE_FACTOR = 255 # usecs / 255
INJECTION_TIMING_PRESCALER = 0xff
LOAD_PRESCALER = 0x85
MAF_PRESCALER = 0x... |
import ged_lib as gl
def tag_ancestors_families():
# print("Tagging Ancestor's Families")
gl.read_individuals()
gl.read_families()
gl.read_children()
gl.get_params()
family_id = int(gl.initial_family)
tree_walk(family_id)
for i in range(0,len(gl.families)):
if ... |
import unittest
import pytest
from helpers.oop.reflection.helpers import is_magic_method as uut
@pytest.mark.usefixtures('oop_reflection_testcase')
class TestIsMagicMethod(unittest.TestCase):
def test_is_magic_method_true_positives(self):
self.assertTrue(uut(self.testcase, '__getattribute__'))
... |
# BSD 2-Clause License
#
# Copyright (c) 2021, Hewlett Packard Enterprise
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright noti... |
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import Response
from fastapi.templating import Jinja2Templates
from read_params import read_params
app = FastAPI()
config = read_params()
templates = Jinja2Templates(directory=config["templa... |
# Ping the webcam so it fixes its delay
# Requires obs-websocket v4.3.0 or newer.
import json
import time
# TODO: Reimplement the essential parts (mainly the handshake) and
# drop the rest. This is a way bigger import than we need.
import websocket # ImportError? Try: pip install websocket-client
# TODO: Parameterize... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def convert_availability_nature(apps, schema_editor):
"""
Convert existing Yes-availabilities to Assigned.
"""
Availability = apps.get_model("scheduling", "Availability")
Availability.objects.filter(n... |
from office365.outlook.calendar.meeting_time_suggestion import MeetingTimeSuggestion
from office365.runtime.client_value import ClientValue
from office365.runtime.client_value_collection import ClientValueCollection
class MeetingTimeSuggestionsResult(ClientValue):
"""
A collection of meeting suggestions if th... |
import datetime
from flask import Blueprint, make_response, request
from flask_babel import gettext
from data_explorer import auth
from data_explorer.course_routes import utils
from data_explorer.download_routes.queries import download_queries
# Instantiate blueprint
downloads = Blueprint('downloads', __name__)
@dow... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.Index.as_view(), name='index'),
path('login', views.Login.as_view(), name='login'),
path('signup', views.SignUp.as_view(), name='signup'),
path('signout', views.Logout.as_view(), name='signout'),
]
|
#!/usr/bin/env python
# Edit this script to add your team's training code.
# Some functions are *required*, but you can edit most parts of the required functions, remove non-required functions, and add your own functions.
################################################################################
#
# Imported fu... |
# coding=utf-8
import os
import urllib
import StringIO
from PIL import Image
from django.conf import settings
from django.db import models
from django.core.files.base import ContentFile
from easy_thumbnails.fields import ThumbnailerImageField
from utils import thumbnail_storage
class SliderImage(models.Model):
... |
import time
class PerfTimer():
def __init__(self) -> None:
self.timer = []
def init(self):
self.timer.append(time.perf_counter())
def log(self, title = 'log'):
print(title + ':', time.perf_counter() - self.timer.pop())
perf_timer = PerfTimer() |
# -*- coding: utf-8 -*-
"""
Created on Tue May 26 14:30:03 2020
@author: Chandan
"""
import pyttsx3
import speech_recognition as sr
engine1 = pyttsx3.init()
MASTER = "Sir"
#speech speed
def eng1_rate(value):
rate = engine1.getProperty('rate')
engine1.setProperty('rate', value)
#speech volume
volume = engi... |
import streamlit as st
from models.seir_bayes import (
run_SEIR_BAYES_model,
make_lognormal_params_95_ci,
seir_bayes_plot,
seir_bayes_interactive_plot,
)
from data.data_params import (
query_dates,
query_params,
load_uf_pop_data,
load_uf_covid_data,
query_ufs
)
import matplotlib.py... |
#!/usr/bin/env python3
import difflib
import logging
import subprocess
import sys
import _utils as utils
def check(path):
with open(path) as f:
original = f.read()
formatted = subprocess.check_output(["clang-format", "-assume-filename", path],
input=original, ... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from datetime import datetime
from io import BytesIO
import pyte... |
from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler
from app import dbutils
from exchanges import Coinbase, Coinmarketcap
cb = Coinbase()
cmc = Coinmarketcap()
sched = BlockingScheduler()
@sched.scheduled_job('interval', minutes=999)
def scheduler_job():
base = 'btc'
... |
from datetime import datetime
from app.db.base_class import Base
from app.settings import settings
from sqlalchemy import Column, Date, Float, Integer
from sqlalchemy.orm import relationship
from sqlalchemy.sql.schema import ForeignKey
class Statistics(Base):
id = Column(Integer, primary_key=True, index=True)
... |
# -*- coding: utf-8 -*-
def default_graph_layout_options():
"""
Default layout options for all graphs.
:returns: a dict of default options.
"""
return {
'paper_bgcolor': 'rgb(52, 58, 64)',
'plot_bgcolor': 'rgb(52, 58, 64)',
'font': {
'color': 'rgba(255, 255, 255... |
import tempfile
import os
from contextlib import contextmanager
import shutil
import pytest
import qcodes as qc
from qcodes.dataset.sqlite.database import initialise_database, connect
from qcodes import new_experiment, new_data_set
n_experiments = 0
@pytest.fixture(scope="function")
def empty_temp_db():
globa... |
#!/usr/bin/python3
# Copyright: University of Queensland, 2018
# Contributors: Ben Foley, Nay San
# This is a file for automatically build the word -> sound dictionary
# input: text file, config file
# output: mapping between unique words and their sound, ordered by their appearance
import argparse
import os
INPUT_... |
if __name__ == '__main__':
for t in range(int(input())):
s = input()
c = 1
m = 0
n = len(s)
while c < n:
if s[c] == 'x':
if s[c-1] == 'y':
c += 2
m += 1
else :
c += ... |
"""
Copyright [2009-present] EMBL-European Bioinformatics 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
Unless required by applicable law o... |
#class A
class A:
def __init__(self, test):
self.text = test
def test(self):
print(self.text)
#class B
class B:
def __init__(self):
pass
def printStar(self):
for i in range(1, 73):
print("*", end = "")
print()
def NineProductNine(sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.