content stringlengths 5 1.05M |
|---|
#!/usr/bin/python
#
# Script decode drum table/patterns from Zoom F/W
# (c) Simon Wood, 10 May 2020
#
from optparse import OptionParser
from construct import *
#--------------------------------------------------
# Define drum table/patterns using Construct (v2.9)
# requires:
# https://github.com/construct/construct
... |
#
# Lockstep Platform SDK for Python
#
# (c) 2021-2022 Lockstep, Inc.
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# @author Lockstep Network <support@lockstep.io>
# @copyright 2021-2022 Lockstep, Inc.
# @link https://github.... |
from django.test import TestCase
from django.core.files.uploadedfile import SimpleUploadedFile
from myhpom.models import State
class StateModelTestCase(TestCase):
def test_order_by_ad(self):
# Files with ADs should be at the front of the list, and they should be
# in alphabetical order (regardles... |
# JDC suggests two tests:
# * Likelihood always zero, confirm that we get uniform distribution
# * Likelihood Gaussian in GB radius, confirm that we get expected result
import numpy as np
import pytest
from networkx import nx
from bayes_implicit_solvent.samplers import tree_rjmc
from bayes_implicit_solvent.typers imp... |
import random
print("Who is going to pay the bill?")
list_name = input("Tell me the names that are going to pay the bill, separated by a coma and a space (, ) ")
names = list_name.split(", ")
number_names = len(names)-1
print(names[random.randint(0,number_names)])
|
"""Test the CO2 Signal config flow."""
from unittest.mock import patch
import pytest
from homeassistant import config_entries
from homeassistant.components.co2signal import DOMAIN, config_flow
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_... |
import os
from flask import Flask, request, session
app = Flask(__name__)
@app.before_request
def set_session():
session["pod"] = os.environ.get("POD_NAME", "default")
@app.route("/")
def index():
return "Pod Id: {}".format(session["pod"])
if __name__ == "__main__":
app.secret_key = "session_key"
... |
import click
from pycobertura.cobertura import Cobertura
from pycobertura.reporters import (
HtmlReporter,
TextReporter,
HtmlReporterDelta,
TextReporterDelta,
)
from pycobertura.filesystem import filesystem_factory
from pycobertura.utils import get_dir_from_file_path
pycobertura = click.Group()
repo... |
# =============================
# tomato-clock.py
# this is a simple application to arrange your time more properly
# author @NearlyHeadlessJack (https://github.com/NearlyHeadlessJack)
# copyright (c) 2022 N.H.J.
# =============================
# import=======================
from pyecharts.charts import Bar
import ti... |
from .imports import *
def to_onehot(y, num_classes=None):
"""Converts label indices to one-hot encoded vectors.
Parameters
----------
y: list or numpy array
Contains the labels as integers from 0 to num_classes.
num_classes: int, optional
The total number of classes.
... |
import torch
from sklearn.metrics import average_precision_score
from sklearn.metrics import precision_recall_curve
from openselfsup.utils import print_log
from .registry import DATASETS
from .base import BaseDataset
from .utils import to_numpy
@DATASETS.register_module
class MultiLabelClassificationDataset(BaseData... |
import sys
from typing_extensions import Final
#: This indicates that we are running on python3.8+
PY38: Final = sys.version_info >= (3, 8)
|
def generate_matlab_files(target_dataset,source_datasets,save_path,file_name):
target_dataset_name = list(target_dataset.keys())[0]
target_dataset_data = target_dataset[target_dataset_name]
source_list = list()
for source_dataset_name,source_dataset_data in source_datasets.items():
source = ... |
# names of hurricanes
names = ['Cuba I', 'San Felipe II Okeechobee', 'Bahamas', 'Cuba II', 'CubaBrownsville', 'Tampico', 'Labor Day', 'New England', 'Carol', 'Janet', 'Carla', 'Hattie', 'Beulah', 'Camille', 'Edith', 'Anita', 'David', 'Allen', 'Gilbert', 'Hugo', 'Andrew', 'Mitch', 'Isabel', 'Ivan', 'Emily', 'Katrina', ... |
#!/usr/bin/env python3
"""
Day 7: Treachery of Whales
https://adventofcode.com/2021/day/7
"""
import math
from functools import partial
from typing import Callable, Union
Data = list[int]
Number = Union[int, float]
gr = (math.sqrt(5) + 1) / 2 # The golden ratio
def parse_file(path: str) -> Data:
with open(pat... |
from datetime import datetime
class CustomMiddleware(object):
def __init__(self, get_response):
# One time configuration and initialisation of the object (with get_response)
# get_response is the next middleware inline to be executed
self.get_response = get_response
def __call__(self,... |
from __future__ import division
#this module tests that sympy works with true division turned on
from sympy import Rational, Symbol, Float
def test_truediv():
assert 1/2 != 0
assert Rational(1)/2 != 0
def dotest(s):
x = Symbol("x")
y = Symbol("y")
l = [
Rational(2),
Float("1.3"),
x,
... |
import torch
from wavenet.model import build_wavenet
from wavenet.train import Trainer
from wavenet.utils import (
set_random_seed,
load_data,
split_data,
LJSpeechDataset
)
from config import set_params
def main():
# set params and random seed
params = set_params()
set_random_seed(params.r... |
from nose.tools import assert_equals, assert_not_equals, assert_false, assert_true
import lean
import os
from lang.expr import *
from lang.env import *
MY_PATH_TO_LEAN_STDLIB = os.environ['MY_PATH_TO_LEAN_STDLIB']
lean.initialize()
env = lean.import_modules([MY_PATH_TO_LEAN_STDLIB], [lean.name("init")], 100000)
a... |
#!/usr/bin/python3
import sys
import time
import ctypes
fullscreen = True
sys.path.append("./shared")
from sbmloader import SBMObject # location of sbm file format loader
from ktxloader import KTXObject # location of ktx file format loader
from textoverlay import OVERLAY_
from shader import shader_... |
import re
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.utils import timezone
import datetime
from authentication.models import Profile
from rest_framework import serializers
from rest_framework.fields import IntegerField
from api.validators import VEHICLE_NUMBER
from f... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# -*- coding: utf-8 -*-"""Documentation about the Fish project module."""
import logging
logger = logging.getLogger(__name__)
# FIXME: put actual code here
def example():
logger.info('Providing information about the excecution of the function.')
print('Hello Fishy Things updated again 2')
if __name__ == "__... |
from gilded_rose import Item, GildedRose
class TestGildedRose(object):
def test_foo(self):
# Given
items = [Item("foo", 0, 0)]
gilded_rose = GildedRose(items)
# When
gilded_rose.update_quality()
# Then
assert items[0].name == "fixme"
|
"""
proxyUtil: Proxy auto-config for Python
===================================
Copyright 2018 Carson Lam
Copyright 2020-2021 Hiroki Fujii
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:... |
from .generator import Generator
class EconomicDispatch:
def __init__(self):
self.generators = dict()
self.load = float # extend it to pd.Series to consider multiple steps
def add_generator(self, generator: Generator):
self.generators[generator.id] = generator
def add... |
import requests
url ="http://www.omdbapi.com/?t=hackers&apikey=6b48d4b6"
#url ="http://www.omdbapi.com/?s=omen&apikey=6b48d4b6"
r = requests.get(url)
json_data =r.json()
for key, value in json_data.items():
print(key + ":", value)
|
import json
import re
import requests
from django.conf import settings
from cathie.exceptions import CatsAnswerCodeException
from cathie import authorization
def cats_check_status():
pass
@authorization.check_authorization_for_cats
def cats_submit_solution(source_text: str, problem_id: int, de_id: int, source... |
import logging
from datawinners.search import update_submission_search_index, form_model_change_handler, entity_search_update, entity_form_model_change_handler
from mangrove.datastore.documents import SurveyResponseDocument, FormModelDocument, EntityFormModelDocument
from mangrove.datastore.entity import Entity
from ma... |
import logging
class BaseACL(object):
def __init__(self, **kwargs):
super(BaseACL, self).__init__()
# Role object if this ACL is associated to a role
self.role = kwargs.get("role")
# User object if this ACL is associated to an user
self.user = kwargs.get("user")
# P... |
import celery_logger
import json
import os
import random
import services_component
import sys
import uuid
from NETlist_connector.subnetParser import NETlist
from celery import Task, Celery, group
from celery.signals import task_prerun, worker_ready
from cmsscan.scanner import scanner as cmsscanner
from configparser imp... |
from .types import *
import msgpack
xtypes = [tuple, set, PHASE0, PHASE1LOCK, PHASE2ACK, RELEASE3, BLSDECISION, BLSACCEPTABLE, BLSLOCK, BLSACK, BLSASK, BLSPUT]
xmap = dict((k, i) for i, k in enumerate(xtypes))
def ext_pack(x):
if type(x) in xtypes:
xid = xmap[type(x)]
return msgpack.ExtType(xid,... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 30 21:55:18 2018
@author: Prosimios
"""
import pickle as pkl
def save_obj(obj, name, folder ):
with open(folder+'/'+ name + '.pkl', 'wb') as f:
pkl.dump(obj, f, pkl.HIGHEST_PROTOCOL)
def load_obj(name, folder ):
with open(folder+'/' + name + '.pkl', 'rb'... |
"""File to handle player related functions."""
from playx.utility import direct_to_play
from playx.cache import search_locally, update_URL_cache, search_URL
from playx.youtube import grab_link, dw, get_youtube_title
from playx.songfinder import search
from playx.logger import Logger
from playx.stringutils import ... |
CONFIG = {
'schema': {
'type': 'object',
'title': 'Comment',
'description': 'Description',
'required': [
'name',
],
'properties': {
'name': {
'type': 'string'
},
'description': {
'type': '... |
import pandas as pd
import matplotlib.pyplot as plt
my_dataset1 = pd.read_excel('Smith_glass_post_NYT_data.xlsx', sheet_name='Supp_traces')
x = my_dataset1.Zr
y = my_dataset1.Th
fig = plt.figure()
ax1 = fig.add_subplot(1, 2, 1)
ax1.scatter(x, y, marker='s', color='#ff464a', edgecolor='#000000')
ax1.set_title("using ... |
import nextcord
from nextcord.ext import commands
from nextcord.ext.commands import has_permissions, MissingPermissions
import os
import datetime
import asyncio
class Moderation(commands.Cog, name="Moderation"):
"""Receives Moderation commands"""
COG_EMOJI = "🛡️"
def __init__(self, bot: commands.Bot):
... |
'''
Created on 8 Jun 2013
@author: dsnowdon
'''
import httplib, mimetypes
import socket
def post_multipart(host, port, selector, fields, files):
"""
Post fields and files to an http host as multipart/form-data.
fields is a sequence of (name, value) elements for regular form
fields.
files is a seq... |
"""Hierarchy of abstract base classes, from _collections_abc.py."""
from pytype import utils
# class -> list of superclasses
SUPERCLASSES = {
# "mixins" (don't derive from object):
"Hashable": [],
"Iterable": [],
"AsyncIterable": [],
"Sized": [],
"Callable": [],
"Awaitable": [],
"Iter... |
from . import abc, patterns, pool
from .abc import DeliveryMode
from .channel import Channel
from .connection import Connection, connect
from .exceptions import AMQPException, MessageProcessError
from .exchange import Exchange, ExchangeType
from .message import IncomingMessage, Message
from .queue import Queue
from .ro... |
import sys
import math
from Tkinter import *
from MemoryAdministrator import MemoryAdministrator
from stack import Stack
memory = MemoryAdministrator()
quads = []
proc = dict()
run = True
current_quad = 0
fill = False
penColor = '#000000000'
fillColor = '#000000000'
penWidth = 1
def actions():
#function that runs wh... |
import sys
"""
def get_input():
'''Prompt user to input message to display.'''
message = input("What would you like the cow to say?")
return message
"""
def split_message(message, lines):
"""Given a message to display and the number of lines to display on,
return a list of the substrings from ... |
from syzscope.interface.s2e import S2EInterface
s2e_path = '/home/xzou017/projects/KOOBE-test/s2e'
kernel_path = '/home/xzou017/projects/KOOBE-test/s2e/images/debian-9.2.1-x86_64-0e2adab6/guestfs/vmlinux'
syz_path = '/home/xzou017/projects/SyzbotAnalyzer/tools/gopath/src/github.com/google/syzkaller'
s2e_project_path =... |
'''
imputation for cmmva and cva on mnist
'''
import os
import sys
import time
import math
import numpy as np
import theano
import theano.tensor as T
import theano.tensor.shared_randomstreams
from util import datapy, color, paramgraphics
from optimization import optimizer
from layer import FullyConnected, nonlineari... |
# Copyright (c) 2013 OpenStack Foundation.
# 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... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/103_FCN.ipynb (unless otherwise specified).
__all__ = ['FCN']
# Cell
from ..imports import *
from .layers import *
# Cell
class FCN(Module):
def __init__(self, c_in, c_out, layers=[128, 256, 128], kss=[7, 5, 3]):
self.conv1 = Conv1d(c_in, layers[0], kss[0],... |
# This script generates an STL file with an engraved ring.
# To use the script the following fonts are included:
# http://www.dafont.com/pacifico.font
# http://www.dafont.com/hearts-for-3d-fx.font
# Run the script as a parameter to the FreeCAD version 0.15
#
# The MIT License (MIT)
#
# Copyright (c) 2016
... |
from pathlib import Path
from typing import Callable, Dict, Any
import pandas as pd
from rich.console import Console
from .._job_utils import (
create_alignment_job_directory_structure,
write_single_tilt_series_alignment_output
)
from ... import utils
def align_single_tilt_series(
tilt_series_id: st... |
import numpy as np
import flox
from . import parameterized
N = 1000
class Combine:
def setup(self, *args, **kwargs):
raise NotImplementedError
@parameterized("kind", ("cohorts", "mapreduce"))
def time_combine(self, kind):
flox.core._npg_combine(
getattr(self, f"x_chunk_{kin... |
#Class to create binary tree
class binaryTree():
def __init__(self, root):
self.key = root
self.leftChild = None
self.rightChild = None
def insertLeftChild(self, new_node):
if(self.leftChild == None):
self.leftChild = binaryTree(new_node)
else:
t... |
import re
from simhash import Simhash
def get_features(s):
width = 6
s = s.lower()
s = re.sub(r'[^\w]+', '', s)
return [s[i:i + width] for i in range(max(len(s) - width + 1, 1))]
h1 = Simhash('ćHow are you? I am fine. Thanks1.')
h2 = Simhash('ćHow are you? I am fine. Thanks2.')
str1 = 'ćHow are you? I... |
"""
Released under BSD 3-Clause License,
Copyright (c) 2021 Cerebras Systems Inc.
All rights reserved.
"""
import logging
import os
from typing import List, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from torch_rev_structs import (
RecomputeSilo,
RevResidualBlock... |
# -*- coding: utf-8 -*-
from scrapy import Spider, Request
from ..items import ChannelItem, RoomItem
import json
class ZhanqiSpider(Spider):
name = 'zhanqi'
allowed_domains = ['zhanqi.tv']
start_urls = [
'https://www.zhanqi.tv/api/static/game.lists/300-1.json'
]
custom_settings = {
... |
import discord
from discord.ext import commands
from src.orm.models import Header
class ErrorEmbed(discord.Embed):
"""
Embed with standard structure to show a simple error message
...
Attributes
----------
header :Header
Header obj with info related to the error
ctx: commands.Conte... |
from __future__ import absolute_import, division, print_function
import pytest
bokeh = pytest.importorskip('bokeh')
from odo.backends.bokeh import convert, pd, ColumnDataSource
import pandas.util.testing as tm
df = pd.DataFrame([[100, 'Alice'],
[200, 'Bob'],
[300, 'Charlie']],
... |
from django.forms.widgets import *
class BootstrapItaliaDateWidget(DateInput):
template_name = 'widgets/date.html'
def __init__(self, *attrs, **kwargs):
super().__init__( *attrs, **kwargs)
class BootstrapItaliaRadioWidget(RadioSelect):
template_name = 'widgets/radio.html'
def __init__(sel... |
# -*- encoding:utf-8 -*-
impar = lambda n : 2 * n - 1
header = """
Demostrar que es cierto:
1 + 3 + 5 + ... + (2*n)-1 = n ^ 2
Luego con este programa se busca probar dicha afirmacion.
"""
def suma_impares(n):
suma = 0
for i in range(1, n+1):
suma += impar(i)
return suma
def main():
print(header)
num ... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab... |
import numpy as np
def collapse(probas, output_type = 'bin'):
"""
Parameters
----------
probas: An array of probablities.
output_type: If ternary, output can be -1, 0 and 1.
Returns
-------
b: An array of binary states, whose dimensionality is identical to probas.
"""
p = n... |
from .books import Books
from .https import convert_to_https |
for _ in range(int(input())):
a,b = input().split()
try:
print(int(a) // int(b))
except Exception as e:
print('Error Code: ' + str(e)) |
from __future__ import annotations
import abc
import operator
from functools import reduce, wraps
from typing import Callable, Sequence, Any
from typing import Tuple
from storage import V
from storage.api import Predicate, E, Var
def force_var(func):
@wraps(func)
def decorated(self, arg):
if not isi... |
"""
Music features Enrichment and Preprocessing
"""
__author__ = "Marcel Kurovski"
__copyright__ = "Marcel Kurovski"
__license__ = "mit"
import logging
import os
import numpy as np
import pandas as pd
_logger = logging.getLogger(__name__)
unscaled_attributes = ["key", "loudness", "tempo"]
scaled_attributes = [
... |
# -*- coding: utf-8 -*-
SERVER_TICK = 0.05
WORLD_SIZE = (100, 100) # width, height
HUNGER_SPEED = 0.005
ILLNESS_SPEED = 0.05
HEALING_SPEED = 0.02
HUNGER_RESTORED_BY_EATING = 0.1
MAX_FOOD_ON_CELL = 10
MAX_GROW_FOOD_SPEED = 0.1
SEND_USER_PERSPECTIVE_RATE = 1
DATABASE = {
'user': 'postgres',
'database':... |
# -*- encoding: utf-8 -*-
"""
Created by eniocc at 11/10/2020
"""
from py_dss_interface.models.Topology.TopologyI import TopologyI
from py_dss_interface.models.Topology.TopologyS import TopologyS
from py_dss_interface.models.Topology.TopologyV import TopologyV
class Topology(TopologyI, TopologyV, TopologyS):
"""... |
import json, os, random
def main():
file = open(os.path.dirname(os.path.realpath(__file__)) + "/teams.json", 'w')
hackers = open(os.path.dirname(os.path.realpath(__file__)) + "/hackers.json", "r")
hackers = json.loads(hackers.read())
SOHO_teams = [[]]
FDBH_teams = [[]]
MedH_teams = [[]]
... |
# Generated by Django 3.0.2 on 2020-01-11 13:22
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Team',
fields=[
('id', models.AutoField(aut... |
# Generated by Django 2.2.5 on 2019-10-30 10:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_hub', '0033_film'),
]
operations = [
migrations.AlterField(
model_name='film',
name='acteurs',
fiel... |
# Copyright 2020 The TensorStore Authors
#
# 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... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# from __future__ import unicode_literals
__author__ = "d01 <Florian Jung>"
__email__ = "jungflor@gmail.com"
__copyright__ = "Copyright (C) 2015-16, Floria... |
#!/usr/bin/env python
u"""
sph_spline.py
Written by Tyler Sutterley (01/2022)
Interpolates a sparse grid over a sphere using spherical surface splines in
tension following Wessel and Becker (2008)
Adapted from P. Wessel, SOEST, U of Hawaii, April 2008
Uses Generalized Legendre Function algorithm from Spanier and O... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, print_function
import unittest
from . import mocks
class OAuth1ProviderTest(unittest.TestCase):
def test_name(self):
provider = mocks.MockOAuth1Provider(**mocks.OAUTH1_CREDENTIALS)
self.assertEqual('mockoauth1provi... |
'''
Q. Given a linkedlist head , find whether the linkedlist has a cycle or not.
Hint: Similiar to finding the middle of the node using 2 nodes
'''
def hasCycle(self, head: ListNode) -> bool:
slow_node = fast_node = head
if head == None:
return False
else:
while(fast_no... |
from .document import Document
class SocialDocument(Document):
"""Object representation of a supporting social document.
Social documents are normally URLs to social media profiles that help
verify the user's identity.
https://docs.synapsepay.com/docs/user-resources#section-social-document-types
... |
"""
stanCode Breakout Project
Adapted from Eric Roberts's Breakout by
Sonja Johnson-Yu, Kylie Jue, Nick Bowman,
and Jerry Liao
YOUR DESCRIPTION HERE
"""
from campy.graphics.gwindow import GWindow
from campy.graphics.gobjects import GOval, GRect, GLabel
from campy.gui.events.mouse import onmouseclicked, onmousemoved
i... |
import yaml
import json
from jinja2 import Template
if __name__ == "__main__":
index = "index.html"
with open("config.yaml", "r") as f:
config = yaml.load(f, Loader=yaml.FullLoader)
# print(json.dumps(config, indent=4))
with open("template.html", 'r') as f:
template = Template(f.re... |
# Skin info and colours
theme_name = ""
theme_author = ""
theme_version = ""
theme_bio = "" # A long bio will get cut off, keep it simple.
window_theme = "Black"
button_colour = "black"
attacks_theme = {"background": "Black", "button_colour": ('white', 'firebrick4')}
banner_size = (600, 100)
banner_padding = ((45, 10)... |
import pandas as pd
def read_kinoeva(input_file):
"""
Arguments:
input_file - path to the text file
Returns:
A pandas dataframe containing the data
"""
# df will have local scope
df = pd.read_csv(input_file, delim_whitespace=True, index_col=0)
# drop last column
df.dro... |
"""
File: maskify_dataset.py
Usage: Given a dataset that contains bounding box annotations and positive and negative
histograms, we can derive the segmentation, or shape, of the object of interest
and record those segmentation values in a COCO formatted JSON data structure
"""
__autho... |
## A SIMPLE SCIENTIFIC CALCULATOR, LEVERING THE MATH CLASS,
## WITH UNLIMITED DEFINABLE VARIABLES, A RUNNING LOG OF ENTRIES
import math
from stack import Stack
class TraceStack(Stack):
def __init__(self):
self.limit = 1000
self.stack = []
def set_limit (self,limit):
... |
# -*- coding: utf-8 -*-
"""
Tools for drawing Python class inherit and MRO graphs with graphviz.
Copyright (c) 2017-2018 Red Liu <lli_njupt@163.com>
Released under the MIT licence.
"""
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documenta... |
import pytest
from pymoku.instruments import LaserLockBox
try:
from unittest.mock import patch, ANY
except ImportError:
from mock import patch, ANY
filt_coeff = [[1.0, 1.0, 0.0, 0.0, 0.0, 0.0],
[1.0, 1.0, 0.0, 0.0, 0.0, 0.0]]
@pytest.fixture
def dut(moku):
with patch(
'pymoku.... |
# Copyright 2015-2018 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
import discord
import aiohttp
import os
from discord.ext import commands
from random import randint
from tabulate import tabulate
from .utils import checks
from .utils.dataIO import dataIO
from .utils.chat_formatting import pagify, box
class Football:
"""Football stats"""
__author__ = 'UltimatePancake'
... |
##########################################################################
# mriWorks - Copyright (C) IRMAGE/INSERM, 2020
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# https://cecill.info/licences/Licence_CeCILL_V2-en.html
# for detai... |
import os
from collections import defaultdict
import mmcv
import numpy as np
from mmcv.utils import print_log
from .api_wrappers import COCO
from .builder import DATASETS
from .coco import CocoDataset
try:
import panopticapi
from panopticapi.evaluation import pq_compute_multi_core, VOID
from panopticapi.... |
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.>
"""Utils to assist with dataclass-related operations."""
import itertools
from dataclasses import is_dataclass
import numpy as np
import pandas as pd
def dataclass_eq(base_dataclass: object, other: object) -> bool:
"""Check if base_dataclass is ... |
import os
import sys
# nametrans_map = {'cascade_mask_rcnn_r50_fpn_1x_dota'}
configs_dota = {
'retinanet_r50_fpn_2x_dota': 'retinanet_r50_fpn_2x_dota' ,
'retinanet_v5_obb_r50_fpn_2x_dota': 'retinanet_obb_r50_fpn_2x_dota',
'mask_rcnn_r50_fpn_1x_dota': 'mask_rcnn_r50_fpn_1x_dota',
'htc_without_semantic_r... |
"""Intialize the smmap package"""
__author__ = "Sebastian Thiel"
__contact__ = "byronimo@gmail.com"
__homepage__ = "https://github.com/gitpython-developers/smmap"
version_info = (3, 0, 1)
__version__ = '.'.join(str(i) for i in version_info)
# make everything available in root package for convenience
from .mm... |
from typing import List, Optional, Text, Tuple
import numpy as np
from numpy import ndarray
from pandas import DataFrame, Timedelta
from pandas.core.series import Series
from pymove.preprocessing import filters
from pymove.utils.constants import (
ADDRESS,
CITY,
DATETIME,
DIST_EVENT,
DIST_HOME,
... |
# --------------------------------------------------------
# SiamMask
# Licensed under The MIT License
# Written by Qiang Wang (wangqiang2015 at ia.ac.cn)
# --------------------------------------------------------
import json
from collections import OrderedDict
from os import listdir
from os.path import dirname, exists... |
#!/usr/bin/env python
from txros import util
from twisted.internet import defer
from navigator import Navigator
import numpy as np
from mil_tools import rosmsg_to_numpy
from geometry_msgs.msg import Vector3Stamped
class PingerAndy(Navigator):
'''
Mission to run sonar start gate challenge using Andy's sonar sy... |
#incompleto
class Cliente:
def __init__(self , nome, telefone):
self.nome=nome
self.telefone=telefone
class Conta:
def __init__(self, clientes, numero, saldo=0):
self.saldo=saldo
self.clientes=clientes
self.numero=numero
def resumo(self):
print('CC Número: ... |
# Copyright 2020 The AutoKeras Authors.
#
# 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 i... |
from django.conf.urls import url, include
from django.contrib.auth import views as auth_views
from django.views.generic import TemplateView
from .forms import MyAuthenticationForm
from .views import RegisterView, UserList, UserDetail, AuthView
app_name = 'user'
urlpatterns = [
url(r'^$', UserList.as_view(), name... |
import sys
sys.stdin = open('inputs/forth_input.txt')
operators = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x // y,
}
def solution(oper_code):
stack = []
opers = operators.keys()
for c in oper_code:
if c == '.':
if ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 24 12:57:41 2020
Last update: Feb. 25, 2021
@authors: Asieh & Samaneh
"""
import pickle
import time
import Initialization as ini
import Tournament_basis as Tour
result_no = 2 ## Change the parameters in Initialization.py file
structure_ID = 5 # Change the ID to cho... |
import pytest
import expressions as ex
class TestClass_Sleep_In():
def test_sleep_in_a(self):
assert ex.sleep_in(False, False) == True
def test_sleep_in_b(self):
assert ex.sleep_in(True, False) == False
def test_sleep_in_c(self):
assert ex.sleep_in(False, True) == True
class T... |
# Copyright (c) 2020, Vercer Ltd. Rights set out in LICENCE.txt
from unittest.mock import patch
from django.test import TestCase
from dqp.exceptions import StatementNotPreparedException, StatementAlreadyPreparedException, StatementNotRegistered
from dqp.prepared_stmt_controller import PreparedStatementController
fro... |
import numpy as np
from core.leras import nn
tf = nn.tf
class BlurPool(nn.LayerBase):
def __init__(self, filt_size=3, stride=2, **kwargs ):
if nn.data_format == "NHWC":
self.strides = [1,stride,stride,1]
else:
self.strides = [1,1,stride,stride]
self.filt_size = fil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.