content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Generated by Django 2.2.7 on 2019-12-18 14:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('catalog', '0003_favourit... | python |
# always write to disk
FILE_UPLOAD_HANDLERS = [
'django.core.files.uploadhandler.TemporaryFileUploadHandler'
]
STATIC_URL = '/static/'
STATIC_ROOT = '/app/public'
MEDIA_ROOT = '/data'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDire... | python |
import os
import keras
import random as rn
import numpy as np
import tensorflow as tf
from keras.layers import Dense, Activation, Embedding
from keras.layers import Input, Flatten, dot, concatenate, Dropout
from keras import backend as K
from keras.models import Model
from keras.engine.topology import Layer
from keras... | python |
from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
import unidecode as udc
import scipy
class CustomOneHotEncoder(BaseEstimator, TransformerMixin):
"""
Clase que convierte a dummies las variables categóricas de un dataFrame. Permite eliminar
las dummies creadas según su re... | python |
# -*- coding: utf-8 -*-
###########################################################
# #
# Copyright (c) 2018 Radek Augustýn, licensed under MIT. #
# #
#######################################################... | python |
"""
Check if 2 strings are anagrams of each other
"""
from collections import Counter
def check_anagrams(str1, str2):
ctr1 = Counter(str1)
ctr2 = Counter(str2)
return ctr1 == ctr2
def check_anagrams_version2(str1, str2):
hmap1 = [0] * 26
hmap2 = [0] * 26
for char in str1:
pos = ord... | python |
import sys
import os
#reference = sys.argv[1]
#os.system("cp "+reference+" "+sys.argv[4])
firstfile = sys.argv[1] #sys.argv[1]
secondfile = sys.argv[2]
thirdfile = sys.argv[3]
seq1 = set()
seq2 = set()
file3 = open(thirdfile, 'r')
for line in file3:
myline = line.strip()
seqnames = myline.split('\t')
seq... | python |
class TicTacToe():
'''
Game of Tic-Tac-Toe
rules reference: https://en.wikipedia.org/wiki/Tic-tac-toe
'''
# coordinates of the cells for each possible line
lines = [ [(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)],
[(0,0), (1,0), (2... | python |
import cv2
import numpy as np
# Read image
img = cv2.imread("imori.jpg")
# Dicrease color
out = img.copy()
out = out // 64 * 64 + 32
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
| python |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import collections.abc
import json
import typing
from azure.functions import _sql as sql
from . import meta
class SqlConverter(meta.InConverter, meta.OutConverter,
binding='sql'):
@classmethod
... | python |
'''
This program parses a txt file containing proteins to analyse with IUPRED/BLAST/JALVIEW
'''
import warnings # allows program to be able to ignore benign warnings
#####
# IGNORE WARNINGS
#####
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufun... | python |
from typing import TYPE_CHECKING
from UE4Parse.BinaryReader import BinaryStream
from UE4Parse.Provider.Common import GameFile
if TYPE_CHECKING:
from UE4Parse.IO import FFileIoStoreReader
from UE4Parse.IO.IoObjects.FIoChunkId import FIoChunkId
from UE4Parse.IO.IoObjects.FIoOffsetAndLength import FIoOffsetA... | python |
# Copyright 2014 The Crashpad 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 applicabl... | python |
import unittest
import numpy as np
import tensorflow as tf
from pplp.core import box_4c_encoder
class Box4cEncoderTest(unittest.TestCase):
def test_np_box_3d_to_box_4c(self):
# Test non-vectorized numpy version on ortho boxes
# Sideways box
box_3d_1 = np.asarray([0, 0, 0, 2, 1, 5, 0])
... | python |
from .xml_style import XMLDataset
class VOCDataset(XMLDataset):
CLASSES = ['spike']
def __init__(self, **kwargs):
super(VOCDataset, self).__init__(**kwargs)
| python |
#!/usr/bin/env python
from .web_api_2 import SwaggerGiant | python |
import os, paramiko, time, schedule, smtplib, ssl
from datetime import datetime
from email.message import EmailMessage
host='localhost'
port='5432'
user='postgres'
password='admin'
database='testdb'
#chemin de sauvegarde locale
local_dir = 'C:\\Users\\Kamla\\projets\\auto-backup-sqldb\\backup\\'
#local_dir = 'Chemin ... | python |
from pathlib import Path
import pandas as pd
from collections import defaultdict
from typing import List, Union
from .types import Child
def create_csv(children: List[Child], output_dir: Union[Path,str]):
header_df = create_header(children)
episodes_df = create_episodes(children)
uasc_df = create_uasc(chi... | python |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--latitude", type=float, required=True, help="The latitude of your bounding box center")
parser.add_argument("--longitude", type=float, required=True, help="The longitude of your bounding box center")
args = parser.parse_args()
dlat = 0.005
dlon =... | python |
from modules.data.fileRead import readMat
from numpy import arange
from modules.modelar.leastSquares import calculate
# Alternativa para caso as constantes escolhidas não forem escolhidas pelo Usuário
SP = 50
OVERSHOOT = 0.10
TS = 70
# Pegando vetores de entrada e saída
ENTRADA, SAIDA, TEMPO = readMat()
# Calculando... | python |
import argparse
import os
import pandas as pd
import re
import spacy
import sys
from datetime import datetime
from geopy.extra.rate_limiter import RateLimiter
from geopy import Nominatim
from epitator.geoname_annotator import GeonameAnnotator
from epitator.date_annotator import DateAnnotator
from epita... | python |
from cmsisdsp.sdf.nodes.simu import *
import numpy as np
import cmsisdsp as dsp
class Processing(GenericNode):
def __init__(self,inputSize,outputSize,fifoin,fifoout):
GenericNode.__init__(self,inputSize,outputSize,fifoin,fifoout)
def run(self):
i=self.getReadBuffer()
o=self.getWrit... | python |
def say_hi():
print("hello world function")
def cube(num):
return num*num*num
say_hi()
print(cube(3))
# Statements
is_male = False
if is_male:
say_hi()
else:
print("Goodbay")
# Statements
is_female = True
if is_female or is_male:
print("Hi")
else:
print("Goodbay")
# Dictionary
mont... | python |
import os
from argh.dispatching import dispatch_command
import application
def start_app():
port = int(os.getenv('PORT'))
application.start(port=port)
if __name__ == '__main__':
dispatch_command(start_app)
| python |
import os
from git import Repo
from django.core.exceptions import PermissionDenied
from base.handlers.extra_handlers import ExtraHandler
from base.handlers.file_handler import FileHandler
from base.handlers.form_handler import FormHandler
from base.handlers.path_handlers import PathHandler
from base.handlers.github_... | python |
from radixlib.api_types.identifiers import AccountIdentifier
from radixlib.serializable import Serializable
from radixlib.api_types import TokenAmount
from typing import Dict, Any
import radixlib as radix
import json
class TransferTokens(Serializable):
""" Defines a TransferTokens action """
def __init__(
... | python |
# -*- coding: utf-8 -*-
from flask import render_template, redirect, request, url_for, flash, jsonify, abort
from flask_login import login_user, logout_user, login_required, current_user
from . import estate
from .. import db
from ..models import SzEstate
import urllib
import os
import time
import math
from datetime i... | python |
# Freetype library
freetype = StaticLibrary( 'freetype', sources = [ 'src/base/*', 'src/gzip/ftgzip.c', 'src/winfonts/winfnt.c', 'src/cid/type1cid.c' ], defines = [ 'FT2_BUILD_LIBRARY', 'FT_CONFIG_OPTION_SYSTEM_ZLIB' ] )
freetype.include( 'include' )
# Add Freetype modules sources
prefix = { 'gzip': 'ft', 'cid': ... | python |
"""
Created on Wednesday Septebmer 25 17:07 2019
tools to work with XRF data from the Geotek MSCL (Olympus head)
@author: SeanPaul La Selle
"""
import os
import sys
import glob
import tkinter
from tkinter import filedialog
import numpy as np
import csv
import pandas
import matplotlib as matplotlib
import matplotlib.... | python |
#!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'fútū'
CN=u'扶突'
NAME=u'futu41'
CHANNEL='largeintestine'
CHANNEL_FULLNAME='LargeIntestineChannelofHand-Yangming'
SEQ='LI18'
if __name__ == '__main__':
pass
| python |
class Bar():
pass
| python |
import os
import core.settings as st
from flask import Flask
from api.login import app as login_router
from api.create_account import app as account_router
from api.products import app as products_router
from api.producer import app as producer_router
from api.shop_car import app as shop_car_router
from api.order impor... | python |
# Copyright (c) 2017 Presslabs 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 law or agreed to in writ... | python |
from .logic import *
from .notifications import *
from .preprocessors import *
from .vigil import *
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2021.03.22
Start operation.
@author: zoharslong
""" | python |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import sys
import os
import time as t
import numpy as np
import theano as th
import theano.tensor as T
import theano.ifelse
import theano.compile
import theano.compile.mode
import hand_io
############## Objective in theano ##################
... | python |
# Copyright 2018 Cisco and its affiliates
#
# 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... | python |
import logging,uuid
from exchangemanager import ExchangeManager
from result import Result
from order import Order
class BacktestManager(ExchangeManager):
def __init__(self, config = {} ):
ExchangeManager.__init__(self, "BTEST", config )
self.balance = None
self.log = logging.getLogger('cry... | python |
# Import libraries
import matplotlib.pyplot as plt
import numpy as np
# Draw
plt.title("Lines") # put title on plot
plt.plot([-4,2], [-2,-2], "b") # Plot the lines to draw a house
plt.plot([-4,-1], [2,3], "b")
plt.plot([-1,1], [3,5], "b")
plt.plot([2,4], [-2,0], "b")
plt.plot([1,4], [5,4], "b")
plt.plot([1,-2], [5,4... | python |
# -*- coding: utf-8 -*-
import sys
from optparse import OptionParser;
from xml.dom import minidom;
import re
import os
import csv
import hashlib
import shutil
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from HorizonBuildFileUtil import HorizonBuildFileUtil
import subprocess
class HorizonUE4Buil... | python |
"""Flategy - a basic playable strategy game & bot."""
import os
import io
import subprocess
import tempfile
import cairo
import IPython.display
import numpy as np
class State:
__slots__ = ['position', 'radius', 'world_shape']
def __init__(self, position, radius, world_shape):
self.position = positi... | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from transformers import BertModel, RobertaModel
class EmbeddingGeneratorGLOVE(nn.Module):
def __init__(self, config, path):
super(EmbeddingGeneratorGLOVE, self).__init__()
self.config = config
print('Loa... | python |
# -*- coding: utf-8 -*-
import time as builtin_time
import pandas as pd
import numpy as np
# ==============================================================================
# ==============================================================================
# ===============================================================... | python |
import workalendar.africa
import workalendar.america
import workalendar.asia
import workalendar.europe
import workalendar.oceania
import workalendar.usa
from pywatts.core.exceptions.util_exception import UtilException
def _init_calendar(continent: str, country: str):
""" Check if continent and country are corre... | python |
from django.shortcuts import render
from morad.models import Car
from django.views.generic import (ListView,DetailView,DeleteView,UpdateView,CreateView)
from django.urls.base import reverse_lazy
class ListCars(ListView):
template_name = 'cars/cars.html'
model = Car
class DetailCar(DetailView):
template_nam... | python |
"""
Tests for string_utils.py
"""
import pytest
from django.test import TestCase
from common.djangoapps.util.string_utils import str_to_bool
class StringUtilsTest(TestCase):
"""
Tests for str_to_bool.
"""
def test_str_to_bool_true(self):
assert str_to_bool('True')
assert str_to_bool(... | python |
import sys
from datetime import timedelta
def print_expected_call_message(additional_message):
print(f"""{additional_message}
Expected application call:
python3 regex_text.py [searched phrase] [left_padding] [right_padding]
Example call:
python3 regex_text.py "I don't know" 2 3""")
def handle_arguments():
i... | python |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... | python |
from import_export import resources
from electricity.models import FeedBack
class FeedBackResource(resources.ModelResource):
class Meta:
model = FeedBack
| python |
from nose import with_setup
from pybbn.causality.ace import Ace
from pybbn.graph.dag import Bbn
from pybbn.graph.edge import Edge, EdgeType
from pybbn.graph.node import BbnNode
from pybbn.graph.variable import Variable
def setup():
"""
Setup.
:return: None.
"""
pass
def teardown():
"""
... | python |
__author__ = 'elsabakiu, neilthemathguy, dmorina'
from rest_framework import status, viewsets
from rest_framework.response import Response
from crowdsourcing.serializers.project import *
from rest_framework.decorators import detail_route, list_route
from crowdsourcing.models import Module, Category, Project, Requeste... | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers import ImplicitGraph
from torch.nn import Parameter
from utils import get_spectral_rad, SparseDropout
import torch.sparse as sparse
class IGNN(nn.Module):
def __init__(self, nfeat, nhid, nclass, num_node, dropout, kappa=0.9, adj_orig=N... | python |
from PIL import Image
import argparse
import os
import sys
current_directory = os.getcwd()
def args_check(args = None):
if(args == None):
print("Arguments are reqiured for execution")
parser = argparse.ArgumentParser(description="Resizer - A lightweight Image size and resolution resizer")
parse... | python |
a,b = 1,2
print a+b
| python |
import shlex
import json
from .BaseClient import BaseClient
from .Response import JSONResponse
from . import typchk
DefaultTimeout = 10 # seconds
class ContainerClient(BaseClient):
class ContainerZerotierManager:
def __init__(self, client, container):
self._container = container
... | python |
import tensorflow as tf
import keras
# print(tf.__version__, keras.__version__)
amv_model_path = "model/frmodel.h5"
export_path = "model/ArtMaterialVerification/2"
model = tf.keras.models.load_model(amv_model_path)
with tf.keras.backend.get_session() as sess:
tf.saved_model.simple_save(
sess,
ex... | python |
import pandas as pd
import numpy as np
import scipy as sp
import random
from scipy.spatial.distance import mahalanobis
class TrainOutlier:
data = None
percentilek = None
valuecountsdict = None
colsum = None
median = None
invcovmx = None
cols = None
threshold = None
... | python |
import os
from twisted.logger import FilteringLogObserver, LogLevelFilterPredicate, LogLevel, jsonFileLogObserver
from twisted.python import logfile
from twisted.python.log import FileLogObserver
log_dir = os.environ.get("LOG_DIR", '/var/log/')
log_level = os.environ.get("TWISTED_LOG_LEVEL", 'INFO').lower()
log_rotat... | python |
# (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
import os
import pytest
from datadog_checks.redisdb import Redis
from . import common
pytestmark = pytest.mark.e2e
def assert_common_metrics(aggregator):
tags = ['redis_host:{}'.format(common.HOST), 'r... | python |
import os
from oelint_adv.cls_rule import Rule
from oelint_parser.helper_files import expand_term
from oelint_parser.helper_files import get_layer_root
class RubygemsTestCase(Rule):
TESTCASE_DIR = "lib/oeqa/runtime/cases"
def __init__(self):
super().__init__(id="rubygems.testcase",
... | python |
# -*- coding: utf-8 -*-
"""Sonos Alarms."""
from __future__ import unicode_literals
import logging
from datetime import datetime
import re
import weakref
from .core import discover, PLAY_MODES
from .xml import XML
log = logging.getLogger(__name__) # pylint: disable=C0103
TIME_FORMAT = "%H:%M:%S"
def is_valid_rec... | python |
"""The core event-based simulation engine"""
import heapq
from abc import abstractmethod
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import Iterator, List, NamedTuple, Optional, Protocol, runtime_checkable
# from .event import EventError, EventLike, StopEngineError
__all__ = [
... | python |
import pdb
import copy
import json
import numpy as np
from utils import game_util
import constants
class ActionUtil(object):
def __init__(self):
self.actions = [
{'action' : 'MoveAhead', 'moveMagnitude' : constants.AGENT_STEP_SIZE},
{'action' : 'RotateLeft'},
... | python |
import requests
apikey = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwODE4ODU1YTcxOGRmNGVkMTkwZjE1ZSIsImlhdCI6MTYxOTEwMTc4MSwiZXhwIjoxNjIxNjkzNzgxfQ.SlyayNaXu8PTPYAtyR9h7tIlR9ooXn72DRn6EAwcgV6rNY1rZQCoSs_d2EESIJs3kb0LwCSfU9o5lWMW9_Twigj3FxX99iAg7_gB1m6TReJ2moZ-rYIst6RTtJtWQWBezZ-37RyACH9s44WQ9qnlrXBYKgnW6LyVi18Kdf... | python |
# coding: utf-8
from distutils.core import setup
__version__ = '0.2.3'
short_description = 'Statistics for Django projects'
try:
import pypandoc
long_description = pypandoc.convert('README.md', 'rst')
except (IOError, ImportError):
long_description = short_description
install_requires = [
'Djang... | python |
import os
sd = None
def set_sd(new_sd):
global sd
sd = new_sd
tmp_dir = "tmp/"
export_tmp = tmp_dir + "dashboard_export.csv"
if not os.path.exists(tmp_dir):
os.mkdir(tmp_dir)
| python |
# Seasons
SEASONS = [
"PRESEASON 3",
"SEASON 3",
"PRESEASON 2014",
"SEASON 2014",
"PRESEASON 2015",
"SEASON 2015",
"PRESEASON 2016",
"SEASON 2016",
"PRESEASON 2017",
"SEASON 2017",
"PRESEASON 2018",
"SEASON 2018",
"PRESEASON 2019",
"SEASON 2019",
]
| python |
import fire
from .utils import *
tfd=test_font_dir
if __name__ == '__main__':
fire.Fire() | python |
print('='* 40)
print('{:^40}'.format('Listagem de Preços!!'))
print('='* 40)
listagem = ('Espeto de Carne', 8.00,
'Espeto de Frango', 5.00,
'Espeto de Linguiça', 5.50,
'Espeto de Kafta', 6.00,
'Espeto de Queijo', 6.50,
'Espeto de Medalhão Frango', 6.00,
... | python |
from django.shortcuts import render
from django.http import HttpResponse
from random import randint
def big(): return randint(0, 1_000_000)
def index(request):
return HttpResponse("Hello, there! Welcome to the base of the project! Your big ugly number is " + str(big()))
| python |
import os
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from settings import CLIENT_NAME, Client, LAUNCH_MODE, LaunchMode, URL, LocatorType
class LauncherNotSu... | python |
import logging
import subprocess
import os
import platform
import sys
from cmd2 import utils
logger = logging.getLogger(__name__.split(".")[-1])
class Command:
"""
Provides a way to run bash commands on local or remote side
Remote execution of commands is done over SSH protocol for given username and ho... | python |
# print ' name ' , multiple times
# for loop
for i in range(1,11):
i = 'Omkar'
print(i)
# while loop
i = 1
while (i<11) :
print('Omkar)
i = i + 1
| python |
# see https://www.codewars.com/kata/614adaedbfd3cf00076d47de/train/python
def expansion(matrix, n):
for _ in range(n):
rows = [x + [sum(x)] for x in matrix]
extraRow = [sum([x[i] for x in rows]) for i in range(len(matrix))] + [sum([matrix[i][i] for i in range(len(matrix))])]
rows.append(extraRow)
mat... | python |
"""
Multi-core and Distributed Sampling
===================================
The choice of the sampler determines in which way parallelization is performed.
See also the `explanation of the samplers <sampler.html>`_.
"""
from .singlecore import SingleCoreSampler
from .mapping import MappingSampler
from .multicore impo... | python |
from game_state import GameState
import arcade as ac
import math
class DrawingManager:
@classmethod
def tick(cls):
if "entities" in GameState.current_state:
for ent in GameState.current_state["entities"]:
if "pos" in ent and "rot" in ent and "drawing" in ent:
... | python |
#!/usr/bin/python3
#
# Copyright 2012 Sonya Huang
#
# 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... | python |
import os, sys
# add NADE to path
nade_path = os.path.join(os.path.abspath('.'), 'bench_models', 'nade')
sys.path.append('./bench_models/nade/')
| python |
"""
Part of BME595 project
Program:
Show statistics of dataset
"""
from collections import Counter
from data import data_loader, _preprocess_dataset_small, _preprocess_dataset_large
def show_distribution(max_len=60, deduplicate=False):
small_sentences, small_polarities, purposes, _ = _preprocess_dataset_small(m... | python |
import re
from behave import given, when, then
from django.core import mail
from {{ cookiecutter.project_slug }}.apps.myauth.tests.factories import VerifiedUserFactory
from {{ cookiecutter.project_slug }}.apps.profile.models import Profile
from features.hints import BehaveContext
@given("a registered user")
def ste... | python |
from mle_monitor import MLEProtocol
meta_data = {
"purpose": "Test MLEProtocol",
"project_name": "MNIST",
"exec_resource": "local",
"experiment_dir": "log_dir",
"experiment_type": "hyperparameter-search",
"base_fname": "main.py",
"config_fname": "tests/fixtures/base_config.json",
"num_s... | python |
"""
Module: 'sys' on esp32 1.9.4
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.9.4', version='v1.9.4 on 2018-05-11', machine='ESP32 module with ESP32')
# Stubber: 1.2.0
argv = None
byteorder = 'little'
def exit():
pass
implementation = None
maxsize = 2147483647
modules = None
path = None
platform = 'es... | python |
import pickle
filename = './data/29_header_payload_all.traffic'
with open(filename, 'r') as f:
traffic = f.readlines()
with open('./data/29_payload_all.traffic','w') as f:
for i in range(len(traffic)):
s_traffic = traffic[i].split()
if s_traffic[10] == '11':
payload = s_traffic[0... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | python |
import falcon
from chromarestserver.resource import (
ChromaSdkResource,
SessionRootResource,
HeartBeatResource,
KeyboardResource
)
from chromarestserver.model import (
KeyboardModel,
SessionModel
)
app = falcon.API()
usb_keyboard = KeyboardModel()
session = SessionModel()
chromasdk = Chroma... | python |
import os
import json
from typing import Optional
from requests import post,get
from fastapi import FastAPI
app = FastAPI()
ha_ip = os.environ['HA_IP']
ha_port = os.environ['HA_PORT']
ha_entity = os.environ['HA_ENTITY'] #must be a sensor
ha_token = os.environ['HA_TOKEN']
ha_friendly_name = os.environ['HA_FRIENDLY_N... | python |
# ISC
#
# Copyright (c) 2022 Adir Vered <adir.vrd@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS... | python |
from huobi.client.trade import TradeClient
from huobi.constant import *
from huobi.utils import *
trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
symbol_test = "eosusdt"
i = 0
n = 3
order_id_list = []
while i < n:
order_id = trade_client.create_order(
symbol=symbol_test,
ac... | python |
from Utils import *
'''
On Adamson data
'''
Data_dir = "/home/luodongyang/SCData/Perturb/Adamson/"
#------------------------------------------------------------------------#
# Read Data
## Matrix
mat=mmread(os.path.join(Data_dir, "GSM2406677_10X005_matrix.mtx.txt"))
cell_ident = pd.read_csv(os.path.join(Data_dir, "GSM2... | python |
# debug_importer.py
import sys
class DebugFinder:
@classmethod
def find_spec(cls, name, path, target=None):
print(f"Importing {name!r}")
return None
sys.meta_path.insert(0, DebugFinder)
| python |
import json
import os
import unittest
from netdice.common import Flow, StaticRoute
from netdice.explorer import Explorer
from netdice.input_parser import InputParser
from netdice.problem import Problem
from netdice.properties import WaypointProperty, IsolationProperty
from netdice.reference_explorer import ReferenceEx... | python |
import os
from datetime import datetime
from flask import Flask, render_template, redirect, flash, abort, url_for, request
from flask.ext.restless import APIManager
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import UserM... | python |
from setuptools import setup, find_packages
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='ciscoaplookup',
version="0.10.0",
author="Steffen Schumacher",
aut... | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 28 11:07:41 2019
@author: Kevin
"""
import numpy as np
import pickle
from shapely.geometry import Point
class TileCreator(object):
def __init__(self, configuration, polygon):
self.output_path = configuration['tile_coords_path']
# A... | python |
from setuptools import setup
setup(
name='YAFN',
version='0.0.1',
author='txlyre',
author_email='me@txlyre.website',
packages=['yafn', 'yafn-tracker'],
url='https://github.com/txlyre/yafn',
license='LICENSE',
description='Yet another p2p file network protocol.',
install_requires=[
'cbor2',
'p... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 14 14:47:38 2021
@author: cxue2
"""
import torch
from xfdlfw import Result
from xfdlfw.metric import ConfusionMatrix, Accuracy, MeanSquaredError, MeanAbsoluteError, CrossEntropy
acc = Accuracy('acc')
ce_ = CrossEntropy('ce_')
mse = MeanSquaredErro... | python |
"""BleBox sensor entities."""
# pylint: disable=fixme
from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.entity import Entity
from . import CommonEntity, async_add_blebox
async def async_setup_platform(hass, config... | python |
from CHECLabPy.spectrum_fitters.gentile import sipm_gentile_spe, \
calculate_spectrum, SiPMGentileFitter, SpectrumParameter
import numpy as np
from numpy.testing import assert_allclose
from numba import typed
def test_sipm_gentile_spe():
x = np.linspace(-1, 20, 1000, dtype=np.float32)
y = sipm_gentile_spe... | python |
# the url address of the REST API server
CDS_LB='https://rest-endpoint.example.com'
# location of client certificate and key
CDS_CERT='../certs/cds_cert.pem'
CDS_KEY='../certs/cds_key.pem'
# the endpoint url of REST server, multiple version can and will be available
CDS_API='/v2.0/DetectionRequests'
CDS_URL=CDS_LB+CDS... | python |
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
import json
import pandas as pd
import numpy as np
import plotly
app = dash.Dash()
app.scripts.config.serve_locally=True
DF_WALMART = pd.read_csv('https:/... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.