content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
from setuptools import setup
import os
import colorutils
if os.path.exists('README.rst'):
description_long = open('README.rst').read()
else:
description_long = """ A utility which allows you to work with colors in Python. """
setup(
name='colorutils',
packages=['colorutils'],
... |
# Copyright 2017 Lyuben Bahtarliev
from __future__ import absolute_import
import logging
import ujson
import datetime
import socket
import re
import netaddr
import urllib
import urllib2
from minemeld.ft.base import _counting
from minemeld.ft import table
from minemeld.ft.utils import utc_millisec
#from minemeld.ft ... |
#!/usr/bin/python3
import json
import paho.mqtt.client as mqtt
MQTT_SERVER = 'mqttpi.rawr.lan'
MQTT_PORT = 1883
def main():
client = mqtt.Client()
client.connect(MQTT_SERVER, MQTT_PORT, 60)
data = {
'bat_v': 4.2,
'temp_f': 72.2,
'light_vis': 10,
'light_ir': 10,
... |
from flask import Flask, render_template, request
import sqlite3 as sql
import pandas as pd
import time
app = Flask(__name__,template_folder="static")
#########################################################################################################################
@app.route('/')
def home():
return render_t... |
from django.test import TestCase
from .models import Product
from rest_framework.test import APITestCase
import json
# Create your tests here.
class CheckProductAPITest(APITestCase):
def test_register_product(self):
product_1 = {'id': '1', 'fk_vendor':'1', 'name': 'test_product', 'price': '0.0', 'photo': '... |
#!/usr/bin/env python3
# coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
"""
Notice that this is used as a submodule of groups'a app module
"""
import logging
from aiohttp import web
from servicelib.aiohttp.application_setup import ModuleCategory, app_module_setup
from .service_client import SciCrunch
from .settings import get_plugin_settings
logger = logging.getLogger(__name__)
@a... |
#!/usr/bin/python
from utils.utils import print_time_log
import time
def find_last_ten_digits(start: int, end: int):
"""
Find the last ten digits of the series,
11 + 22 + 33 + ... + 10001000.
:param start:
:param end:
:return:
"""
start_time = time.time()
numbers = []
for n... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def getCountRec(... |
# Affichage de la date de refresh des données
from datetime import datetime
tree = etree.parse(configGet('tmpFileDataXml'))
msg_1='Last update : '
msg_2=''
msg_3=''
msg_4='?'
for datas in tree.xpath("/devices/device/timerefresh"):
msg_4=datetime.utcfromtimestamp(int(datas.text)).strftime('%H:%M:%S %Y-%m-%d')
... |
import PikaStdLib
import PikaStdDevice
import PikaStdData
import GTestTask
import PikaMath
import PikaDebug
from PikaObj import *
pkdb = PikaDebug.Debuger()
i = 0
while i < 10:
i = i + 1
print('i :' + str(i))
# pkdb.set_trace()
|
# -*- coding: utf-8 -*-
# Copyright 2016 Yelp 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 ag... |
import os
from riffdog.config import RDConfig
DEFAULT_REGION="us-east-1"
def add_args(parser):
group = parser.add_argument_group('AWS Resource')
group.add_argument('--aws_region', help="AWS regions to use", action='append')
def config():
config = RDConfig()
config.aws_regions = get_default_regi... |
import json
import pytest
import server
@pytest.fixture
def client():
"""Set up a test client"""
with server.app.test_client() as client:
yield client
def test_nonexistent_routed(client):
"""Request a non-existent endpoint"""
resp = client.get('/random')
assert resp.status_code == server.... |
#;this program filter out odd points in the vector v, one-year ndvi curve should be both sides are low and middle is hight.if ther are some points with very low values,they are considered as odd points, take them off and interpol them.
#;input, v---vector,output: returned vector named rtr. if minpoint-lowvalu > 0.4 tak... |
import os
from pathlib import Path
from step import Step
from util import Util
from app_settings import AppSettings
class ProjectCreateFolders(Step):
def __init__(self):
super().__init__()
# folders define in Step
# folders defined in project_environment
self.description=['Create fo... |
import random
import secrets
import os
from datetime import datetime
from flask import Flask, render_template, redirect, url_for, send_file, request
from flask_sqlalchemy import SQLAlchemy
from flaskwebgui import FlaskUI
from win10toast import ToastNotifier
from flask_uploads import UploadSet, configure_uploads, ALL
im... |
from header import *
from models import load_model
from dataloader import load_dataset
def parser_args():
parser = argparse.ArgumentParser(description='train parameters')
parser.add_argument('--dataset', default='zh50w', type=str)
parser.add_argument('--model', type=str)
parser.add_argument('--batch_si... |
from outils import *
_media_endings = ['odt', 'doc', 'docx', 'xls', 'xlsx', 'wp']
def open(filenames):
first = filenames[0]
ext = get_extension(first)
if ext in _media_endings:
return ['libreoffice', '--view'] + filenames
|
import pysfm
import serial
print pysfm.__version__
module = pysfm.Module("COM6")
if module.connect() == False:
exit(-100)
print ('Start >>')
parameter_id = pysfm.UF_SYS_TIMEOUT
parameter_value = 0x33
# Read system parameter
module.send_command(command=pysfm.UF_COM_SR,param=0, size=0, flag=parameter_id)
module... |
class SuuntoException(Exception):
pass
class SuuntoDurationException(SuuntoException):
pass
|
'''OpenGL extension NV.bindless_texture
This module customises the behaviour of the
OpenGL.raw.GLES2.NV.bindless_texture to provide a more
Python-friendly API
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/NV/bindless_texture.txt
'''
from OpenGL import platform, co... |
import argparse
import gc
import os
import sys
import timeit
import torch
from torch import optim
from tqdm import tqdm
# import project module
import feeders
from config import load_config
from model.tc_laau_bd import TC_LAAU_BD
from utils import AverageMeter, init_seed, save_checkpoint, format_time, Logger, calc_to... |
from app.dto.user_input import UserInput
from app.dto.user_response import UserResponse
from app.dto.user_update import UserUpdate
from app.core.auth import *
from app.services.users import *
from fastapi import APIRouter, status
router = APIRouter()
@router.get("/user", tags=["user"], response_model=UserResponse)
d... |
# @Author : bamtercelboo
# @Datetime : 2018/1/31 10:01
# @File : train.py
# @Last Modify Time : 2018/1/31 10:01
# @Contact : bamtercelboo@{gmail.com, 163.com}
"""
FILE : train.py
FUNCTION : None
"""
import os
import sys
import torch
import torch.nn.functional as F
import torch.nn.utils as utils
import shutil... |
from Vector import *
class Function():
|
""" Functions for generating report tables in different formats """
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the ... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, so... |
import discord
import random
import datetime
import time
from discord.utils import get
from discord.ext import tasks
import sys
import os
current_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(current_dir)
parent_dir = os.path.dirname(parent_dir)
sys.path.append(parent_dir)
import Packa... |
model = dict(
input_size = 320,
init_net = True,
pretrained = 'None', # res series, directly load the pretrained weights when defining them
rgb_means = (104, 117, 123),
label_type = 'both' , #there are both positive label and negative label,use one of these or use both,
crop_type = True # if to crop ... |
# coding: utf-8
# 封装其他模块对模型的修改接口
# 外部模块只能通过本文件的函数对模型进行修改
from global_data import SUCCESS, Orders, Trucks, Bases
# truck接单,修改模型相关状态:truck/order/base
# 传入参数为object
# 返回是否修改成功
from model.base_model.base import Base
def model_truck_take_orders(truck_id, order_ids):
result = SUCCESS
truck = Trucks[truck_id]
... |
from datetime import datetime, date
import os
import errno
log_dir = ""
plot_hash = ""
plot_type = ""
num_points = 0
def log_complete(successful):
if log_dir:
make_sure_path_exists(log_dir)
_datetime = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
_date = date.today().strftime("%Y-%m-%d")
i... |
from setuptools import setup
version = '0.1'
setup(
name='tf2schema',
packages=['tf2schema'],
version=version,
description='Python lib for various tf2 schema related tasks',
author='Jędrzej Szadejko',
author_email='shadyprywatny@gmail.com',
license='MIT',
url='https://github.com/Jertu... |
sm.warp(262010000, 0)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file contains the additional color segmentation algorithms used after the
color filters have been run
"""
import sklearn.linear_model as lm
import sklearn.neighbors as nei
import numpy as np
from . import settings
# this function creates the color masks
# give... |
# vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# 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... |
import jinja2
import math
import os
import sys
from datetime import date
from taiga import TaigaAPI
from taiga.exceptions import TaigaException
from weasyprint import HTML
from .configuration import Configuration
from .messages import success_message, error_message, progress_message
from .prompts import ask_credenti... |
import factory
from faker import Factory as FakerFactory
from pytest_factoryboy import register
from activities.models import Activity, Tag
from tests.unit_tests.test_accounts.factories import UserFactory
faker = FakerFactory.create()
class TagFactory(factory.django.DjangoModelFactory):
class Meta:
mode... |
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from urllib import quote_plus
from datetime import datetime
from datetime import timedelta
import base64
import hmac
import hashlib
import json
UPLOADIFY_OPTIONS = ('auto', 'buttonImg', 'buttonText', 'cancelImg', 'checkScript', 'd... |
# The contents of this file are subject to the BitTorrent Open Source License
# Version 1.1 (the License). You may not copy or use this file, in either
# source code or executable form, except in compliance with the License. You
# may obtain a copy of the License at http://www.bittorrent.com/license/.
#
# Softwa... |
#misc
import sys
#data processing
import numpy as np
import pandas as pd
from scipy.fftpack import rfft
from scipy import optimize
from statsmodels.tsa.arima_model import ARIMA
#plotting
import matplotlib.pyplot as plt
#home-made
sys.path.append('../../utils')
from preprocessing import temp_forecasting_shape_processing... |
from flask import render_template, Blueprint, g, request, current_app
from flask_babel import _
multilingual = Blueprint('multilingual', __name__, template_folder='templates',
url_prefix='/<lang_code>')
@multilingual.url_defaults
def add_language_code(endpoint, values):
values.setdefault... |
import pickle
class QSerializer:
def __init__(self):
self.elements = {}
# Add an element to the serializer (e.g: name = "statevector", obj = <the statevector object>)
def add_element(self, name, obj):
self.elements[name] = obj
# Convert all the elements to one string
def encode(se... |
"""Test for showroom_podcast.py."""
import logging
from click.testing import CliRunner
from showroompodcast.cli import showroom_podcast
class TestShowroomPodcast:
"""Test for ShowroomPodcast."""
@staticmethod
# Reason: pytest fixture. pylint: disable=unused-argument
def test(
mock_requrst_r... |
#cria um dicionario
#cada chave possui em valores 1 ou mais elementos
#depois imprimi chaves e valores
lugares_favoritos = {
'alan' : ['copacabana','fernando noronha'],
'lucas' : ['rio grande do norte'],
'monica': ['rio de janeiro','porto seguro','ilha bela'],
}
for name, lugares in lugares_favoritos.i... |
from django.apps import AppConfig
class DjangoecommerceappConfig(AppConfig):
name = 'DjangoEcommerceApp'
|
from sympy import *
from part_b.b_constants import R
def A_s(A_e, A_ratio):
return A_e / A_ratio
def Thrust_eq(P0, Pa, Pe, gamma_s, gamma_e, As, Ae, T0, Me, R=R):
P_0 = Symbol('P_0')
P_a = Symbol('P_a')
P_e = Symbol('P_e')
g_s = Symbol('γ*')
g_e = Symbol('γₑ')
A_s = Symbol('A*')
A_e = Symbol('Aₑ')
T_0 = Sy... |
import json
import os
import sys
import argparse
import codecs
import re
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument('-b', dest='base', type=str)
parser.add_argument('-s', dest='source', type=str)
parser.add_argument('-d', dest='destination', type=str)
parser.add_argument('--debug',... |
from .collab import Collab, BaseCollab, collab_from
from .schema_base import Schema
from .auth import AuthKey, create_key, Auth |
from .base_action import *
from resource import *
@Actions.register("mysql.exec")
class MySQLExecAction(BaseAction):
"""
:param sql || string
:param mysqlconnection || string
"""
def execute_impl(self, context, db):
with db.cursor() as cursor:
action_config = self.get_action_... |
# webhook.py
import os
from app import app
from app.toolbox import albumdetails, averagecolor
import sys
def temp_token():
'''Generates Webhook Verify Token to work until server is killed'''
import binascii
temp_token = binascii.hexlify(os.urandom(24))
return temp_token.decode('utf-8')
def setup_tok... |
from suds.client import Client
from suds import WebFault
from model.project import Project
class SoapHelper:
def __init__(self, app):
self.app = app
def can_login(self, username, password):
client = Client(self.app.soap_url)
try:
client.service.mc_login(username, password... |
#
# NB! Several GC2D parameters that are not used yet have been
# "disabled" in set_gc2d_parameters() and in the GUI info
# file, such as "lapse_rate".
#
#-----------------------------------------------------------------------
# Copyright (c) 2009-2020, Scott D. Peckham
#
# May 2020. Added disable_all_output(... |
# Reinforcement learning for CTR optimization - Thompson Sampling
import numpy as np
import random
# this is an Lucko515'a implementation of the Thompson Sampling algorithm that I found on his GitHub:
# https://github.com/lucko515/ads-strategy-reinforcement-learning/blob/master/Thompson%20sampling%20Algorithm/thompso... |
# Simple demo of reading each analog input from the ADS1x15 and printing it to
# the screen.
# Author: Tony DiCola
# License: Public Domain
import time
import math
# Import the ADS1x15 module.
import Adafruit_ADS1x15
# Create an ADS1115 ADC (16-bit) instance.
adc = Adafruit_ADS1x15.ADS1115()
# Or create an ADS1... |
from enum import Enum, auto
class SymbolType(Enum):
EXTERN = auto()
MACRO = auto()
NO_TYPE = auto()
PARAM = auto()
ROUTINE = auto()
UNDEFINED = auto()
UNKNOWN = auto()
VAR = auto()
class Symbol:
def __init__(self, name='', symbol_type=SymbolType.UNDEFINED, value=None):
self... |
from __future__ import annotations
#
from framework.database import models, BaseModel
from utils.snowflake import new_id
class User(models.Model, BaseModel):
class Meta:
app_label = 'trade'
db_table = 'user'
unique_together = [
('user_id',),
('openid',),
]
... |
def get_model_name(model):
"""
Get name of model
:param model:
:return:
"""
return model['hyper_params']['name']
|
import requests
import json
def test_face_match():
url = 'http://127.0.0.1:5001/face_match'
# open file in binary mode
files = {'file1': open('sample_images/peter.jpg', 'rb'),
'file2': open('sample_images/peter2.jpg', 'rb')}
resp = requests.post(url, files=files)
print( 'face_matc... |
from unittest import mock
import pytest
from datahub.search.apps import get_search_app, get_search_app_by_model
@mock.patch('datahub.search.apps._load_search_apps')
class TestGetSearchApp:
"""Tests related to `get_search_app`."""
def test_found(self, mocked_load_search_apps):
"""
Test that ... |
from metaflow import FlowSpec, step, DoltDT
import json
import numpy as np
class DoltDemoFlow(FlowSpec):
@step
def start(self):
import pandas
self.df = pandas.read_csv('movies.csv')
self.next(self.add_random)
# Add a random number to the gross column.
@step
def add_rando... |
import argparse
import json
import logging
from datetime import datetime
from os import path
from sbeval.constants import LOGGING_CONFIG
from sbeval.weat_test import weat_score
from sbeval.word_vectors import CustomEmbeddings
def weat_evaluation(lexicons: dict, embeddings_model) -> dict:
weat_results = {}
... |
import os
import boto3
from datetime import date
from google.cloud import storage
data_earliest_year = 2020
data_earliest_month_in_earliest_year = 8
def get_months_covering_data_as_of_today():
today = date.today()
return get_months_covering_data(today.year, today.month)
def get_months_covering_data(year, m... |
"""
This file contains configuration variables used to interact with the COVID-NET API.
Author: Eu Jing Chua
Created: 2020-06-12
"""
class APIConfig:
"""Static configuration variables."""
# API Parameters
INIT_URL = "https://gis.cdc.gov/grasp/covid19_3_api/GetPhase03InitApp"
MMWR_COLS = ["year", "wee... |
from utils import CanadianJurisdiction
class StrathconaCounty(CanadianJurisdiction):
classification = 'legislature'
division_id = 'ocd-division/country:ca/csd:4811052'
division_name = 'Strathcona County'
name = 'Strathcona County Council'
url = 'http://www.strathcona.ca'
|
#!/usr/bin/env python3
import subprocess
import sys
import executor
def get_active_sink():
return executor.execute('pacmd list-sinks | grep "* index" | awk \'{print $3}\'')
def get_volume():
return executor.execute('amixer -D pulse get Master | grep -o "\[.*%\]" | grep -o "[0-9]*" | head -n1')
def set_volume(pe... |
# Generated by Django 3.1.8 on 2021-05-18 07:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("aidants_connect_web", "0055_auto_20210503_1729"),
]
operations = [
migrati... |
#!/usr/bin/env python3
import serial
PORT = 'COM10' # The com port to receive data
BAUD = 115200 # Baud rate used by the com port
TIMEOUT_S = 1
# Open the connection
with serial.Serial(PORT, BAUD, timeout=TIMEOUT_S) as com:
# Keep receiving data until FicTrac closes
while com.is_open:
... |
__all__ = ('KPMain', )
from kivy.properties import ObjectProperty, NumericProperty
from kivy.event import EventDispatcher
from kivy.factory import Factory as F
from kivy.lang import Builder
import asynckivy
Builder.load_string('''
#:import theme kivy_paint.theme
#:import md_icons kivymd.icon_definitions.md_icons
<KP... |
#This is for
# Get the Suitable references
import sys
sys.path.append("c:\\projects\\sharpduino\\sharpduino\\bin\\debug")
import clr
clr.AddReference("Sharpduino")
# Import namespaces that we need
from Sharpduino import *
from Sharpduino.SerialProviders import *
from Sharpduino.Messages import *
from Sharpduino.Cons... |
from collections import Counter
from itertools import chain
from textgraph import TextGraph, count_ww_dw, count_dw
def prepare_dummy_data():
corpus = [
"The quick brown fox jumps over the lazy dog",
"The fox is quick",
"The dog is lazy",
"The fox is brown",
... |
from __future__ import with_statement
from pyps import workspace,module
#Deleting workspace
workspace.delete("hyantes")
#Creating workspace
w = workspace("hyantes/hyantes.c","hyantes/options.c",cppflags='-Ihyantes',name="hyantes",deleteOnClose=True)
#Add some default property
w.props.abort_on_user_error=True
w.acti... |
'''
Built on on SAC implementation from
https://github.com/pranz24/pytorch-soft-actor-critic
'''
import random
import numpy as np
from operator import itemgetter
class ReplayMemory:
"""
Replay buffer for training SAC task policy and associated Q function
"""
def __init__(self, capacity, seed):
... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from builtins import zip
from builtins import range
from builtins import object
from ..ternary import normal
from ..misc import *
import itertools
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from m... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.exceptions import ObjectDoesNotExist
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=mode... |
from django.shortcuts import render
# Create your views here.
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from .models i... |
from ..abstract_formulation import AbstractFormulation
from ...runtime_utils import parallelized_rt
class NCFlowAbstract(AbstractFormulation):
@property
def runtime(self):
return self.runtime_est(14) # Hardcoded for GCR machines
def runtime_est(self, num_threads, breakdown=False):
rts =... |
################
"""
sb ExportNodesAsScript
Simon Bjork
October 2014
Version 1.0
bjork.simon@gmail.com
Synopsis: Exports the selected nodes as a script, including the Root node (most knobs).
OS: Windows/OSX/Linux
Installation (menu.py):
nuke.menu('Nuke').findItem('File').addCommand('Export Nodes As Script (... |
# -*- coding: utf-8 -*-
import torch.nn as nn
__all__ = ['mlp']
class MLP(nn.Module):
def __init__(self, dataset, num_layers, hidden_size, drop_rate):
super(MLP, self).__init__()
self.dataset = dataset
# init
self.num_layers = num_layers
self.num_classes = self._decide_n... |
#!/usr/bin/env python3
"""Advent of Code 2021 Day 5 - Hydrothermal Venture"""
import re
with open('inputs/day_05.txt', 'r') as aoc_input:
lines = [re.findall(r'(\d*),(\d*)', x) for x in aoc_input.readlines()]
lines = [[(int(x), int(y)) for x, y in tup] for tup in lines]
coords_dict = {}
for line in lines:
... |
# encoding: utf-8
#pylint: disable=R0904
""" The kicad parser test class """
# upconvert.py - A universal hardware design file format converter using
# Format: upverter.com/resources/open-json-format/
# Development: github.com/upverter/schematic-file-converter
#
# Copyright 2011 Upverter, Inc.
#
# Licensed unde... |
import tensorflow as tf
def content_lookup(memory_matrix, key, key_strength):
def cosine_sim(u, v):
return tf.math.truediv(tf.linalg.matmul(u, v), tf.math.multiply(tf.norm(u), tf.norm(v)))
key = tf.transpose(key)
return tf.nn.softmax(cosine_sim(memory_matrix, key) * key_strength)
|
import PyPluMA
class TSVFilterPlugin:
def input(self, filename):
self.inputfile = open(filename, 'r')
def run(self):
self.parameters = dict()
for line in self.inputfile:
contents = line.strip().split('\t')
self.parameters[contents[0]] = contents[1]
self.filestuff =... |
#!/usr/bin/env python
from netmiko import ConnectHandler
from getpass import getpass
user = input("Insert your Python class Username: ")
passcode = getpass("Insert your Password: ")
device1 = {
'host' : 'nxos1.lasthop.io',
'username' : user,
'password' : passcode,
'device_type' : 'cisco_nxos',
... |
import numpy as np
# import cv2
# create gaussian filter kernel matrix
def create_kernel(o, n):
return list(cv2.getGaussianKernel(ksize=n,sigma=o).T[0])
# apply gaussian filter to 1 action of the skeleton data
# notes:
# - input: skeleton data for 1 action (x, 20, 5)
# - output: skeleton data with GF appl... |
import numpy as np
import operator
from imp import reload
# k近邻算法实现
# data=[[1,1.1],[1,1],[0,0],[0,0.1]]
# dataSet=np.array(data)
# labels=['A','A','B','B']
def classify0(inX,dataSet,labels,k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inX,(dataSetSize,1)) - dataSet
sqDiffMat = diffMat**2
sqDis... |
class CharParser(object):
def __init__(self):
self.details = {
'name': 'Char Name',
'player': 'Unknown Player'
}
def parse(self, text):
raise NotImplementedError()
|
"""
This module defines tests to run against the fields module.
https://docs.djangoproject.com/en/3.0/topics/testing/
"""
from datetime import datetime, timezone
from django.test import TestCase
from .forms import AgreementBaseForm
class AgreementBaseFormTestCase(TestCase):
"""Tests for the AgreementBaseForm.... |
expected_output={
'bfd-session-information': {'bfd-session': {'adaptive-asynchronous-transmission-interval': '1.000',
'adaptive-reception-interval': '1.000',
'bfd-client': {'client-name': 'OSPF',
... |
#!/usr/bin/env python3
from zipfile import ZipFile
from os.path import isdir
from os import listdir
def jar_extract(mcpath):
if (isdir("assets/") == False):
versions = listdir(mcpath + 'versions/')
for i in range(len(versions)):
print(i, ":", versions[i])
try :
v = i... |
import numpy as np
g = {1: [2, 5, 8, 17],
3: [4, 6, 19],
5: [3],
7: [1, 8],
11: [16],
14: [5],
17: [2],
20: [15]}
def salsa(hub_ids, auth_ids, g):
# create map from matrix index to id in graph
hlen = len(hub_ids)
alen = len(auth_ids)
hmap = dict([p for p in enumera... |
# This module is automatically generated by autogen.sh. DO NOT EDIT.
from . import _Azure
class _Identity(_Azure):
_type = "Identity"
_icon_dir = "resources/azure/Identity"
class ActiveDirectoryConnectHealth(_Identity):
_icon = "active-directory-connect-health.png"
class ActiveDirectory(_Identity):
... |
import pytest
from mock import patch, call
import requests
from botbot_plugins.base import DummyApp
from botbot_plugins.plugins import github
class FakeResponse(object):
"""Dummy response from GitHub"""
status_code = 200
json = lambda x: {
'title': 'PICARD-XX: Test YYY',
'html_url': 'https... |
import json
import time
import os
import joblib
import numpy as np
import pandas as pd
from joblib import load, dump
from tqdm import tqdm
import logging
from pymoo.core.problem import Problem
from pymoo.algorithms.moo.nsga2 import NSGA2
from pymoo.optimize import minimize
from pymoo.factory import get_sampling, get_... |
from httprunner import exceptions, logger, parser, utils
class SessionContext(object):
""" HttpRunner session, store runtime variables.
Examples:
>>> variables = {"SECRET_KEY": "DebugTalk"}
>>> context = SessionContext(variables)
Equivalent to:
>>> context = SessionContext()
... |
import secrets
from py4web import response
from .fixtures import auth
from .schemas import DiscordUser, GameSessionFull, GameSessionRole, GameSessionRule, GameSignupFull, SignupRole, \
SignupTime
# ---- api utils ----
def success(data, code=200):
response.status = code
return {"success": True, "data": d... |
from neo4j import GraphDatabase
import json
import os
driver = GraphDatabase.driver("bolt://localhost:7687/")
session = driver.session()
def searchForStaticBufferOverflows():
configFile = os.path.join(os.path.dirname(__file__), "defaultConfigs.json")
with open(configFile, "r") as configs:
configuratio... |
def store_email(liste_mails):
res = {}
for addr in liste_mails:
n = addr.split('@')
if n[1] not in res:
res[n[1]] = []
res[n[1]].append(n[0])
res[n[1]].sort()
return res
print(store_email(["ludo@prof.ur", "andre.colon@stud.ulb",
"thierry@profs.ulb"... |
import os
import pygame
import inspect
import argparse
import importlib
from multiprocessing import Process
from arena import Arena
def get_agent():
# Get agent type
p_type = input("Player type: ")
agent_mod = importlib.import_module(p_type + ".agent")
for name, cls in inspect.getmembers(agent_mod, inspect.i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.