content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Generated by Django 2.0.3 on 2018-04-13 22:35
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', '0006_auto_201... | python |
import numpy as np
from gym.spaces import Box, Dict, Discrete
from database_env.foop import DataBaseEnv_FOOP
from database_env.query_encoding import DataBaseEnv_QueryEncoding
class DataBaseEnv_FOOP_QueryEncoding(DataBaseEnv_FOOP, DataBaseEnv_QueryEncoding):
"""
Database environment with states and actions as... | python |
def intercala(nomeA, nomeB, nomeS):
fileA = open(nomeA, 'rt')
fileB = open(nomeB, 'rt')
fileS = open(nomeS, 'wt')
nA = int(fileA.readline())
nB = int(fileB.readline())
while
def main():
nomeA = input('Nome do primeiro arquivo: ')
nomeB = input('Nome do segundo arquivo: ')
nomeS = input('Nome para o arquiv... | python |
import RPi.GPIO as GPIO
import time
class Motion:
def __init__(self, ui, pin, timeout=30):
self._ui = ui
self._pin = int(pin)
self._timeout = int(timeout)
self._last_motion = time.time()
GPIO.setmode(GPIO.BCM) # choose BCM or BOARD
GPIO.setup(self._pin, GPIO.IN)
... | python |
#
# PySNMP MIB module H3C-DOMAIN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-DOMAIN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:08:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | python |
import sys
import numpy as np
from matplotlib import pyplot as plt
from tensorflow import keras
from tensorflow.keras import layers
def preprocess(array: np.array):
""" Normalizes the supplied array and reshapes it into the appropriate format """
array = array.astype("float32")/255.0
array = np.reshape(ar... | python |
import math
from time import sleep
from timeit import default_timer as timer
LMS8001_C1_STEP=1.2e-12
LMS8001_C2_STEP=10.0e-12
LMS8001_C3_STEP=1.2e-12
LMS8001_C2_FIX=150.0e-12
LMS8001_C3_FIX=5.0e-12
LMS8001_R2_0=24.6e3
LMS8001_R3_0=14.9e3
class PLL_METHODS(object):
def __init__(self, chip, fRef):
self... | python |
# Generated by Django 2.1.14 on 2019-12-02 11:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('djautotask', '0030_task_phase'),
('djautotask', '0028_task_secondary_resources'),
]
operations = [
]
| python |
# -*- coding: utf-8 -*-
import dataiku
from dataiku.customrecipe import *
import pandas as pd
import networkx as nx
from networkx.algorithms import bipartite
# Read recipe config
input_name = get_input_names_for_role('Input Dataset')[0]
output_name = get_output_names_for_role('Output Dataset')[0]
needs_eig = get_re... | python |
import json
import gmplot
import os
import random
import collections
# FIX FOR MISSING MARKERS
# 1. Open gmplot.py in Lib/site-packages/gmplot
# 2. Replace line 29 (self.coloricon.....) with the following two lines:
# self.coloricon = os.path.join(os.path.dirname(__file__), 'markers/%s.png')
# self.col... | python |
import pytest
from cx_const import Number, StepperDir
from cx_core.stepper import MinMax, Stepper, StepperOutput
class FakeStepper(Stepper):
def __init__(self) -> None:
super().__init__(MinMax(0, 1), 1)
def step(self, value: Number, direction: str) -> StepperOutput:
return StepperOutput(next_... | python |
# Generated by Django 2.1.5 on 2019-01-25 19:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0008_shoppingcart'),
]
operations = [
migrations.AddField(
model_name='shoppingcart',
name='total_price'... | python |
import numpy as np
def Adam_Opt(X_0, function, gradient_function, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8, max_iter=500,
disp=False, tolerance=1e-5, store_steps=False):
"""
To be passed into Scipy Minimize method
https://docs.scipy.org/doc/scipy/reference/generated/scipy.... | python |
from __future__ import absolute_import
from rest_framework.response import Response
from sentry import options
from sentry.api.bases.project import ProjectEndpoint
from sentry.models import ProjectKey
class ProjectDocsEndpoint(ProjectEndpoint):
def get(self, request, project):
data = options.get('sentry... | python |
import tensorflow as tf
from groupy.gconv.make_gconv_indices import make_c4_z2_indices, make_c4_p4_indices,\
make_d4_z2_indices, make_d4_p4m_indices, flatten_indices
from groupy.gconv.tensorflow_gconv.transform_filter import transform_filter_2d_nchw, transform_filter_2d_nhwc
def gconv2d(input, filter, strides, ... | python |
# Generated by Django 2.0.9 on 2019-12-05 20:27
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... | python |
class SeedsNotFound(Exception):
pass
class ZoneNotFound(Exception):
pass
class TooManyZones(Exception):
pass
| python |
"""
@author: acfromspace
"""
"""
Notes:
Find the most common word from a paragraph that can't be a banned word.
"""
from collections import Counter
class Solution:
def most_common_word(self, paragraph: str, banned: [str]) -> str:
unbanned = []
for character in "!?',;.":
paragraph =... | python |
import itertools
import os
import random
import pytest
from polyswarmd.utils.bloom import BloomFilter
@pytest.fixture
def log_entries():
def _mk_address():
return os.urandom(20)
def _mk_topic():
return os.urandom(32)
return [(_mk_address(), [_mk_topic()
fo... | python |
# -*- coding: utf-8 -*-
"""Unit test package for fv3config."""
| python |
from SimPy.SimulationRT import Simulation, Process, hold
import numpy as np
import scipy as sp
import scipy.io as spio
import networkx as nx
import matplotlib.pyplot as plt
import ConfigParser
from pylayers.util.project import *
import pylayers.util.pyutil as pyu
from pylayers.network.network import Network, Node, PNe... | python |
# Import libraries
from bs4 import BeautifulSoup
import requests
import psycopg2
import dateutil.parser as p
from colorama import Fore, Back, Style
# Insert the results to the database
def insert_datatable(numberOfLinks, selected_ticker, filtered_links_with_dates, conn, cur):
if filtered_links_with_dates:
... | python |
import random
import torch.nn as nn
import torch.nn.functional as F
from torch import LongTensor
from torch import from_numpy, ones, zeros
from torch.utils import data
from . import modified_linear
PATH_TO_SAVE_WEIGHTS = 'saved_weights/'
def get_layer_dims(dataname):
res_ = [1,2,2,4] if dataname in ['dsads'] els... | python |
from core.advbase import *
def module():
return Pia
class Pia(Adv):
conf = {}
conf['slots.a'] = [
'Dragon_and_Tamer',
'Flash_of_Genius',
'Astounding_Trick',
'The_Plaguebringer',
'Dueling_Dancers'
]
conf['slots.d'] = 'Vayu'
conf['acl'] = """
`dragon(c3-s-end), not en... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Benjamin Vial
# License: MIT
"""
The :mod:`pytheas.homogenization.twoscale2D` module implements tools for the
two scale convergence homogenization of 2D metamaterials for TM polarization
"""
from .femmodel import TwoScale2D
| python |
import os.path as osp
import numpy as np
import numpy.linalg as LA
import random
import open3d as o3
import torch
import common3Dfunc as c3D
from asm_pcd import asm
from ASM_Net import pointnet
"""
Path setter
"""
def set_paths( dataset_root, category ):
paths = {}
paths["trainset_path"] = osp.join(... | python |
import gym
import gym_maze
import copy
#env = gym.make("maze-random-10x10-plus-v0")
#env = gym.make("maze-sample-100x100-v0")
#env = gym.make("maze-random-30x30-plus-v0")
env_name= "maze-sample-10x10-v0"
env = gym.make(env_name)
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
max_steps = e... | python |
# program that asks user for number and prompts user to guess number untill the user guess the right number
# helen o'shea
# 20210211
import random
number = random.randint(0,100)
guess = int(input("Please guess the number between 0 and 100: "))
attempt = 1
while guess!=number:
if guess<number:
attempt +=1
... | python |
# -*- coding: utf-8 -*-
"""
Script to retrieve regobs data relevant for forecast analysis at NVE.
"""
__author__ = 'kmu'
import datetime as dt
import pandas as pd
from varsomdata import getobservations as go
def get_snow_obs(from_date, to_date):
all_data_snow = go.get_all_observations(from_date, to_date, geohaza... | python |
def f(*a<caret>rgs):
"""
""" | python |
#!/usr/bin/python
# This creates the level1 fsf's and the script to run the feats on condor
import os
import glob
studydir ='/mnt/40TB-raid6/Experiments/FCTM_S/FCTM_S_Data/Analyses'
fsfdir="%s/group/lvl2_B_hab_feats_v1"%(studydir)
subdirs=glob.glob("%s/1[0-9][0-9][0-9][0-9]"%(studydir))
#subdirs=glob.glob("%s/1830... | python |
import tempfile
import mdtraj
import pandas as pd
from kmbio import PDB
from kmtools import sequence_tools, structure_tools
from .distances_and_orientations import (
construct_residue_df,
construct_residue_pairs_df,
residue_df_to_row,
residue_pairs_df_to_row,
validate_residue_df,
validate_resi... | python |
# -*- coding: UTF-8 -*-
# Copyright (c) 2010 - 2014, Pascal Volk
# See COPYING for distribution information.
"""
vmm.password
~~~~~~~~~~~~~~~~~~~~~~~~~~~
vmm's password module to generate password hashes from
passwords or random passwords. This module provides following
functions:
hashed_p... | python |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.utils.translation import gettext as _
from .models import *
class MyUserCreationForm(UserCreationForm):
d... | python |
from memoria import *
class Filas():
def __init__(self, dic_process_id):
self.filas = [[],[],[],[]]
self.dic_process_id = dic_process_id
self.memoria = Memoria()
self.ultimo_executado = None
self.qtd_processos = len(dic_process_id) # qtd de processos.
se... | python |
def assert_keys_exist(obj, keys):
assert set(keys) <= set(obj.keys())
| python |
#!/usr/bin/env python3
import requests
from datetime import datetime, timedelta
import time
import numpy as np
import pandas as pd
import psycopg2
from psycopg2.extras import execute_values
import config as cfg
def connect_to_rds():
conn = psycopg2.connect(
host=cfg.HOST,
database=cfg.DATABASE,
... | python |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from itertools import product, count
from matplotlib.colors import LinearSegmentedColormap
# it produce more vectors pointing diagonally than vectors pointing along
# an axis
# # generate uniform unit vectors
# def generate_unit_vectors(n)... | python |
from aiogram import Dispatcher
from bulletin_board_bot.misc.user_data import UserDataStorage
from bulletin_board_bot.dependencies import DIContainer
from bulletin_board_bot.middlewares.di import DIContainerMiddleware
from bulletin_board_bot.middlewares.userdata import UserDataMiddleware
def setup_middlewares(dp: Dis... | python |
from django.contrib import admin
from core.models import Profile, BraFitting, Suggestion, Resource
# Register your models here.
@admin.register(BraFitting)
class BraFittingAdmin(admin.ModelAdmin):
pass
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
pass
@admin.register(Suggestion)
class Sugge... | python |
"""Tests for _get_tablename_schema_names association schemas function."""
import pytest
from open_alchemy.schemas import association
class TestGetTablenameSchemaNames:
"""Tests for _get_tablename_schema_names."""
# pylint: disable=protected-access
TESTS = [
pytest.param({}, set(), {}, id="empt... | python |
from django.template import Library
from ..classes import Menu, SourceColumn
register = Library()
def _navigation_resolve_menu(context, name, source=None, sort_results=None):
result = []
menu = Menu.get(name)
link_groups = menu.resolve(
context=context, source=source, sort_results=sort_results
... | python |
from esipy.client import EsiClient
from waitlist.utility.swagger.eve import get_esi_client
from waitlist.utility.swagger import get_api
from waitlist.utility.swagger.eve.universe.responses import ResolveIdsResponse,\
CategoriesResponse, CategoryResponse, GroupResponse, GroupsResponse,\
TypesResponse, TypeRespon... | python |
titulo = str(input('qual o titulo: '))
autor = str(input('escritor: '))
comando = ['/give @p written_book{pages:[', "'", '"','] ,title:', ',author:', '}', titulo, autor] #estrutura do comando
l = str(input('cole aqui: ')) #livro em si.
tl = len(l) #total de caracteres do livro
print(tl)
qcn = (tl/256) #quantidade... | python |
r"""
Super Partitions
AUTHORS:
- Mike Zabrocki
A super partition of size `n` and fermionic sector `m` is a
pair consisting of a strict partition of some integer `r` of
length `m` (that may end in a `0`) and an integer partition of
`n - r`.
This module provides tools for manipulating super partitions.
Super partiti... | python |
from ..job.job_context import JobContext
from ..task.task_context import TaskContext
from ..tc.tc_context import TcContext
class VerticalContext:
def __init__(self,
sys_conf_dict,
task_context: TaskContext = None,
job_context: JobContext = None,
... | python |
import numpy as np
import random
import heapq
from itertools import count
def time_fun(x, slope, shift):
return 1/(1+np.exp((slope*x - shift)))
class eligibility_trace():
def __init__(self, lambda_v, r, slope=3, shift=5):
self.E = 0
self.lambda_v = lambda_v
self.r = r
self.sl... | python |
'''
true_env = ["../../../../../../Downloads/data_timeoutsAndtransitions_acrobot/acrobot/online_learning/esarsa/step50k/gridsearch_realenv/"]
k1_notimeout = ["../../../../../../Downloads/data_timeoutsAndtransitions_acrobot/acrobot/offline_learning/knn-ensemble/k1_notimeout/esarsa/step10k/optimalfixed_eps0/"]
k1_timeout... | python |
# Copyright 2021 Universidade da Coruña
#
# 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 ... | python |
"""
Code for the paper "Mesh Classification with Dilated Mesh Convolutions."
published in 2021 IEEE International Conference on Image Processing.
Code Author: Vinit Veerendraveer Singh.
Copyright (c) VIMS Lab and its affiliates.
We adapt MeshNet to perform dilated convolutions by replacing the Stacked Dilated
Mesh Conv... | python |
from collections import namedtuple
import hexbytes
from eth_utils import is_checksum_address
from relay.signing import eth_sign, eth_validate, keccak256
EcSignature = namedtuple("EcSignature", "v r s")
class Order(object):
def __init__(
self,
exchange_address: str,
maker_address: str,
... | python |
#!/usr/bin/env python3
# Test whether a client subscribed to a topic receives its own message sent to that topic, for long topics.
from mosq_test_helper import *
def do_test(topic, succeeds):
rc = 1
mid = 53
keepalive = 60
connect_packet = mosq_test.gen_connect("subpub-qos0-test", keepalive=keepalive... | python |
import numpy as np
from pydeeprecsys.rl.agents.agent import ReinforcementLearning
from typing import Any, List, Optional
from pydeeprecsys.rl.experience_replay.experience_buffer import ExperienceReplayBuffer
from pydeeprecsys.rl.experience_replay.buffer_parameters import (
ExperienceReplayBufferParameters,
)
from p... | python |
# -*- coding: utf-8 -*-
# Copyright 2022 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... | python |
from source.exceptions.not_found import NotFoundException
from source.repositories.player_tournament import PlayerTournamentRepository
import source.commons.message as message
class PlayerTournamentBusiness:
def __init__(self):
self.player_tournament_repository = PlayerTournamentRepository()
def fin... | python |
from datetime import datetime
from pathlib import Path
from typing import Optional, Tuple, Union, Sequence, List
from pydantic import BaseModel, validator
class MdocSectionData(BaseModel):
"""Data model for section data in a SerialEM mdoc file.
https://bio3d.colorado.edu/SerialEM/hlp/html/about_formats.htm
... | python |
from logging import getLogger
from typing import List
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import backref, relationship
from app.models import orm
from app.settings import env_settings
logger = getLogger(__name__)
class Acto... | python |
import numpy as np
import pandas as pd
import os
import sklearn
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
# normalize numerical columns
# one-hot categorical columns
def get_data(classification=True, regression=False, download=False):
url = 'https://raw.githubusercontent.com/Shane-Nee... | python |
import logging, sys, os, json, uuid
from datapackage_pipelines.wrapper import ingest, spew
from datapackage_pipelines.utilities.resources import PROP_STREAMING
CLI_MODE = len(sys.argv) > 1 and sys.argv[1] == '--cli'
if CLI_MODE:
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logg... | python |
#!/usr/bin/python
import logging
import os
import json
import io
import uuid
# --------------------------------------------------------------------------------------
# Save this code in file "process_wrapper.py" and adapt as indicated in inline comments.
#
# Notes:
# - This is a Python 3 script.
# - The inputs will... | python |
from spec2wav.modules import Generator, Audio2Mel, Audio2Cqt
from pathlib import Path
import yaml
import torch
import os
def get_default_device():
if torch.cuda.is_available():
return "cuda"
else:
return "cpu"
def load_model(spec2wav_path, device=get_default_device()):
"""
Args:
... | python |
from app import app
app.run('0.0.0.0') | python |
import concurrent.futures as cf
import numpy as np
from multiprocessing import cpu_count
from tqdm import tqdm
from worms.util import jit, InProcessExecutor
from worms.search.result import ResultJIT
from worms.clashgrid import ClashGrid
def prune_clashes(
ssdag,
crit,
rslt,
max_clash_check=-1,... | python |
import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from ResNet import ResNet
import argparse
from utils import *
import time
from common.utils import allocate_gpu
def find_next_time(path_list, default=-1):
if default > -1:
return default
run_times = [int(path.split('_')[0]) for path in path_list]
... | python |
#!/usr/bin/env python
# Copyright (C) 2015 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this li... | python |
import os,sys
model = sys.argv[1]
stamp = int(sys.argv[2])
lr = float(sys.argv[3])
dropout = float(sys.argv[4])
bsize = int(sys.argv[5])
filein = 'test_result/' + model + '_' + str(dropout) + '_' + str(lr) + '_x_test.npy'
fileout = 'test_result/' + model + '_' + str(dropout) + '_' + str(lr) + '_x_test_' + str(stamp) ... | python |
from tkinter import *
from tkinter.ttk import Combobox
from qiskit import IBMQ
import qiskit
import math
# THIS PART IS THE QUANTUM SHIT SO PUCKER YOUR BUTTHOLES
_backend = qiskit.BasicAer.get_backend('qasm_simulator')
_circuit = None
_bitCache = ''
def setqbits(n):
global _circuit
qr = qiskit.QuantumRegiste... | python |
from selenium import webdriver
from bs4 import BeautifulSoup
import time
driver = webdriver.PhantomJS()
client_info_search_url = "https://xclient.info/search/s/"
app_list = ["cleanmymac", "alfred", "betterzip", "beyond compare", "iina", "Navicat Premium", "charles", "DaisyDisk",
"paw", "Typora"]
class u... | python |
__author__='Pablo Leal'
import argparse
from keras.callbacks import LambdaCallback
import trainer.board as board
import trainer.loader as loader
import trainer.modeller as modeller
import trainer.saver as saver
from trainer.constans import BATCH_SIZE, CHECKPOINT_PERIOD
from trainer.constans import EPOCHS
from train... | python |
# -*- coding: utf-8 -*-
"""
awsecommerceservice
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class ItemSearchRequest(object):
"""Implementation of the 'ItemSearchRequest' model.
TODO: type model description here.
Attributes:
actor (string): TODO:... | python |
a, b, c = map(int, input().split())
print((a+b)%c)
print((a%c+b%c)%c)
print((a*b)%c)
print((a%c*b%c)%c) | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#===============================================================================
from __future__ import unicode_literals
#===============================================================================
def read_input(strip=True):
return raw_input().strip() if strip el... | python |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import re
from typing import Any
import pytest
from _pytest.python_api import RaisesContext
from omegaconf import DictConfig, OmegaConf
from hydra._internal import utils
from hydra._internal.utils import _locate
from hydra.types import ObjectConf
... | python |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'QuestionnaireText'
db.create_table('cmsplugin_questionnairetext', (
('cmsplugin_... | python |
def fibonacci(n):
for i in range(n+1):
fibo = [0, 1]
if i == 0:
print ("fibo( 0 ) = ", 0)
elif i == 1:
print ("fibo( 1 ) = ", 1)
else:
flag = True
for j in range(2, i):
if flag: # Replace first element fibonacci(n) + fib... | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
'''
Contains function to identify bad channels based on time and freq domain
methods.
authors: Niko Kampel, n.kampel@gmail.com
Praveen Sripad, pravsripad@gmail.com
'''
import numpy as np
import mne
from sklearn.cluster import DBSCAN
from sklearn.metrics.pairwis... | python |
#!/usr/bin/python
# coding=utf-8
################################################################################
from __future__ import with_statement
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collecto... | python |
"""Testing phantombuild."""
import tempfile
from pathlib import Path
import pytest
import phantombuild as pb
from phantombuild.phantombuild import (
CompileError,
HDF5LibraryNotFound,
PatchError,
RepoError,
)
VERSION = '3252f52501cac9565f9bc40527346c0e224757b9'
def test_get_phantom():
"""Test ... | python |
import os
import time
from github import Github
from django.db import models
from calaccess_raw import get_model_list
from django.template.loader import render_to_string
from calaccess_raw.management.commands import CalAccessCommand
class Command(CalAccessCommand):
help = 'Create GitHub issues for fields missing ... | python |
"""
just run this script with python converter.py .
It will convert pytorch.ipynb to html page docs/pytorch-examples.html
"""
import nbformat
import markdown
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
notebook = nbformat.read('Pytorch.ipynb', ... | python |
#!/usr/bin/env python3
"""This is an example to train a task with CMA-ES.
Here it runs CartPole-v1 environment with 100 epoches.
Results:
AverageReturn: 100
RiseTime: epoch 38 (itr 760),
but regression is observed in the course of training.
"""
from metarl import wrap_experiment
from metarl.envs... | python |
import uvicorn
from .main import app
uvicorn.run(app)
| python |
import collections
from torch.optim.lr_scheduler import LambdaLR
def chunk(seq, num):
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return out
def flatten(d, parent_key='', sep='__'):
items = [... | python |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import scipy
import random
# Titan modules
import create_model
## Generate initial data set
N = 400
sig3 = 1 # 3-sigma error (controls the statistical fluctuation)
a = 10 # radius of the helix
b = 33/(2*np.pi) # 2*pi*b ... | python |
from ast.Expresion import Expresion
from ast.Symbol import Symbol
from ast.Expresion import Expresion
from ast.Symbol import TIPOVAR as Tipo
from ast.Sentencia import Sentencia
import Reportes.ReporteD as Sentencias
class Select(Sentencia):
#SELECT selectclausules FROM selectbody wherecondicion
#Selecttable :... | python |
"""Function wrapping logic."""
import importlib
import os
import sys
import logging
import tempfile
import atexit
import functools
import typing
import traceback
from flask import request
import dploy_kickstart.errors as pe
import dploy_kickstart.transformers as pt
import dploy_kickstart.annotations as pa
log = lo... | python |
#!/usr/bin/python
# minimal imports for faster startup
import os
from logger import logger
def run():
import time
import sys
import signal
import json
os.environ["QT_QPA_PLATFORM"] = "xcb" # window oddly resizes when regaining focus
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, ... | python |
from __future__ import print_function, absolute_import
import abc
import six
from lazy import lazy
from pyreference.utils.genomics_utils import iv_from_pos_range, \
iv_from_pos_directional_before_after, dict_to_iv
class GenomicRegion(object):
""" Base class for both Gene and Transcript """
def __init__(... | python |
import os
import dill
import unittest
import collections
from swamp.utils import remove
from swamp.mr.mrresults import MrResults
RESULTS = collections.namedtuple('results', ['results'])
WORKDIR = os.path.join(os.environ['CCP4_SCR'], 'test_workdir')
MR_DIR = os.path.join(WORKDIR, 'swamp_mr')
class MrResultsTestCase(u... | python |
import functools
import itertools
import math
from evm.constants import (
UINT_255_MAX,
UINT_256_CEILING,
)
def int_to_big_endian(value):
byte_length = math.ceil(value.bit_length() / 8)
return (value).to_bytes(byte_length, byteorder='big')
def big_endian_to_int(value):
return int.from_bytes(val... | python |
"""
Copyright 2014-2016 University of Illinois
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 |
"""
A complex number is a number in the form a + b * i where a and b are real and i satisfies i^2 = -1.
`a` is called the real part and `b` is called the imaginary part of `z`.
The conjugate of the number `a + b * i` is the number `a - b * i`.
The absolute value of a complex number `z = a + b * i` is a... | python |
"""
Module: 'sys' on pyboard 1.13.0-95
"""
# MCU: (sysname='pyboard', nodename='pyboard', release='1.13.0', version='v1.13-95-g0fff2e03f on 2020-10-03', machine='PYBv1.1 with STM32F405RG')
# Stubber: 1.3.4
argv = None
byteorder = 'little'
def exit():
pass
implementation = None
maxsize = 2147483647
modules = None
p... | python |
# Copyright 2009-2010 10gen, Inc.
#
# 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,... | python |
#!/usr/bin/python
#:deploy:OHsentinel:/usr/local/bin
#standard imports
import sys
import ConfigParser
import logging
import os
#custom imports
if os.path.isdir("/usr/local/share/OHsentinel"):
sys.path.append("/usr/local/share/OHsentinel")
elif os.path.isdir("/usr/share/OHsentinel"):
sys.path.append("/usr/share/OHs... | python |
import unittest
from policosm.utils.levels import get_level
class LevelsTestCase(unittest.TestCase):
def test_known(self):
for highway in ['construction', 'demolished', 'raceway', 'abandoned', 'disused', 'foo', 'no','projected', 'planned','proposed','razed','dismantled','historic']:
self.asse... | python |
import torch
import torch.nn as nn
from torchsummary import summary
from lib.medzoo.BaseModelClass import BaseModel
"""
Code was borrowed and modified from this repo: https://github.com/josedolz/HyperDenseNet_pytorch
"""
def conv(nin, nout, kernel_size=3, stride=1, padding=1, bias=False, layer=nn.Conv2d,
B... | python |
from sht3x_raspberry_exporter.sht3x import _crc8
def test_crc8():
assert _crc8(0xBE, 0xEF, 0x92) | python |
import choraconfig, os.path
tool = choraconfig.clone_tool("chora")
tool["displayname"] = "CHORA:sds"
tool["shortname"] = "chora:sds"
tool["cmd"] = [choraconfig.parent(2,choraconfig.testroot) + "/duet.native","-chora-debug-recs","-chora-summaries","-chora-debug-squeeze","-chora","{filename}"]
| python |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import numpy as np
from ...core.loop.candidate_point_calculators import RandomSampling
from ...core.loop.loop_state import create_loop_state
from ...core.loop.model_updaters import NoopModelUpdater
from ...... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.