content stringlengths 5 1.05M |
|---|
import unittest
import pandas as pd
from altcoin_max_price_prediction import preprocess_trade_data
class PreprocessTradeDataTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.main_class = preprocess_trade_data.PreprocessTradeData()
cls.main_class.history_size = 3
cls.main_c... |
# -*- coding: utf-8 -*-
import os
from ..glue.datasets import GlueDataset
from ..common import SentenceExample
__all__ = ["AGNEWSDataset", "TRECDataset", "DBPEDIADataset", "YELPDataset"]
class AGNEWSDataset(GlueDataset):
def __init__(self, dara_dir):
self.name = "agnews"
self.data_dir = dara_dir... |
# Copyright 2018 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 applicab... |
def make_matrix(rows=0, columns=0, list_of_list=[[]]):
'''
(int, int, list of list) -> list of list (i.e. matrix)
Return a list of list (i.e. matrix) from "list_of_list" if given
or if not given a "list_of_list" parameter,
then prompt user to type in values for each row
and return a matrix with ... |
"""Classes for the configuration of hermes-audio-server."""
import json
from pathlib import Path
from hermes_audio_server.config.mqtt import MQTTConfig
from hermes_audio_server.config.vad import VADConfig
from hermes_audio_server.exceptions import ConfigurationFileNotFoundError
# Default values
DEFAULT_CONFIG = '/et... |
import tensorflow as tf
import numpy as np
import time
import json
import hparams as hp
from model import transformer
from optimizer import get_optimizer
from preprocess import get_vocab
from pathlib import Path
from absl import app, flags
# Training hparams
hp.add("shuffle_buffer", 1, help="Shuffle buffer")
hp.add("m... |
"""
Django settings for rl_arena project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
from core.s... |
# Copyright (c) 2014 University of California, Davis
#
#
# 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, modify,... |
def display_menu():
print("The Book Catalog program")
print()
print("COMMAND MENU")
print("show - Show book info")
print("add - Add book")
print("edit - Edit book")
print("del - Delete book")
print("exit - Exit program")
def show_book(book_catalog):
i = 1
for key, value in bo... |
def foo(x: int):
pass
|
from .GridEmitter import *
from .ForceEmitter import *
from .HardCodeEmitter import * |
from time import sleep, strftime, time
import matplotlib.pyplot as plt
import numpy as np
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)
#What Data Do We Need?
Print = True#For Debugging and Cal... |
from .imports import *
class CubeVisualizer(Talker):
'''
A tool for visualizing a squishable cube.
'''
def __init__(self, cube=None):
'''
Initialize a visualizer, and link it to a Squishable or Binned cube.
'''
Talker.__init__(self)
self.cube = cube
@prope... |
import base64
import datetime
import hashlib
import hmac
import json
import requests
# Update the customer ID to your Log Analytics workspace ID
customer_id = ""
# For the shared key, use either the primary or the secondary Connected Sources client authentication key
shared_key = ""
# The log type is the name of the... |
class Solution:
def longestPalindrome(self, s: str) -> str:
if s==None or len(s)<1: return ''
start, end = 0, 0
for i in range(len(s)):
len1 = self.expandAroundCenter(s,i,i)
len2 = self.expandAroundCenter(s,i,i+1)
max_len = max(len1, len2... |
import os
class BadConfigFile(Exception):
pass
class Config:
''' Configurations class for the server '''
def __init__(self, args, config_file='boring.config'):
self.args = args
self.file = config_file # self.load(config_file)
self._options = {}
def load(self):
path ... |
#
# Example on the use of the CastImageFilter
#
import itk
from sys import argv
itk.auto_progress(2)
dim = 2
IType = itk.Image[itk.US, dim]
OIType = itk.Image[itk.UC, dim]
reader = itk.ImageFileReader[IType].New( FileName=argv[1] )
filter = itk.CastImageFilter[IType, OIType].New( reader )
writer = itk.ImageFileWri... |
from __future__ import annotations
from .basis import Basis, _gaps2x
from . import grid
from .util import roarray, input_as_list, compute_angles, qhull_interpolation_driver, _piece2bounds
from .attrs import check_vectors_inv, convert_vectors_inv, convert_coordinates, check_coordinates, convert_values,\
check_value... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
This script allows controlling a P9813 light strip connected to the Raspberry device
It listens to the STDIN stream and expect an array of values to apply [R, G, B, R, G, B ....]
Note 1: You MUST enable SPI communication in your Raspberry, for example by executing the 'ras... |
#!/us/bin/python
impot sys
if len(sys.agv)>=4:
filetype = sys.agv[1]
sub_filename = sys.agv[2]
output_filename = sys.agv[3]
else:
pint("Remove ovelapping/complementay tails fom long eads, keep a single full pass of the inset sequence")
pint("usage: ./RemoveBothTails.py filetype sub_file output_sub... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from pokemongo_bot.constants import Constants
from pokemongo_bot.step_walker import StepWalker
from pokemongo_bot.worker_result import WorkerResult
from pokemongo_bot.base_task import BaseTask
from utils import distance, format_dist, fort_details
class ... |
from pathlib import Path
import sys
import tokens
def bytes_debug_explicit(b) :
# variable passed was a single int : convert it to byte
if isinstance(b, int):
b = b.to_bytes(1, 'big')
result = ""
count = 0
for b_element in b:
count+=1
result += format(b_element,'08b') + " "
... |
from django.db import models
from djgeojson.fields import PointField
# Create your models here.
class Generalenquiries(models.Model):
contact_person= models.CharField(max_length=200, null=True, blank=True)
contact_email = models.EmailField(max_length=200, null=True, blank=True)
contact_telephone = models.CharFiel... |
import sys, re, urllib.request, xmltv, xml.etree.ElementTree as ET
from datetime import datetime, date, time, timedelta
BASE_URL = "https://appletv.redbull.tv/products/tv"
request = urllib.request.Request(BASE_URL, headers={"Accept" : "application/xml"})
response = urllib.request.urlopen(request)
xml = ET.parse(... |
import pstats
p=pstats.Stats("profile.stats")
p.sort_stats("cumulative")
#p.print_stats()
#p.print_callers()
p.print_callees() |
#!/usr/bin/env python3
"""
Bitmine Courier
"""
import requests
import os
import random
import json
import time
url = os.environ.get('URL')
mine_count = int(os.environ.get('MINE_COUNT'))
def main():
for i in range(mine_count):
headers = {"Ce-Id": f"{i}",
"Ce-Specversion": "1.0",
... |
'''conditional logit and nested conditional logit
nested conditional logit is supposed to be the random utility version
(RU2 and maybe RU1)
References:
-----------
currently based on:
Greene, Econometric Analysis, 5th edition and draft (?)
Hess, Florian, 2002, Structural Choice analysis with nested logit models,
... |
# -*- coding: utf-8 -*-
"""
@file
@brief Module *code_beatrix*.
.. faqref::
:title: Pourquoi Python?
`Python <https://www.python.org/>`_
est un langage de programmation très répandu aujourd'hui
qui fut choisi à l'`ENSAE <http://www.ensae.fr/ensae/fr/>`_ en
2005 pour remplacer le `C++ <https://fr.w... |
#
# Copyright 2018 National Renewable Energy Laboratory
#
# 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 la... |
import unittest
from robotide.controller.basecontroller import WithNamespace
from robotide.namespace.namespace import Namespace
from robotide.preferences.settings import Settings
class TestWithNamespace(unittest.TestCase):
def test_get_all_cached_library_names(self):
with_namespace = WithNamespace()
... |
import unittest
from pybox.containers.pqueue import PQueue
class PQueueTest(unittest.TestCase):
def setUp(self):
self.q1 = PQueue()
self.q2 = PQueue([('baz', 3), ('foo', 1)])
def tearDown(self):
pass
def test_init(self):
self.assertEqual(len(self.q1), 0)
self.asse... |
#!/usr/bin/env python3
# encoding: utf-8
import torch as th
import torch.nn as nn
default_act = 'relu'
Act_REGISTER = {}
Act_REGISTER[None] = lambda: lambda x: x
Act_REGISTER['relu'] = nn.ReLU
Act_REGISTER['elu'] = nn.ELU
Act_REGISTER['gelu'] = nn.GELU
Act_REGISTER['leakyrelu'] = nn.LeakyReLU
Act_REGISTE... |
# Used by other modules to determine if proxy will be
# used instead of direct connection.
proxy = None
def set_proxy(ip):
global proxy
import re
# I thinks tcp ports are around 65000? What do you think?
m = re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,5}$', ip)
if m:
proxy = 'htt... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 Clione Software
# Copyright (c) 2010-2013 Cidadania S. Coop. Galega
#
# 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.or... |
from bs4 import BeautifulSoup
from selenium import webdriver
import requests
def download_url(url, save_path, chunk_size=128):
r = requests.get(url, stream=True)
with open(save_path, 'wb') as fd:
for chunk in r.iter_content(chunk_size=chunk_size):
fd.write(chunk)
class Downloader... |
import numpy as np
import pandas as pd
from sklearn import ensemble
import synthimpute as si
def test_rf_quantile():
N = 1000
x = pd.DataFrame({"x1": np.random.randn(N), "x2": np.random.randn(N)})
# Construct example relationship.
y = x.x1 + np.power(x.x2, 3) + np.random.randn(N)
rf = ensemble.Ran... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2021 Evgeni Golov
#
# This program 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.
#
# ... |
"""Test logic blocks."""
from mpf.tests.MpfFakeGameTestCase import MpfFakeGameTestCase
from mpf.tests.MpfTestCase import test_config_directory
class TestLogicBlocks(MpfFakeGameTestCase):
def get_config_file(self):
return 'config.yaml'
def get_machine_path(self):
return 'tests/machine_files/l... |
from os import environ as env
import requests
_DARKSKY_KEY = env['DARKSKY_KEY']
_URL = 'https://api.darksky.net/forecast'
def _get_single_forecast(coord):
lat, lng = coord
url = '{url}/{key}/{lat},{lng}?exclude=minutely,hourly,daily,alerts,flags'.format(url=_URL, key=_DARKSKY_KEY,
... |
# ====================================================================================================================
# trainModel.py
# ====================================================================================================================
## AUTHOR: Vamsi Krishna Reddy Satti
# This script t... |
from deck_themer.helpers import *
# Test for experimenting with HDP and with HDP hyperparameters.
# The 'corpus' created below is necessary for both the lda_param_checker() method and the create_lda() method. The
# 'decklists' created below is only used for the lda_param_checker().
decklists, corpus, df = corpus_make... |
from keras import models
from keras import layers
from keras import optimizers
from matplotlib import pyplot as plt
import pickle
class NeuralNet:
def __init__(self, x_train, y_train, lr=0.001):
self.model = models.Sequential()
self.x_train = x_train
self.y_train = y_train
self.pa... |
try:
while 1:
T=input()
if T!='END': print(T[::-1])
except: pass |
from autorecon.plugins import ServiceScan
class SMTPUserEnum(ServiceScan):
def __init__(self):
super().__init__()
self.name = 'SMTP-User-Enum'
self.tags = ['default', 'safe', 'smtp', 'email']
def configure(self):
self.match_service_name('^smtp')
async def run(self, service):
await service.execute('hydr... |
# -*- coding: UTF-8 -*-
from SMInfoParser.StateMachineInfo import StateJumpInfo
from SMInfoParser.StateMachineInfoParser import SMInfoParser
from re import (findall,
sub)
class GraphvizSMInfoExtractor(SMInfoParser):
"""
State Machine information extractor, this class help extract information fr... |
from .entity import Entity
class Player(Entity):
pass
class Gorilla(Player):
type = 'gorilla'
|
"""Documentation related tests."""
|
# Copyright 2018 Microsoft Corporation
#
# 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... |
import tkinter as tk
import os, time
from xml.dom.minidom import parse
from awesometkinter.bidirender import add_bidi_support # https://github.com/Aboghazala/AwesomeTkinter
import arabic_reshaper # https://github.com/mpcabd/python-arabic-reshaper
import vlc ... |
import os
import PIL.Image
import cv2
import numpy as np
import pytest
def test_opencv_avc1():
filename = 'test.mp4'
if os.path.exists(filename):
os.unlink(filename)
width = height = 256
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'avc1')
out = cv... |
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')
import pytest
from unittest import TestCase
from src.builder import Builder
# 暫時跳過
# @pytest.mark.skipif()
class BuilderTest(TestCase):
"""測試 Builder"""
def setUp(self):
"""測試前先建立好環境"""
self... |
from fjsp import Solver, Problem, Job, Operation, Machine, Task, Resource
from typing import List, Tuple
import numpy as np
class Chromosome:
def __init__(self, machine_selection: List[int], operation_sequence: List[int]):
self.machine_selection = machine_selection
self.operation_sequence = operati... |
import os
from os.path import join
import json
def foo(dirname, fnames, outname):
data = []
for fname in fnames:
data.extend(json.load(open(join(dirname, fname))))
with open(join(dirname, outname), 'w') as f:
f.write(json.dumps(data, indent=2))
dirname = 'ull_both_5_100'
fnames = [
... |
# ************
# File: vnnlib_parser.py
# Top contributors (to current version):
# Panagiotis Kouvaros ([email protected])
# This file is part of the Venus project.
# Copyright: 2019-2021 by the authors listed in the AUTHORS file in the
# top-level directory.
# License: BSD 2-Clause (see the file LICENSE ... |
# coding=utf-8
# noinspection PyUnresolvedReferences
import maya.cmds as cmds
#
from LxBasic import bscMethods
from LxPreset import prsConfigure
#
none = ''
#
def setOutProxy(fileString_, renderer, exportMode=0):
temporaryFile = bscMethods.OsFile.temporaryName(fileString_)
# Export
if renderer == prsConf... |
# Copyright 2018 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, s... |
"""
Tidy Scenario: A robot uses its hand to tidy up the table, pushing the objects into a bin/cart etc.
EE = 'End Effector', which is the gripper / suction cup
"""
import torch
import random
import stillleben as sl
from sl_cutscenes.constants import SCENARIO_DEFAULTS
import sl_cutscenes.constants as CONSTANTS
from sl_... |
from __future__ import print_function, division
import torch
import torch.nn as nn
class ConvBlock(nn.Module):
def __init__(self, inplanes, outplanes, name, nums=3,
kernel_size=3, padding=1, stride=1):
super(ConvBlock, self).__init__()
self.nums = nums
self.relu = nn.ReLU(... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import mxnet as mx
import numpy as np
import sklearn
from mxnet import ndarray as nd
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
import face_i... |
import click
import sys
def init_subroutine():
global subroutine_stack
subroutine_stack = []
def push_subroutine(cmd_name: str):
global subroutine_stack
subroutine_stack.append(cmd_name)
def pop_subroutine():
global subroutine_stack
last = subroutine_stack[-1]
subroutine_stack = subroutine... |
import pytest
from arc import ARC
@pytest.fixture(scope="module")
def decomposition_samples() -> ARC:
return ARC(idxs={8, 10, 16, 17, 30})
# NOTE: This test is a little ambiguous, as the red object
# might reasonably be a rectangle missing 2 points, or a line trace.
def test_8(decomposition_samples: ARC):
b... |
from airflow.contrib.kubernetes.kubernetes_request_factory.pod_request_factory import (
SimplePodRequestFactory as AirflowSimplePodRequestFactory,
)
from airflow.contrib.kubernetes.secret import Secret
class DbndPodRequestFactory(AirflowSimplePodRequestFactory):
def create(self, pod):
req = super(Dbnd... |
import logging
import os
import re
from pathlib import Path
from typing import Dict
import anndata as ad
import pandas as pd
from sqlalchemy.orm import Session
from histocat.core.acquisition import service as acquisition_service
from histocat.core.dataset import service as dataset_service
from histocat.core.dataset.d... |
from transitions import Machine
#from transitions.extensions import GraphMachine as Machine
from utils import send_text_message
from utils import send_image_url
from utils import send_button_message
from data import data
class TocMachine(Machine):
def __init__(self, **machine_configs):
self.machine = Mach... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.v3_gtsabbreviation import (
v3GTSAbbreviation as v3GTSAbbreviation_,
)
__all__ = ["v3GTSAbbreviation"]
_resource = _ValueSet.parse_file(Path(__file__).with_suf... |
import unittest
import pinocchio as pin
pin.switchToNumpyMatrix()
import numpy as np
@unittest.skipUnless(pin.WITH_HPP_FCL,"Needs HPP-FCL")
class TestGeometryObjectBindings(unittest.TestCase):
def setUp(self):
self.model = pin.buildSampleModelHumanoid()
self.collision_model = pin.buildSampleGeomet... |
from helper import *
import math
from queue import PriorityQueue
#from path_finding import *
class Node():
def __init__(self, x, y):
self.coords = (x, y)
self.estimate = 0
self.cost = 0
def __gt__(self, other):
return self.estimate > other.estimate
def __eq__(self, other):... |
from utipy.string.letter_strings import letter_strings
def test_letter_strings():
# n: int, num_chars: Optional[int] = None, upper: bool = False, descending: bool = False
assert letter_strings(n=3) == ["a", "b", "c"]
# 2 chars
ls = letter_strings(n=27)
assert len(ls) == 27
assert ls[:3] == ... |
# coding: utf8
'''
LintCode:http://www.lintcode.com/zh-cn/problem/balanced-binary-tree/
93. 平衡二叉树
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
样例
给出二叉树 A={3,9,20,#,#,15,7}, B={3,#,20,15,7}
A) 3 B) 3
/ \ \
9 20 20
/ \ ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 14 15:59:11 2017
@author: af5u13
"""
#exec(open("/home/andi/dev/visr/src/python/scripts/testPanningCalculator.py").read())
import visr
import panning
import numpy as np;
#conffile = """<?xml version=\"1.0\" encoding=\"utf-8\"?>
#<panningConfiguration dimension=\"2\" i... |
import math
import matplotlib.pyplot as plt
import numpy
import pandas
import scipy
import numpy.linalg as linalg
import sklearn.cluster as cluster
import sklearn.neighbors as neighbors
Spiral = pandas.read_csv('C:\\Users\\minlam\\Documents\\IIT\\Machine Learning\\Data\\jain.csv',
... |
#!/usr/bin/env python3
import asyncio
from async_generator import aclosing
from amqproto.adapters.asyncio_adapter import AsyncioConnection, run
async def main():
try:
async with AsyncioConnection(host='localhost') as connection:
async with connection.get_channel() as channel:
... |
from normality import collapse_spaces, stringify
from pprint import pprint # noqa
from datetime import datetime
from lxml import html
from opensanctions import constants
MAX_RESULTS = 160
SEEN = set()
COUNTRIES_URL = "https://www.interpol.int/en/How-we-work/Notices/View-Red-Notices"
SEXES = {
"M": constants.MALE... |
"""Class for RESQML Earth Model Interpretation organizational objects."""
from ._utils import (equivalent_extra_metadata, extract_has_occurred_during, equivalent_chrono_pairs,
create_xml_has_occurred_during)
import resqpy.olio.uuid as bu
import resqpy.olio.xml_et as rqet
from resqpy.olio.base imp... |
# Introduction to Python
In this second workshop we'll take our first look at programming in Python. We'll cover the key data types (including NumPy arrays), as well as functions, and control flow statements. You could do an entire course focused on learning Python as a general purpose programming languague. For our g... |
# -*- coding:utf-8 -*-
# Created by Hans-Thomas on 2011-05-11.
#=============================================================================
# logger.py --- Logger meta class
#=============================================================================
import logging
class MetaLogger(type):
def __new__(self,... |
from typing import Any
try:
import cv2
import numpy as np
except ImportError:
raise ImportError(
"cv2 is not installed. Please install it with `pip install opencv-python`."
)
try:
import mss
except ImportError:
raise ImportError("mss is not installed. Please install it with `pip instal... |
import requests
class Nacos:
"""
Nacos api
"""
def __init__(self, url, namespace):
"""
:param url: Nacos的地址
:param namespace: 应用的namespace
"""
self.url = url
self.namespace = namespace
def get_config(self, data_id, group="DEFAULT_GROUP"):
""... |
from typing import List
from sqlalchemy.orm import Session
from fastapi import APIRouter, Depends, status, Response
from util.public import get_dirs_by_uid
from schema import DirectoryOut, DirectoryBase, BookmarkOut
from models import User, Directory
from database import get_db
from router.client.c_auth import get_cu... |
RSA_KEY_LEN = 512
AES_KEY_LEN = 32 # 暂定为32位
UPDATE_KEY_DURATION = 60 * 10 # 密钥更新时间间隔
|
from django.urls import path
from . import views
app_name = 'oidc_provider'
urlpatterns = [
path('.well-known/<str:service>', views.well_known,
name="_well_known"),
path('registration', views.registration,
name="registration"),
path('registration_read', views.registration_read,
... |
#!/usr/bin/env python3
"""Simple example on how to move the robot."""
import json
import sys
import robot_fingers
from rrc_iprl_package.example import move_up_and_down
# Number of actions in one episode (1000 actions per second for two minutes)
episode_length = 2 * 60 * 1000
def main():
# the difficulty level ... |
import os
import re
import pandas as pd
import numpy as np
import zipfile
def strftime_to_re_pattern(strftime_format):
"""infer the regular expression pattern of a strftime format string
Parameters
----------
strftime_format: str
string with the strftime format of the whatsapp file
Retur... |
# Copyright 2022 by Autodesk, Inc.
# Permission to use, copy, modify, and distribute this software in object code form
# for any purpose and without fee is hereby granted, provided that the above copyright
# notice appears in all copies and that both that copyright notice and the limited
# warranty and restricted ... |
from flask import Flask
from flask import render_template
from flask_sqlalchemy import SQLAlchemy
from models.DB import db_session
from flask_cors import CORS
from models.objects import SystemUser
app = Flask(__name__)
#TODO- Generate new key ie: print(os.urandom(24))
app.config['SECRET_KEY'] = '\xf2K\xed\xa3\x80r\... |
"""
Copyright 2018 InfAI (CC SES)
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... |
import falcon
import jwt
import os
from .dataset_fixtures import *
def test_add_commit_info(client):
ds_id = 'ds000001'
file_data = 'Test annotating requests with user info'
name = 'Test User'
email = '[email protected]'
user = {
'name': name,
'email': email,
'sub': '123456... |
import os
import importlib
import pytest
def create_usage_test(dash_duo, filename, dir_name='usage'):
app = importlib.import_module(filename).app
dash_duo.start_server(app)
dash_duo.wait_for_element_by_id("cytoscape", 20)
directory_path = os.path.join(
os.path.dirname(__file__),
'scr... |
from NetWork import NetWork
import time
'''
v0.1.1
'''
class MLManager:
def __init__(self, hp) -> None:
self.host = '127.0.0.1'
self.port = hp
pass
def check(self) -> bool: # 暂时建议仅限测试使用
resp = NetWork.pureGet([self.port, "check"])
if resp == "okok":
retur... |
import pandas as pd
import numpy as np
from scipy.stats import entropy
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import seaborn as sn
import mdscaling as mds
# Loading Directed Bipartite Twitter graphs
DG={}
for country in ['chile','france']:
DG[country] = mds.DiBipartite('datasets/twit... |
# -*- coding: utf-8 -*-
description = 'common detector devices provided by QMesyDAQ'
group = 'lowlevel'
devices = dict(
timer = device('nicos.devices.generic.VirtualTimer',
description = 'QMesyDAQ timer',
lowlevel = True,
unit = 's',
fmtstr = '%.1f',
),
mon1 = device('nic... |
"""
Application global configuration.
"""
from dataclasses import dataclass
from .interfaces import IStdLibFilter
class AppConfigurationAlreadySetException(Exception):
"""
Exception when you try to set app configuration twice.
"""
@dataclass(frozen=True)
class AppConfiguration:
"""
Configuratio... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
# This is the version of this source code.
manual_verstr = "1.9"
auto_build_num = "1"
verstr = manual_verstr + "." + auto_build_num
try:
from pyutil.version_class import Version as pyutil_Version
except (Import... |
# Copyright 2019 Matthew Treinish
# Copyright (c) 2009 testtools developers.
#
# 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 requ... |
import requests
import os
switch = {
409: "User is not authorized to access Asset.",
404: "Asset not found."
}
def downloadPlace(placeID, auth):
headers = {
'authority': 'assetdelivery.roblox.com',
'sec-ch-ua': '"(Not(A:Brand";v="8", "Chromium";v="99", "Google Chro... |
from abc import ABC, abstractmethod
class ByteInterface(ABC):
@abstractmethod
def convert(self):
pass |
# @date 2020-10-03
# @author Frederic Scherma
# @license Copyright (c) 2020 Dream Overflow
# Volume Profile indicator and composite
from strategy.indicator.indicator import Indicator
from strategy.indicator.models import VolumeProfile
from instrument.instrument import Instrument
from database.database import Database... |
import unittest
from translator import englishToFrench, frenchToEnglish
class TestTranslateEnToFr(unittest.TestCase):
"""
Class to test the function englishToFrench
"""
def test1(self):
"""
Function to test the function englishToFrench
"""
self.assertIsNone(englishToFren... |
""" Get the county museum lists from wikipedia.
Doing it this way, rather than cutting and pasting ensures that the same
encoding is used as urllib2 uses."""
__author__ = "Joe Collins"
__copyright__ = "Copyright (c) 2016 Black Radley Limited."
import io
import requests # for getting the pages from Wikipedia
import ... |
'''
Exercício Python 086: Crie um programa que declare uma matriz de dimensão 3x3
e preencha com valores lidos pelo teclado. No final, mostre a matriz na tela,
com a formatação correta.
'''
## VERSÃO GUANABARA:
matriz = [[0,0,0],[0,0,0],[0,0,0]]
for l in range(0,3):
for c in range(0,3):
matriz[l][c] = int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.