content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
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... | nilq/baby-python | 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
... | nilq/baby-python | 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... | nilq/baby-python | python |
def f(*a<caret>rgs):
"""
""" | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | python |
def assert_keys_exist(obj, keys):
assert set(keys) <= set(obj.keys())
| nilq/baby-python | 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,
... | nilq/baby-python | 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)... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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
... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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,
... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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 ... | nilq/baby-python | 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... | nilq/baby-python | 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,
... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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
... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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:
... | nilq/baby-python | python |
from app import app
app.run('0.0.0.0') | nilq/baby-python | 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,... | nilq/baby-python | 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]
... | nilq/baby-python | 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... | nilq/baby-python | 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) ... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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:... | nilq/baby-python | 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) | nilq/baby-python | 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... | nilq/baby-python | 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
... | nilq/baby-python | 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_... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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 ... | nilq/baby-python | 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 ... | nilq/baby-python | 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', ... | nilq/baby-python | 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... | nilq/baby-python | python |
import uvicorn
from .main import app
uvicorn.run(app)
| nilq/baby-python | 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 = [... | nilq/baby-python | 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 ... | nilq/baby-python | 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 :... | nilq/baby-python | 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... | nilq/baby-python | 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, ... | nilq/baby-python | 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__(... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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,... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | 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... | nilq/baby-python | python |
from sht3x_raspberry_exporter.sht3x import _crc8
def test_crc8():
assert _crc8(0xBE, 0xEF, 0x92) | nilq/baby-python | 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}"]
| nilq/baby-python | 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 ...... | nilq/baby-python | python |
ar = [float(i) for i in input().split()]
ar_sq = []
for i in range(len(ar)):
ar_sq.append(ar[i]**2)
ar_sq = sorted(ar_sq)
print(ar_sq[0], end = ' ')
for i in range(1, len(ar_sq)):
if ar_sq[i] != ar_sq[i-1]:
print(ar_sq[i], end = ' ')
| nilq/baby-python | python |
from chroniclr import window
if __name__ == '__main__':
window = window.AppWindow() | nilq/baby-python | python |
import atexit
import sys
import inspect
import json
import time
from .Autocomplete import Autocomplete
from .Connection import Connection, ConnectionError
from .Controller import Controller, ControllerError, parse_key
from .Device import (Device, DeviceError, parse_hex, parse_hsv,
parse_hsv_normal... | nilq/baby-python | python |
# pylint: disable=redefined-outer-name
""" py.test dynamic configuration.
For details needed to understand these tests, refer to:
https://pytest.org/
http://pythontesting.net/start-here/
"""
# Copyright © {{ cookiecutter.year }} {{ cookiecutter.full_name }} <{{ cookiecutter.email }}>
#
# ## LICENS... | nilq/baby-python | python |
import subprocess
import codecs
goal_goals = []
#txt_dirs = ['ted_originals/', 'ted_transcripts/']
#txt_dirs = ['orig_lower/']
txt_dirs = ['trans_preprocessed/', 'orig_preprocessed/']
for txt_dir in txt_dirs:
with codecs.open('goal_goals.txt') as goal_goals_in:
for line in goal_goals_in:
if li... | nilq/baby-python | python |
import unittest
import os
NOT_FATAL = 0
iverilog = "iverilog -y./tb -y./main_unit/ -o ./tb/main_unit__adc_capture__tb.vvp ./tb/main_unit__adc_capture__tb.v"
vvp = "vvp ./tb/main_unit__adc_capture__tb.vvp"
class adc_capture(unittest.TestCase):
def test_adc_capture(self):
self.assertEqual(os.system(iverilog), NOT... | nilq/baby-python | python |
import random
import math
import sys
import copy
# import os
class Bracket:
def __init__(self, teams):
self.numTeams = 1
# self.numTeams = len(teams)
self.teams = list(teams)
self.maxScore = len(max(["Round "]+teams, key=len))
self.numRounds = int(math.ceil(math.log(self.nu... | nilq/baby-python | python |
import re
import numpy
import os
import pdb
### INPUT FILES
rd_folder = "../raw_data/"
traits_file = rd_folder+"data_dental_master.csv"
bio_file_all = rd_folder+"data_sites_IUCN_narrowA.csv"
occurence_file = rd_folder+"occurence_IUCN_%s.csv"
bio_legend_file = rd_folder+"bio_legend.txt"
### OUTPUT FILES
pr_folder = ".... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2020 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
from torchvision.models import resnet
class BasicBlock1d(nn.Module):
def __init__(self, inplanes, planes, stride, size,downsample):
super(BasicBlock1d, self).__init__()
self... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from sqlalchemy import MetaData
from py_privatekonomi.utilities import common
class ModelContext(object):
def __init__(self, context = {}):
self.__context = common.as_obj(context)
self.__context._metadata = MetaData... | nilq/baby-python | python |
from setuptools import setup
setup(
name = 'json2html',
packages = ['json2html'],
version = '1.3.0',
description = 'JSON to HTML Table Representation',
long_description=open('README.rst').read(),
author = 'Varun Malhotra',
author_email = 'varun2902@gmail.com',
url = 'https://github.com... | nilq/baby-python | python |
class Solution:
# @param {integer} A
# @param {integer} B
# @param {integer} C
# @param {integer} D
# @param {integer} E
# @param {integer} F
# @param {integer} G
# @param {integer} H
# @return {integer}
def computeArea(self, A, B, C, D, E, F, G, H):
def area(x, y):
... | nilq/baby-python | python |
def roll_new(name, gender):
pass
def describe(character):
pass | nilq/baby-python | python |
"""Integrate with NamecheapDNS."""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.const import CONF_HOST, CONF_ACCESS_TOKEN, CONF_DOMAIN
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_time_interval
from... | nilq/baby-python | python |
celsius = float(input('Insira a temperatura em °C:'))
fahrenheit = celsius * 1.8 + 32
kelvin = celsius + 273.15
print(f'{celsius}°C vale {fahrenheit}°F e {kelvin}K.')
| nilq/baby-python | python |
"""
A Python package module for simulating falling objects with simple aerodynamic drag.
Developed by FIRST Robotics Competition Team 6343 - Steel Ridge Robotics
Strong
Trustworthy
Empowering
Effective
Leadership
"""
__VERSION__ = "1.0.0b1"
| nilq/baby-python | python |
"""
pluginName = dashcam
Senario Continuous Video Series like a Dashcam
----------------------------------------------
You want to take a series of videos like a dash cam.
You can manage disk space and delete oldest videos when disk
is close to full or run video session for a set number of minutes.
Edit the settings ... | nilq/baby-python | python |
load_dotenv('.env.txt') | nilq/baby-python | python |
import discord
from discord.ext import commands
from cogs.utils import checks
from .utils.dataIO import dataIO, fileIO
from __main__ import send_cmd_help
import os
import io
import requests
import json
import asyncio
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
creditIcon = "htt... | nilq/baby-python | python |
"""
Module to implement a plugin that looks for hard tabs in the files.
"""
from pymarkdown.plugin_manager import Plugin, PluginDetails
class RuleMd040(Plugin):
"""
Class to implement a plugin that looks for hard tabs in the files.
"""
def get_details(self):
"""
Get the details for th... | nilq/baby-python | python |
from django.dispatch import Signal
# providing_args: "orderId", "recipientAmount"
result_received = Signal()
| nilq/baby-python | python |
"""
Generic module for managing manual data transfer jobs using Galaxy's built-in file browser.
This module can be used by various external services that are configured to transfer data manually.
"""
import logging, urllib2, re, shutil
from data_transfer import *
log = logging.getLogger( __name__ )
__all__ = [ 'Manua... | nilq/baby-python | python |
# coding: utf-8
# In[36]:
# In[39]:
import numpy as np
import powerlaw
edges= np.array([[1,2],[0,2],[0,3],[2,3],[3,4],[4,1]])
class karpatiGraphSolution:
def __init__(self,edges):
assert type(edges)==np.ndarray, "input is not an edge list"
self.edgeList=edges
self.numNodes=np.amax(edg... | nilq/baby-python | python |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
class GuildManagerAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('GuildManagerAI')
| nilq/baby-python | python |
from xviz.builder.base_builder import XVIZBaseBuilder, CATEGORY
from xviz.v2.core_pb2 import Pose, MapOrigin
class XVIZPoseBuilder(XVIZBaseBuilder):
"""
# Reference
[@xviz/builder/xviz-pose-builder]/(https://github.com/uber/xviz/blob/master/modules/builder/src/builders/xviz-pose-builder.js)
"""
def... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.