content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
import pytest
from . import BaseTestSuit, AssertDesc, gen_test_string
TEST_USERNAME = 'user_' + gen_test_string(6)
TEST_PASSWORD = 'test_password'
class TestSuitUser(BaseTestSuit):
API_PATH_ROOT = '/api/v1/users'
def setup_class(self):
pass
def teardown_class(self):
... |
# =========================================================================
# Copyright (C) 2021. Huawei Technologies Co., Ltd. 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 Lice... |
from rdflib import Graph, RDF
from IPython.core.display import display, HTML
import os
import json
import csv
import uuid
from SPARQLWrapper import SPARQLWrapper, SPARQLWrapper2, JSON, JSONLD, CSV, TSV, N3, RDF, RDFXML, TURTLE
import pandas as pds
import itertools
import numpy as np
from plotnine import *
__author_... |
"""dhcp.py"""
import logging
import string
import time
import binascii
from random import randint, choice
from scapy.config import conf
#conf.use_pcap = True
conf.verb = 0
from scapy.arch import linux, pcapdnet
from scapy.arch.pcapdnet import *
#conf.L3socket = linux.L2Socket
from scapy.all import Ether, Dot1Q, ... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from django_addons_formlib import __version__
setup(
name='django-addons-formlib',
version=__version__,
description='django-addons Framework form library',
author='Divio AG',
author_email='[email protected]',
url='https://github.co... |
# %%
import pandas as pd
import numpy as np
import pathlib
import matplotlib.pyplot as plt
from scipy.stats.mstats import gmean
from our_plot_config import derived_dir, setplotstyle, fig_dir
setplotstyle()
# %%
# Input file
f_kappas = derived_dir / 'official-kappas.parquet'
f_firms = derived_dir / 'firm-info.parqu... |
# head percolation table
from pyparsing import OneOrMore, nestedExpr
def all_left(label, child_labels):
return 0
def all_right(label, child_labels):
return len(child_labels) - 1
def ftb(label, children):
for rule in ftb_rules:
if label == rule[0] or rule[0] == "*":
for subrule in r... |
"""Wrapper to make the a1 environment suitable for OpenAI gym."""
import gym
from mpi4py import MPI
from motion_imitation.envs import env_builder
from motion_imitation.robots import a1
from motion_imitation.robots import robot_config
class A1GymEnv(gym.Env):
"""A1 environment that supports the gym interface."""
... |
# MIT License
# Copyright (c) 2022 christiandimaio
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge... |
'''Put item'''
import json
import logging
import os
import boto3
from tenacity import retry, stop_after_delay, wait_random_exponential
log_level = os.environ.get('LOG_LEVEL', 'INFO')
logging.root.setLevel(logging.getLevelName(log_level)) # type: ignore
_logger = logging.getLogger(__name__)
# DynamoDB
DDB_TABLE_NAM... |
from codalab.bundles.dataset_bundle import DatasetBundle
from codalab.bundles.make_bundle import MakeBundle
from codalab.bundles.program_bundle import ProgramBundle
from codalab.bundles.run_bundle import RunBundle
from codalab.bundles.private_bundle import PrivateBundle
BUNDLE_SUBCLASSES = (DatasetBundle, MakeBundle,... |
from aes.transformations import *
from aes.key_expansion import *
TESTKEY = bytearray(range(16))
def test_sboxes():
"""
>>> test_sboxes()
63 7c 77 7b f2 6b 6f c5 30 01 67 2b fe d7 ab 76
ca 82 c9 7d fa 59 47 f0 ad d4 a2 af 9c a4 72 c0
b7 fd 93 26 36 3f f7 cc 34 a5 e5 f1 71 d8 31 15
04 c7 23 c3 18 96 05 9a ... |
import itertools
import numpy as np
import tensorflow as tf
from tensorflow.python.util import nest
from video_prediction import ops, flow_ops
from video_prediction.models import VideoPredictionModel
from video_prediction.models import pix2pix_model, mocogan_model, spectral_norm_model
from video_prediction.ops import... |
#
# Copyright 2008 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
#... |
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
from gui.list.specieslist import speciesList
from core.localisation import _
class speciesListDialog(QtGui.QDialog):
"""
Class to list the current world's species.
"""
_table = None
def __init__(self, parent, app):
"""
Initialisation of the window, cr... |
# Copyright 2020 Board of Trustees of the 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 requir... |
import click
@click.group()
@click.option("-p", "--path", default=None)
def iunctus(path):
pass
from iunctus.cli.add import add
from iunctus.cli.new import new
from iunctus.cli.show import show
iunctus.add_command(add)
iunctus.add_command(new)
iunctus.add_command(show)
if __name__ == "__main__":
iunctus()... |
# encoding: utf-8
"""
Test suite for the docx.api module
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
import pytest
from docx.api import Document
from docx.enum.text import WD_BREAK
from docx.opc.constants import CONTENT_TYPE as CT, RELATIONSHIP_TYPE as RT
from docx... |
#!/usr/bin/python3
from cc.parser import Parser
from cc.optimizer import Optimizer
from cc.translator import Translator
from asm.assembler import Assembler
from link.linker import Linker, BinaryType
import sys
if __name__ == '__main__':
c_files = []
asm_files = []
stop_at_comp = False
... |
def map_signals(signals):
m = {}
for s in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:
appearances = list(filter(lambda x: s in x, signals))
if len(appearances) == 6:
m[s] = 'b'
continue
elif len(appearances) == 4:
m[s] = 'e'
continue
elif ... |
# -*- coding: utf-8 -*-
from scrapy import Spider, Request
from ..items import ChannelItem, RoomItem
import json
class HuyaSpider(Spider):
name = 'huya'
allowed_domains = ['huya.com']
start_urls = [
'http://www.huya.com/g'
]
custom_settings = {
'SITE': {
'code': 'huya... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE 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/lic... |
import unittest
from conans.test.utils.tools import TestClient, TestServer
from conans.paths import CONANFILE, BUILD_INFO
from conans.util.files import load, save
import os
from conans.test.utils.test_files import temp_folder
from conans.model.info import ConanInfo
conanfile = """from conans import ConanFile
class C... |
import os
from uuid import uuid4
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from urllib.parse import urlparse, quote_plus, unquote
from flask import Flask, request, jsonify, render_template, redirect
# Init app
app = Flask(__name__)
basedir = os.path... |
import csv
def importListFromCSV(filename, dest):
with open(filename) as csvDataFile:
csvReader = csv.reader(csvDataFile)
for row in csvReader:
dest.append(row[0])
def importTwoListsFromCSV(filename, dest1, dest2):
with open(filename) as csvDataFile:
csvReader = csv.reader(... |
import requests
from bs4 import BeautifulSoup as soup
import pandas as pd
url = 'https://www.newegg.com/p/pl?Submit=StoreIM&Depa=1&Category=38'
uClient = requests.get(url)
page = uClient.content
uClient.close()
page_html = soup(page, 'html.parser')
container = page_html.find(class_='items-view is-grid') ... |
import os
import sys
from operator import itemgetter
from methods import dates
from db.elastic import Elastic
from db.postgresql import PostgreSQL
GEONAMES_USERNAME = ""
if not GEONAMES_USERNAME:
print("Please fill out GEONAMES_USERNAME in geotag/config.py")
# sys.exit()
# Folder to save GeoNames data
GEONAM... |
# ==================================================================================
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to de... |
# coding=utf-8
__author__ = '[email protected]'
__date__ = "2018/11/20 下午9:38:00"
import sys
reload(sys)
sys.setdefaultencoding("utf8")
import os
from datetime import datetime
from tornado.ioloop import IOLoop
from tornado.log import app_log
from tornado.options import define, options, parse_command_line
from ... |
# -*- coding: utf-8 -*-
# Copyright 2019–2020 The Matrix.org Foundation C.I.C.
#
# 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 re... |
# -*- coding: utf-8 -*-
import os
from mootdx.utils import get_stock_market
from pytdx.exhq import TdxExHq_API
from pytdx.hq import TdxHq_API
# 股票市场
class Quotes(object):
@staticmethod
def factory(market='std', **kwargs):
if market=='ext':
return ExtQuotes(**kwargs)
elif market=='... |
'''deployments.py - azurerm functions for Deployments'''
from .restfns import do_get
from .settings import get_rm_endpoint, BASE_API
def list_deployment_operations(access_token, subscription_id, rg_name, deployment_name):
'''List all operations involved in a given deployment.
Args:
access_token (str... |
# Author: Jean-Remi King <[email protected]>
#
# License: BSD (3-clause)
import numpy as np
from .mixin import TransformerMixin
from .base import BaseEstimator
from ..time_frequency.tfr import _compute_tfr, _check_tfr_param
from ..utils import fill_doc, _check_option
@fill_doc
class TimeFrequency(TransformerMi... |
# Generated by Django 3.2.6 on 2021-08-20 10:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='usersettings',
name='country_of_news',
... |
'''
RandDist:
----------
This minimal package generates a list of int or float numbers within a specific range and steps with custom probability distribution. \n
It has two methods:\n
1. randint\n
2. randfloat\n
each take same parameters and output same data
'''
from randdist.generate import randint, randfloat |
from time import sleep
from importlib import import_module
from bloody_hell_bot.core.bot import BloodyHellBot
def main(config_module='config.dev'):
config = import_module(config_module)
bot = BloodyHellBot(config)
bot.message_loop()
while 1:
sleep(10)
if __name__ == '__main__':
main()
|
"""
:Created: 24 August 2016
:Author: Lucas Connors
"""
from django.apps import apps
from django.contrib.auth.models import User
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from django.test import TransactionTestCase
from pigeon.test import RenderTestCase
from menu.mo... |
expected = [(True, 0.9749367759562906, 0.0017697497084894365, 0.0001226379059079931, 0.00016402878019849648, 0.00012344246793706903, 0.00031922002005261777, 0.0005362138683486838, 0.0006850762300778668, 0.0004942567639564529, 0.00018708933024663262, 0.0006994743745435789, 0.00040398057664498856, 0.0012545958406222754, ... |
"""
This module allows to perform a specific extrinsic evaluation of files by a specified criteria.
Antoine Orgerit - François Gréau - Lisa Fougeron
La Rochelle Université - 2019-2020
"""
import langid
import json
import copy
import subprocess
from os import listdir, remove
from os.path import isfile, join
from utils... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 7 22:59:01 2018
@author: jeanfernandes
"""
import pandas as pd
base = pd.read_csv('./bigData/census.csv')
previsores = base.iloc[:, 0:14].values
classe = base.iloc[:, 14].values
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
encod... |
import getpass
import json
import os
from xdg import XDG_CONFIG_HOME
PROGRAMAKER_BRIDGE_ENDPOINT_ENV = 'PLAZA_BRIDGE_ENDPOINT'
PROGRAMAKER_AUTH_TOKEN_ENV = 'PLAZA_BRIDGE_AUTH_TOKEN'
PROGRAMAKER_BRIDGE_ENDPOINT_INDEX = "plaza_bridge_endpoint"
PROGRAMAKER_AUTH_TOKEN_INDEX = 'plaza_authentication_token'
global directo... |
import pytest
from mlagents.plugins.stats_writer import register_stats_writer_plugins
from mlagents.trainers.settings import RunOptions
from mlagents_plugin_examples.example_stats_writer import ExampleStatsWriter
@pytest.mark.check_environment_trains
def test_register_stats_writers():
# Make sure that the Examp... |
#!/usr/bin/env python
# Copyright (c) 2006-2010 Tampere University of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rig... |
import numba
from numba import cuda, float32, int32
import numpy as np
import math
import cmath
@cuda.jit(device=True)
def euclidean_distance(x1, y1, z1, x2, y2, z2):
square_distance = (x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2
distance = math.sqrt(square_distance)
return distance
@cuda.jit(device... |
from django.conf.urls import url
urlpatterns = [
url(r'^$', 'hello.views.index'),
url(r'^hello/?$', 'hello.views.hello'),
url(r'^hello/([^/]+)$', 'hello.views.hello_user'),
]
|
#!/usr/bin/env python3
from pwn import *
binary = ELF('sort_it')
binary.write(0x1208,5*b'\x90')
binary.save('sort_it_patched')
os.chmod('sort_it_patched',0o755)
|
import os
import sys
import django
# Find the path to the current file and add the path to cbe to the system path
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(BASE_DIR, 'cbe')) #cbe is a sub directory of this file
# Initialize django
os.environ['DJANGO_S... |
# Generated by Django 2.0.6 on 2018-09-24 05:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ContestSpace', '0002_results'),
]
operations = [
migrations.AddField(
model_name='pendingrequests',
na... |
from .whcontrol import main
NAME = "WHControl"
|
from datetime import datetime
#############################################################################################################
# Prints a message with a prefix containng the date, time & log level
def Template(Message, Level):
Message = "{0} - [{1}] - {2}".format(datetime.now(), Level, Message)
p... |
import ImportedFile as IF
IF.func()
# <ref> |
try:
with open("input.txt", "r") as fileContent:
segments = [[segment.split(" -> ")]
for segment in fileContent.readlines()]
segments = [tuple([int(axis) for axis in coordinate.strip().split(",")])
for segment in segments for coordinates in segment for coordin... |
import functools
import spanda.core as _core
from .typing import *
import spanda.sql.functions as F
def wrap_dataframe(func: Callable) -> Callable:
@functools.wraps(func)
def f(*args, **kwargs):
df = func(*args, **kwargs)
return _core.DataFrameWrapper(df)
return f
def wrap_col_args(func:... |
import psycopg2
import configparser
import sys
import os
import pandas as pd
import datetime
sql_template = """
"""
class Connector:
def __init__(self, config_path, system_name, template=sql_template):
'''
parameters
----------
config_path: str
con... |
#!/usr/bin/env python
from __future__ import print_function
import matplotlib.pylab as plt
import os
from .builder import create_trajectory
def new_line(f):
def wrapper(*args, **kwargs):
print()
f(*args, **kwargs)
print()
return wrapper
def plot_trajectory(name):
STEPS = 600
... |
#!/usr/bin/env python
import argparse
from numpy import ndarray
from LhcVaspTools.BasicUtils import saveData2Json, Vaspdata
def parseArgv() -> argparse.Namespace:
parser: argparse.ArgumentParser = argparse.ArgumentParser(description=
'This script is u... |
class SenderAction(object):
SENDER_ACTIONS = [
'mark_seen',
'typing_on',
'typing_off'
]
def __init__(self, sender_action):
if sender_action not in self.SENDER_ACTIONS:
raise ValueError('Invalid sender_action provided.')
self.sender_action = sender_action
... |
# -*- coding: utf-8 -*-
import tmonkeysettings as tm
import monkeyutility as mu
import monkeyegg
class UpdateEgg( monkeyegg.MonkeyEgg ):
def __init__(self):
monkeyegg.MonkeyEgg.__init__(self);
def get_commands(self):
return [
( ("update"), self.update )
]
... |
import os
from .character import Character
class Scanner(object):
"""docstring for Scanner."""
ENDMARK = '\0'
def __init__(self, source_text):
super(Scanner, self).__init__()
self.source_text = source_text
self.last_index = len(source_text) - 1
self.source_index = -1
... |
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "E07000242"
addresses_name = "local.2019-05-02/Version 1/Democracy_Club__02May2019E Herts.tsv"
stations_name = "local.2019-05-02/Version 1/Democracy_Club__02Ma... |
import sys
from datetime import datetime, timedelta
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.fields.field_user_value import FieldUserValue
from office365.sharepoint.listitems.listitem import ListItem
from tests import test_team_site_url, test_client_credentials, test_user... |
import os, nltk, json, argparse
from gensim.models import Word2Vec
def gen_formatted_data_imdbv1(data_dir):
data = []
for filename in os.listdir(data_dir):
file = os.path.join(data_dir, filename)
with open(file, 'r') as f:
content = f.readline().lower()
content_formatted... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .building_type import BuildingType
class MaintainableBuilding(BuildingType):
""" A Massilian building that requires maintenance each year. """
building_maintenance = models.DecimalField(_('Maintenance expenses'), max_di... |
# -*- coding: utf-8 -*-
"""
=============================
Crack Egg
=============================
This an example of how to crack an egg (take a slice of subjects/lists from it)
"""
# Code source: Andrew Heusser
# License: MIT
#import
import quail
#load data
egg = quail.load('example')
#crack egg
cracked_egg = qu... |
# -*- coding: utf-8 -*-
import KBEngine;
from KBEDebug import *;
import GameUtils;
MAX_FOOD_CNT = 100
class Room(KBEngine.Entity):
def __init__(self):
KBEngine.Entity.__init__(self);
INFO_MSG("Cell Room init ...");
KBEngine.globalData["CellRoom"] = self;
for i in range(MAX_FOOD_CNT... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/firestore_v1beta1/proto/write.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection... |
# -*- coding: utf-8 -*-
# Copyright (C) 2016-2017 Cordell Bloor
# Published under the MIT License
"""Find C or C++ header files with incorrect or missing include guards."""
from __future__ import print_function
import argparse
import sys
import os
from functools import partial
from .pattern_compiler import compile_pa... |
import os
import re
import subprocess
from functools import partial
from typing import List, NewType, cast
from utils import get_console_encoding
console_encoding = get_console_encoding()
Drive = NewType("Drive", str)
# Get a list of logical drive letters
def get_logical_drives() -> List[Drive]:
result = sub... |
# --------------
#Code starts here
senior_citizens=census[census[:,0]>60]
working_hours_sum=np.sum(senior_citizens[:,6])
senior_citizens_len=senior_citizens[:,0].size
avg_working_hours=working_hours_sum/senior_citizens_len
print(avg_working_hours)
# --------------
#Code starts here
race_0=census[census[:,2]==0]... |
#!/usr/bin/env python
# The listen action in a task plan
import rospy
import actionlib
from task_executor.abstract_step import AbstractStep
from actionlib_msgs.msg import GoalStatus
from hlpr_speech_msgs.srv import SpeechService
class ListenAction(AbstractStep):
# Currently we use the service to get the speec... |
#!/usr/bin/env python
import sys, time
import serial
from pexpect import fdpexpect
# Speech synthesis is optional and requires espeak (for Linux)
try:
import pyttsx3
enable_speech = True
except ImportError:
enable_speech = False
def check_prompt(AP):
time.sleep(0.1)
AP.send('\n')
time.sl... |
def test_metronome(dcos_api_session):
job = {
'description': 'Test Metronome API regressions',
'id': 'test.metronome',
'run': {
'cmd': 'ls',
'docker': {'image': 'busybox:latest'},
'cpus': 1,
'mem': 512,
'disk': 0,
'user'... |
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.ContactView.as_view(), name="form"),
url(r'^/success$', TemplateView.as_view(template_name="contact/success.html"), name="success"),
]
|
from bika.lims import bikaMessageFactory as _, t
from bika.lims import logger
from bika.lims.browser import BrowserView
from bika.lims.config import POINTS_OF_CAPTURE
from bika.lims.idserver import renameAfterCreation
from bika.lims.interfaces import IResultOutOfRange
from bika.lims.utils import isnumber
from bika.lims... |
import dash_bootstrap_components as dbc
from dash import html
from .util import make_subheading
tooltip = html.Div(
[
make_subheading("Tooltip", "tooltip"),
html.P(
[
"I wonder what ",
html.Span(
"floccinaucinihilipilification", id="t... |
# encoding: utf-8
import logging
import torch
import torch.nn as nn
from torch.nn import DataParallel
# from engine.data_parallel import DataParallel
# #self create dataparallel for unbalance GPU memory size
from ignite.engine import Engine, Events
from ignite.handlers import ModelCheckpoint, Timer,global_step_from_... |
"""Unit tests for the configuration variables"""
from ..src import config as cf
import numpy as np
def test_backendport():
assert isinstance(cf.BACKEND_PORT, int)
def test_host():
assert isinstance(cf.HOST, str)
def test_model():
assert isinstance(cf.MODEL, str)
def test_model_url():
assert isi... |
import os
import numpy as np
import torch
import random
import time
import numba as nb
import yaml
import pickle
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader, Dataset, Sampler, random_split
from tqdm import tqdm
from scipy import stats as s
class SemanticKittiModule(Lightni... |
import numpy as np
import cv2
import utils_box3d
import time
import yaml
image_orig=cv2.imread('kitti.png')
yaw = 0.019480967695382434 #+ np.pi/2
dims = np.array([1.48773544, 1.59376032, 3.74524751])
box_2D = np.array([ 767., 176., 1084., 357.], dtype=np.float)
P = np.array([[7.215377000000e+02, 0.000000000000e+00, ... |
"Implementation of test-runner for nose2 tests."
import os
import traceback
import nose2
from cosmic_ray.testing.test_runner import TestRunner
from cosmic_ray.util import redirect_stdout, redirect_stderr
class Nose2ResultsCollector(object):
"Nose plugin that collects results for later analysis."
def __ini... |
import github3
import pytest
from tests.utils import BaseCase, load
from unittest import TestCase
class TestEvent(BaseCase):
def __init__(self, methodName='runTest'):
super(TestEvent, self).__init__(methodName)
self.ev = github3.events.Event(load('event'))
self.o = load('org')
def set... |
from dataclasses import dataclass
@dataclass
class AdapterConfig(object):
"""Implements the adapter configuration proposed by Houlsby et. al, 2019
in https://arxiv.org/abs/1902.00751."""
add_layer_norm_before_adapter: bool = False
add_layer_norm_after_adapter: bool = False
non_linearity: str = "ge... |
"""
__author__ = HackPrinceton 2017 Best Team
__description__ = Initializes files for processing module
"""
|
# Copyright 2020 The FedLearner 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 utime
import math
from array import array
from machine import Pin, PWM, Timer
from sound import Sound
def read_words(filename):
buffer = bytearray(128)
with open(filename, 'rb', buffering=0) as file:
while True:
n = file.readinto(buffer)
if n == 0:
break
... |
from __future__ import division
import os
import datetime
import pandas as pd
import numpy as np
from configparser import ConfigParser, NoOptionError, NoSectionError
import glob
import cv2
from pylab import cm
from simba.rw_dfs import *
from simba.drop_bp_cords import *
def ROI_directionality_other_anima... |
#camera.py
import cv2
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
def __del__(self):
self.video.release()
def get_frame(self):
success, image = self.video.read()
ret, jpeg = cv2.imencode('.jpg', image)
return jpeg.tobytes()
|
from __future__ import division, print_function, absolute_import
from nnmnkwii import paramgen as G
import numpy as np
def _get_windows_set():
windows_set = [
# Static
[
(0, 0, np.array([1.0])),
],
# Static + delta
[
(0, 0, np.array([1.0])),
... |
import asyncio
import blinker
from .reify import reify
from .periodic import Periodic
from .timers import Timers
import logging
logger = logging.getLogger(__name__)
class Deck:
key_spacing = (36, 36)
def __init__(self, deck, keys=None, clear=True, loop=None, **kw):
self._loop = loop or asyncio.get_... |
from django.conf.urls import url
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
url('^$',views.home,name='home'),
url(r'^location/(\d+)',views.location,name='location'),
url(r'^search/',views.search,name='search')
]
if settings.DEBUG:
urlp... |
import argparse
from pathlib import Path
from metadata import SEQUENCES
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--skeleton", type=str, default="BODY_135")
args = parser.parse_args()
root = args.root
skeleton ... |
from requests import get
import zipfile
from tkinter import messagebox
def update(interface):
data = get(interface.data["version_url"])
with open("./{0}/siva_update.zip".format(interface.data["directory_name"]), "wb") as out:
out.write(data.content)
zip = zipfile.ZipFile("./siva_files/siva_update.z... |
import networkx as nx
import numpy as np
word_delimiters = ['!', '"', '#', '%', '&', '(', ')', '*', '+',
',', '-', '.', '...', '......', '/', ':', ';',
'<', '=', '>', '?', '@', '[', ']', '^', '_',
'`', '{', '|', '}', '~', ',', '。', '。。。',
'。。。... |
from helper import unittest, PillowTestCase, hopper
# Not running this test by default. No DOS against Travis CI.
from PIL import PyAccess
import time
def iterate_get(size, access):
(w, h) = size
for x in range(w):
for y in range(h):
access[(x, y)]
def iterate_set(size, access):
(... |
import json
import os
import re
import sys
from jsonschema import validate, exceptions
from icon_validator.rules.validator import KomandPluginValidator
from icon_validator.exceptions import ValidationException
class OutputValidator(KomandPluginValidator):
def __init__(self):
super().__init__()
s... |
# 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 archr
import unittest
from common import build_container
class TestAnalyzerQTrace(unittest.TestCase):
@classmethod
def setUpClass(cls):
build_container("cat")
def check_qtrace_results(self, target, **kwargs):
import qtrace
analyzer = archr.analyzers.QTraceAnalyzer(target)... |
""" This script contains the implementation of the MAML algorithms designed by
Chelsea Finn et al. (https://arxiv.org/pdf/1703.03400).
Implementation inspired from the following github repo:
https://github.com/facebookresearch/higher/blob/master/examples/maml-omniglot.py
Terminology:
------------
Support set : a set... |
from cloudshell.shell.core.driver_context import ResourceCommandContext, AutoLoadDetails, AutoLoadAttribute, \
AutoLoadResource
from collections import defaultdict
class LegacyUtils(object):
def __init__(self):
self._datamodel_clss_dict = self.__generate_datamodel_classes_dict()
def migrate_autol... |
# Copyright (c) 2022, Josef Engelskirchen and Contributors
# See license.txt
# import frappe
import unittest
class TestComplaintText(unittest.TestCase):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.