content stringlengths 5 1.05M |
|---|
import matplotlib.pyplot as plt
import datetime
import solarsystem
def create_positions():
now = datetime.datetime.utcnow()
now = datetime.datetime.now(datetime.timezone.utc)
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
UT... |
import warnings
import numpy as np
from numpy.linalg import multi_dot, inv
import scipy.sparse as sparse
from sklearn.base import BaseEstimator, ClassifierMixin
from cvxopt import matrix, solvers
import osqp
class SSLFramework(BaseEstimator, ClassifierMixin):
"""Semi-supervised Learning Framework
"""
@cl... |
"""
Interfaz para las Unidades.
"""
from typing import Optional
from discord import Interaction, SelectOption
from discord.ui import Select, select
from ..archivos import (DiccionarioGuia, actualizar_guia, cargar_guia,
lista_carpetas, lista_unidades)
from ..constantes import DEFAULT_VERSION, ... |
#
# Modules Import
#
import boto3
import json
import os
#
# Variables Definition
#
ecs_cluster = os.environ['ECS_CLUSTER']
excluded_services = os.environ['EXCLUDED_SERVICES'].split(' ')
result = { 'stoppedServices': [ ], 'excludedServices': [ ] }
#
# Function to print the boto3 responses in JSON format
#
def json_res... |
"""
This is a useful table when we want to test all possible column types.
"""
from piccolo.columns.column_types import (
JSON,
JSONB,
UUID,
BigInt,
Boolean,
Bytea,
Date,
DoublePrecision,
ForeignKey,
Integer,
Interval,
Numeric,
Real,
SmallInt,
Text,
Times... |
import os, itertools
from datetime import datetime, timedelta
import numpy as np
import xarray as xr
import pandas as pd
import logging
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
"""
SCALING of fields
---Flash extent density---
For 330 ms time separation critera, the max flash rate per ... |
# coding: utf-8
from py2neo import Graph
from py2neo import Node, Relationship
import json
import pandas as pd
import sys
import os
# Connecting to neo4j graph database
graph = Graph('http://localhost:7474', password='1234')
# These are the entities on which data is extracted
entities = ['imran khan',... |
import unittest
import json
from src.Validator.TimeValidator import TimeValidator, check_if_format_matches
from src.Validator.Parser import decode_record
def get_setup_object():
f = open('sample.json', 'r')
file_content = json.load(f)['content']
validator = TimeValidator([decode_record(x) for x in file_co... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, serge van Ginderachter <serge@vanginderachter.be>
# based on Matt Hite's bigip_pool module
# (c) 2013, Matt Hite <mhite@hotmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
from ws.RLUtils.common.app_info_lib import DotDict
app_info = DotDict(
{
"NUM_EPISODES": 500,
"BATCH_SIZE": 64,
"GAMMA": 0.99,
"LEARNING_RATE": 0.01,
"EPSILON": 0.1,
"RHO": 0.99,
"DISCOUNT_FACTOR": 0.9,
}
)
def fn_add_configs(api_info):
... |
import numpy as np
from opytimizer.optimizers.swarm import ffoa
from opytimizer.spaces import search
def test_ffoa_compile():
search_space = search.SearchSpace(n_agents=10, n_variables=2,
lower_bound=[0, 0], upper_bound=[10, 10])
new_ffoa = ffoa.FFOA()
new_ffoa.comp... |
import pytest
import os
from SCNIC.general import simulate_correls
from SCNIC.within_correls import within_correls
from biom.util import biom_open
@pytest.fixture()
def args1():
class Arguments(object):
def __init__(self):
self.input = "table1.biom"
self.output = "out_dir"
... |
# 09/04/2017
from time import time
is_palindrome = lambda x: x == x[::-1]
for dic in ["enable1.txt", "natura.txt"]:
with open("../../other/" + dic, encoding="utf-8") as f:
words = {s.strip() for s in f}
out = []
start = time()
for w in words:
prefix = [w[:i][::-1] for i in range(0, le... |
"""
HexitecFEM for Hexitec ODIN control.
Christian Angelsen, STFC Detector Systems Software Group, 2019.
"""
from __future__ import division
import numpy as np
# Required to convert str to bool:
import distutils.util
import time
from datetime import datetime
import logging
import configparser
import os
from hexitec... |
"""Game of Life"""
# старая посылка
# https://contest.yandex.ru/contest/29167/run-report/54247495/
# новая посылка
# https://contest.yandex.ru/contest/29167/run-report/54829714/
import pygame
# параметры экрана
DISPLAY_WIDTH = 620
DISPLAY_HEIGHT = 480
# размер клетки
CELL_SIZE = 20
# цвета
WHITE = (... |
#!/usr/bin/python
import os
import numpy as np
from manipulation.grip.robotiq85 import rtq85nm
from panda3d.bullet import BulletWorld
from panda3d.core import *
import pandaplotutils.pandactrl as pandactrl
import pandaplotutils.pandageom as pandageom
from manipulation.grip import freegripcontactpairs as fgcp
from ut... |
from typing import List
from clingo import ast
# pylint: disable=all
def atom(location: ast.Location, positive: bool, name: str, arguments: List) -> ast.AST:
"""
Helper function to create an atom.
Arguments:
location -- Location to use.
positive -- Classical sign of the atom.
name -- T... |
import copy
import json
from django.contrib.auth.models import User
from django.test import TestCase
from rest_framework.test import (APIRequestFactory, APIClient,
force_authenticate)
from rest_framework import status
from document_index.views import GroupList, GroupDetail
from document_index.models import Grou... |
#!/usr/bin/env python3
import numpy as np
import csv
import sys
################################# Parameters ##################################
#sys.argv = ["SynData_PPMTF.py", "SmplA1"]
if len(sys.argv) < 2:
print("Usage:",sys.argv[0],"[ParamA]" )
sys.exit(0)
# City
City = "TK"
#City = "OS"
# T... |
import urllib.request
import gzip
import shutil
import tarfile
import os
working_directory ='pdf_download/'
pdf_directory = '../pdf/'
infile = '../data/pmcid_to_oa_url_for_new_papers.lst'
def download_pdf():
os.chdir(working_directory)
f = open(infile)
for line in f:
download_one_pdf(line)
... |
#
# Test if all procedures,s functionName parameter works correctly
# Francois Maillet, 22 sept 2015
# This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
#
import random, datetime
from mldb import mldb, ResponseException
# Create toy dataset
dataset_config = {
'type' : 'sparse.mutable'... |
# math2d_polyline.py
import copy
import math
from math2d_vector import Vector
from math2d_triangle import Triangle
from math2d_line_segment import LineSegment
class Polyline(object):
def __init__(self):
self.vertex_list = []
def Copy(self):
return copy.deepcopy(self)
def Serialize(self)... |
from djaveAPI.find_models import publishable_model_from_name
from djaveAPI.problem import Problem
def get_publishable_model(model_name):
model = publishable_model_from_name(model_name)
if not model:
raise Problem(
'There is no {} API'.format(model_name), status_code=404)
return model
|
# Alex Ciaramella and Greg Suner
# Abstract Tournament Class
# Tournament is observable while players are observers
import Message
import Observable
import ScoreKeeper
class Tournament(Observable.Observable):
# set up a list of players when tournament is initialized
def __init__(self):
Observable.Ob... |
from zaggregator.procbundle import *
from zaggregator.utils import *
name = "zaggregator"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# python client for ASL
# asl generator and pipeline
# prototype and demo
import json
import sys
import os
import xml.dom.minidom
import StringIO
import re
import logging
import uuid
# locate analyic_server from the build/checker library
# sys.path.append(sys.path.append... |
from dnnv.properties import expressions
from dnnv.properties.expressions.terms.constant import Constant
from dnnv.properties.visitors import ExpressionVisitor
def test_ExpressionVisitor():
visitor = ExpressionVisitor()
visitor.visit(expressions.Symbol("A"))
visitor.visit(
expressions.And(
... |
from tkinter import *
from tkinter import messagebox
from modules.Sounds import click
from modules.Credentials import db_connection, bookTable, bid_check
def add_check():
with open(r"counters\addbook.txt", "r") as file:
a = file.read()
return True if a == "1" else False
def add_open():
with open... |
# Copyright 2021 qclib project.
# 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, ... |
# encoding: utf8
# miner.py
import logging
from itertools import zip_longest, tee
from functools import partial, reduce
from operator import itemgetter
from pprint import pprint
from requests import Session, codes
from time import time, sleep
from tqdm import tqdm
from miptclass import models
from miptclass.api ... |
from setuptools import setup
# Read a __version__
exec(open('alfpy/version.py').read())
# Long description
fh = open('README.rst')
long_description = fh.read()
fh.close()
setup(
name='alfpy',
version=__version__,
description="Alignment-free package to compare DNA/RNA/protein sequences (bioinformatics).",
... |
from Libraries.EmailService.LibraryGeneral.EmailService import ServicioEmail
email = ServicioEmail(emailOrigenBase64 = "d2lzcm92aS5yb2RyaWd1ZXpAZ21haWwuY29t",
passwordEmailBase64 = "RkM1SkI2RU0=",
nombreRemitenteBase64 = 'V0lTUk9WSQ==')
tituloMensaje = 'Final Trabajo'... |
from typing import List
class CompleteBinaryWriteImpulse:
uri: str
uploadId: str
chunks: List[str]
def __init__(self, uri: str, uploadId: str, chunks: List[str]):
self.uri = uri
self.uploadId = uploadId
self.chunks = chunks
def __eq__(self, other):
return self.uri... |
# Importing the Kratos Library
from KratosMultiphysics.kratos_utilities import CheckIfApplicationsAvailable
if not CheckIfApplicationsAvailable("CompressiblePotentialFlowApplication"):
raise ImportError("The CompressiblePotentialFlowApplication is not available!")
# Importing the base class
from KratosMultiphysic... |
from ..core import StateStatus, State
class PrintState(State):
_text: str
def __init__(self, name: str, text: str):
"""Constructor for PrintState
Parameters
----------
name : str
Name of the State, useful in Debugging.
text : str
Text to print... |
# --------------------------------------------------------------
# bm_ShuffleShortcuts.py
# Version: 2.0.0
# Author: Ben McEwan
#
# Last Modified by: Ben McEwan
# Last Updated: November 8th, 2021
# --------------------------------------------------------------
# ---------------------------------------------------... |
import torch
import torchvision
import torchvision.transforms as T
import model
import config
import dataset
import numpy as np
import time
from tqdm import tqdm
__all__ = ["train_fn", "eval_fn"]
def train_fn(train_dataloader, detector, optimizer, device, scheduler=None):
detector.train()
for images, targets... |
import os.path
import shutil
from unittest import skipUnless
from django.test import TestCase
from peacecorps.models import DonorInfo, Account
class GPGTests(TestCase):
def setUp(self):
self.account = Account.objects.create(code='FUNDFUND')
def tearDown(self):
self.account.delete()
def... |
# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
import inspect
from contextlib import contextmanager
"""
Implicit self emulation in Python using context managers, inspection and locals manipulation.
"""
def is_public(field_name: str):
return False if field_name.startswith('__') else True
@contextmanager
def in_context(context_object):
decorator_frame = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
pymrt.computation: generic computation utilities for MRI data analysis.
See Also:
pymrt.recipes
"""
# ======================================================================
# :: Future Imports
from __future__ import absolute_import
from __future__ import division
... |
from pydantic import BaseModel
from pathlib import Path
class Config(BaseModel):
PACKAGE_DIR = Path(__file__).parent.resolve()
DATASET_DIR = PACKAGE_DIR / "data"
TRAINED_MODELS_DIR = PACKAGE_DIR / "trained_models"
# Create directories
TRAINED_MODELS_DIR.mkdir(exist_ok=True)
DATASET_DIR.mkdir(... |
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
|
import numpy
import rospy
from openai_ros import robot_gazebo_env
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
from nav_msgs.msg import Odometry
from openai_ros.openai_ros_common import ROSLauncher
class CubeSingleDiskEnv(robot_gazebo_env.RobotGazeboEnv):
"""Superclass for all CubeSingl... |
# ingreso = input("ingrese palabras")
# def totalElementos(ingreso) :
# count = 0
# for element in ingreso:
# count += 1
# return count
# print("The total number of elements in the list: ", totalElementos(ingreso))
# listaPalabras = ingreso.split()
# frecuenciaPalab = []
# for i in listaPalabra... |
from typing import Generic, Iterable, Optional, Tuple, TypeVar, cast
from jstools.screeps import *
__pragma__('noalias', 'name')
__pragma__('noalias', 'undefined')
__pragma__('noalias', 'Infinity')
__pragma__('noalias', 'keys')
__pragma__('noalias', 'get')
__pragma__('noalias', 'set')
__pragma__('noalias', 'type')
__... |
from typing import Any, Callable, Iterable, List, Mapping, Set, TypeVar
from . import Input, BufferedInput
InputType = TypeVar('InputType', Input, BufferedInput)
class InputSynchronizer:
input_names: List[str]
inputs: Set[InputType]
ready: Set[InputType]
handler: Callable[[Iterable[Input]], Any]
... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
#
# CC Vary Header is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Default configuration."""
from __future__ import absolute_import, print_function
from invenio_indexer.api impo... |
def first_derivative(xs, ys, mode='centered'):
if mode == 'forward':
x = xs[:-1]
y = ys[:-1]
x_next = xs[1:]
y_next = ys[1:]
derivs = (y_next - y) / (x_next - x)
elif mode == 'centered':
x1 = xs[:-2]
y1 = ys[:-2]
x2 = xs[1:-1]
y2 = ys[1:-1]... |
# flake8: noqa
from .base import *
ALLOWED_HOSTS = ['127.0.0.1']
INTERNAL_IPS = ['127.0.0.1']
# Application definition
THIRD_PARTY_APPS += ()
LOCAL_APPS += ()
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
... |
from rest_framework import serializers
from .models import Images, Post, Comment
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'title', 'content', 'create_date', 'update_date', 'image', 'user')
class PostCreateSerializer(serializers.ModelSerializer):
... |
# Copyright 2021, Peter Birch, mailto:peter@lightlogic.co.uk
#
# 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... |
from datetime import datetime
from typing import Generator
import pytest
from sqlalchemy.orm import Session
from app.database.models import Event, Invitation, User
from app.internal.utils import create_model, delete_instance
@pytest.fixture
def invitation(
event: Event, user: User, session: Session
) -> Gen... |
from django.contrib import admin
# Register your models here.
from .models import TopicTag, SkillTag, UserProfile
admin.site.register(TopicTag)
admin.site.register(SkillTag)
admin.site.register(UserProfile)
|
#!/usr/bin/env python3
import io
import os
import sys
import pyperclip
from PIL import Image
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QSystemTrayIcon,qApp,QMenu,QAction
from system_hotkey import SystemHotkey
from PyQt5.QtCore im... |
import torch
import numpy as np
from typing import Dict, Any, List
import math
import gym
from core.envs import BaseDriveEnv
from ding.torch_utils.data_helper import to_ndarray
DEFAULT_ACC_LIST = [
(0, 1),
(0.25, 0),
(0.75, 0),
]
DEFAULT_STEER_LIST = [
-0.8,
-0.5,
-0.2,
0,
0.2,
0.5... |
import sys
import serial
from time import sleep
path = '/dev/ttyUSB0'
baud = 115200
# OPTION A
# To disable /RESET after hangup
#
# import termios
# with open(path) as f:
# attrs = termios.tcgetattr(f)
# attrs[2] = attrs[2] & ~termios.HUPCL
# termios.tcsetattr(f, termios.TCSAFLUSH, attrs)
# OPTION B
# To d... |
from cstraining.web.rest.main import App
from cstraining.web.rest.model import StateColors
@App.path(path='state_colors/{obj_class}', model=StateColors)
def get_state_color_model(app, obj_class):
return StateColors(obj_class)
|
# Copyright 2020 Google LLC. 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 applicable law or a... |
# Copyright 2016 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... |
import pytest
import taichi as ti
@ti.test(arch=ti.cpu)
def test_binary_op():
@ti.kernel
def bitwise_float():
a = 1
b = 3.1
c = a & b
with pytest.raises(SystemExit):
bitwise_float()
|
# ObjectID: 1000013
# Character field ID when accessed: 744000000
# ParentID: 9330193
# Object Position X: 623
# Object Position Y: 245
|
"""
This class is used to establish the db connection, retrieve the data required to populate the initial values in the
dropdowns of the aggregation levels and the changes in the data entities based on the choice of the aggregation levels.
"""
import sys
import os
import imp
import configparser as cp
sys.path.append(... |
from textabstractor.about import __project_name__, __version__ # noqa F401
import pluggy
hookimpl = pluggy.HookimplMarker(__project_name__)
from textabstractor import app # noqa: E402, F401
from textabstractor import nlp # noqa: E402, F401
|
class Element:
E_LABEL = 1
E_GOTO = 2
E_SCALAR = 3
def __init__(self):
self.id = ""
self.type = -1
def constructor1(self, id, type) -> None:
self.id = id
self.type = type
def copy(self, copy):
if copy != None:
self.id = copy.id
s... |
import os
from functools import wraps
from logger.get_logger import get_logger
logger = get_logger(__name__)
def save_request_id(lambda_handler):
@wraps(lambda_handler)
def set_request_id_to_environ(event, context):
try:
os.environ['LAMBDA_REQUEST_ID'] = context.aws_request_id
ex... |
from typing import Optional, Union
from libcst import CSTTransformer, Comment, RemovalSentinel, SimpleStatementLine, BaseStatement, FlattenSentinel, \
MaybeSentinel, ClassDef, Name, FunctionDef, CSTNode, BaseSmallStatement, Assign, Attribute, AnnAssign, Import, \
Tuple, List, ImportFrom, ImportStar
from libcst... |
from krita import DockWidgetFactory, DockWidgetFactoryBase
from .docker_template import DockerTemplate
DOCKER_ID = 'template_docker'
instance = Krita.instance()
dock_widget_factory = DockWidgetFactory(DOCKER_ID,
DockWidgetFactoryBase.DockRight,
... |
from unetschema.schema import B58_CHARS, ADDRESS_CHECKSUM_LENGTH
from unetschema.hashing import double_sha256
from unetschema.error import InvalidAddress
def b58decode(v):
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += B58_CHARS.find(c) * (58 ** i)
result = ''
while ... |
# -*- coding:utf-8 -*-
from src.Update.Conf.config import *
class ReadConfigFile():
"""
该类负责读取配置文件,属于实际操作类
"""
def __init__(self, fileName='./conf/main.ini'):
self.config = ConfigParser.ConfigParser()
self.fileName = fileName
def readConfigFile(self, configMainName, configSubNa... |
#!/usr/local/bin/python3
import sys, re, json
import pathlib
import argparse
from ruamel.yaml import YAML
from os import path as path
from os import scandir as scandir
from os import remove as deleteFile
from collections import OrderedDict
here_path = path.dirname( path.abspath(__file__) )
this_script = re.sub(".py",... |
from calendar import monthrange, month_name
from datetime import date
from django import template
register = template.Library()
@register.simple_tag
def format_timespan(month, year):
if date.today().month == int(month) and date.today().year == int(year):
return '{} 1 - {} {}, {}'.format(
... |
from django.contrib import admin
from .models import ExerciseTemplate, Exercise, WorkloadTemplate, Workload, SetTemplate, Set
class ExerciseTemplateAdmin(admin.ModelAdmin):
pass
class ExerciseAdmin(admin.ModelAdmin):
pass
class WorkloadTemplateAdmin(admin.ModelAdmin):
pass
class WorkloadAdmin(admin.... |
import abc
import random
# Python 3.5
class Tombola(abc.ABC):
""" Globo de bingo
- Carregar itens
- Inspecionar itens
- Saber se está vazia
- Sortear itens
- Misturar itens
A tombola deve armazenar seus itens num atributo chamado itens.
"""
@abc.abstractmethod
def carrega(sel... |
from src.core.functions.shell import *
class Generator(object):
"""
Description:
Instance of this class will generate
various stuff depending on the requirements,
as of right now, it can generate :
- Directory Structure (with empty files)
"""
def __init__(self):
super(Genera... |
#!/usr/bin/env python
import sys
import numpy as np
import time
from optparse import OptionParser
import logging
def normalize(A):
column_sums = A.sum(axis=0)
new_matrix = A / column_sums[np.newaxis, :]
return new_matrix
def inflate(A, inflate_factor):
return normalize(np.power(A, inflate_factor))
d... |
# *-* coding: utf-8 *-
import requests
import re
from bs4 import BeautifulSoup
import traceback
def crawl():
print('hello')
stock_index_url = 'http://quote.eastmoney.com/center/gridlist.html#hs_a_board'
stock_info_base_url = 'https://gupiao.baidu.com/stock/'
stock_code_list = get_stock_list(stock_ind... |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `` li... |
from .action_scheme import ActionScheme, DTypeString, TradeActionUnion
from .continuous_actions import ContinuousActions
from .discrete_actions import DiscreteActions
from .multi_discrete_actions import MultiDiscreteActions
# 交易动作字典
_registry = {
'continuous': ContinuousActions,
'discrete': DiscreteActions,
... |
import tensorflow as tf
IDENTIFIER_OUTPUT_LAYER = "Output"
def get_out(output_layer: str, out_feature_dim, scale_node_size, name: str = 'decoder'):
if output_layer == "gaussian":
output_decoder_layer = GaussianOutput(
original_dim=out_feature_dim,
use_node_scale=scale_node_size,
... |
#!/usr/bin/env python
# The adjacent candidate segments were joined and the boundary is relocated by the outmost ORF if an ORF intersects with a segment.
# Note: the segment will only be extended
# For features: sum the numbers; recompute the percentages
#
# Author: Bingxin Lu
# Affiliation : National University of Si... |
from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.db.models.query import QuerySet
from django.urls import reverse
from django.utils.html import format_html
from .models import Post, Category, Tag, Comment, Link, SideBar
class BaseOwnerAdmin(admin.ModelAdmin):
exclude =... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server.models.mqtt import MQTT # noqa: F401,E501
from swagger_server import util
class SourceOutput(... |
import argparse
import os
import sys
from infraboxcli.push import push
from infraboxcli.run import run
from infraboxcli.graph import graph
from infraboxcli.validate import validate
from infraboxcli.list_jobs import list_jobs
from infraboxcli.log import logger
from infraboxcli.init import init
from infraboxcli.pull imp... |
from django.contrib.auth import get_user_model
from phoenix.core.models import Outage, Solution, System
def get_outage(with_solution=False):
user = get_user_model().objects.create(username="unittest", password="unittest")
system = System.objects.create(name="Unittest-system")
outage = Outage(
sum... |
#
# PySNMP MIB module TIMETRA-LOG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-LOG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:09:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls.defaults import patterns, url
from django.contrib import admin
from django.contrib.admin.util import unquote, model_ngettext
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.utils import fo... |
# coding=utf-8
from celery import Celery
from flask import current_app
from . import celeryconfig
factorial_app = Celery("factorial_app")
factorial_app.config_from_object(celeryconfig)
@factorial_app.task(shared=False)
def my_factorial(n):
result = 1
for i in range(1, n+1):
result *= i
print(f"... |
from pathlib import Path
from pymmcore_plus import CMMCorePlus
from useq import MDASequence
from raman_mda_engine import RamanEngine
metadata = {
"raman": {
"z": "center",
"channel": "BF",
},
}
mda = MDASequence(
metadata=metadata,
stage_positions=[(100, 100, 30), (200, 150, 35)],
... |
import datetime
from decimal import Decimal
from itertools import cycle
from django.test import TestCase
from contracts.mommy_recipes import get_contract_recipe
from ..models import Contract, convert_to_tsquery
class ContractTestCase(TestCase):
def make_contract_with_rates(self, **kwargs):
final_kwargs ... |
import commands
import glob
import os
import sys
from waflib import Build, Logs, Node, Options, Task, TaskGen, Utils
##----------------------------------------------------------------##
@TaskGen.extension('.mm')
def mm_hook(self, node):
"Bind the c++ file extensions to the creation of a :py:class:`waflib.Tools.cxx.... |
import pygame
from .system import System
from component import config
from logcat import LogCat
class GameWindow(System):
def __init__(self, window, background):
super().__init__()
self._window = window
self._background = background
self._ui_font = pygame.freetype.SysFont(
... |
import networkx as nx
import csv
def compute_top_k(map__node_id__score, k=20):
list__node_id__score = [(node_id, score) for node_id, score in map__node_id__score.items()]
list__node_id__score.sort(key=lambda x: (-x[1], x[0]))
return list__node_id__score[:k]
complete_input_graph_file_name = "./Part_2/data... |
import contextlib
from typing import Any, List, Optional
from flask import Flask
from werkzeug.routing import Rule
from . import util
from .blueprint.blueprint import openapi_documentation
from .converters.base import Converter
from .documentation import Documentation
from .exceptions import MissingConfigContext, Mis... |
import pressio4py as p4py
def test_version():
print(p4py.__version__)
if __name__ == '__main__':
test_version()
|
# -*- coding: utf-8-*-
import sys
import os
import time
import yaml
import lib.diagnose
from baseVoice import AbstractVoiceEngine
import lib.appPath
from lib.voice.snowboy import snowboydetect
class SnowboyVoice(AbstractVoiceEngine):
"""
Uses the snowboy hotword detector
"""
TAG = "snowboy"
d... |
# 多項ロジスティック回帰
import numpy as np
import seaborn as sns
import pandas
import matplotlib.pyplot as plt
import mcmc_tools
from scipy.stats import norm
from sklearn.linear_model import LinearRegression
import time
# 商品購買
# Age: 年齢
# Sex: 性別
# Income: 収入
# Y: 購買商品ID
category = pandas.read_csv('data-category.txt')
print(cat... |
# -*-coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
from alpharotate.libs.models.detectors.single_stage_base_network_batch import DetectionNetworkBase
from alpharotate.libs.models.losses.losses_fcos ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Data Cleaning Codes
"""
'''
The data for the social network of the eight masters of the Tang and Song
are extracted from China Biographical Database Project (CBDB).
This code is intended to prepare two excel tables for visualization in Gephi.
input: query_results.xl... |
import requests
from game_apis.rest.api import API
from game_apis.log import get_logger
LOG = get_logger('rest', 'rest.log')
# https://developer.riotgames.com/api-methods/
class Riot(API):
ID = 'RIOT'
LIMIT = 1
def __init__(self, config, region=None, sandbox=False, local_config=False, ignore_limiter=Fals... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.