content stringlengths 5 1.05M |
|---|
import io
import os
import re
import time
from unit.applications.lang.java import TestApplicationJava
from unit.option import option
from unit.utils import public_dir
class TestJavaApplication(TestApplicationJava):
prerequisites = {'modules': {'java': 'all'}}
def test_java_conf_error(self, temp_dir, skip_ale... |
from collections import Counter, Iterable, defaultdict
from itertools import chain, islice, product
from warnings import warn
import Bio.Data.CodonTable
import numpy as np
from Bio.Seq import Seq
# create the genetic_codes and codons_for_aa dicts
genetic_codes = {}
codons_for_aa = {}
synonymous_codons = {}
for code_... |
import numpy as np
import pandas as pd
def plot_turbine(HR_coord,power):
for i in range(HR_coord.shape[0]):
color_value = power[i,:]/np.max(power)
point1 = [HR_coord[i,0]-1.5*np.sin(HR_coord[i,2]),HR_coord[i,1]+1.5*np.cos(HR_coord[i,2])]
point2 = [HR_coord[i,0]+1.5*np.sin(HR_coord[i,2]),HR... |
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db=SQLAlchemy()
class Flight(db.Model):
__tablename__="flights"
id = db.Column(db.Integer,primary_key=True)
origin = db.Column(db.String,nullable=False)
destination = db.Column(db.String,nullable=False)
duration = db.C... |
import csv
import os
import difflib
import statistics
import matplotlib.pyplot as plt
SMALL_SIZE = 12
MEDIUM_SIZE = 14
LARGE_SIZE = 18
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
# plt.rc('title', titlesize=MEDIUM_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=LARGE_SIZE, ... |
import re
import sys
sys.path.append("../../../..")
from text import *
#import importlib
#import os
#import pdb
#----------------------------------------------------------------------------------------------------
text = Text("../../../../testData/harryMosesDaylight/daylight_1_4.eaf",
"../../../../testData/... |
# proxy module
from kiva.trait_defs.kiva_font_trait import *
|
import pandas as pd
def read_table(path):
'''
Read a csv file and return a DataFrame object
Params:
path(str): file's path
'''
df = pd.read_csv(path, encoding='utf-8')
return df
|
# Written by Kamran Bigdely
# Example for Compose Methods: Extract Method.
import math
def print_stat():
'''Prints Statistics'''
grade_list = []
# Get the inputs from the user
n_student = 5
for _ in range(0, n_student):
grade_list.append(int(input('Enter a number: ')))
mean = ... |
#!c:\users\whq672437089\envs\engr597\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
import os
path = "score.txt"
res = 0
cnt = 0
with open(path) as f:
string = f.readlines()
for line in string:
res += float(line.split()[2])
cnt += 1
print(f"合計: {res}")
print(f"平均: {res / cnt}")
|
# Generated by Django 3.0.5 on 2020-05-01 08:04
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Dictionary',
fields=[
('id', models.AutoFie... |
from random import choice
import requests
'''
this simple funciton in py language return a list with very random names
'''
def main() -> list:
names = []
names_and_surname = []
for x in range(0, 10):
api = requests.get('http://gerador-nomes.herokuapp.com/nomes/10')
for name in api.json()... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#import usefull stuff
import csv
#defining the analysis function
def ymaze():
with open("ymazeanalysis.csv", mode="a", newline="") as f:
writer = csv.writer(f, delimiter=",")
print("enter the animal code, then the abc string")
animal = input... |
# 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, software
# distrib... |
# -*- coding: utf-8 -*-
# This module contains some defaults for the logging system.
import logging
import sys
LOG_FORMATTER = logging.Formatter(
"%(asctime)s :: %(name)s :: %(levelname)-7s :: %(message)s",
datefmt='%a, %d %b %Y %H:%M:%S')
CONSOLE_HANDLER = logging.StreamHandler(sys.stdout)
CONSOLE_HANDLER... |
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.title("Tela de exemplo")
#funções
def subtracao():
subtracao = float(ent1.get())-float(ent2.get())
messagebox.showinfo('Resultado', "A subtracao deu: {}".format(subtracao))
#componentes:
lbl1 = tk.Label(window, text = "Numero 1: ")
... |
from __future__ import division, absolute_import, print_function
import numpy as np
from numpy.testing import TestCase, run_module_suite, assert_array_almost_equal
from numpy.testing import assert_array_equal
import threading
import sys
if sys.version_info[0] >= 3:
import queue
else:
import Queue as queue
de... |
import pytest
from unittest.mock import mock_open
from yml_reader import YmlReader
@pytest.fixture
def unit_under_test(mocker):
return YmlReader("test_file")
def test_read_file_exists(unit_under_test, mocker):
mocker.patch('os.path.isfile', return_value=True)
mocker.patch('builtins.open', mock_open())
... |
def arithmetic_arranger(problems, print_ans = False):
count = 1
if len(problems)>5:
return "Error: Too many problems."
line_1 = ""
line_2 = ""
dash_line = ""
ans_line = ""
for problem in problems:
chars = problem.split()
try :
num1 = int(chars[0])
operator = chars[1]
n... |
import os
os.path.getmtime("aspiration.pdf")
#time stamp, unix jan first 1970 |
#!/usr/bin/env python3
import hashlib
import os
import datetime
import argparse
import time
def size_of_file(full_path_file):
return int(os.path.getsize(full_path_file))
def hash_of_file(full_path_file):
block_size = 512 * 1024 * 1024 # 512 MB
md5 = hashlib.md5()
with open(full_path_file, "rb")... |
# Generated by Django 2.2.10 on 2021-04-21 08:11
from django.db import migrations, models
import django.db.models.deletion
import muni_portal.core.models
class Migration(migrations.Migration):
dependencies = [
("core", "0037_auto_20210326_0554"),
]
operations = [
migrations.AlterField(
... |
# Generated by Django 3.0.5 on 2020-07-24 20:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quotas', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='userquota',
name='max_file_size',
... |
#author:rujia
#website:www.rujia.uk
#version:1.0
from flask import session,request
from . import app
from core import blind_demo
from core import until
@app.route("/setParamsUser", methods=['GET'])
def setParamsUser():
try:
uid = until.get_mac_address()
secp = session.get(uid+'secp')
... |
#!/usr/bin/env python3
# ================================================================================
# -- File: day_05/05_code.py
# -- Project: advent-of-code-2020
# -- Project URL: https://adventofcode.com/2020/
# -- Create Date: 2020-12-05 18:41
# -- Author: moosploit
# -- Company: ... |
# Copyright 2015 Mirantis, 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 ... |
import vast.io_mesh as io
import numpy as np
import h5py
import vast.volume_tools as vt
import vast.surface_tools as st
from functools import partial
import concurrent.futures
import os
import vast.math_helpers as mh
import time
class SurfaceVolumeMapper(object):
def __init__(self, white_surf=None, gray_surf... |
#!/usr/bin/python3
import binascii
import errno
import math
import os
import subprocess
import sys
import parted
from hemeraplatformsdk.imagebuilders.devices.BaseDevice import BaseDevice
from hemeraplatformsdk.imagebuilders.devices.BaseDevice import ExtractedFileTooBigException
from hemeraplatformsdk.imagebuilders.d... |
# Copyright (c) 2021 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import io
import logging
import pytest
from inators import log as inat... |
from mayan.apps.dependencies.classes import PythonDependency
PythonDependency(
module=__name__, name='gevent', version_string='==20.4.0'
)
PythonDependency(
module=__name__, name='gunicorn', version_string='==20.0.4'
)
PythonDependency(
module=__name__, name='whitenoise', version_string='==5.0.1'
... |
from django.shortcuts import render_to_response, redirect
from django.contrib import messages
from django.template import RequestContext
from django.contrib.sites.models import Site
from django.shortcuts import render_to_response, redirect
from django.contrib.auth.models import User
from registration.models import Regi... |
"""Data model and functions for Tapis apps
"""
from tapis_cli.commands.taccapis.v2 import SERVICE_VERSION
from tapis_cli.commands.taccapis import TapisModel
from tapis_cli.display import Verbosity
from tapis_cli.search import argtype, argmod
__all__ = ['Metadata', 'API_NAME', 'SERVICE_VERSION']
API_NAME = 'meta'
cl... |
# WARNING: Please don't edit this file. It was generated by Python/WinRT
from pyrt import _import_ns
import typing
import enum
__ns__ = _import_ns("Windows.Media")
try:
import pyrt.windows.applicationmodel.appservice
except:
pass
try:
import pyrt.windows.foundation
except:
pass
try:
import pyrt... |
from PIL import Image, ImageDraw, ImageFont # type: ignore
from view import View
class Label(View):
def __init__(self, text: str, width: int = None, color: int = 0xffffff, font: ImageFont = None) -> None:
self.text = text
self.color = color
self.font = font or ImageFont.load_default()
... |
from sqlalchemy.orm import relationship
from zeeguu_core.model.feed import db, RSSFeed
from zeeguu_core.model.user import User
import sqlalchemy
class RSSFeedRegistration(db.Model):
__table_args__ = {'mysql_collate': 'utf8_bin'}
__tablename__ = 'rss_feed_registration'
id = db.Column(db.Integer, primary_... |
import asyncio
import pandas as pd # type: ignore
import pyEX # type: ignore
from collections import deque
from datetime import datetime, timedelta
from tqdm import tqdm # type: ignore
from aat.exchange import Exchange
from aat.config import InstrumentType, EventType, Side, TradingType
from aat.core import ExchangeT... |
import warnings
import math
import struct
import pyctrl.block as block
import pyctrl.bbb.mpu9150 as mpu9150
import numpy
class Raw(block.Block):
def read(self):
#print('> read')
if self.enabled:
# read imu
self.output = mpu9150.read()
#print('< read')
... |
#!/usr/bin/env python
__author__ = 'Will Kamp'
__copyright__ = 'Copyright 2013, Matrix Mariner Inc.'
__license__ = 'BSD'
__email__ = 'will@mxmariner.com'
__status__ = 'Development' # 'Prototype', 'Development', or 'Production'
'''This is a database of sorts for nautical chart regions, their providing hydro-graphic o... |
"""Just a quick routine for resampling committor analysis results with a new settings object and without assuming the
existence of a restart.pkl file in the working directory."""
import os
import re
import glob
import shutil
from atesa import factory
from atesa import main
def resample_committor_analysis(settings):
... |
# Copyright (c) 2013, Jeff Terrace
# All rights reserved.
"""Module for connecting to and controlling the Logitech Harmony Link"""
|
# This Python module is part of the PyRate software package.
#
# Copyright 2021 Geoscience Australia
#
# 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/... |
"""
统计标注文件 xml 文件中图片的尺寸信息,宽高和深度
"""
import sys
import os
import matplotlib.pyplot as plt
import numpy as np
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
ann_path = "E:/VOC/VOC2007/Annotations/" # xml 文件所在的路径
xml_file_list = [ann_path+i for i in os... |
import logging
import sys
import arrow
import requests
GROUPME_NO_MESSAGE_STATUS_CODE = 304
# logging setup
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
stdoutput = logging.StreamHandler(sys.stdout)
stdoutput.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s... |
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from amu_bachelor_thesis_app.models import User
@login_required
def login_redirect(request):
if not request.user.is_authenticated:
return HttpResponse('Unau... |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
''' IMPORTS '''
# disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' GLOBAL VARS '''
SERVER_NAME = demisto.params()['server']
USERNAME = demisto.params()['credentials']['identifier']
PASSWORD = demisto.p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : MeUtils.
# @File : np_utils
# @Time : 2020/11/12 11:35 上午
# @Author : yuanjie
# @Email : yuanjie@xiaomi.com
# @Software : PyCharm
# @Description :
import numpy as np
# 分组
# np.array_split(range(6), 3)
# iteration_utili... |
# Generated by Django 2.0 on 2017-12-25 05:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20171221_0621'),
]
operations = [
migrations.AddField(
model_name='game',
name='num_players',
... |
from django.core.cache import cache
from datetime import datetime
from museum_site.models.detail import Detail
from museum_site.models.file import File
from museum_site.constants import TERMS_DATE
from museum_site.common import (
DEBUG, EMAIL_ADDRESS, BOOT_TS, CSS_INCLUDES, UPLOAD_CAP, env_from_host,
qs_sans
... |
# -*- coding: utf-8
import sys
import os
import io
import stat
import errno
import operator
import functools
from . import os, strings, collections
from .itertools import filterfalse
from .operator import methodcaller, identity as _sanitize_path_sep
from zipfile import *
import zipfile as _zipfile
__all__ = _zipfile._... |
import base64
import hashlib
import hmac
import json
import re
import time
from collections import defaultdict
import numpy as np
import pandas as pd
import pytz
import requests
# import six
from six import iteritems
from catalyst.assets._assets import TradingPair
from logbook import Logger
from catalyst.exchange.exc... |
"""
Intended to be imported by a lambda through 'package_objects'
"""
MAGIC_VALUE = 21
def magic_function():
return MAGIC_VALUE
|
"""
Set operations for arrays based on sorting.
:Contains:
unique,
isin,
ediff1d,
intersect1d,
setxor1d,
in1d,
union1d,
setdiff1d
:Notes:
For floating point arrays, inaccurate results may appear due to usual round-off
and floating point comparison issues.
Speed could be gained in some operations by ... |
from __future__ import division
from __future__ import print_function
import math
import mxnext as X
from models.retinanet.builder import RetinaNetHead
class FreeAnchorRetinaNet(object):
def __init__(self):
pass
@staticmethod
def get_train_symbol(backbone, neck, head):
gt_bbox = X.var("... |
"""
Java processes running on a machine.
"""
|
# Copyright 2016, 2021 John J. Rofrano. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
# BlooP allows only bounded loops (for loop with predetermined set of values)
def two_to_the_three_to_the(n):
three_pow = 1
for i in range(n):
three_pow = three_pow * 3
two_pow = 1
for i in range(three_pow):
two_pow = two_pow * 2
print(two_pow)
def is_prime(n):
if n == 0:
... |
# You are given a string S. Find the lexicographically smallest string S′ obtained by permuting the characters of S.
# Here, for different two strings s=s1s2…sn and t=t1t2…tm, s<t holds lexicographically when one of the conditions below is satisfied.
# There is an integer i (1≤i≤min(n,m)) such that si<ti and sj... |
#!/usr/bin/env python
import rospy
import cv2
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import CompressedImage, Image
import numpy as np
class ImageAverage(object):
def __init__(self):
# Save the name of the node
self.node_name = rospy.get_name()
rospy.logi... |
import os
import glob
import argparse
from argparse import RawTextHelpFormatter
from subprocess import call
import imageio as imgio
import numpy as np
import skimage
from swc_to_tiff_stack import swc_to_tiff_stack
parser = argparse.ArgumentParser(add_help=True, \
description='Trace fil... |
import streamlit as st
import datetime
from store_page import *
from cart_page import *
from market_page import *
from db_functions import *
from register_page import *
from order_history import *
def main():
st.title("Kroger Market")
pages = {
"Market": market_page,
"Cart": cart_page,
... |
import pyttsx3
friend = pyttsx3.init()
speech = input("Say Something: ")
friend.say(speech)
friend.runAndWait() |
"""
Tests for prediction pipeline
"""
import pytest
from eogrow.utils.testing import create_folder_dict, run_and_test_pipeline
@pytest.fixture(scope="session", name="folders")
def config_folder_fixture(config_folder, stats_folder):
return create_folder_dict(config_folder, stats_folder, "mapping")
@pytest.mark.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##
# @file simo_swt_classification_tut.py
# @author Kyeong Soo (Joseph) Kim <kyeongsoo.kim@gmail.com>
# @date 2018-08-23
#
# @brief A scalable indoor localization system based on Wi-Fi fingerprinting
# using a stage-wise trained multi-class classification ... |
"""Base schema module"""
from marshmallow import Schema, fields
from ..utilities.error_handler.handle_error import ValidationError
class BaseSchema(Schema):
"""Base schema for all models"""
id = fields.String(dump_only=True)
created_at = fields.String(dump_only=True, dump_to='createdAt')
updated_at =... |
import sys
from typing import List
from models import ApiResponse
from inference.errors import Error
from starlette.responses import FileResponse
from starlette.staticfiles import StaticFiles
from starlette.middleware.cors import CORSMiddleware
from deep_learning_service import DeepLearningService
from fastapi import F... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Test")
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(
'/store/relval/CMSSW_3_2_1/RelValSingleMuPt100/GEN-SIM-RECO/MC_31X_V3-v1/0006/DC15F12B-9477-DE11-B1E0-000423D98C20.root',
'/store/relval/CMSSW_3_2_1/... |
"""pynetdicom configuration options"""
LOG_HANDLER_LEVEL = 'standard'
"""Default (non-user) event logging
* If ``'none'`` then events will not be logged at all, however there will still
be some logging (warnings, errors, etc)
* If ``'standard'`` then certain events will be logged (association
negotiation, DIMSE ... |
#!/usr/bin/python3
# -*- mode: python; coding: utf-8 -*-
# Copyright (C) 2014, Oscar Acena <oscaracena@gmail.com>
# This software is under the terms of Apache License v2 or later.
from __future__ import print_function
import sys
from gattlib import GATTRequester
if __name__ == '__main__':
if len(sys.argv) < 2:
... |
import logging
import os
import json
import time
from tornado.gen import coroutine
from lib.tornado_yieldperiodic.yieldperiodic import YieldPeriodicCallback
from utils import Config, Przystanki, TramwajFactory
from db import MpkDb, PrzystankiDb
class SpawnWorker(YieldPeriodicCallback):
def __init__(self):
... |
import logging
import operator
from src.ham.radio.default_radio.dmr_contact_default import DmrContactDefault
from src.ham.radio.default_radio.dmr_id_default import DmrIdDefault
from src.ham.radio.default_radio.dmr_user_default import DmrUserDefault
from src.ham.radio.default_radio.radio_channel_default import RadioCha... |
import math
from game.common.hitbox import Hitbox
def check_collision(hitbox_one: Hitbox, hitbox_two: Hitbox) -> bool:
return (hitbox_one.top_left[0] < hitbox_two.top_right[0] and
hitbox_one.top_right[0] > hitbox_two.top_left[0] and
hitbox_one.top_left[1] < hitbox_two.bottom_left[1] and
... |
def vsum(nums: list[float]) -> float:
''' Sum together all the numbers in a list using tail recursion and if.
:param nums: List of numbers.
:returns: The sum of the numbers in the list.
'''
def loop(nums: list[float], total: float = 0.0) -> float:
if not nums:
return total
... |
# coding=utf-8
from commands.abstract_command import AbstractCommand
from config import Config
from model.karma import Karma
class GetLeaderBoardCommand(AbstractCommand):
def get_purpose(self):
return "Shows the best of the best!"
def execute(self, size: int=3):
return Karma.get_le... |
def is_palindrome(s):
if len(s) < 1:
return True
else:
if s[0] == s[-1]:
k=s[1:-1]
return is_palindrome(k)
else:
return False
a=str(input("Enter string:"))
if(is_palindrome(a)==True):
print("String is a palindrome!")
else:
print("S... |
from abc import ABC, abstractmethod #Library that forces abstraction, similar to abstract classes in java
class subgod(ABC):
"""
This is the subgod class from which all other subgods/servant god classes derive
"""
version = '0.1'
@abstractmethod
def __init__(self, name, type, hitpoints, devoti... |
"""Utility Functions for the CNC_VIDEO app -- Library"""
import collections
import logging
import threading
import time
# Map of type names into types
TYPES = {
'int': int,
'float': float,
'string': str,
'boolean': bool
}
# Take a type name and a string and return the value cast to the given type.
... |
import rich
import json
import click
import secrets
from typing import Union
from typing import Callable
from flask import Flask
from flask import request
from flask import redirect
from flask import Response
from flask.views import View
from werkzeug.security import generate_password_hash
from flask_login import ... |
import jwt
import re
import six
import sys
from shopify.utils import shop_url
if sys.version_info[0] < 3: # Backwards compatibility for python < v3.0.0
from urlparse import urljoin
else:
from urllib.parse import urljoin
ALGORITHM = "HS256"
PREFIX = "Bearer "
REQUIRED_FIELDS = ["iss", "dest", "sub", "jti", ... |
import sys
import commands
def interpret(code):
memory_pointer = 0
memory = [0]
i = 0
while i < len(code):
if code[i] == '[' and memory[memory_pointer] == 0:
i = commands.find_end_of_loop(code, i)
elif code[i] == ']' and memory[memory_pointer] != 0:
i = commands.find_start_of_loop(code, i)... |
import os
import sys
import numpy as np
import requests
import zipfile
from collections import Counter
from clint.textui import progress
from filtering import semantic_clustering
class AverageWordEmbedding(semantic_clustering.SemanticClustering):
'''
Averaged word embeddings clustering method. The meaning vector... |
import arcpy, os
from arcgis.gis import GIS
from arcgis.features import FeatureLayerCollection
import os
import sys
# Sign in to portal/set workspace
user = "Username"
password = "Password"
arcpy.SignInToPortal('https://www.arcgis.com', user, password)
portal = "http://www.arcgis.com"
gis = GIS(portal, user, password)... |
import time
import csv
import sys
import logging
import config as c
import utils
from DB import utils as db_utils
TWITTER_BATCH_LIMIT = 100
def fetch(config, users, db):
if not (hasattr(db, 'getAuthor') and hasattr(db, 'saveAuthor')):
db = c.load_db_driver('sqlite')
logging.info(f"looking for: {... |
import csv
import logging
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Set
from hed_utils.support import google_spreadsheet
__all__ = [
"AStorage",
"CsvJobsStorage",
"GoogleSheetsJobsStorage"
]
_log = logging.getLogger(__name__)
_log.addHandler(logging.NullH... |
#!/usr/bin/env python3
# encoding: utf-8
import numpy as np
import torch as th
import torch.nn.functional as F
from rls.algorithms.base.sarl_off_policy import SarlOffPolicy
from rls.common.data import Data
from rls.common.decorator import iton
from rls.nn.models import BCQ_DCT, BCQ_Act_Cts, BCQ_CriticQvalueOne
from r... |
#!/usr/bin/python
"""
Quick Bezier profile editor
...Sorta
"""
from __future__ import division # Need to get floats when dividing intergers
from Qt import QtWidgets, QtGui, QtCore, QtCompat
import maya.OpenMayaUI as mui
# Thank you Freya Holmer | Neat Corp
# https://youtu.be/NzjF1pdlK7Y
def lerp(a, b, t):
ret... |
import torch
import torch.nn as nn
import torch.nn.init as init
from torch.autograd import Variable
from utils import *
acts = {
'RELU': nn.ReLU,
'ELU': nn.ELU,
'TANH': nn.Tanh,
'NONE': nn.Identity,
}
def load_MAC(cfg, vocab):
kwargs = {
'vocab': vocab,
'num_answers': len(vocab[... |
"""A shot in MPF."""
from mpf.core.device_monitor import DeviceMonitor
from mpf.core.enable_disable_mixin import EnableDisableMixin
import mpf.core.delays
from mpf.core.events import event_handler
from mpf.core.mode import Mode
from mpf.core.mode_device import ModeDevice
from mpf.core.player import Player
@DeviceMo... |
tb = [-1]*1005
def fib_dp(n):
global tb
if n == 0:
return 0
if n == 1:
return 1
if tb[n] != -1:
return tb[n]
tb[n] = (fib_dp(n - 1) + fib_dp(n - 2)) % 1000000007
return tb[n]
while True:
try:
n = int(input())
f = fib_dp(n)
print("fib({})= {... |
from vunit import VUnit
# Create VUnit instance by parsing command line arguments
vu = VUnit.from_argv()
vu.add_osvvm()
# Create library 'lib'
lib = vu.add_library("lib")
# Add all files ending in .vhd in current working directory to library
lib.add_source_files("*.vhd")
# Run vunit function
vu.main()
... |
from __future__ import print_function
from Components.config import config
from enigma import eTimer
from Tools.Notifications import AddPopup
from Screens.MessageBox import MessageBox
from RSSFeed import BaseFeed, UniversalFeed
from twisted.web.client import getPage
from xml.etree.cElementTree import fromstring as ... |
import importlib
import os
import requests
import uuid
import shutil
from resources.series.model.serie import Serie
from resources.series.common.utils import Utils
from resources.series.common.log import Log
from resources.series.common.code import Code
class Subtitle:
@staticmethod
def _getPath():
return Utils.g... |
import sys
import os
import re
import subprocess
import shutil
import glob
import logging
import hashlib
def get_log():
log = logging.getLogger()
log.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("[%(levelname)s] %(message)s"))
log.addHandler(handl... |
#!/usr/bin/env python
# pylint: disable=no-member
"""
Run the sample-metadata API through the analysis runner
in a very generic, customisable way!
For example:
python scripts/arbitrary_sm.py \
sample get_sample_by_external_id \
--json '{"project": "acute-care", "external_id": "<external-id>"}'
""... |
#!/usr/bin/env python3
# Copyright (c) 2020 The Bitcoin Unlimited developers
"""
Tests the electrum call 'blockchain.transaction.get_merkle'
"""
import asyncio
from test_framework.util import assert_equal
from test_framework.test_framework import BitcoinTestFramework
from test_framework.electrumutil import (
ER... |
import itertools
from hazelcast.future import combine_futures, ImmediateFuture
from hazelcast.near_cache import NearCache
from hazelcast.protocol.codec import map_add_entry_listener_codec, map_add_entry_listener_to_key_codec, \
map_add_entry_listener_with_predicate_codec, map_add_entry_listener_to_key_with_predica... |
import pytest
from gradgpad import Approach, ResultsProvider
def check_all_values(nested_dictionary):
for key, value in nested_dictionary.items():
if type(value) is dict:
check_all_values(value)
else:
# print(key, ":", value)
if isinstance(value, float):
... |
import numpy as np
row = np.arange(0, 10).reshape(1, 10)
episodes = np.vstack([row] * 5)
print('Before indexing:')
print(episodes)
row_indices = []
col_indices = []
row_to_col = {
0: 3,
1: 4,
2: 5,
3: 0,
4: 1
}
for row_index in range(5):
for col_index in range(row_to_col[row_index], row_to... |
# -*- coding: utf-8 -*-
#
# Ashes documentation build configuration file, created by
# sphinx-quickstart on Thursday June 25 03:02:01 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
import os
import sys
import sphinx
CUR_PATH = os.path.dirname(os.path.abspath(__file__))
PROJ... |
import sys
import os
import unittest
import uuid
def _create_random_voice(app):
id = uuid.uuid4().hex[:3]
name = 'vn_' + uuid.uuid4().hex[:4]
lang = uuid.uuid4().hex[:2]
acc = uuid.uuid4().hex[:2]
gender = uuid.uuid4().hex[:5]
directory = uuid.uuid4().hex[:5]
with app.app_context():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.