content
stringlengths
5
1.05M
"""TODO(rpeloff) Author: Ryan Eloff Contact: ryan.peter.eloff@gmail.com Date: September 2019 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import logging import numpy as np from moonshot.experiments.flickr_speech import flickr_speech ...
from django.urls import reverse from django.test import SimpleTestCase from netbox_dns import __version__ from netbox_dns.tests.custom import APITestCase class NetboxDnsVersionTestCase(SimpleTestCase): """ Test for netbox_dns package """ def test_version(self): assert __version__ == "0.11.0"...
""" Implements the base Parser as a Context Manager. """ from abc import ABCMeta, abstractmethod class Parser: """ Base abstract class for a parser. Further parsers should inherit from this and override the abstract parse() method. """ __metaclass__ = ABCMeta def __init__(self, filename)...
from tool.runners.python import SubmissionPy from collections import defaultdict from string import ascii_uppercase import bisect class DavidSubmission(SubmissionPy): NUM_WORKERS = 5 FIXED_WORK_DURATION = 60 def run(self, s): # :param s: input in string format # :return: solution flag ...
# Copyright 2019 The OpenSDS 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 in ...
from __future__ import absolute_import from logging import warning from traceback import print_exc from traceback import print_stack from traceback import extract_stack from dramatis.actor.name.interface import Interface as _Interface class PropertyProxy(object): def __init__(self,attr,actor,options): su...
## @file # process FD Region generation # # Copyright (c) 2007 - 2014, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license ...
# -*- coding: utf-8 -*- import numpy as np from vispy import gloo, visuals import os class YTVisual(visuals.Visual): data_vbo = None dtype = () visual_name = None def __init__(self): super(YTVisual, self).__init__() self.shaders = {} curpath = os.path.dirname(os.path.abspath(_...
import json import os from common.renderers.excel_renderer import _write_excel_file import logging from django.contrib.gis.geos import Point from users.models import MflUser from django.core.management import BaseCommand from django.conf import settings from facilities.models import Facility from mfl_gis.models impo...
import pygame from pygame import * from constants import PLAYER, ASSETS, WORLD from worldobject import Movable try: import pygame.mixer as mixer except: import android.mixer as mixer class Player(Movable): def __init__(self, x, y, color_code, width = PLAYER.width, height = PLAYER.height): Movable...
from sys import argv from time import time def main(argv): """Main function for the program.""" # Ensure proper usage. if len(argv) != 4: print("Usage: python %s file_name target_left target_right" % argv[0]) exit(1) file_name = argv[1] start = int(argv[2]) end = int(argv[3]) ...
class MinHeap: def __init__(self): self.H = [None] def size(self): return len(self.H)-1 def __repr__(self): return str(self.H[1:]) def satisfies_assertions(self): for i in range(2, len(self.H)): assert self.H[i] >= self.H[i//2], f'Min heap pro...
import datetime from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import AuthenticationForm from dayslog.models import DaysLog def homepage(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POS...
#!/usr/bin/python3 # -*- encoding: utf-8 -*- __version__ = 1.3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from bs4 import BeautifulSoup from urllib.request import urlopen from mailcomposer import MailComposer from threading import Thread import os import sys import sqlite3 import webbro...
# (c) 2021 Ruggero Rossi ############################################################################# # robosoc2d Matplotlib draw ############################################################################# # to install (be sure to have matplotlib and robosoc2d installed previously): # python3 setup.py install # # t...
# Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. # # Example: # # Input: 3 # Output: # [ # [ 1, 2, 3 ], # [ 8, 9, 4 ], # [ 7, 6, 5 ] # ] class Solution(object): def generateMatrix(self, n): """ :type n: int :rtype: List[List[int]] ...
def uri_to_zip_entry_name(base, uri): if uri.startswith("/"): return uri[1:] else: return base + "/" + uri def replace_fragment(uri, fragment): hash_index = uri.find("#") if hash_index != -1: uri = uri[:hash_index] return uri + "#" + fragment
from typing import List class Solution: def letterCombinations(self, digits: str) -> List[str]: if len(digits) == 0: return [] num_to_char = { "2": ["a", "b", "c"], "3": ["d", "e", "f"], "4": ["g", "h", "i"], "5": ["j", "k", "l"], ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from wdom.event import Event from wdom.themes import H1 def rev_text(event: Event) -> None: elm = event.currentTarget elm.textContent = elm.textContent[::-1] def sample_app(**kwargs) -> H1: h1 = H1('Click!') h1.addEventListener('click', rev_text) r...
# 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 # d...
from charmhelpers.core import hookenv def log_start(service_name): hookenv.log('saiku starting')
from . import db from werkzeug.security import generate_password_hash, check_password_hash from flask_login import UserMixin from datetime import datetime from . import login_manager from flask import jsonify class Roles(db.Model): ''' ''' __tablename__ = 'roles' id = db.Column(db.Integer, primary_key...
def laberinto(dimension, muro): laberinto=[] for i in range(dimension): fila=[] for j in range(dimension): if tuple([i, j]) in muro: fila.append("x") else: fila.append(" ") laberinto.append(fila) return(laberint...
#! /usr/bin/env python3 def isSum(data, number) : return any(True for i in range(len(data)) if number - data[i] in data[i + 1:]) with open("input", "r") as fd : numbers = [int(x) for x in fd.read().split('\n')] for i in range(25, len(numbers)) : if not isSum(numbers[i - 25:i], numbers[i]) : print...
import os import sys import pytest sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from app import create_app, db from app.models import Task tasks = [ { 'id': 1, 'title': '交電話費', 'note': '500元', 'done': False }, { 'id': 2, 'tit...
import urllib.parse from django.contrib.auth.models import User from django.test import TestCase from dfirtrack_main.models import Systemtype class SystemtypeViewTestCase(TestCase): """ systemtype view tests """ @classmethod def setUpTestData(cls): # create object Systemtype.objects.cr...
''' Code specific to Neuron devices ------------------------------------------ ''' import struct import datetime from dali.bus import Bus import dali.gear.general from math import sqrt from tornado import gen from tornado.ioloop import IOLoop from modbusclient_tornado import ModbusClientProtocol, StartClient from pym...
# coding: utf-8 # Copyright 2013 The Font Bakery 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 re...
from gettext import gettext as _ name = _("Working with videos") description = _("Work with videos using multiple functions")
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> def generate_concept_HTML(concept_title, concept_description): html_lesson_1 = ''' <div class="concept"> <div class="concept-title"> '...
from multidict import MultiDict def as_list(key, data): v = data.get(key) if isinstance(v, str): v = [v] elif not isinstance(v, list): v = [] data[key] = v return data def as_dict(data, key="data"): return {key: data} if not isinstance(data, dict) else data def as_params(*,...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-09-28 14:06 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blog', '0009_auto_20170922...
""" Create a Logger for spark application. """ class Log4j: def __init__(self, spark, *args, **kwargs): """Wrapper class for Log4j JVM object. Parameters ---------- spark : session object of spark application """ super(Log4j, self).__init__(*args, **kwargs) ...
from random import Random from bomberman.agents.BaseAgent import BaseAgent from bomberman.states.State import State from bomberman import defines from bomberman.defines import t_action class RandomAgent(BaseAgent): def __init__(self, player_num): self.player_num = player_num print("I Am a random agen...
import pandas as pd import xarray as xr import numpy as np from os.path import abspath, dirname, join # path to the indices directory INDICES_ROOT = dirname(dirname(abspath(__file__))) # path to the folder with large scale indices DATA_ROOT = join(INDICES_ROOT, 'data') def aaoi_index(): filepath = join(DATA_ROOT...
from django.shortcuts import render from vehicles.context_processor import global_context_processor from .forms import ContactForm from dynamic_preferences.registries import global_preferences_registry # import settings so send_mail can have access to email settings from django.conf import settings from django.core.ma...
#-*- coding: utf-8 -*- import hashlib import time from http.server import BaseHTTPRequestHandler, HTTPServer # 이거 파이썬 3.0버전에서만 사용가능함 from socketserver import ThreadingMixIn import json import re from urllib.parse import parse_qs from urllib.parse import urlparse import threading import cgi import uuid from tempfile im...
import telebot from config import keys, TOKEN from utils import CryptoConverter, ConvertionException bot = telebot.TeleBot (TOKEN) @bot.message_handler(commands=['start', 'help']) def help(message: telebot.types.Message): text = 'Чтобы начать работу введите комманду боту в следущем формате:\n<имя валюты> ...
import wave import sys import AudioParse import AudioSteganography """ AudioMain.py Written by: Your Name Here EE Python Workshop 2019 """ """ Description: This is the main file which you use to run your audio steganography program. What this program will do is, based on user inputs, be able to either: ...
""" Loxone constants For more details about this component, please refer to the documentation at https://github.com/JoDehli/pyloxone-api """ # Loxone constants TIMEOUT = 10 KEEP_ALIVE_PERIOD = 240 IV_BYTES = 16 AES_KEY_SIZE = 32 SALT_BYTES = 16 SALT_MAX_AGE_SECONDS = 60 * 60 SALT_MAX_USE_COUNT = 30 TOKEN_PERMISSI...
import unittest import lippy as lp class TestSimplexMethod(unittest.TestCase): """Class for testing Simplex Method.""" def test_primal_linear_programming(self): c_vec = [6, 6, 6] a_matrix = [[4, 1, 1], [1, 2, 0], [0, 0.5, 4]] b_vec =...
from typing import List, Optional from tpp.models.encoders.base.fixed_history import FixedHistoryEncoder from tpp.pytorch.models import MLP class MLPFixedEncoder(FixedHistoryEncoder): """MLP network using a fixed history encoder. Args units_mlp: List of hidden layers sizes. activation_mlp: A...
from common import * def test_1282(env): env.expect('FT.CREATE idx ON HASH SCHEMA txt1 TEXT').equal('OK') env.expect('FT.ADD idx doc1 1.0 FIELDS txt1 foo').equal('OK') # optional search for new word would crash server env.expect('FT.SEARCH idx', '~foo').equal([1L, 'doc1', ['txt1', 'foo']]) env.expect('FT.SE...
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") def sim_stats(arr): """ Descriptive statistics of simulation results. Parameters ---------- arr: np.array Array of BlackJack simulation results. ...
from dataclasses import dataclass from datetime import date from typing import Callable, Generator import pendulum # type: ignore import pytest # type: ignore from aiohttp import web from aiohttp_storage.tests import storage # type: ignore from config import EnvValueProvider, load # type: ignore from config.provid...
# Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html from scrapy.item import Item, Field from scrapy.contrib.djangoitem import DjangoItem from stamps.models import Stamp, StampInCatalog class ColnectItem(DjangoItem): django_model = Stamp ...
# -*- coding: utf-8 -*- ''' for database schema migration. Memo for Usage: migrate.migrate(torcms_migrator.rename_table('e_layout', 'mablayout')) migrate.migrate(torcms_migrator.drop_column('tabtag', 'role_mask')) ''' from playhouse import migrate from playhouse.postgres_ext import BinaryJSONField import conf...
# Generated by Django 3.1.3 on 2021-03-27 23:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('classic_tetris_project', '0042_auto_20210327_2218'), ] operations = [ migrations.AlterModelOptions( name='tournament', ...
from collections import abc from qtpy import QtCore from qtpy.QtCore import ( QAbstractItemModel, QModelIndex, Qt, ) from qtpy.QtWidgets import QAbstractItemView, QTreeView from databroker.core import BlueskyEventStream class RunTree: """Lazily populate the tree as data is requested. """ def __...
from pydantic import BaseModel class Token(BaseModel): access_token: str token_type: str expires_in: int refresh_token: str id_token: str class User(BaseModel): username: str email: str first_name: str last_name: str
from utils.crypt import Encoder, Decoder from utils.helpers import Parser from api.wsmanager import RoomsManager from db.database import Database from core.config import settings manager = RoomsManager() encoder = Encoder(settings.SECRET_KEY) decoder = Decoder(settings.SECRET_KEY) database = Database() parser = Parser...
# https://leetcode.com/problems/powerful-integers from typing import List class Solution: def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]: st = set() if x == 1 and y == 1: if 2 <= bound: return [2] else: return [] ...
# -*- coding: utf-8 -*- """ Created on Sat Dec 24 14:04:20 2016 @author: Rupak Chakraborty """ import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import BaggingClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import AdaBoostClassifier...
def nomes_com_vogais(nomes): vogais = ["A", "E", "I", "O", "U"] # Nomes que começam com vogais comecam = 0 n_comecam = 0 for nome in nomes: if nome[0] in vogais: comecam += 1 else: n_comecam += 1 return [comecam, n_comecam] print(nomes_com_vogais(["André", "Carlos", "João", "Otavi...
VERSION = (0, 22, 0)
""" Injects context into all views """ from datetime import datetime import pytz from sga.backend.constants import SGA_DATETIME_FORMAT, EPOCH_FORMAT, Roles def logged_in_user(request): """ Injects user data and roles """ try: return { "user_name": request.user.get_full_name(), ...
#!/usr/bin/python #encoding=utf8 import os import sys import subprocess import re import glob ignores = ['.git'] def fnames_filter(fnames): for fname in ignores: if fname in fnames: fnames.remove(fname) def gen_zipfile_name(dirname, start_id): while True: zipfname = os.path.join(dirname, "{:05d}.7z".format(...
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url, include import views urlpatterns = patterns('', # Example chat room. url(r"room/(?P<id>\d+)/$", views.window, name="jqchat_test_window"), url(r"room/(?P<id>\d+)/ajax/$", views.BasicAjaxHandler, name="jqchat_ajax"), # Second example r...
import numpy as np import cifParsing as cPrs import matrices_new as mat from anytree import NodeMixin # from itertools import combinations as combinations # from bisect import bisect_right def check_symmetries_in_cell(cell, matrices=mat.all_matrices): # def func(cell: numpy2d_array(float), # matrices: numpy3d...
# Copyright 2021 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...
#First Solution #O(2^n) time | O(n) space complexity def getNthFib(n): if n == 2: return 1 elif n == 1: return 0 else: return getNthFib(n-1) + getNthFib(n - 2) #Second Solution # O(n) time | O(n) space complexity def getNthFib(n, memoize =-{1: 0, 2: 1}): if n in memoize: ...
import update import pickle import numpy as np import pandas as pd import logging import requests import json from google.cloud import storage from datetime import timedelta from datetime import timezone import googleapiclient.discovery def download_file(filename) : storage_client = storage.Client() ...
from pathlib import Path from fhir.resources.codesystem import CodeSystem from oops_fhir.utils import CodeSystemConcept __all__ = ["v3AcknowledgementType"] _resource = CodeSystem.parse_file(Path(__file__).with_suffix(".json")) class v3AcknowledgementType: """ v3 Code System AcknowledgementType This...
# pixhawk connection # parameter to connect raspberry pi with pixhawk connection = "/dev/ttyS0" # when connecting to pixhawk via serial connection timeout = 30 # how long in second dronekit should keep reconnect baud = 57600 # baudra...
from .pwlf import PiecewiseLinFit # noqa F401 from .version import __version__ # noqa F401
# # dopo aver eseguito il programa si puù iniziare subito a giocare # # la macchina arancione verrà controllata dal tasto Q # # la macchina azzurra verrà controllata dal tasto R # # la macchina rossa verrà controllata dal tasto U # # la macchina verde verrà controllata dal tasto P # # # per vincere bisogna ...
import json from pathlib import Path import numpy as np import pandas as pd import pytest from pandera.typing import DataFrame from pytest_mock import MockerFixture from sklearn.exceptions import NotFittedError import socceraction.spadl as spadl import socceraction.xthreat as xt from socceraction.spadl import SPADLSc...
from typing import List from kafka import KafkaConsumer from atlas_kafka_event_listener.HiveEventHandler import HiveEventHandler from atlas_kafka_event_listener.LogManager import LogManager my_logger = LogManager(__name__).get_logger() my_logger.debug("Init kafka consumer") class KConsumer: def __init__( ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from pathlib import Path from time import sleep from unittest import TestCase import numpy as np import pandas as pd from bayes_opt import BayesianOptimization as BO_ref from sklearn.gaussian_process.kernels import Matern from concurrent.futu...
"""Test code for reduce.""" import os import numpy as np import tvm import topi def verify_reduce_map_ele(in_shape, axis, keepdims, type="sum"): # Build the logic and compile the function A = tvm.placeholder(shape=in_shape, name="A") if type == "sum": B = topi.sum(A, axis=axis, keepdims=keepdims) ...
""" CURRENTLY A PLACEHOLDER Author: Jason Cabezuela """
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: #from django.contrib import admin #admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^bookmarks/', include('bookmarks.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindo...
import py import pytest from django.apps import apps from django_docutils.lib.fixtures.tests.conftest import create_bare_app from django_docutils.lib.fixtures.utils import ( find_app_configs_with_fixtures, find_rst_files, find_rst_files_in_app, get_model_from_post_app, ) @pytest.fixture(scope='funct...
# -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (C) 2015-2016 GEM Foundation # # OpenQuake is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the Licen...
from django.http import HttpResponseRedirect from django.conf import settings LOGIN_REQUIRED = getattr(settings, 'LOGIN_REQUIRED', False) class LoginRequiredMiddleware: """ If LOGIN_REQUIRED is True, redirect all non-authenticated users to the login page. """ def process_request(self, request): ...
from typing import List, Dict, Optional import torch import torch.nn as nn class MessagePolicy(nn.Module): def __init__(self, model:nn.Module): super(MessagePolicy, self).__init__() self.model = model def parameters(self): return self.model.parameters() def save_inner_state(self)...
"""The netio component."""
#!/usr/bin/env python import argparse import sys import os from redis import Redis from rq_scheduler.scheduler import Scheduler from rq_scheduler.utils import setup_loghandlers def main(): parser = argparse.ArgumentParser(description='Runs RQ scheduler') parser.add_argument('-H', '--host', default=os.envir...
import hashlib from datetime import timedelta from urllib.parse import unquote import pytz from django.http import ( Http404, HttpResponse, HttpResponseNotModified, HttpResponsePermanentRedirect, ) from django.urls import resolve, reverse from django.utils.functional import cached_property from django.utils.timezo...
from jsonschema import validate from dateutil import parser import os import datetime import json from threading import RLock from collections import defaultdict from walnut.timeseries import FixedHorizonTimeSeries from walnut.storage import Storage _dir = os.path.dirname(__file__) class Engine(object): """The...
import logging from ..core import Core from .credentials import Credentials from .autodiscover import Autodiscover from .impersonation import Impersonation from ..service.resolvenames import ResolveNames from ..utils.exceptions import IncorrectParameters from ..utils.exchangeversion import ExchangeVersion __LOGGER__ =...
# Priority Queue implementation using Lists (Pseudo Arrays) from typing import Any, Callable from datastax.arrays.queue import Queue from datastax.errors import OverFlowError, UnderFlowError class PriorityQueue(Queue): def __init__(self, *, capacity: int = None, custom_comparator: Callable = Non...
""" Copyright 2021 Novartis Institutes for BioMedical Research 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...
import logging as log class State(object): def on_trigger(self, trigger): pass def _on_trigger(self, trigger): log.debug('== ' + str(self)) return self.on_trigger(trigger) def on_enter(self, trigger): pass def _on_enter(self, trigger): log.debug('-> ' + str(...
from django.urls import path, re_path from .views import BuildingViewsetAPI app_name = "city_map" urlpatterns = [ re_path( r"^building/$", BuildingViewsetAPI.as_view( { "get": "list", "post": "create", } ), name="building", ...
from enum import Enum, auto from labelbox.orm.db_object import DbObject, Updateable, Deletable from labelbox.orm.model import Field, Relationship class Review(DbObject, Deletable, Updateable): """ Reviewing labeled data is a collaborative quality assurance technique. A Review object indicates the quality of...
from django.contrib import admin from .models import Battle, PokemonTeam, Team admin.site.register(Battle) admin.site.register(PokemonTeam) admin.site.register(Team)
#!/usr/bin/env python # vim: tabstop=4 shiftwidth=4 softtabstop=4 """ Name : server_mgr_db_convert.py Author : Abhay Joshi Description : This file contains code that provides REST api interface to configure, get and manage configurations for servers which are part of the cont...
import pandas as pd import pandas_gbq import numpy as np from google.cloud import bigquery def load_data(opt:str='new'): """ opt: {'hist', 'new'} """ urls = { "hist":"https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.zip", "new":"https://www.ecb.europa.eu/stats/eurofxref/eurofxre...
"""Create pipeline to train models with the Many Models Solution Accelerator https://github.com/microsoft/solution-accelerator-many-models """ import logging import os from typing import List, Union import pandas as pd from azureml.data.dataset_consumption_config import DatasetConsumptionConfig from azureml.core impo...
""" Code for reading a dataset into a Pandas DataFrame """ from pyxll import xl_func import pandas as pd import os @xl_func("str name, dict dtypes, str[] parse_dates, bool infer_datetime_format: object") def read_csv_data(name, dtype=None, parse_dates=None, infer_datetime_format=False): """Reads a csv file into a...
import sys import unittest from linkml.generators.typescriptgen import TypescriptGenerator from tests.test_generators.environment import env SCHEMA = env.input_path('kitchen_sink.yaml') OUT = env.expected_path('kitchen_sink.ts') class TypescriptGeneratorTestCase(unittest.TestCase): def test_tsgen(self): ...
# -*- coding: utf-8 -*- """ Created on Mon Feb 14, 2011 @author:Isabel Restrepo Compuets PCA reconstruction error. Each block is processed in a separate thread. This script assumes that the pca basis has been computed as gone by extract_pca_kernels.py """ import os; import bvpl_octree_batch import multiprocessing imp...
# -*- coding: utf-8 -*- ''' stacking.py raet protocol stacking classes ''' # pylint: skip-file # pylint: disable=W0611 # Import python libs import socket import os import errno from collections import deque, Mapping try: import simplejson as json except ImportError: import json try: import msgpack excep...
import numpy as np import struct from glob import glob def load_mnist(path, kind='train'): """Load MNIST data from `path`""" images_path = glob('./%s/%s*3-ubyte' % (path, kind))[0] labels_path = glob('./%s/%s*1-ubyte' % (path, kind))[0] with open(labels_path, 'rb') as lbpath: magic, n = struct.unpack('>I...
from fruits.preparation.abstract import DataPreparateur from fruits.preparation.dimension import * from fruits.preparation.transform import * from fruits.preparation.filter import *
"""This component provides basic support for Dahua IP cameras.""" import logging import voluptuous as vol from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_platform from homeassistant.components.camera import SUPPORT_STREAM, Camera from custom_components.dahua import DahuaDataUpda...
import sys import matplotlib.pyplot as plt import numpy as np import scipy.signal # from extras.python import auto_gain_control from extras.python import dsp from extras.python.tactile import energy_envelope from extras.python.tactile import post_processor sample_rate_hz = 16000 wav_file = '/home/getreuer/projects/...
import gym import torch.nn as nn import torch.nn.functional as F class CNN(nn.Module): """ Implementation of a Deep Convolutional Neural Network. The architecture is as follows: conv1: conv2d(210, 210, kern_size = (12, 12), stride=16) (conv2): conv2d(210, 128, kern_size = (10, 10), stride=8) (conv...
#!/usr/bin/env python3 import sys from Packet import * STATUS_INTERVAL = 50000 MAX_RTT = 0.1 if len(sys.argv) < 4: print("Usage: python parse_rtt_tcp.py directory num_clusters evaluatedprefix") exit(1) data_dir = sys.argv[1] num_clusters = sys.argv[2] prefix = sys.argv[3] lines_read = 0 unmatched_sent =...