text stringlengths 1 927k |
|---|
# Plan for testing
# - Decide to use weak team or strong team (i.e. always lose battles or always win battles)
# - Random walk with bias towards tiles that have not been visited, or have been visited least recently
# - Quit after N number of steps, where N is a random number between 100 and 500
import array
import ran... |
from eazieda.missing_impute import missing_impute
import pandas as pd
import numpy as np
from pytest import raises, fixture
@fixture
def df_miss():
df = pd.DataFrame(
[[1.0, "x"], [np.nan, "y"], [2.0, np.nan], [3.0, "y"]],
columns=["a", "b"],
)
return df
@fixture
def df_miss_2():
df ... |
from typing import Sequence, Mapping
from numpy import mod
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from .model_utils import get_fully_connected_layers
from scETM.logging_utils import log_arguments
class BatchClassifier(nn.Module):
"""Docstring (TODO)
"""
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-29 10:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0004_victim_gender'),
]
operations = [
migrations.CreateModel(
... |
"""
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
distributed ... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: yandex/cloud/mdb/mysql/v1/cluster_service.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection ... |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import demistomock as demisto
# !!!IMPORTANT!!! If this script should be modified, the updated version must be copied to Scripts/IsRFC1918Address to
# fulfill its unit test. This is a necessary workaround for CI configuration
# borrowed from https://stackoverflow.com/questions/819355/how-can-i-check-if-an-ip-is-in-a-... |
#
# 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... |
import math, random, time, pygame, sys
from pygame.locals import *
from PIL import Image
import numpy as np
import json
print("i tried")
def random_select(distribution, color, iteration):
random_r = int(np.random.normal(color[0], distribution[0] * 60 / (20*(iteration+1))))
random_g = int(np.random.normal(colo... |
"""Tests for the Freedompro switch."""
from datetime import timedelta
from unittest.mock import ANY, patch
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SERVICE_TURN_ON
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, STATE_OFF, STATE_ON
from homeassistant.helpers import entity_... |
from fastapi import APIRouter, Depends
from app.db.crud import get_video_captions
from app.db.session import get_db
from app.model import tf_idf
words_router = r = APIRouter()
@r.get("/topics/{topic}/{number_of_words}")
def by_topic(topic: str, number_of_words: int):
most_important_words = tf_idf.run(topic, num... |
#!/usr/bin/env python
# Copyright (c) 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import re
import scm
import subprocess2
import sys
import urlparse
# Current version of me... |
String - Reverse Words [ZOHO]
A string S is passed as the input. The program must reverse the order of the words in the string and print them as the output.
Input Format:
The first line will contain S.
Output Format:
The first line will contain the words in the string S in the reverse order.
Boundary Conditions:
Lengt... |
import trisicell as tsc
def binarym_filter_private_mutations(df):
df.drop(df.columns[df.sum() == 1], axis=1, inplace=True)
def binarym_filter_clonal_mutations(df):
x = (df == 1).sum()
x = x[x == df.shape[0]]
df.drop(x.index, axis=1, inplace=True)
def binarym_filter_nonsense_mutations(df, alt_in=2,... |
from setuptools import setup, find_packages
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
with open('requirements.txt') as f:
required = f.read().splitlines()
required = [r.split('==')[0] for r in required]
setup(
name='ggmodel_dev',
version='0.0.25',
description=... |
from django.apps import AppConfig
class Dbexample2Config(AppConfig):
name = 'dbexample2' |
#!/usr/bin/env python
#
# switch_tests.py: testing `svn switch'.
#
# Subversion is a tool for revision control.
# See http://subversion.apache.org for more information.
#
# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or mo... |
#!/usr/bin/env python
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
matplotlib.rcParams["font.family"] = "Serif"
matplotlib.rcParams["font.size"] = 10
matplotlib.rcParams["axes.labelsize"] = 10
matplotlib.rcParams["xtick.labelsize"] = 10
matplotlib.rcParams["ytick.labelsize"] = 10
matplotlib.rc... |
if __name__ == '__main__':
for t in range(int(input())):
ts = int(input())
count = 0
while ts%2 == 0:
ts //= 2
if ts:
print(ts//2)
else:
print(0) |
#!/usr/bin/env python
#
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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... |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from polymorphic_tree.models import PolymorphicMPTTModel, PolymorphicTreeForeignKey
# A base model for the tree:
@python_2_unicode_... |
import transformers
import argparse
def none_or_str(value):
if value == 'None':
return None
return value
def primary_parse():
parser = argparse.ArgumentParser()
parser.add_argument('--level') # {"token" "comment"}
parser.add_argument('--max_len', type=int, default=256)
parser.add_argument('--max_len_context'... |
""" collection of functions that are useful for several classes but non-specific to any """
import slicer
import logging
def getBinaryLabelmapRepresentation(segmentationNode, segmentID: str):
segmentLabelmap = slicer.vtkOrientedImageData()
segmentationNode.GetBinaryLabelmapRepresentation(segmentID, segmentLabelm... |
import unittest
import json
import requests
from pystexchapi.response import StockExchangeResponseParser, APIResponse
from pystexchapi.exc import APIDataException, APIResponseParsingException
from tests import TICKER_RESPONSE, GENERIC_ERROR_RESPONSE
def raise_value_error():
raise ValueError()
class TestStockEx... |
""" read_xml_export.py
REPOSITORY:
https://github.com/DavidJLambert/Two-Windows-Event-Log-Summarizers
SUMMARY:
Scans XML exports of the Windows Event Log and reports summary statistics.
AUTHOR:
David J. Lambert
VERSION:
0.1.1
DATE:
July 10, 2020
"""
# -------- IMPORTS.
from __future__ import print_funct... |
import csv
import pandas as pd
from tqdm import tqdm
from collections import Counter
dbRead = open('db.csv', "r", newline='', encoding='utf8')
db = list(csv.reader(dbRead, delimiter=","))
column = [row[-1] for row in db]
for row in tqdm(db):
row[-2]=Counter(column)[row[-1]]
df=pd.DataFrame(data=db)
df.to_csv('db.cs... |
#!/usr/bin/env python
#---------------------------------------------------------------------
# IDAPython - Python plugin for Interactive Disassembler
#
# Original IDC.IDC:
# Copyright (c) 1990-2010 Ilfak Guilfanov
#
# Python conversion:
# Copyright (c) 2004-2010 Gergely Erdelyi <gergely.erdelyi@d-dome.net>
#
# All righ... |
# Copyright 2017 Google 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, ... |
# orm/properties.py
# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""MapperProperty implementations.
This is a private module which defines the behav... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
from enum import Enum
import logging
import optparse
import os
import p... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyMsal(PythonPackage):
"""The Microsoft Authentication Library (MSAL) for Python library enables
your app t... |
# coding: utf-8
"""
Mask R-CNN - Train on Nuclei Dataset (Updated from train_shape.ipynb)
This notebook shows how to train Mask R-CNN on your own dataset.
To keep things simple we use a synthetic dataset of shapes (squares,
triangles, and circles) which enables fast training. You'd still
need a GPU, though, becaus... |
import os
import re
import logging
from functools import reduce
from itertools import zip_longest
from collections.abc import Iterable
import html
logger = logging.getLogger(__name__)
RE_SPLIT_OR = "(?<!\\\)\|"
class BlockContent(list):
def __init__(self, roam_objects=[]):
"""
Args:
... |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
"""
# pip install prototools
from prototools import Menu
from prototools.colorize import magenta, cyan, red
from empresa import Empresa
def main():
empresa = Empresa()
menu = Menu(
cyan("Menu"),
exit_option_text=red("Salir"),
... |
'''
Author: Hannah Meyers
This file contains the experiment code for attempting to model
protein nanopore traces via HMMs. Please see inline comments
for an explanation of what each piece of the code is doing.
'''
from __future__ import print_function
from PyPore.parsers import *
from PyPore.DataTypes import *
from h... |
# -*- coding: utf-8 -*-
"""Application configuration."""
import os
class Config(object):
"""Base configuration."""
SECRET_KEY = "uidhbao7dbaudw8yebqnmrbqiyrnqxurgqhrqeioryq89894873264234bvm234l234pu2347" #os.environ.get('KELBYAPP_SECRET', 'secret-key') # TODO: Change me
APP_DIR = os.path.abspath(os.path... |
# -*- coding: utf-8 -*-
"""
"""
class StyleUtil(object):
"""
"""
@staticmethod
def create_gradient(column, vp=None):
"""
:param column:
:param vp:
"""
pass |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework import filters
from rest_framework.authtoken.views import ObtainAuthToken
from res... |
"""Tests for the clip module."""
import warnings
from distutils.version import LooseVersion
import numpy as np
import pandas as pd
import shapely
from shapely.geometry import (
Polygon,
Point,
LineString,
LinearRing,
GeometryCollection,
MultiPoint,
)
import geopandas
from geopandas import Ge... |
# Copyright (c) 2017-2021 Advanced Micro Devices, 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 list of ... |
import serial
import numpy
import matplotlib.pyplot as plt
from drawnow import *
ACx= []
ACy= []
ACz = []
Temperatura = []
Girx = []
Giry = []
Girz = []
arduinoData = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
plt.ion() #avisando o matplot que quero fazer algo live
cnt=0
def makeFig(): #... |
# -*- coding: utf-8 -*-
'''
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
patch,
NO_MOCK,
N... |
import json
import numpy as np
import torch
import pycocotools
import argparse
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from terminaltables import AsciiTable
from collections import OrderedDict
import torch.backends.cudnn as cudnn
from data.coco import COCODetection
from modules.buil... |
from bson import ObjectId
from mini_gplus.models import Post
from mini_gplus.utils.profiling import timer
from .cache import r
RPost = "post"
def set_in_post_cache(post: Post):
r.hset(RPost, str(post.id), post.to_json())
@timer
def get_in_post_cache(oid: ObjectId):
r_post = r.hget(RPost, str(oid))
if n... |
__version__ = '3.1.11' |
# -*- coding: utf-8 -*-
from recommonmark.parser import CommonMarkParser
source_parsers = {
'.md': CommonMarkParser,
}
extensions = []
templates_path = ['_templates']
source_suffix = ['.rst', '.md']
master_doc = 'index'
# General information about the project.
project = u'Das tttool-Buch'
copyright = u'2019, Joa... |
#
# @lc app=leetcode id=693 lang=python3
#
# [693] Binary Number with Alternating Bits
#
# https://leetcode.com/problems/binary-number-with-alternating-bits/description/
#
# algorithms
# Easy (58.47%)
# Likes: 359
# Dislikes: 74
# Total Accepted: 52.4K
# Total Submissions: 89.1K
# Testcase Example: '5'
#
# Given... |
import setuptools
import pkg_resources
from setuptools import setup, Extension
def is_installed(requirement):
try:
pkg_resources.require(requirement)
except pkg_resources.ResolutionError:
return False
else:
return True
if not is_installed('numpy>=1.11.0'):
print("""
... |
from os import environ
from firebase_admin import credentials, db, initialize_app
from flask import Flask, request
from telebot import TeleBot, types
from wikipedia import (
WikipediaPage,
geosearch,
page,
random,
search,
set_lang,
suggest,
summary,
)
# Firebase connection
cred = crede... |
"""
Processes event api from slack
:license: MIT
"""
import json
import os
from typing import Dict
from src.modules.create_signedup_homepage import create_home_tap
from src.dependencies.dependency_typing import Requests, PynamoDBConsultant
from src.dependencies.requests_provider import get_requests_provider
fr... |
#
# Copyright 2018 EveryUP Srl
#
# 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 t... |
"""apartment URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
# coding: utf-8
# # Day One
# ## Table of Contents
# 1. [Data Model](#Data-Model)
# 2. [Data Structures](#Data-Structures)
# 3. [Control Flow](#Control-Flow)
# 4. [Input and Output](#Input-and-Output)
# 5. [`os`](#os)
# 6. [`glob`](#glob)
# 7. [`subprocess`](#subprocess)
#
# Links to documentation will be provided ... |
import datetime
import bson
from common.mongo import oplog
from common import event_emitter
mo = oplog.MongoOplog('mongodb://eslocal:PHuance01@172.16.100.150,172.16.100.151,172.16.100.152/?replicaSet=foobar',
ts=bson.Timestamp(1524735047, 1))
@event_emitter.on(mo.event_emitter, 'data')
def on_d... |
'''
Tests for vrp package construction module
'''
import pytest
import vrp.constructive as cn
import vrp.io as io
@pytest.mark.parametrize("warehouse, selected_sectors, expected_cost",
[
('L51', ['L51', 'L1', 'L10', 'L100','L101'], 196.1*2),
... |
import sys
from tkinter import *
from tkinter import ttk
import time
myGui = Tk()
myGui.geometry('300x200')
myGui.title('Retro Code 80s')
style = ttk.Style()
style.configure("black.Horizontal.TProgressbar", background='black')
bar = ttk.Progressbar(myGui,orient ="horizontal",length = 200, style='black.Horizontal.TPr... |
"""
Local endpoint tests.
Requires that the app is running locally (run `uvicorn main:app --reload`)
"""
import os
import pytest
from tests.endpoint_scenarios import SCENARIOS
from tests.endpoint_test_utils import run_endpoint_test
os.environ["LOCAL"] = "True"
@pytest.mark.parametrize("scenario", list(SC... |
import flow
from flow.module import Module, Linear
from flow.optim import SGD
from flow import function as F
import numpy as np
class Net(Module):
def __init__(self):
super().__init__()
self.fc1 = Linear(2, 10)
self.fc2 = Linear(10, 1)
def forward(self, a):
x = self.fc1(a)
... |
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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... |
import urllib
import urllib2
import time
import json
#install using facebook-sdk"
import facebook
def main():
access = "https://graph.facebook.com/"
ACCESS_TOKEN = XXXXXXXXXXXXX #enter your access token here
datafile = urllib2.urlopen(access + 'me?fields=feed&access_token='+ACCESS_TOKEN)
sigma = 0
t... |
from setuptools import setup
import bip32
import io
with io.open("README.md", encoding="utf-8") as f:
long_description = f.read()
with io.open("requirements.txt", encoding="utf-8") as f:
requirements = [r for r in f.read().split('\n') if len(r)]
setup(name="bip32",
version=bip32.__version__,
des... |
from django.contrib.admin import AdminSite
from django.contrib.admin.apps import AdminConfig
from django.urls import path
class CustomAdminSite(AdminSite):
def get_urls(self):
from degvabank.core import views
urls = super().get_urls()
my_urls = [
path(
'reports/... |
import asyncio
import inspect
import io
import textwrap
import traceback
import re
from contextlib import redirect_stdout
from copy import copy
import discord
from redbot.core import checks, commands
from redbot.core.i18n import Translator
from redbot.core.utils.chat_formatting import box, pagify
"""
Notice:
95% of ... |
# ***************************************************************
# Copyright (c) 2021 Jittor. All Rights Reserved.
# Maintainers:
# Guoye Yang <498731903@qq.com>
# Dun Liang <randonlang@gmail.com>.
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this s... |
import datetime
import os
import pipes
import signal
import time
from gppylib.mainUtils import *
from gppylib.utils import checkNotNone
from gppylib.db import dbconn
from gppylib import gparray, gplog
from gppylib.commands import unix
from gppylib.commands import gp
from gppylib.commands import base
from gppylib.gpar... |
import ply.yacc as yacc
# get the token map from the lexer
from lex import tokens
import sys
import pushdown
Pushdown = pushdown.Pushdown
State = pushdown.State
Rule = pushdown.Rule
ParseState = pushdown.ParseState
Production = pushdown.Production
Shift = pushdown.Shift
Reduce = pushdown.Reduce
# Grammar
#
# file ... |
import copy
import datetime
import logging
import traceback
import warnings
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from urllib.parse import urlparse
from great_expectations._version import get_versions # isort:skip
__version__ = get_versions()["version"] # isor... |
import math
a=str(input('输入一串数字或字母:',))
a=a.replace('a','01')
a=a.replace('b','02')
a=a.replace('c','03')
a=a.replace('d','04')
a=a.replace('e','05')
a=a.replace('f','06')
a=a.replace('g','07')
a=a.replace('h','08')
a=a.replace('i','09')
a=a.replace('j','10')
a=a.replace('k','11')
a=a.replace('l','12')
a=a.replace('m',... |
import collections
import pytest
from typingx import (
Annotated,
Any,
Callable,
Collection,
Constraints,
Dict,
FrozenSet,
Generic,
List,
Listx,
Literal,
Mapping,
NewType,
NoneType,
Optional,
Sequence,
Set,
Tuple,
Tuplex,
Type,
TypedD... |
## 粗粒度ner加crf层的例子
import torch
from tqdm import tqdm
import unicodedata
import os
import time
from torch.utils.data import Dataset, DataLoader
from bert_seq2seq import Tokenizer, load_chinese_base_vocab
from bert_seq2seq import load_bert
data_path = "./state_dict/corase_train_update.txt"
vocab_path = "./state_dict/ro... |
import unittest
from msgraph_async.common.odata_query import *
class TestODataQuery(unittest.TestCase):
def setUp(self):
pass
@classmethod
def setUpClass(cls):
pass
def get_instance(self):
return ODataQuery()
def test_empty_odata(self):
i = self.get_instance()
... |
"""
Django settings for backend project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
im... |
import os
import subprocess
try:
import polib
except ImportError:
print('Msg to the package releaser: prerelease hooks will not work as you have not installed polib.')
raise
import copy
import codecs
def prereleaser_before(data):
"""
1. Run the unit tests one last time before we make a release.
... |
from unittest import TestCase
from RotateArray import RotateArray
class TestRotateArray(TestCase):
def test_rotate(self):
ra = RotateArray()
array0 = [1]
ra.rotate(array0, 1)
self.assertEqual(array0, [1])
array1 = [1, 2]
ra.rotate(array1, 1)
self.assertEq... |
"""
pyart.testing.sample_files
==========================
Sample radar files in a number of formats. Many of these files
are incomplete, they should only be used for testing, not production.
.. autosummary::
:toctree: generated/
MDV_PPI_FILE
MDV_RHI_FILE
CFRADIAL_PPI_FILE
CFRADIAL_RHI_FILE
C... |
# Copyright 2020 Joseph T. Iosue
#
# 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... |
#!/usr/bin/env python3
"""
Load a list of lat/lons from a CSV file and reverse-geocode them to LLSOA.
- Jamie Taylor <jamie.taylor@sheffield.ac.uk>
- First Authored: 2020-04-16
"""
import sys
import os
import argparse
import time as TIME
import pandas as pd
from geocode import Geocoder, query_yes_no
def parse_optio... |
""" Aula - 016 - Tuplas"""
# Teoria:
# Variáveis compostas:
'''
Tuplas, o que são?:
Em uma explicação bem simples, é uma variável que guarda vários valores!
As tuplas usam indexições para indentificar seu componentes internos!
As tuplas são imultáveis!
'''
# Parte prática:
lanche = ('Hamb... |
"""
Set up the plot figures, axes, and items to be done for each frame.
This module is imported by the plotting routines and then the
function setplot is called to set the plot parameters.
"""
#--------------------------
def setplot(plotdata=None):
#--------------------------
"""
Specify what is ... |
from pathlib import Path
import click
import cv2
from .core import VideoWriter
@click.group()
def cli():
pass
@cli.command()
@click.argument('image-dir')
@click.option('-o', '--output', default=None)
@click.option('--fps', default=60)
def merge(image_dir, output, fps):
r"""Create video from images"""
... |
import os
from enb import icompression
from enb.config import get_options
options = get_options()
class HEVC(icompression.WrapperCodec, icompression.LosslessCodec):
def __init__(self, config_path=None, chroma_format="400"):
config_path = config_path if config_path is not None \
else os.path.j... |
"""This file contains by default (without config file) ONE lint message.
for EVERY linter:
- flake8
- mypy
- pydocstyle
- pylint
"""
X = lambda: 1
def one() -> int:
"""One.
"""
return one
return 1 |
from typing import Optional, Tuple
import torch
def marginal_pdf(
values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float = 1e-10
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Calculate the marginal probability distribution function of the input tensor based on the number of
histogram ... |
#!/usr/bin/env python2
#
# Copyright 2015-2016 Carnegie Mellon University
#
# 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 require... |
# Generated by Django 2.1.4 on 2018-12-13 17:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quiz', '0015_auto_20181209_0433'),
]
operations = [
migrations.AlterField(
model_name='quizattempt',
name='finish_ti... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import zmq
import click
import logging
BATSIM_PORT = 28000
@click.command()
@click.option('-d', '--debug', is_flag=True, help='Debug flag.')
@click.option('-l', '--logfile', type=click.STRING, help='Specify log file.')
@click.option('-c', '--controller', type=click.STR... |
import argparse
import librosa
import numpy as np
def make_subclips(audio, sr, clip_size, pad=True):
# Given a list of audio files and corresponding sample rates,
# return a 2D list of subclips, each of size clip_size
# Optional padding takes care of audio files shorter than clip size
clips = []
fo... |
# -- coding: utf-8 --
# 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
# "Li... |
#!/usr/bin/env python
from typing import Any, Dict, Optional, Type, TypeVar
import esper # type: ignore
import tabulate
T = TypeVar("T")
class WorldExt(esper.World):
def __init__(self, timed=False):
super(WorldExt, self).__init__(timed)
self.resources: Dict = {}
def _process(self, *args, ... |
# Copyright 2014 Diamond Light Source Ltd.
#
# 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 t... |
import operator
import uuid
from unittest import mock
from django import forms
from django.core import serializers
from django.core.exceptions import ValidationError
from django.core.serializers.json import DjangoJSONEncoder
from django.db import (
DataError, IntegrityError, NotSupportedError, OperationalError, co... |
# Once for All: Train One Network and Specialize it for Efficient Deployment
# Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han
# International Conference on Learning Representations (ICLR), 2020.
import os
import time
import json
import math
from tqdm import tqdm
import numpy as np
import copy
import torc... |
# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applica... |
def test_extraction():
from sematch.nlp import Extraction
from sematch.semantic.sparql import EntityFeatures
upm = EntityFeatures().features('http://dbpedia.org/resource/Technical_University_of_Madrid')
extract = Extraction()
assert extract.extract_nouns(upm['abstract']) is not None
assert extra... |
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
from OpenNE.src.libnrl import graph
from OpenNE.src.libnrl import grarep
from OpenNE.src.libnrl import line
from OpenNE.src.libnrl import node2vec
from OpenNE.src.libnrl.gcn import gcnAPI
from itertools import product
import networkx as nx
import numpy as np
import tensorflow as tf
def nx_to_openne_graph(nxgraph, stri... |
#!/usr/bin/env python
#
# Copyright 2017 Google Inc. 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 requir... |
# coding: utf8
from coll_avoidance_modules.solo_coll_wrapper_c import *
from coll_avoidance_modules.collisions_controller import *
from PA_utils_mpc import PyBulletSimulator
import numpy as np
import argparse
# from solo12 import Solo12
# from pynput import keyboard
from PA_logger import Logger
# from utils.qualisysC... |
# Copyright Pincer 2021-Present
# Full MIT License can be found in `LICENSE` at the project root.
"""sent when a guild integration is updated."""
from ..core.dispatch import GatewayDispatch
from ..objects.events.guild import GuildIntegrationsUpdateEvent
from ..utils import Coro
from ..utils.conversion import construc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.