content
stringlengths
5
1.05M
""" Global settings - these are loaded then overwritten in hostname specific files See __init__.py in this dir for details """ import os import socket from collections import defaultdict from library.django_utils.django_secret_key import get_or_create_django_secret_key from library.git import Git # if certain user...
import torch import torch.nn as nn import torchvision.models as models import torch.nn.functional as F # module not yet ready def customize_inception_v3(model, num_classes=1000): if num_classes != 1000: model.fc = nn.Linear(2048, num_classes) return model class inception_v3(nn.Module): def _...
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from pydantic import EmailStr from sqlalchemy import String, Column from sqlmodel import Field, Relationship from models.base import BaseModel, BaseTableFields if TYPE_CHECKING: from models.session import Session from models.role i...
from pathlib import Path from tqdm import tqdm import tensorflow as tf from modules.esrgan import rrdb_net, discriminator_net from modules.lr_scheduler import MultiStepLR from modules.data import load_dataset from modules.losses import get_pixel_loss, get_content_loss from modules.losses import get_discriminator...
# Generated by Django 3.0.6 on 2020-07-25 02:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('survey', '0009_auto_20200725_0248'), ] operations = [ migrations.AddField( model_name='surveyresponse', name='sessio...
import pytest import pyteal as pt from .compile_asserts import assert_new_v_old def user_guide_snippet_dynamic_scratch_var() -> pt.Expr: """ The user guide docs use the test to illustrate `pt.DynamicScratchVar` usage. pt.If the test breaks, then the user guide docs must be updated along with the test. ...
#!/usr/bin/python # (c) Copyright 2015 Hewlett Packard Enterprise Development LP # # GNU Zebra 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 2, or (at your option) any # later version. # # GN...
import numpy as np from scipy.stats import multinomial from sklearn.neighbors import NearestNeighbors def knn_smooth_pred_class( X: np.ndarray, pred_class: np.ndarray, grouping: np.ndarray = None, k: int = 15, ) -> np.ndarray: """ Smooths class predictions by taking the modal class from each ...
# Copyright 2016 Thomas C. Hudson # Governed by the license described in LICENSE.txt import libtcodpy as libtcod import algebra import map import actions import ai import miscellany import bestiary MIN_CARAVANSERAI_SIZE = 14 MAX_CARAVANSERAI_SIZE = 26 BANDIT_COUNT_GOAL = 4 class Caravanserai(object): def __ini...
import time from base_handler import BlogHandler from models import Post class EditBlogHandler(BlogHandler): def get(self, post_id): # user_id = check_for_valid_cookie(self) # cookie_user = User.get_by_id(int(user_id)) cookie_user = self.get_user_from_cookie() post = Post.get_by_id(...
#!/usr/bin/env python from __future__ import absolute_import, print_function, unicode_literals import os import sys # Allow interactive execution from CLI, cd tests; ./test_cli.py if __package__ is None: sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import unittest from ksconf.fi...
'''NAME 9-DeLaCruzAngel-Euler.py VERSION 1.0 AUTHOR Angel Adrian De la Cruz Castillo <angeldc@lcg.unam.mx> DESCRIPTION Programa que calcula soluciones de ecuaciones diferenciales usando el metodo de Euler CATEGORY Calculadora de soluciones de ecuaciones diferenciales USAGE...
# Generated by Django 2.2.13 on 2020-09-24 17:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('translations', '0008_remove_couch_id'), ] operations = [ migrations.AlterField( model_name='transifexblacklist', na...
import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC op = webdriver.ChromeOptions() op.binary_location = "chrome-wi...
import os from os.path import dirname import sys ROOT = dirname(dirname(dirname(os.path.abspath(__file__)))) sys.path.append(ROOT)
# coding=utf-8 """ Reference: https://github.com/hongyi-zhang/mixup """ import torch import numpy as np @torch.no_grad() def mixup_data(x, y, alpha=1.0, use_cuda=True): '''Returns mixed inputs, pairs of targets, and lambda''' if alpha > 0: lam = np.random.beta(alpha, alpha) else: lam = 1 batch_size = x.si...
SUCCESS = { 'SIGN_UP': '''Thank you for creating a {} account on UberLite! An \ activation code has been sent to the telephone number you provided.''', 'ACTIVATION_SMS_TEXT': '''<#> {} is your Uberlite {} account activation \ code.''', 'ACCOUNT_ACTIVATION': 'This account has been successfully activated', ...
#!/usr/bin/env python import os import sys import argparse # get all .log files from a specific folder. # identify machines # identify 3 tests: # - 4K 100% read, 100% random # - 4K 100% write, 100% random # - 8K 70% read, 30% write, 100% random # log file name format: # [VM_NAME]-[TEST_DESC]-[ITERATION]-test....
import glob import os import cv2 save_path = 'resources/video_fotos.avi' img_dir = "resources/orquidea/" img_array = [] image_list = glob.glob(f"{img_dir}/*.jpg") sorted_images = sorted(image_list, key=os.path.getmtime) cont = len(image_list) frames_per_seconds = 1 dims = 640, 480 # tamanho(largura, altura) for fil...
# Generated by Django 2.1.5 on 2019-04-10 07:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Legal', '0006_auto_20190409_1407'), ] operations = [ migrations.AlterField( model_name='category', name='status', ...
import cv2 import numpy as np class HTimp(): def __init__(self, image, distance = 150, param = (200, 20), radius = (0, 0)): ''' All the parameters required to run opencv Hough transform ''' self.image = image self.distance = distance self.param1 = param[0] se...
import ffmpeg import numpy as np import tensorflow as tf import cv2 transnet_verbose = False class ShotTransNetParams: F = 16 L = 3 S = 2 D = 256 INPUT_WIDTH = 48 INPUT_HEIGHT = 27 CHECKPOINT_PATH = None class ShotTransNet: def __init__(self, params: ShotTransNetParams, session=None): s...
from utils.intcode import Amp from utils.solution_base import SolutionBase class Solution(SolutionBase): def solve(self, part_num: int): self.test_runner(part_num) func = getattr(self, f"part{part_num}") result = func(self.data) return result def test_runner(self, part_num): ...
from __future__ import annotations import logging from typing import Any, Dict, Iterable, Optional from abc import ABC, abstractmethod from app.messaging.base import Command class BaseCommandHandler(ABC): @abstractmethod def handle(self, command: Command) -> Iterable[Command]: pass class CommandHand...
import click from src import settings from src.ertaoz import ertaoz_bot BOT_NAMES = [ertaoz_bot.BOT_USERNAME] @click.command() def cli(): ertaoz_bot.run(token=settings.BOT_ERTAOZ_TOKEN) if __name__ == "__main__": cli()
from day_5 import ( parse_data, count_overlaps, main, go_through_coordinates, ) def test_parse_data() -> None: list_of_coordinates = [ [(0, 9), (5, 9)], [(8, 0), (0, 8)], [(9, 4), (3, 4)], [(2, 2), (2, 1)], [(7, 0), (7, 4)], [(6, 4), (2, 0)], ...
model_name = './models/model.hdf5' models_path = './models' input_shape = (300, 300, 3) images_folder = './dataset/images' test_images_folder = './dataset/images' images_count = 718 epoch = 3 batch = 10 emb_size = 64
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\postures\posture_state_spec.py # Compiled at: 2020-04-15 01:17:36 # Size of source mod 2**32: 27750 ...
import doctest import local_settings.color_printer def load_tests(loader, tests, ignore): tests.addTests(doctest.DocTestSuite(local_settings.color_printer)) return tests
# Copyright (c) 2020, NVIDIA CORPORATION. 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 appli...
# -*- coding: utf-8 -*- """ Created on Mon Jun 8 21:43:30 2020 @author: Vito """ import bibtexparser import re class Paper: def __init__(self,title=None, scholar_link=None, scholar_page=None, cites=None, link_pdf=None): self.title = title self.scholar_page = scholar_page ...
import numpy as np import pyopencl as cl import h5py as h5 class CResize(object): def __init__(self): platforms = cl.get_platforms() print "Available devices:" for platform in platforms: devices = platform.get_devices() for device in devices: print " ...
from wagtail.test.utils.wagtail_tests import * # noqa
# encoding = utf-8 __author__ = "mcabana.com" import multiprocessing import datetime import logging from concurrent.futures import ProcessPoolExecutor start = datetime.datetime.now() FORMAT = "%(asctime)s %(processName)s %(process)d %(threadName)s %(thread)d: %(message)s" logging.basicConfig(format=FORMAT, level=lo...
#!/usr/bin/env python3.7 """ Mastering Object-Oriented Python 2e Code Examples for Mastering Object-Oriented Python 2nd Edition Chapter 10. Example 1. JSON """ # Persistence Classes # ======================================== # A detail class for micro-blog posts from typing import List, Optional, Dict, Any, Default...
# -*- coding: utf-8 -*- import logging from functools import partial from renormalizer.model import MolList from renormalizer.mps import Mpo, Mps from renormalizer.utils import TdMpsJob, Quantity, CompressConfig logger = logging.getLogger(__name__) class SpinBosonModel(TdMpsJob): def __init__(self, mol_list:...
#!/usr/bin/env python # -*- coding: utf-8 -*- def traduce_a_ingles(palabra_espanol): diccionario_espanol_ingles = { "casa": "house", "tarta": "cake" } try: return diccionario_espanol_ingles[palabra_espanol] except KeyError: return None if __name__ == "__main__": ...
import picamera from time import sleep camera = picamera.PiCamera() camera.rotation = 180 i = 0 while True: i = i % 6 camera.start_recording('sample{}.h264'.format(i)) sleep(5) camera.stop_recording() text = open('/home/pi/Desktop/programs/input.txt','w') print 'start' if i == 0: ...
def apreco(cod,preco): import pyautogui import time if len(cod) == len(preco): pyautogui.PAUSE = 1.8 pyautogui.press('winleft') pyautogui.write('gestor') pyautogui.press('enter') pyautogui.write('mercadovizinhanca1762@gmail.com') pyautogui.press('tab') ...
""" .. module:: django_core_models.demographics.views :synopsis: django_core_models demographics application views module. *django_core_models* demographics application views module. """ from __future__ import absolute_import from django_core_utils.views import ObjectListView, ObjectDetailView from . import mo...
# Script for calculating vx, vy, vz for stars with RVs. # This is just for validating results. import numpy as np import pandas as pd import aviary as av df = pd.read_csv("../data/gaia_mc5.csv") # m = df0.radial_velocity.values != 0 # df = df0.iloc[m] # for i, row in enumerate(df): xyz, vxyz = av.simple_calc_vxyz(d...
from __future__ import unicode_literals from frappe import _ def get_data(data): return { 'fieldname': 'task', 'transactions': [ { 'label': _('Activity'), 'items': ['Timesheet', 'Drawing', 'Sample', 'Pattern', 'Work Order'] }, { 'label': _('Accounting'), 'items': ['Expense Claim'] }, ...
# FIX TKINTER ISSUE WITH XMING SERVER - FIXED! # https://stackoverflow.com/questions/48254530/tkinter-in-ubuntu-inside-windows-10-error-no-display-name-and-no-display-env # SHOULD CONSIDER BINDING INFLUX CLIENT TO FRONT-END # FILEPATH ERROR: CLICKING UPLOAD AND THEN IMMEDIATELY EXITING DESTROYS FILEPATH INFORMATION # M...
class Hypothesis(object): """ Class for storing a basic hypothesies """ def __init__(self, target_protein, base_mol_ids, driver, inform_mol_ids=None, comment=None, structural_data=None): """ Instantiate a new register instance for a given compound :param targe...
from envparse import env DISCORD_TOKEN = env.str("DISCORD_TOKEN")
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from libnmap.parser import NmapParser from libnmap.reportjson import ReportDecoder, ReportEncoder nmap_report_obj = NmapParser.parse_fromfile("libnmap/test/files/1_hosts.xml") # create a json object from an NmapReport instance nmap_report_json = json.dumps(n...
import uuid from flask import request from mongo_orm import MongoDB, AnyField from datetime import datetime #Cache of OADR POLL messages. It is done in memory but if too many messages are in the queue it can be moved to the DB from oadr_core.exceptions import InvalidVenException from project_customization.flexcoop.ut...
import redis import socket class Reporter: def __init__(self, host, port, quiet): self.host = host self.port = port self.name = socket.getfqdn() self.live_expiry = 30 self.quiet = quiet def get_name(self): return self.name def get_key(self, key): return...
# DENG: dynamic engine - powerful 3D game engine # licence: Apache, see LICENCE file # file: FilePicker.py - Embeddable python script for file dialog picker # author: Karl-Mihkel Ott import tkinter as tk from tkinter.filedialog import askopenfilename tk.Tk().withdraw() filename = askopenfilename() print(filename)
from collections import OrderedDict def distinct(lst): order = OrderedDict.fromkeys(lst) print(order) result = [key for (key, value) in order.items()] print(', '.join(map(str, result))) if __name__ == "__main__": lst = [12, 3, 5, 12, 4, 3] distinct(lst)
""" Basic Python API to MongoDB Atlas Services ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Author:Joe.Drumgoole@mongodb.com """ import os import pprint import logging import json from requests.auth import HTTPDigestAuth import requests from enum import Enum from mongodbatlas.atlaskey import AtlasKey from mongodbatla...
# this can run on a laptop for self-service password reset adminUser = raw_input('Enter the admin username, without the domain (e.g. dhay):') adminPassword = raw_input('Enter the admin password: ') import gdata.apps.client def updateUser(email): #a function for creating a user account #logFile = open(logFileName...
def json(v, accept=None, reject=None): if isinstance(v, dict): return v reject(f'expected_json_object')
from matplotlib import pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def make_figure_calibration(confidence, accuracy, plot_ax=None): # if plot_ax is None: # plot_ax = plt.gca() plt.figure(figsize=(5, 5)) plt.plot(confidence, accuracy) plt.p...
import pytest from heka_api import create_app from heka_api.models import db, VaccineContainer import json @pytest.fixture(scope="module") def client(): app = create_app(TESTING=True) with app.test_client() as client: yield client VaccineContainer.query.filter_by(id="06aec48a-952b-4f2f-b375-00d...
import aiohttp import uuid import asyncio ########################################## # # Currently not working. # ########################################## async def main(): async with aiohttp.ClientSession(loop=loop) as session: uid = "c2a88d1b-5d00-4f87-bcc3-5f00807e10d1.jpeg" headers = {'conten...
import os import random from wavedata.tools.obj_detection import obj_utils from tools.visualization import vis_utils import config as cfg import constants as const def visualize_objects(objects, img_idx, show_results, alt_persp, perspID, fulcrum_of_points=True, use_intensity=False, view_r...
from django.urls import path from . import views from django.contrib.auth import views as auth_views from rest_framework.authtoken import views as drf_views from .views import UserCreateView, UserListView, UserChangeView, UserCarsView, CarRentChangeView urlpatterns = [ path('', auth_views.LoginView.as_view(templa...
import os import socket import logging.config from datetime import datetime from os import path import asyncio from src.psenti.service.sentiment import SentimentAnalysis, SentimentConnection, Document # create logger logging.config.fileConfig('logging.conf', disable_existing_loggers=False) logger = logging.getLogger...
# coding: utf-8 # In[1]: #!/usr/bin/env python ################################################################ # Copyright (C) 2015 OpenEye Scientific Software, Inc. ################################################################ # run this script in AlkEthOH_distrib directory containing *.oeb from __future__ i...
from django.template.defaulttags import register @register.filter def get_post_Cat(dictionary, key): return dictionary.get(str(key))
#-*- coding: utf-8 -*- import json import logging from datetime import datetime from six.moves import http_client from .signature import Signature def new_logger(name, verbose=False): logging.basicConfig() if verbose: http_client.HTTPConnection.debuglevel = 0 requests_log = logging.getLogge...
from typing import Coroutine from cherline import Cherline, Operation from settings import Setting async def notified_cancel_invitation_group( client: Cherline, op: Operation, setting: Setting ) -> Coroutine: """グループ招待がキャンセルされた時の処理 Args: client (Cherline): Cherline Client op (Operation):...
# Data Processor import pandas as pd, streamlit as st, datetime as dt ### Functions ### # Wide Mode st.cache(show_spinner=False) def auto_wide_mode(): st.set_page_config(layout="wide") # Update dataset st.cache(show_spinner=False) def app_data(): data = pd.read_csv(r'https://raw.githubusercontent.com/iData...
# -*- coding: utf-8 -*- """ Created on Sat Jun 12 00:09:55 2021 @author: Saptarshi """ arr = list(map(int,input().split())) n = len(arr) stack = [] ans = [] for i in range(n-1,-1,-1): if len(stack)==0: ans.append(-1) elif len(stack)>0 and stack[-1]<arr[i]: ans.append(stack[-1]) ...
#!/usr/bin/env python # # Internode usage applet for Avant Window Navigator # # Copyright (C) 2011 Dale Maggee (antisol [at] antisol [dot] org) # # Originally Based on internode Gnome Applet, which is copyright Sam Pohlenz # see: http://www.sampohlenz.com/ # # BSD Licensed. See license.txt for details. """ TODO ITEM...
import exceptions import utils from utils import configure
def sum_earning(string): values = string.split(',') # Handle non-number value errors for iteration, value in enumerate(values[:]): try: values[iteration] = int(value) except ValueError: return 0 # Handle all negative number values if all(value <= 0 for value i...
""" To load various datasets """ import os, gc import copy import json import numpy as np from PIL import Image # torch... import torch import torchvision from torchvision import datasets, transforms # ------------------------------------------------------------------------------ # Globals # -----------------...
""" NNgen: A Fully-Customizable Hardware Synthesis Compiler for Deep Neural Network Copyright 2017, Shinya Takamaeda-Yamazaki and Contributors 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 Li...
import datetime import itertools import numpy from couchbase.bucket import Bucket class GenericDocgen: def __init__(self, master_file_path, cb_url, bucket_name, chunk_size=1024): self.chunk_size = chunk_size self.items = 100 self.master_file_path = master_file_path self.dateBuild...
### The following code is derived from: ### https://github.com/GiggleLiu/QuantumCircuitBornMachine/blob/master/LICENSE ### The original resource is under MIT license, which is pasted below for convenience # MIT License # Copyright (c) 2017 Leo # # Permission is hereby granted, free of charge, to any person obtaining a...
(lambda __builtin__: (lambda __print, __y, __d: [[[[[[[[[[(lambda __after: (lambda __after: (lambda ___: __after(__d))(__print('Usage: python main.py inputfilename [outputfilename]')) if __d.len(__d.sys.argv)<=1 else [(lambda __after: [__after(__d) for __d.outfilename in [(__d.sys.argv[2])]][0] if __d.len(__d.sys.argv)...
import nltk import re import sys import pronouncing from nltk.probability import FreqDist from Utilities.geniusHelper import artistSongToUrl from Components.functions import scrape_song url = artistSongToUrl(sys.argv[1],sys.argv[2]) if len(sys.argv) > 2 else 'Logic-out-of-sight-lyrics' song = scrape_song('https://geni...
# Copyright 2017 ProjectQ-Framework (www.projectq.ch) # # 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 app...
import scanDir, os from Tracker import Tracker class CompletionLister: def __init__(self, classifier): self.classifier = classifier self.tracker = Tracker() def scanDirs(self, directories): """Recursively walk directory to train classifier""" self.directories = directories for dire...
## -*- coding: utf-8 -*- from maya.app.general.mayaMixin import MayaQWidgetDockableMixin import uuid from maya import cmds from maya import mel from maya import OpenMayaUI as omui # Import available PySide or PyQt package, as it will work with both try: from PySide2.QtCore import Qt, QPoint, QSize from PySid...
from django.shortcuts import get_object_or_404, redirect, render from django.http import JsonResponse from django.views.decorators.http import require_POST from django.utils.translation import gettext_lazy as _ from django.contrib import messages from froide.foirequest.models import FoiRequest from froide.foirequest.v...
import unittest from mock import Mock from datawinners.accountmanagement.registration_backend import RegistrationBackend class TestRegistrationBackend(unittest.TestCase): def setUp(self): self.backend = RegistrationBackend() self.request = Mock() SUBSCRIBED_ORGANIZATION_PARAMS = {'organizat...
# -*- coding: utf-8 -*- # Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FIWARE 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: # # htt...
var_a = int(input("Enter a integer: ")) if var_a%2 == 0: print("a is even") else: print("a is odd")
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: splitflap.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _ref...
from unittest import TestCase from openslides_backend.action.action import merge_write_request_elements from openslides_backend.shared.interfaces.event import EventType from openslides_backend.shared.interfaces.write_request_element import ( WriteRequestElement, ) from ..util import get_fqid class ActionBaseTes...
''' Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. If there are multiple solutions, return any subset is fine. ''' # def largestDivisibleSubset(nums): # if len(nums) == 0: # return [] # ...
# -*- coding: utf-8 -*- """Hypothesis strategies.""" from typing import Sequence from hypothesis.strategies import lists, dictionaries, booleans, sampled_from def propositional_words(propositions: Sequence[str], min_size=0, max_size=None): return lists( dictionaries(sampled_from(propositions), booleans()...
################# ## This code submit jobs to a PC cluster with various input parameters. ################# #!/usr/bin/env python # -*- coding: utf-8 -*- import os import subprocess data = "galaxy" # galaxy or mock zbin = 1 # 1 or 3 MULTIPOLE = [] MONO = [(0,0,0),(1,1,0),(2,2,0),(3,3,0),(4,4,0)] QUAD = [(2,0,2),(1...
# -*- coding: utf-8 -*- # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe import calendar from frappe import _ from frappe.desk.form import assign_to from frappe.utils.jinja import validate_templa...
from typing import Final import matplotlib.pyplot as plt from misc import fit_exp class Records: """ Container for time-dependent variables recorded in the log file. """ runs_read_in = [] #: Run indexes. NCON: Final[int] = 5 #: Number of connections. TIME_UN...
# Generated by Django 3.1.3 on 2020-11-22 19:53 import ckeditor.fields from decimal import Decimal import django.core.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import uuid class Migration(migrations.Migration): initial = True dependenc...
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from views_generator import ViewsStyleGenerator import unittest class ViewsStyleGeneratorTest(unittest.TestCase): def setUp(self): self.generat...
from __future__ import division, print_function, absolute_import import numpy as np import matplotlib.pyplot as plt import streamlit as st import pandas as pd #Load demographics @st.cache def load_csv(file): data = pd.read_csv(file) return data #Load data @st.cache def load_data(file): xls = pd.ExcelFile...
import gym import numpy as np from matplotlib import pyplot as plt env = gym.envs.make("MountainCar-v0") env.reset() plt.figure() plt.imshow(env.render(mode='rgb_array')) [env.step(0) for x in range(10000)] plt.figure() plt.imshow(env.render(mode='rgb_array')) env.render(close=True)
from dataclasses import dataclass, asdict from typing import Optional, Any, Callable, Dict, List, Tuple from ConfigSpace import ConfigurationSpace, Configuration from ConfigSpace.read_and_write import json as config_json from sklearn.pipeline import Pipeline from xautoml.graph_similarity import pipeline_to_networkx, ...
url = "https://code.soundsoftware.ac.uk/projects/vamp-plugin-sdk/files"
from django.conf.urls import url from . import views, models urlpatterns = [ url(r'^submit/$', views.submit_profile, name='submit_profile'), url(r'^(?P<pk>[0-9]+)/mem/$', views.show_profile, {'profile_type': "mem"}, name='mem_profile'), url(r'^(?P<pk>[0-9]+)/cpu/$', views.show_profile, {'profile_type': "cp...
""" ================================ Download the data set from CRCNS ================================ In this script, we download the data set from CRCNS. A (free) account is required. Cite this data set ------------------ This tutorial is based on publicly available data `published on CRCNS <https://crcns.org/data...
from asynctest import TestCase as AsyncTestCase from asynctest import mock as async_mock from aries_cloudagent.config.injection_context import InjectionContext from aries_cloudagent.connections.models.connection_record import ConnectionRecord from aries_cloudagent.messaging.base_handler import HandlerException from ar...
from acacia_main.settings import BASE_URL from django.core.urlresolvers import reverse import requests def api_get(method, auth_token, params, args=None): r = requests.get( BASE_URL + reverse(method, args=args), headers=auth_header(auth_token), params=params ) r = r.json() if r...
""" Common base classes for Annalist stored entities (collections, data, metadata, etc.) This module implements a common pattern whereby an entity is related to a parent, with storage directories and URIs allocated by combining the parent entity and a local identifier (slug) for the descendent. This module also imple...
import numpy as np import torch.nn as nn import torch import torch.nn.functional as F from torch.autograd import Variable class Agent: '''Agent Base.''' def __init__(self, game, display=None): self.game = game self.display = display def play(self, max_iter=np.inf, verbose=False): ...