content stringlengths 5 1.05M |
|---|
#!/usr/bin/python3.8
from constants import *
from cl_notify import tg
from cl_sqlite import sqlite as db
from cl_client import client
from nacl.public import PrivateKey, PublicKey
import os, sys, argparse, json, yaml
from base64 import b64encode
parser = argparse.ArgumentParser(description='Init arguments parse')
pars... |
# producer
import time
import json
import random
from kafka import KafkaProducer
BOOTSTRAP_SERVER = "35.233.3.112:9092"
producer = KafkaProducer(
bootstrap_servers=[BOOTSTRAP_SERVER],
value_serializer=lambda m: json.dumps(m).encode('ascii')
)
def on_success(record):
print("Message envoyé ... |
from rest_framework import viewsets
# importing serializers
# from django.contrib.auth import get_user_model
# User = get_user_model()
from rest_framework.decorators import action
# importing models
from rest_framework.response import Response
from src.apps.test.main.models import Test
from src.apps.test.main.serial... |
import requests
from bs4 import BeautifulSoup
class Api:
def __init__(self):
pass
def user_cycle_search(self,user):
cycle = []
ccle = ''
cycle_count = requests.get("https://repl.it/@"+user)
supper = BeautifulSoup(cycle_count.content,'html.parser')
httm = supper.fi... |
#!/usr/bin/env python
import stretch_body.hello_utils as hello_utils
import importlib
import stretch_body.robot_params
"""
Print out the robot parameters to the command line,
including where each parameter value originates from
"""
def build_rep(prefix, params, origin,rep):
for k in params.keys():
np = p... |
# The MIT License (MIT)
#
# Copyright (c) 2016 Maciej Borzecki
#
# 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 use, copy, m... |
#!/usr/bin/env python3
"""
Podsaver v0.1: tool for local podcast archive creation
Copyright (c) 2017-2021 Chirag Kakad
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, includi... |
import geopandas as gpd
import numpy as np
import pandas as pd
from shapely.ops import cascaded_union
import os
#This script splits the global basins (in total: 57025) following the Pfafstetter rules until all basins are under 5000 km2
#Peirong Lin, October 2019
def trace_upstream_id(COMID,riv):
#function to trac... |
import asyncio
import logging
import os
from pyvivint.vivint import Vivint
async def main():
logging.getLogger().setLevel(logging.DEBUG)
logging.info("demo started")
vivint = Vivint(username=os.environ["username"], password=os.environ["password"])
await vivint.connect(load_devices=True, subscribe_f... |
from tkinter import N
nome = input('digite seu nome ')
separado = (nome.split())
junto = (''.join(separado))
print (f'{nome.upper()}\n{nome.lower()}\n{len(junto)}\n{len(separado[0])}')
|
import utils
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from tqdm import tqdm
import numpy as np
import pandas as pd
from itertools import combinations, permutations
import heapq
# Here we created a class in order to store the index... |
from ctreport_selenium.utility_classes import Status, Priority
def chart(theme, tests):
pass_ = [0, 0, 0]
fail_ = [0, 0, 0]
skip_ = [0, 0, 0]
broken_ = [0, 0, 0]
for test in tests:
if test._result == Status.PASS:
if test._priority == Priority.HIGH:
pass_[0] += 1... |
import numpy as np
import pyrenderer
TIMING_STEPS = 10
def getKernelNames(volume_resolution):
KERNEL_NAMES_NORMAL = [
#("DVR: DDA - fixed step (control points)", "baseline", 0.001),
("DVR: Fixed step size - trilinear (control points) - doubles", "baseline", 0.0001),
("DVR: Fixed step size - trilinear (... |
import argparse
import csv
import json
from collections import OrderedDict
from os import makedirs, pardir
from os.path import join as path_join
from os.path import realpath, abspath
def save_to_dir(path, data, language, postfix, offset_64bit=False):
for json_path in data:
json_data = {"Has64BitOffsets": ... |
import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Model, save_model
from tensorflow.keras.layers import LSTM, Dense, BatchNormalization, concatenate, Input
from utils import plot_figures
class SingleDayNetwork:
def _... |
from unittest.case import TestCase
from probability.distributions import Normal
class TestNormal(TestCase):
def setUp(self) -> None:
self.n1 = Normal(0, 1)
self.n2 = Normal(1, 2)
def test_normal__lt__normal(self):
self.assertGreater(self.n1 < self.n2, 0.5)
self.assertLess... |
#!/usr/bin/env python3
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GObject, Gdk
import datetime
#import gobject
import threading
import cairo
from config import *
class DockWindow(Gtk.Window):
def __init__(self, left=[], centr=[], right=[]):
Gtk.Window.__init__(self, title="Unknown... |
from httpx import Response
from neuroio.base import APIBase, APIBaseAsync, APIBaseBase
from neuroio.constants import (
DEFAULT_EXACT_THRESHOLD,
DEFAULT_HA_THRESHOLD,
DEFAULT_JUNK_THRESHOLD,
)
from neuroio.utils import request_dict_processing
class SettingsBase(APIBaseBase):
def get_url(self, key: str... |
from tkinter import *
STYLEGROUP = 'styles-common'
AHISTPREF = 'history-ahist-foreground'
APREF = 'history-a-foreground'
ATEMPPREF = 'history-atemp-foreground'
class ImageWindow(Frame):
image_loaded = 0
def __init__(self, viewer, url, src, alt, usemap, ismap, align,
width, height, borderwid... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2014 CNRS
# 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 ... |
from ccinput.constants import SYN_TYPES
def format_dict_str(d, name, label2="Synonyms"):
arr_l = [len(name)]
for k, syns in d.items():
arr_l.append(len(k))
arr_l += [len(s) for s in syns]
ll = max(arr_l)
tab = """{} ========\n{:<{}} {}\n{} ========\n""".format(
ll * "=", name... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#
# This file is part of AceQL Python Client SDK.
# AceQL Python Client SDK: Remote SQL access over HTTP with AceQL HTTP.
# Copyright (C) 2021, KawanSoft SAS
# (http://www.kawansoft.com). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in comp... |
from myhdl import instance, always, intbv, Signal
@instance
def key_expand_128(clk, key, w0, w1, w2, w3, key_load):
"""
key_load : when high, load with initial
values from supplied key
low, load with expanded keys
according to the algo
"""
key = intbv(0)[128:]
w0 = intbv(0)[32:]
w1 = intbv(0)[32:... |
import logging
import subprocess
import time
def get_public_ip_address():
ips = subprocess.check_output(['hostname', '-I']).decode().split(' ')
return ips[1].strip()
def write_hostapd_conf(ip_address):
args = [
'interface=wlan0',
'bridge=br0',
'ssid=SplunkAR ({})'.format(ip_addre... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null = True)
phone = models.CharField(max_length=200, null = Tr... |
"""Unit tests for thing.py"""
# standard library
import math
import unittest
# special import for tracking coverage
__test_target__ = 'samples.thing'
class BasicTests(unittest.TestCase):
"""Basic tests."""
def test_add(self):
self.assertEqual(2, Thing.add(1, 1), '1 + 1 = 2')
def test_div(self):
self... |
def make_select_languages(languages):
from uliweb.i18n import get_language, format_locale
from uliweb.contrib.i18n import LANGUAGES
lang = get_language()
s = []
s.append('''<script type="text/javascript">
function SetCookie( name, value, expires, path, domain, secure )
{
var tod... |
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import schemas, crud
from app.api.deps import get_db
router = APIRouter()
@router.get("", response_model=List[schemas.ProductResponse])
def read_products(db: Session = Depends(get_... |
import os
ROOT_DIR='.'
INCLUDE_DIRS=['.github']
PROPERTY_SPLITER='='
TOKEN_FILE='DELETEME.txt'
TOKEN = '@'
TOKEN_GROUP = '{{' + TOKEN + '}}'
def build_include_dirs():
full_include_dirs = []
for dir in INCLUDE_DIRS:
full_include_dirs.append(os.path.join(ROOT_DIR, dir))
return full_include_dirs... |
from recbole.evaluator.abstract_evaluator import *
from recbole.evaluator.proxy_evaluator import *
from recbole.evaluator.metrics import *
from recbole.evaluator.evaluators import *
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Copyright (c) 2010 Gerson Minichiello
#
#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 righ... |
# add pymetis_mesh if inplace
import sys
sys.path.append('../')
from pymetis_mesh import *
import numpy as np
from load_mesh import load_mesh
def test_buffere():
nv, ne, eptr, eind = load_mesh()
epart = np.empty(ne, dtype='int32')
outputs = part_mesh(nv, eptr, eind, 4, ncommon=3, epart=epart)
assert s... |
class Parameters:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def info(self):
print("The parameters, and data-type are: ")
for key,values in self.__dict__.items():
print("{} = {}, {}\n".format(key, values, type(values))) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 6 14:01 2021
A full C level implementation of H2MM and python wrappers for access in Jupyter Notebooks
@author: Paul David Harris
"""
from setuptools import setup
from setuptools import Extension
from Cython.Distutils import build_ext
import numpy a... |
"""
Constructs the dataset from hdf5 file, which was created using datapreprocess script
"""
import torch
from torch.utils.data import Dataset
import h5py
import numpy as np
class CaptionDataset(Dataset):
def __init__(self, transform):
self.h = h5py.File('dataset.hdf5','r',driver='core')
self.cap... |
import sys
with open(sys.argv[1]) as f:
lines = f.readlines()
lines = [int(line.strip()) for line in lines if line != '']
inc = 0
for i in range(len(lines) - 1):
if lines[i+1] > lines[i]:
inc += 1
print(inc)
|
import os
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
tfb = tfp.bijectors
tfd = tfp.distributions
from gauss_1d_analysis import analyse_objective_fn_for_1d_gauss, analyse_objective_for_1d_gauss_multiple_sample_sizes... |
from random import randint
print('''Suas opções:
[0] PEDRA
[1] PAPEL
[2] TESOURA''')
jogador = int(input("Escolha sua opção: "))
itens = ('PEDRA', 'PAPEL', 'TESOURA')
pc = randint(0, 2)
print("Computador jogou {}.".format(itens[pc]))
print("Jogador jogou {}.".format(itens[jogador]))
if pc == 0: #pc jogou pedra
if... |
"""Linked List
=== CSC148 Winter 2018 ===
University of Toronto,
Computer Science
__author__ = 'Eric Koehli'
=== Module Description ===
This module contains code for a linked list implementation with two classes,
LinkedList and _Node. This code was made by combining professor David Liu's
implementation with professor... |
import hashlib
import os
import tkinter
import buyer
import seller
import manager
import pygubu
import logging.config
# import ee
# from main import for_pygubu, hex
from db_ctrl import get_user
from tkinter import messagebox
start_win = {
"MANAGER": manager.startUI,
"BUYER": buyer.startUI,
"SELLER": seller... |
from rest_framework import permissions
class UpdateOwnProfile(permissions.BasePermission):
""" Allow user to edit their own profile """
def has_object_permission(self, request, view, obj):
""" Check if the user is trying to edit their own profile"""
if request.method in permissions.SAFE_METHO... |
import numpy as np
import os
# Uses least squared approximation to compute the best true binary approximations
# for HWGQ binarization.
def get_binary_repr(value, bits):
output = np.zeros(shape=bits)
for bit in reversed(range(bits)):
bit_set = int(value / 2**bit) != 0
output[bit] = bit_set
... |
#!/usr/bin/python
import unittest
from docutils import nodes
from src import rack
#-------------------------------------------------------------------
class testSubterm(unittest.TestCase):
def test01_no_Text(self):
pack = rack.Subterm(3)
self.assertEqual('', str(pack))
self.assertEqual('<S... |
import importlib
import inspect
from tark.rule_variables import base_rule_variable, default_rule_variables
from tark.entities.models import rule_variable
from tark import exception
class RuleVariableTypeManager(object):
rule_variables_mapping = {
default_rule_variables.LabeledInt.NAME: default_rule_vari... |
import matplotlib.pyplot as plt
import pandas as pd
loc = "/home/linhdn/Developer/unified-framework-for-trading/data/stock-data/vnm-data.csv"
dat = pd.read_csv(loc)
print(dat.head())
print(len(dat['Close']))
plt.figure(figsize=(12,7))
plt.plot(range(1500), dat['Close'][:1500].values, color='b', label="Train set")
... |
"""
Course scraper
"""
import src.scrape.util.helpers as helpers
import src.settings as settings
from src.logger import get_logger
from src.scrape.util.cache import get_html, set_html
import re
_LOG = get_logger("course_scraper")
def course(course_code):
"""
Scrapes title, description, offering and prerequis... |
import os
import numpy as np
def clear_directory(location):
os.chdir(location)
current_files = [i for i in os.listdir(location)]
for file in current_files:
os.remove(file)
def clean_deg_data(deg_data):
output_space = []
for array in deg_data:
if array[0].size > 0:
... |
import argparse
import csv
import json
from collections import OrderedDict
from core_data_modules.logging import Logger
from core_data_modules.cleaners import Codes
from core_data_modules.traced_data.io import TracedDataJsonIO
from id_infrastructure.firestore_uuid_table import FirestoreUuidTable
from storage.google_cl... |
import random, string
from django.db import models
from rest_framework import serializers
class OrderedThroughModel (models.Model):
order = models.IntegerField(blank=True)
class Meta:
abstract = True
ordering = ['order']
def siblings(self, min_order=0):
SelfModel = self._meta.mod... |
#Criação de servidor HTTP
from flask import Flask, render_template, request
#Render template utilizado para renderizar arquivos que se encontram na pasta templates
#Pórem podemos passar o paramentro template_folder no Flas() para indicar qual será a nossa pasta de templates
app = Flask(__name__)
#Podemos passar um 2º... |
# -*- coding: utf-8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from routes import bp_list
from middlewares import before_request_funcs, after_request_funcs
from apps.db import db, SQLALCHEMY_DATABASE_URI
app = Flask('tools')
# SQLAlchemy config
app.confi... |
# --------------------------------------------------------
# Dragon
# Copyright(c) 2017 SeetaTech
# Written by Ting Pan
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
try:
import cPickle
except... |
#!/Users/edelsonc/miniconda3/bin/python
"""
An implementation of a simple python queue object. Created for use in
Stochastic Gradient Descent Method for NCF graduate program.
author: edelsonc
created: 11/23/2016
"""
class SimpleQueue(object):
"""
Implementation of a simple queue in python. Queue is fixed at a... |
__author__ = 'tinglev@kth.se'
import os
import unittest
from test import mock_test_data
from modules.steps.write_cache_entry import WriteCacheEntry, get_cache_key
from modules.util import data_defs, cache_defs, environment
class TestWriteCacheEntry(unittest.TestCase):
def test_generate_image_versions(self):
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pyisis.engine import Engine
XML_PARSE_ERROR = _('XML Parse Error')
FORM_PARSE_ERROR = _('Form Parse Error')
DB_NAME_ERROR = _('Database name not specified!')
COLLECTION_NAME_ERROR = _('Collection name not specified!')
DB_ALREADY_EXISTS = _('Databa... |
__author__ = 'nengfang.han' |
import os
import timeit
import logging
import uuid
import datetime
import json
import numpy
import pymapd
import re
import sys
from pandas import DataFrame
from argparse import ArgumentParser
# For usage info, run: `./<script_name>.py --help`
def verify_destinations(**kwargs):
"""
Verify script output dest... |
from django.shortcuts import render, redirect
from .models import Event
from model_utils.fields import StatusField
from model_utils import Choices
import datetime
# Create your views here.
def intro(request):
if not request.user.is_authenticated:
return render(request, 'index.html')
else:
return... |
import logging
from django.http import HttpResponse
from kombu.utils import json
from rest_framework.views import APIView
from log.log import SystemLog
Logger = logging.getLogger(__name__)
sys_log = SystemLog()
class SearchSystemLog(APIView):
def post(self, request, *args, **kwargs):
level = request.da... |
import sys
import time
import psutil
busy_pids = set()
index = 0
while True:
busy_now = set()
no_longer_busy = set()
for pid in psutil.pids():
try:
p = psutil.Process(pid)
if p.name() in ('apache2', 'uwsgi') and p.cpu_percent(interval=30.0) > 90.0:
busy_now.... |
from pyglet import gl
# Texture min/mag filters
NEAREST = 0x2600
LINEAR = 0x2601
NEAREST_MIPMAP_NEAREST = 0x2700
LINEAR_MIPMAP_NEAREST = 0x2701
NEAREST_MIPMAP_LINEAR = 0x2702
LINEAR_MIPMAP_LINEAR = 0x2703
# Texture wrapping
REPEAT = gl.GL_REPEAT
CLAMP_TO_EDGE = gl.GL_CLAMP_TO_EDGE
CLAMP_TO_BORDER = gl.... |
# Generated by Django 4.0.3 on 2022-04-07 17:28
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clients', '0020_auto_20211226_0547'),
('agents', '0046_alter_agenthistory_command'),
]
operations = [
... |
"""Code with ingest capability logic for Illumina sequencer output (BCL files).
- Use ``Operation.PUT_SYNC`` to update changed files in addition to uploading new ones.
- Handle initial upload and update of ``RunInfo.xml`` and ``runParameters.xml`` and update
collection AVU.
- When a run folder is first seen write cu... |
class Motor:
def __init__(self):
self.velocidade = 0
def acelerar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
self.velocidade = max(0, self.velocidade)
NORTE="Norte"
SUL="Sul"
LESTE="Leste"
OESTE="Oeste"
class Direcao:
# o código DO IF ABAIXO foi sub... |
from distutils.core import setup
setup(
name='tflarrivals',
packages=['tflarrivals'],
version='0.1.2',
license='MIT',
description='Library to fetch arrival times from TfL Unified API',
author='Giancarlo Grasso',
author_email='ggrasso.dev@gmail.com',
url='https://github.com/Giannie/tflarrivals',
down... |
from dataclasses import dataclass
import pytest
from sanic import text
from sanic.exceptions import SanicException
from sanic.views import HTTPMethodView
from sanic_ext import Extend
def test_injection_not_allowed_when_ext_disabled(bare_app):
ext = Extend(bare_app, built_in_extensions=False)
with pytest.ra... |
import pytest
from pydantic import ValidationError
from openpecha.core.annotation import Span
def test_span_end_must_not_be_less_than_start():
with pytest.raises(ValidationError):
Span(start=2, end=1)
|
# autor : colson (Yeong Jun Kim)
# https://www.github.com/YeongJunKim
import pyaudio
import wave
import logging
import time
import aiy.voicehat
import threading
import datetime
import RPi.GPIO as GPIO
from aiy_led import MyLed
from aiy_log import MyLogger
from aiy_play import MyAudio
GPIO.setmode(GPIO.BCM)
button = a... |
import torch
class BaseClient(torch.nn.Module):
def __init__(self, model, user_id=0):
super().__init__()
self.model = model
self.user_id = user_id
def forward(self, x):
return self.model(x)
def upload(self):
pass
def download(self):
pass
def trai... |
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2018, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
# Copyright (C) 2014, Zebra Technologies
# Authors: Matt Hooks <me@matthooks.com>
# Zachary Lorusso <zlorusso@gmail.com>
#
# Redistribution and use in sou... |
"""
IOT commute client for Python
-----------------------------
Aniket Patel (c) 2017
License
-------
iot commute Python library is licensed under the MIT License
Design
------
As project statment we are are building library that could work with `IOT
communicate` project with simplicity.
Basic idea is revolving aroun... |
"""jdata.py test unit
To run the test, please run
python3 -m unittest discover -v test
or
import testjd
testjd.run()
in the root folder.
Copyright (c) 2019 Qianqian Fang <q.fang at neu.edu>
"""
import unittest
import jdata as jd
import numpy as np
from collections import OrderedDict
class TestModule(... |
from distutils.core import setup
from distutils.extension import Extension
import os
import sys
import platform
openmm_dir = '@OPENMM_DIR@'
deepmd_plugin_header_dir = '@DEEPMD_PLUGIN_HEADER_DIR@'
deepmd_plugin_library_dir = '@DEEPMD_PLUGIN_LIBRARY_DIR@'
deepmd_lib_header_dir = '@DEEPMD_DIR@/include'
deepmd_lib_library... |
import random
from .Board import Board
from .Drawable import Drawable
class Food(Drawable):
SYMBOL = "+"
def __init__(self, board, engine):
super().__init__(coords = (0, 0), symbol = Food.SYMBOL)
self.board = board
self.eaten = True # Damit Essen direkt zufällig spawnt
s... |
from dataclasses import dataclass
from typing import Dict
@dataclass
class WorkerMetadata:
module_name: str
args: Dict
interval_seconds: int
error_resiliency: int
|
def filter_rollbar_ignored_exceptions(exc_info, **kw):
_, exc, _ = exc_info
if getattr(exc, '_rollbar_ignore', False):
return False
return exc_info
def filter_by_level(target, **kw):
if 'level' in kw and kw['level'] == 'ignored':
return False
return target
|
# https://stackoverflow.com/a/20972950
|
# hintli dayi = line detection project - part4
# kodlar bana ait - orjinali icin Hintli Dayi'yi izle
import cv2 as cv
import numpy as np
def crop_roi(img, vertices):
mask = np.zeros_like(img)
cv.fillPoly(mask, vertices, 255)
masked_image = cv.bitwise_and(mask, img)
return masked_image
def drow_lin... |
#
# test lib.autotest
#
# @ author becxer
# @ email becxer87@gmail.com
#
from test_pytrain import test_Suite
from pytrain.KNN import KNN
from pytrain.lib import autotest
class test_autotest(test_Suite):
def __init__(self, logging = True):
test_Suite.__init__(self, logging)
def test_process(self):
... |
from unittest.mock import patch
import pytest
@pytest.fixture
def mock_get_primary_validator(primary_validator_node):
with patch('node.blockchain.facade.BlockchainFacade.get_primary_validator', return_value=primary_validator_node):
yield
@pytest.fixture(autouse=True)
def start_send_new_block_task_mock(... |
# Copyright 2020, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
from abc import ABC, abstractmethod
from typing import List
from overrides import EnforceOverrides
from ..model.cell import CellValue
from ..utils import Point2D
class GUI(ABC, EnforceOverrides):
"""
Interface for some controller to send and display information and data.
"""
@abstractmethod
def... |
from django.shortcuts import render
def start(request):
return render(request, 'start.html') |
import json
from ocdskingfisher.database import DatabaseStore
class Store:
def __init__(self, config, database):
self.config = config
self.collection_id = None
self.database = database
def load_collection(self, collection_source, collection_data_version, collection_sample):
s... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
from django.core.management import call_command
from django.db import migrations
def _migrate_roles_permissions(apps, schema_editor):
call_command('migrate_roles_permissi... |
# Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and
# other Shroud Project Developers.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (BSD-3-Clause)
########################################################################
from __future__ import print_function
from __f... |
class Color(object):
# Basic colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREY = (123, 123, 123)
GREY_DARK = (30, 30, 50)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (0, 255, 255)
# Palette colours
PURPLE_DARK = (48, 0, 15)
PURPLE_MID = (73,... |
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .models import *
from .forms import *
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
model = get_user_model()
list_display = ('user... |
"""
Tests for connecting to a client, logging in, state changes, and whether the
respective callbacks are made, and events triggered.
"""
from __future__ import absolute_import, division, print_function, with_statement
from __future__ import unicode_literals
from deepstreampy.message import connection
from deepstreamp... |
import sys
from pylps.constants import *
from pylps.exceptions import *
from pylps.lps_objects import Action, Event, Fact, Fluent
from pylps.lps_data_structures import convert_arg, Variable
from pylps.kb import KB
types_dict = {
ACTION: Action,
EVENT: Event,
FACT: Fact,
FLUENT: Fluent,
}
valid_dynamic_... |
class Weapon:
adjective = ''
type = ''
stat = ''
# optional weapon bonus
bonus = ''
# preposition used to indicate weapon stat
preposition = 'of'
def __init__(self, adjective, type, stat='', bonus=''):
"""Constructor"""
self.adjective = adjective
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:
# Emma E. M. Hobbs
#
# Contact
# eemh1@st-andrews.ac.uk
#
# Emma E. M. Hobbs,
# Biomolecular Sciences Building,
# University of St Andrews,
# North Haugh Campus,
# St Andrews,
# KY16 9ST
# Scotland,
# UK
#
# The MIT License
"""Retrieve all protein annotations from... |
"""
viewer
-------------
View meshes and scenes via pyglet or inline HTML.
"""
from .notebook import (in_notebook,
scene_to_notebook,
scene_to_html)
from .. import exceptions
try:
# try importing windowed which will fail
# if we can't create an openGL context
... |
import aqt
def test_cli_help(capsys):
expected = "".join(["usage: aqt [-h] [--logging-conf LOGGING_CONF] [--logger LOGGER]\n",
" {install,doc,examples,src,tool,list,help} ...\n",
"\n",
"Installer for Qt SDK.\n",
... |
# -*-coding:utf-8-*-
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['sk_resnext29_16x32d', 'sk_resnext29_16x64d']
class SKConv(nn.Module):
def __init__(self, features, M, G, r, stride=1, L=32):
""" Constructor
Args:
features: input channel dimensionalit... |
"""Test the github module.
"""
from subprocess import CalledProcessError
from requests.exceptions import HTTPError
from xinstall.utils import run_cmd
from xinstall import github
import subprocess as sp
def test_install_py_github():
"""Test the install_py_github command.
"""
cmd = "xinstall dsutil -e docke... |
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
# Quick test of TFT FeatherWing (ST7789) with Feather M0 or M4
# This will work even on a device running displayio
# Will fill the TFT black and put a red pixel in the center, wait 2 seconds,
# then fill the screen blue (with... |
from .base_api import API
class Annotations(API):
def __init__(self, document):
super().__init__(document)
self.document = document
@property
def _base_endpoint(self):
return f"{self.document._base_endpoint}/annotations"
def __iter__(self):
return iter(... |
from typing import List, Tuple
from itertools import product
import logging
import ctypes as ct
import iptc
from pkg_resources import parse_version
from sh import iptables
logger = logging.getLogger('agent.iptables_helper')
TABLE = 'filter'
DROP_CHAIN = 'WOTT_LOG_DROP'
OUTPUT_CHAIN = 'WOTT_OUTPUT'
INPUT_CHAIN = 'WOT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.