content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
from setuptools import setup
GITHUB_URL = 'https:github.com/jonas-hagen/bootstrap-sources'
VERSION = '4.0.0-1'
setup(
author='Jonas Hagen',
author_email='jonas.hagen3@gmail.com',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
... |
#
# Pyserini: Python interface to the Anserini IR toolkit built on Lucene
#
# 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... |
"""
# trans-tool
# The translation files checker and syncing tool.
#
# Copyright ©2021 Marcin Orlowski <mail [@] MarcinOrlowski.com>
# https://github.com/MarcinOrlowski/trans-tool/
#
"""
import re
from typing import Dict, Union
from transtool.decorators.overrides import overrides
from transtool.prop.items import Tran... |
class Recorder:
def __init__(self):
self.model_score = 0
self.domain_score = 0
self.record_list = []
pass
def get_record_list(self):
return self.record_list
def append(self, record):
# {"size": size, "game": game, "index": round,
# "value": val, "be... |
# CPU: 0.05 s
start, end, _ = map(int, input().split())
walk = list(map(int, input().split()))
bus = list(map(int, input().split()))
interval = list(map(int, input().split()))
for idx in range(len(walk)):
# Time taken on a bus
if idx != 0:
start += bus[idx - 1]
# Time to walk to the next station
... |
import json
import os
import shutil
import hashlib
from shutil import copyfile
from .steady_download_and_compute_sha1 import steady_download_and_compute_sha1
import random
import time
from .filelock import FileLock
import mtlogging
# TODO: implement cleanup() for Sha1Cache
# removing .record.json and .hints.json files... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Task',
fields=[
('id', models.AutoField(verbose... |
from ._utils import getImageFromElementCSS
from ._conditions import is_crime_news
from ._request import simple_get
from ._parser import parse, tojson
class JoyScraper:
@staticmethod
def get_headlines(retry=False, retrytimes=0, retrymillis=0):
response = simple_get('https://www.myjoyonline.com/ghana-n... |
import os
import sys
from pathlib import Path
import pytest
from isort import exceptions, settings
from isort.settings import Config
from isort.wrap_modes import WrapModes
class TestConfig:
instance = Config()
def test_init(self):
assert Config()
def test_init_unsupported_settings_fails_gracef... |
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import pandas as pd
from PIL import Image
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
import csv
plt.rcParams.update({'font.size': 18})
import plotly.express as px # Be sure to import... |
# -*- coding: utf-8 -*-
from pasa.utils import get_or_else
# カテゴリー辞書のためのクラス
# カテゴリ辞書の構成
# Categorys
# - [Category]<-
# - [noun]
# - category_name
class CategoryDict(object):
def __init__(self, yaml):
self.category_name = get_or_else(yaml, 'category_name', "")
self.noun = set(get... |
# -*- coding: utf-8 -*-
#
# This file is part of SplashSync Project.
#
# Copyright (C) 2015-2020 Splash Sync <www.splashsync.com>
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPO... |
from django.contrib import admin
from ..models import Language, LanguageLang, RetiredLanguage, \
MacroLanguageMapping, Script, ScriptLang, Country, CountryLang, \
Subdivision, SubdivisionLang, SubdivisionType, SubdivisionTypeLang, Lang, \
LangLang, Locale, LocaleLang
class LanguageAdmin(admin.ModelAdmin):... |
#!/usr/bin/python
# -*- coding: utf8 -*-
from datetime import datetime, timedelta
from base_test_case import BaseTestCase
from models import Goal
from flow import app as tst_app
from constants import USER, TASK
from models import Habit, HabitDay, Task, Project, Event, Readable, Quote, Snapshot
from services.agent impo... |
from attrdict import AttrDict
from annotator_store.models import BaseAnnotation, AnnotationQuerySet
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.urls import reverse
from djiffy.models import Canvas
from derrida.books.models import Language
from derrida.common.models im... |
import logging
import re
from datetime import datetime, timedelta
from functools import total_ordering
from sqlalchemy import (
Boolean,
Column,
DateTime,
ForeignKey,
Index,
Integer,
String,
Unicode,
and_,
delete,
desc,
func,
select,
update,
)
from sqlalchemy.exc... |
import argparse
import ast
import json
import random
from pathlib import Path
import numpy as np
import pandas as pd
import spacy
from spacy.gold import GoldParse
from spacy.util import minibatch
import torch
from spacy_transformers import TransformersLanguage
from spacy_transformers.util import PIPES, cyclic_triangu... |
from flask_microservices import MicroServicesApp
app = MicroServicesApp(__name__)
enabled_modules = [
'admin',
'forum',
'home'
]
# By default, this will assume your modules directory is "./modules"
# if a second argument is not provided.
app.register_urls(enabled_modules)
app.config['DEBUG'] = True
#app... |
# Generated by Django 3.2.3 on 2021-05-26 20:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0005_post_last_edited_date'),
]
operations = [
migrations.AddField(
model_name='post',
name='thumbnail',
... |
from selenium.webdriver.common.by import By
from Locators import Locator
class Login(object):
def __init__(self, driver):
self.driver = driver
self.Login = driver.find_element(By.XPATH, Locator.Login)
self.Password = driver.find_element(By.XPATH, Locator.Password)
self.En... |
#!/usr/bin/python
#***************************************************************************
# Copyright 2015 IBM
#
# 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.a... |
"""
ulid/consts
~~~~~~~~~~~
Contains public API constant values.
"""
from . import ulid
__all__ = ['MIN_TIMESTAMP', 'MAX_TIMESTAMP', 'MIN_RANDOMNESS', 'MAX_RANDOMNESS', 'MIN_ULID', 'MAX_ULID']
#: Minimum possible timestamp value (0).
MIN_TIMESTAMP = ulid.Timestamp(b'\x00\x00\x00\x00\x00\x00')
#: Maximu... |
import unittest
import logging
import os
import json
from unittest.mock import patch
from Museum_API.museum import MuseumAPI
logging.basicConfig(filename='logging_statements.log', level=logging.DEBUG,
format='%(asctime)s:%(levelname)s:%(message)s')
class TestMuseumApi(unittest.TestCase):
def... |
'''
handles all kind of database connection tasks
'''
from django.db import models
class users(models.Model):
"""Store users information"""
user_name = models.CharField(max_length=50,null=False,blank=False,primary_key=True)
password = models.CharField(max_length=50,null=False,blank=False)
token ... |
import logging
import threading
import time
result_T1=['vide',0,0,0]
result_T2=['vide',0,0,0]
result_T3=['vide',0,0,0]
result_T4=['vide',0,0,0]
def thread_function1(name):
global result_T1
local_result_T1 = result_T1
logging.info("Thread %s: starting", name)
for i in range (0,10000):
for j in... |
import json
from authemail.models import SignupCode
from django.core import mail
from django.core.urlresolvers import reverse
from django.test import TransactionTestCase
from django.utils.translation import activate
from rest_framework.test import APIClient
from rest_framework_jwt.settings import api_settings
from ap... |
#!/usr/bin/python
# coding:utf-8
import urllib2
import re
import os
def execute_answer():
headers = {
'Cookie': 'gr_user_id=3949c66a-56d6-49be-99e6-dc48710481cd; uuid=5811c0d121dd4; è¿é¢ççæ¡æ¯oreo=eyJpdiI6Ik13RVwvTVlPd0pHMGFkWTJFdElndnhRPT0iLCJ2YWx1ZSI6ImJKUlMxaFA4a1lYV2J3b0NnN0ZUS1E9PSIsIm1hYyI6... |
from itertools import product as cartesian_product
from extmath.meta import infinitelist, duality, indexargument
from extmath.basic import product, group, sumexp
@infinitelist([2, 3])
def primes(base):
'''Prime number sequence'''
def index(self, n):
if n not in self:
raise ValueError('{} ... |
from threading import RLock
from wampnado import processors
from wampnado.uri import URIType
from wampnado.uri.topic import Topic
from wampnado.uri.procedure import Procedure
from wampnado.uri.error import Error
from wampnado.identifier import create_global_id
from wampnado.features import Options
from wampnado.messag... |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from spellbook.models import Spellbook
User = get_user_model()
class SpellbookSlotViewsCase(TestCase):
"""
A spellbook should be editable through the spellbook details page
"""
@classmeth... |
from flask import Flask, request, abort, send_file, jsonify, send_from_directory
import os, shutil, glob, random, string, tempfile, requests
import sys
sys.path.insert(0,'shortbol')
import shortbol.run as shb_run
app = Flask(__name__)
shortbol_libs = os.path.join("shortbol", "templates")
@app.route("/status")
def sta... |
#---------------------------------------------------------------------------
# Copyright 2013 The Open Source Electronic Health Record Agent
#
# 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
#
... |
from .stat import Stat
class Player:
def __init__(self,data:bytearray):
self.data = data
self.name = self.data[:32].decode('utf-16-le')
self.face_type = Stat(self.data, 108, 2, 3, "Face type")
self.skin_colour = Stat(self.data, 91, 0, 3, "Skin Colour")
self.face_id = Stat(se... |
from itertools import (permutations,
product)
from typing import Tuple
from hypothesis import given
from robust.hints import Point
from robust.projection import signed_length
from robust.utils import (to_perpendicular_point,
to_sign)
from tests.utils import (equivalenc... |
"""
Access the Helio Event Catalogue
"""
import io
import os
from lxml import etree
from requests import Session
from zeep import Client
from zeep.transports import Transport
from astropy.io.votable.table import parse_single_table
from sunpy.net import attrs as a
from sunpy.net.base_client import BaseClient, QueryRe... |
from retrobiocat_web.app.biocatdb import bp
from flask import flash, url_for, request, jsonify
from flask_security import roles_required, current_user
from retrobiocat_web.mongo.models.user_models import User, Role
from retrobiocat_web.mongo.models.biocatdb_models import Sequence, Activity, Paper, EnzymeType
from retro... |
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
import skopt
from scipy.optimize import OptimizeResult
# taken from skopt.plots and slightly modified
def plot_convergence(*args, **kwargs):
"""Plot one or several convergence traces.
Parameters:
args[i] (OptimizeResult, li... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 변수
'''
Python에서는 변수를 선언하여 사용할 수 있다.
변수 이름은 문자나 숫자로 이루어지는데,
변수 이름은 숫자나 '_' 이외의 특수문자로 시작할 수 없고,
이미 역할이 지정된 keyword는 변수 이름으로 사용할 수 없다.
'''
for a in (1, 3, 10, -2):
print('a =', a)
print('a × 3 + 1 =', a * 3 + 1, '\n')
# 상수
'''
Python에서 변수와 같은 이름을 갖는 상수를 선언하는 방법은
기... |
from flaml.automl import AutoML
from flaml.model import BaseEstimator
from flaml.data import get_output_from_log
from flaml.version import __version__
import logging
from os.path import join, exists
import datetime as dt
from os import listdir, remove, mkdir
import pathlib
import json
root = pathlib.Path(__file__).p... |
#!/usr/bin/python
'''
Author : tom-snow
Date : 2022-03-16 19:32:32
LastEditTime : 2022-04-24 17:27:30
LastEditors : tom-snow
Description :
FilePath : /awesome-testflight-link/scripts/del_link.py
'''
import sqlite3
import re, os, sys
TABLE_MAP = {
"macos": "./data/macos.md",
"ios": "./data... |
try:
import sys
import os
from metashare.storage.models import StorageObject
f = os.fdopen(5, 'w')
stos = StorageObject.objects.all()
sto1 = stos[0]
sto1.deleted = True
sto1.save()
sto1.update_storage()
f.write(sto1.identifier)
except:
sys.exit(1)
sys.exit(0)
|
import logging
import re
from fuzzywuzzy import fuzz
logging.getLogger().setLevel(logging.INFO)
def _add_start_end_fuzzy_search(element_to_add, text, sub_text, start_index, move_text_left=0):
sub_text_start = re.sub(r'(?<!AM|PM)( \.)', '.', sub_text[move_text_left:30 + move_text_left])
sub_text_end = re.sub(... |
# **************************************************************************************************************************************************************************************************** #
# ****************************************************************************** 2. To simulate Full-Subtractor Circui... |
# Generated by Django 2.1.5 on 2019-05-05 08:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('rankings', '0032_individualresult_round'),
]
operations = [
migrations.Alt... |
"""[Perspective](https://github.com/finos/perspective#readme) is an interactive visualization
component for large, real-time datasets. It enables analysts and traders at large banks like
J.P.Morgan to understand their data in real time.
Panel provides the [`Perspective`](https://panel.holoviz.org/reference/panes/Persp... |
import math
import requests
from urllib.parse import quote, urlencode
from .utils import get_hr_size, get_key_from_value
def get_magnet(info_hash, torrent_name):
trackers = [
"udp://tracker.coppersurfer.tk:6969/announce",
"udp://9.rarbg.me:2850/announce",
"udp://9.rarbg.to:2920/announce",
... |
__author__ = "Alex"
import time
import sys
import os
sys.path.insert(-1, os.getcwd())
sys.path.insert(-1, os.path.dirname(os.getcwd()))
from spambayes import quickselect
from random import shuffle
def main():
k_smallest = quickselect.k_smallest
l_1 = []
l_1 = [i for i in range(10000)]
shuffle(l_1)
l_2 = [item... |
import math
import numpy
from scipy.spatial import cKDTree
def deduplicate(
points,
max_distance,
doublecheck_values=None,
doublecheck_function=lambda x, y : x == y,
check_negative=False
):
'''
check_negative is for use with Quaternions
'''
if doublecheck_values is not None:
... |
from __future__ import unicode_literals
import datetime
from django.core import signing
from django.db import models
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.uti... |
import sys
import backend as bk
from PyQt5 import QtGui, QtCore, QtWidgets
from osmnx.errors import UnknownNetworkType
class Controller:
def __init__(self):
self.mainwindow = MainAppWindow()
self.centrality = CentralityWindow()
self.accessibility = AccessibilityWindow()
def open_main(... |
## this converts fantendo wiki to a game
import gradio
def Game_Generator(Game_Name, Game_Type, Game_Description, Game_Rules, Game_Setup, Game_Play, Game_End):
Game_Name = input
Game_Type = input
Game_Description = input
Game_Rules = input
Game_Setup = input
Game_Play = input
G... |
import logging
from typing import List, Union
import torch
import torch.nn
import flair.nn
from flair.data import Dictionary, Label, Sentence
from flair.embeddings import TokenEmbeddings
log = logging.getLogger("flair")
class WordTagger(flair.nn.DefaultClassifier[Sentence]):
"""
This is a simple class of m... |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
from torch import Tensor
import random
from typing import List, Optional, Tuple
from utils.math_utils import bound_fn
from .base_layer import BaseLayer
class RandomApply(BaseLayer):
"""
This layer random... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import tensorflow as tf
import load_data
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', default=1000, type=int, help='batch size')
parser.add_argument('--train_steps', ... |
# -*- coding: utf-8 -*-
#
# Copyright 2019 Jim Martens
#
# 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 appl... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 10 14:38:28 2020
@author: peterpiontek
"""
import pandas as pd
import os
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv("data/final_data.csv", index_col = 0, parse_dates = True)
df = df[(df.index.year > 2017) & (df.index.year < 2019)]
df = df[["sp... |
# Generated by Django 3.0.3 on 2020-08-06 17:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('guidebook', '0016_auto_20200806_1756'),
]
operations = [
migrations.AlterField(
model_name='guidebook',
name='is_app... |
"""\
Plotting: PL
============
.. automodule:: scanpy
.. note::
See the :ref:`settings` section for all important plotting configurations.
Generic
-------
.. autosummary::
:toctree: .
pl.scatter
pl.heatmap
pl.dotplot
pl.violin
pl.stacked_violin
pl.matrixplot
pl.clustermap
pl.rankin... |
# Combinatoric selections
from sympy import binomial
LIMIT = 100
def solve():
return sum(
int(binomial(n, r)) > 1_000_000 for n in range(1, LIMIT + 1)
for r in range(1, n))
if __name__ == "__main__":
print(solve())
|
import argparse
import csv
import json
import sklearn.manifold
import torch
import umap # type: ignore
# No type stubs for umap-learn. Ignore mypy
def parse_arguments():
parser = argparse.ArgumentParser(description="MiniConf Portal Command Line")
parser.add_argument("papers", default=False, help="paper fil... |
# -*-coding:utf-8-*-
import torch
import torch.nn as nn
class DenseBottleneck(nn.Module):
def __init__(self, in_channels, growth_rate):
super().__init__()
inner_channel = 4 * growth_rate
self.bottle_neck = nn.Sequential(
nn.BatchNorm2d(in_channels),
nn.Sigmoid(),
... |
# encoding: utf-8
# author: Taehong Kim
# email: peppy0510@hotmail.com
from wx.lib.embeddedimage import PyEmbeddedImage
SmallUpArrow = PyEmbeddedImage(
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAADxJ"
"REFUOI1jZGRiZqAEMFGke2gY8P/f3/9kGwDTjM8QnAaga8JlCG3CAJdt2MQxDCAUaOjyjKMp"
... |
from flask import Flask
from marshmallow import Schema, fields, pre_load, validate
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy
# from sqlalchemy import UniqueConstraint
ma = Marshmallow()
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'users'
# __table_args__ = ... |
# -*- coding: utf-8 -*-
"""Contains Cleaner class and clean function."""
import logging
import numpy
from cleanset.base import BaseEstimator, TransformerMixin
logger = logging.getLogger(__name__)
class CleansetError(Exception):
"""Base class for pcdhit exceptions."""
class InvalidEntriesDefinitionError(Clea... |
# @author:leacoder
# @des: 递归 二叉树的前序遍历
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
result = []
self.helper(root,result)
return result
def helper(self,root,result):
if not root:
return
result.append(root.val)
self.helper... |
from UE4Parse.BinaryReader import BinaryStream
from UE4Parse.Assets.Objects.FGuid import FGuid
from UE4Parse.Assets.Objects.FLevelSequenceLegacyObjectReference import (
FLevelSequenceLegacyObjectReference,
)
class FLevelSequenceObjectReferenceMap:
position: int
Map: dict
def __init__(self, reader: Bi... |
import tensorflow as tf
import numpy as np
from rank_metrics import rank_eval
import argparse
def ill_cal(pred, sl):
nll = 0
cur_pos = 0
for i in range(len(sl)):
length = sl[i]
cas_nll = pred[cur_pos : cur_pos+length]
cur_pos += length
nll += (np.sum(cas_nll)/float(length))
... |
import torch
from torch import nn
from src.config import data
from src.utils import init_weights
class EncoderModel(nn.Module):
def __init__(self):
super().__init__()
self.calculate_mu = nn.Sequential(
nn.Linear(data.x_size, 16, bias=False),
nn.BatchNorm1d(16),
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-07-24 09:55
from __future__ import unicode_literals
import backend.account.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import imagekit.models.fields
class Migration(migrations.Migration):
... |
__author__ = 'lynevdv'
from lenstronomy.LensModel.Profiles.elliptical_density_slice import ElliSLICE
import numpy as np
import pytest
import numpy.testing as npt
class TestElliSLICE(object):
"""
tests the elliptical slice lens model
"""
def setup(self):
self.ElliSLICE = ElliSLICE()
def ... |
class Addon(object): # can be subclassed to create custom addons
def __init__(self, page):
self.page = page
self.queued_modifications = []
def start(self):
print("Addon started")
def get_modifications(self): # each modification should be a string
modification_string = ""
... |
from discord.ext import commands
import discord
from momiji.modules import permissions
from momiji.reusables import send_large_message
class WastelandConfiguration(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="wasteland_ignore_channel", brief="Ignore audit logging for... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
import argparse
import json
import os
def parse_args():
# setup arg parser
parser = argparse.ArgumentParser()
# add argument... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainW... |
# Copyright 2014 Cloudbase Solutions Srl
#
# 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 l... |
import re
from django.core.exceptions import ValidationError
from app.common.serializers import BaseModelSerializer
from app.content.models import ShortLink
class ShortLinkSerializer(BaseModelSerializer):
class Meta:
model = ShortLink
fields = ["name", "url"]
def validate_name(self, data):
... |
from smallboard import *
class BigBoard(object):
def __init__(self):
self.it = [[SmallBoard() for j in range(3)] for i in range(3)]
self.active = (-1, -1)
def __getitem__(self, index):
return self.it[index]
def __setitem__(self, index, value):
self... |
import os
import sys
import requests
from prettytable import PrettyTable
# Get risk meter information, and return a dictionary of tuples containing risk meter ID,
# risk meter score, and last update time.
def get_risk_meters(base_url, headers):
risk_meters = {}
list_risk_meters_url = f"{base_url}asset_groups"
... |
#! /usr/bin/env python
import rospy, actionlib
from motion_planning.msg import PickUpPoseAction, PickUpPoseGoal
def test_client_client():
client = actionlib.SimpleActionClient('pick', PickUpPoseAction)
client.wait_for_server()
# Creates a goal to send to the action server.
goal = PickUpPoseGoal()
... |
import unittest
from application import TestingConfig, create_app, db
from application.apps.data import app_list
class DbUnitTest(unittest.TestCase):
def setUp(self):
self.test_app = create_app(TestingConfig).test_client()
db.create_all()
def tearDown(self):
db.session.remove()
... |
from __future__ import absolute_import
from __future__ import print_function
from owmeta_core.data import DataUser
from .DataTestTemplate import _DataTest
from owmeta.cell import Cell
class CellTest(_DataTest):
ctx_classes = (Cell,)
def test_DataUser(self):
do = Cell('', conf=self.config)
s... |
import os
import bpy
import bpy_extras
from .. import plugin, plugin_prefs, utils
from .. import context
from ..obj.exp import props as obj_exp_props
from . import imp
from . import exp
from ..version_utils import get_import_export_menus, assign_props, IS_28
class ImportDmContext(context.ImportMeshContext):
def... |
"""
This contains wrapper functions that simplify plotting raster
and vector data for publication-ready figures.
The documentation of the examples can be found here:
https://lsdtopotools.github.io/LSDTopoTools_ChiMudd2014/
Simon Mudd and Fiona Clubb, January 2018
Released under GPL3
"""
im... |
import os
import sys
import logging
from databases import Database
from yoyo import read_migrations, get_backend
logger = logging.getLogger("uvicorn.default")
try:
DATABASE_USER = os.getenv("POSTGRES_USER")
DATABASE_PASS = os.getenv("POSTGRES_PASSWORD")
DATABASE_NAME = os.getenv("POSTGRES_DB")
except KeyE... |
#!/usr/bin/env python3
"""
Solve any size rubiks cube:
- For 2x2x2 and 3x3x3 just solve it
- For 4x4x4 and larger, reduce to 3x3x3 and then solve
This is a work in progress
"""
# standard libraries
import argparse
import datetime as dt
import logging
import resource
import sys
from math import sqrt
from pprint impor... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 22 13:13:16 2018
Intro to Analytics 501 HW6
@author: Yunjia
"""
#### Import Libraries ####
from sklearn import datasets
import pandas as pd
import numpy as np
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn im... |
# -*- coding: utf-8 -*-
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell
<Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (t... |
#-- gestures supported by Otto
#-- OttDIY Python Project, 2020
OTTOHAPPY = const(0)
OTTOSUPERHAPPY = const(1)
OTTOSAD = const(2)
OTTOSLEEPING = const(3)
OTTOFART = const(4)
OTTOCONFUSED = const(5)
OTTOLOVE = const(6)
OTTOANGRY = const(7)
OTTOFRETFUL = const(8)
OTTOMAGIC = cons... |
import sys
from scapy.all import conf, get_if_hwaddr
if sys.platform.startswith('win'):
from scapy.all import get_windows_if_list
interfaces = get_windows_if_list()
windows = True
else:
from scapy.all import get_if_list
interfaces = get_if_list()
windows = False
def get_ifaces():
"""Get ... |
from typing import Callable, Mapping, Sequence
import numpy as np
import torch
from ignite.engine import Engine, Events
from ignite.utils import convert_tensor
from torch.utils.data import DataLoader
from somen.pytorch_utility.extensions.extension import PRIORITY_WRITER, Extension
class BatchEvaluator(Extension):
... |
from yapsy.IPlugin import IPlugin
from yapsy.PluginManager import PluginManager
from django.template import loader, Context
from django.db.models import Count
from server.models import *
from django.shortcuts import get_object_or_404
import server.utils as utils
class MachineDetailSecurity(IPlugin):
def plugin_typ... |
import re
from django import forms
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy as _lazy
from mozillians.phonebook.validators import validate_username
from mozillians.users.models import UserProfile
REGEX_NUMERIC = r... |
# Copyright (c) 2021 Egor Tensin <Egor.Tensin@gmail.com>
# This file is part of the "cgitize" project.
# For details, see https://github.com/egor-tensin/cgitize.
# Distributed under the MIT License.
import logging
from github import Github, GithubException
from cgitize.repo import Repo
class GitHub:
def __init... |
from __future__ import print_function, absolute_import, unicode_literals, division
from collections import OrderedDict, Counter
import pandas as pd
from sklearn.metrics import cohen_kappa_score
import matplotlib.pyplot as plt
# Adapted from https://gist.github.com/ShinNoNoir/4749548
from amt.detect_spam import get_c... |
import os
import sys
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../utils'))
import tensorflow as tf
import numpy as np
import tf_util
from pointnet_util import pointnet_sa_module, pointnet_fp_module, point2sequence_module
def placeholder_inputs(batch_size, nu... |
# To run this, download the BeautifulSoup zip file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
... |
#############
#strings
#############
#strings:
seq = 'GAATTCAACTG'
step = 2
startseq = 'AT'
print(seq)
print('a sequence has a start position and an end position [start:end]')
print('[{}:] makes: {}'.format(2,seq[2:]))
print('[{}:{}] makes: {}'.format(0,8,seq[0:8]))
print('[:{}] makes: {}'.format(8,seq[:8]))
print(... |
import string
def triangle(n):
return (n*(n+1)/2)
def isTriangle(x):
i=1
while(True):
k=triangle(i)
if(k==x):
return True
if(k>x):
return False
i+=1
alpha={} #The Dictionary which holds the values for the alphabets
alphabet=string.ascii_uppercase
fo... |
from pydantic import BaseModel
from datetime import datetime
class EventStreamX(BaseModel):
"""
Defines types and required fields for this event
"""
id: str
received_at: datetime
anonymous_id: str
context_app_version: str
context_device_ad_tracking_enabled: bool
context_device_man... |
from lib import BaseTest
import uuid
import os
try:
import swiftclient
if 'OS_USERNAME' in os.environ and 'OS_PASSWORD' in os.environ:
auth_username = os.environ.get('OS_USERNAME')
auth_password = os.environ.get('OS_PASSWORD')
# Using auth version 2 /v2.0/
auth_url = os.environ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.