content stringlengths 5 1.05M |
|---|
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse_lazy
from django.views.generic.edit import CreateView
from authentication_service.user_migration import views
migration_wizard = views.MigrateUserWizard.as_view(
url_name="migra... |
import os
import numpy as np
import scipy.stats as stats
from scipy.stats import norm
class limitfunc:
def __init__(self, func_name = None):
if func_name is None:
raise ValueError('Please provide a limit state function name.')
self.func_name = func_name
def evaluate_func(self, p... |
import datetime
import matplotlib.pyplot as plt
import pytest
from sitdown.filters import FilterSet, StringFilter
from sitdown.core import MutationSet
from sitdown.views import MonthSet, MonthMatrix, Month, MonthBin, MonthSeries
from tests.factories import MutationFactory
@pytest.fixture
def mock_filtered_data(long... |
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
width = max(x1, x2) - min(x1, x2)
height = max(y1, y2) - min(y1, y2)
print(width * height)
print(2 * (width + height)) |
# coding: utf-8
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environmen... |
import numpy
import pandas.testing
from ..adapters.dataframe import DataFrameAdapter
from ..adapters.mapping import MapAdapter
from ..client import from_tree
tree = MapAdapter(
{
# a dataframe divided into three partitions
"basic": DataFrameAdapter.from_pandas(
pandas.DataFrame(
... |
#!/usr/bin/env python
"""A simple parser for power tool output"""
from __future__ import print_function
from collections import namedtuple
import argparse
import re
import sys
PowerOutput = namedtuple('PowerOutput', ['filename', 'frequency', 'realtime',
'systime', 'usrtime',... |
import rain.lexer as L
import rain.token as K
import pytest
def test_factory():
assert L.factory('return') == K.keyword_token('return')
assert L.factory('this') == K.name_token('this')
assert L.factory('Multi_Word') == K.name_token('multiword')
def test_keywords():
stream = L.stream(' '.join(L.KEYWORDS))
fo... |
import json
from stability_label_algorithm.modules.dataset_generator.dataset import Dataset
from stability_label_algorithm.modules.dataset_generator.dataset_item import DatasetItem
class DatasetJsonReader:
def __init__(self):
pass
@staticmethod
def from_json(json_str: str):
json_object =... |
# 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 ... |
"""
Aries Cloud Agent
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v0.7.2
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from acapy_cli... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""Tests for cublas-functions benchmark."""
import numbers
from tests.helper import decorator
from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, ReturnCode, Platform
@decorator.cuda_test
def test_cublas_functions():
"""Te... |
# Example 5.1 from "Test and roll: profit maximizing A/B tests"
# https://pubsonline.informs.org/doi/abs/10.1287/mksc.2019.1194
import numpy as np
import matplotlib.pyplot as plt
import pyprobml_utils as pml
def optimal_sample_size(N, s, sigma):
# eqn 10
t = (s/sigma)**2
n = np.sqrt(0.25*N*t + (0.75*t)**... |
from kubernetes import client
from django.conf import settings
from libs.utils import get_list
from polyaxon_k8s import constants as k8s_constants
from scheduler.spawners.templates import constants
from scheduler.spawners.templates.env_vars import get_resources_env_vars
from scheduler.spawners.templates.gpu_volumes i... |
import os
import classification.data_loading as dl
from classification.lstm_model import SmelLSTM
from classification.util import get_classes_list
from e_nose.measurements import DataType
# specify model to test
model_name = 'LSTMTrainable_15750966_1740_batch_size=128,dim_hidden=6,lr=0.004831,return_sequences=True_20... |
import discord
import os
import requests
from discord.ext import commands, tasks
from nerdlandbot.commands.GuildData import get_all_guilds_data, get_guild_data, GuildData
from nerdlandbot.helpers.channel import get_channel
from nerdlandbot.helpers.log import info, fatal
from nerdlandbot.helpers.TranslationHelper impo... |
"""
Copyright 2016 Platform9 Systems Inc.(http://www.platform9.com)
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... |
#
# Copyright (C) Open End AB 2007-2009, All rights reserved
# See LICENSE.txt
#
import os
import mimetypes
from BaseHTTPServer import BaseHTTPRequestHandler
from wsgiref import headers
from wsgiref.util import shift_path_info
def status_string(code):
return "%d %s" % (code, BaseHTTPRequestHandler.responses[code... |
import os
import mg_server # register components
from mg_server.morphable_graph_state_machine import DEFAULT_CONFIG
SERVER_TYPE_MAP = dict()
SERVER_TYPE_MAP["tcp"] = "animation_websocket_server"
SERVER_TYPE_MAP["websocket"] = "animation_server"
DATA_DIR = r".\data"
IN_CONFIG = dict()
def setup_scene(app, model_pat... |
#! /usr/bin/env python3
import serial
import sys
ser = serial.Serial('/dev/ttyACM0', 9600)
while 1 :
tmp = ser.readline()
print tmp,
sys.stdout.flush()
|
sample_replay_filepath = './Game_20210408T225110.slp'
sample_replay_video = './Game_20210408T225110.avi'
def test_record_replay():
pass
def test_generate_commfile():
pass
def test_video_trim():
pass
def test_video_num_frames():
pass
|
from django.shortcuts import render
# Create your views here.
def index(req):
return render(req, 'landing/index.html') |
"""
Faça um Programa que leia um vetor de 10 caracteres, e diga quantas consoantes foram lidas. Imprima as consoantes.
"""
vetor = list()
vogais = ['A', 'E', 'I', 'O', 'U']
consoantes = list()
for i in range(0,10):
vetor.append(input('Letra: ').upper())
if vetor[i] not in vogais:
pass
els... |
"""
Class for retrieving data from several datasets
"""
import importlib
import os.path
from .metadatareader.xray_image_metadata import XRayImageMetadata
class DatasetBaseInterface: #pylint: disable=too-few-public-methods
"""
Interface for Dataset Reader Classes
"""
dataset = None
def get_data(sel... |
# Copyright 2017 Midokura SARL
#
# 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... |
#!/usr/bin/env python
"""
Setup file.
"""
from setuptools import setup, find_packages
setup(
name='wx',
version='0.1',
description='',
long_description=open('README.md').read(),
author='Kyle Marek-Spartz',
author_email='kyle.marek.spartz@gmail.com',
py_modules=['wx'],
url='',
incl... |
import numpy as np
from utils.transforms.transform_base import Transform
class Mixup(Transform):
def __init__(self, mix_labels=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.mix_labels = mix_labels
def forward(self, array_list: list[np.ndarray], mix_array_list: list[np.ndarra... |
from micropython import const
PACKETCONFIG1 = const(0x37) |
import os
import shutil
import tempfile
from asgiref.sync import sync_to_async
from channels.routing import URLRouter
from channels.testing import WebsocketCommunicator
from django.contrib.auth.models import Permission, User
from django.contrib.sessions.middleware import SessionMiddleware
from django.core.files.upload... |
import io
import json
import logging
from vortex.restful.RestfulResource import HTTP_REQUEST
from vortex.restful.RestfulResource import PluginRestfulResource
from twisted.trial import unittest
from twisted.web.test.requesthelper import DummyRequest
from vortex.Tuple import Tuple
from vortex.Tuple import TupleField
fro... |
import logging
from fractions import Fraction as F
from functools import cmp_to_key
from typing import Dict, List, Tuple
from .config import Config
from .order import Order
from .order_util import IntegerTraits
logger = logging.getLogger(__name__)
def sorted_orders_by_exec_priority(orders):
"""Sorts orders by d... |
from nr.utils.re import MatchAllError, match_all
import pytest
def test_match_all():
matches = [x.groups() for x in match_all(r'(\d+)([A-Z]+)', '30D2A53BO')]
assert matches == [('30', 'D'), ('2', 'A'), ('53', 'BO')]
matches = [x.group(0) for x in match_all(r'\d{2}', '1234567890')]
assert matches == ['12', '... |
from enum import IntEnum, unique
@unique
class SupportedLanguage(IntEnum):
"""
Language supported by the app.
"""
EN = 1
@staticmethod
def get(ietf_tag: str) -> int:
"""
Return language by IETF language tag.
- "EN" will be returned, if specified
language not s... |
import socket
from threading import *
from _thread import *
import wave, pyaudio, time
HANDSHAKE_MESSAGE = "mysecretfornow"
BUFFER_SIZE = 1024
BROADCASTING_PORT = 11067
TEXT_LISTENING_PORT = 3480
VOICE_LISTENING_PORT = 3481
VOICE_SENDING_PORT = 11067
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.... |
#!/usr/bin/env python
from qiskit import QuantumRegister, QuantumCircuit, Aer, execute
q = QuantumRegister(1)
circuit = QuantumCircuit(q)
simulator = Aer.get_backend("statevector_simulator")
job = execute(circuit, simulator)
result = job.result()
statevector = result.get_statevector()
print(statevector)
print(c... |
#!/usr/bin/env python3
import sports_book_manager.model_probability as mp
import unittest
class TestMP(unittest.TestCase):
"""
Tests valid inputs for model_probability return results.
"""
def test_valid_tests(self):
"""
Tests to make sure outputs are occuring with valid inputs.
... |
import os
import dash
import dash_core_components as dcc
import dash_html_components as html
import numpy
import pandas as pd
import psycopg2
import semver
import yaml
from dash.dependencies import Input, Output
from dotenv import load_dotenv
from plotly import express as px
from plotly import graph_objects as go
# f... |
"""
Note: The high-level Python interface is currently experimental and may change in a future release.
``CodesFile`` class that implements a file that is readable by ecCodes and
closes itself and its messages when it is no longer needed.
Author: Daniel Lee, DWD, 2016
"""
from .. import eccodes
import io
class Cod... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Python -*-
__author__ = "Ivo Woltring"
__copyright__ = "Copyright (c) 2013 Ivo Woltring"
__license__ = """
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 L... |
# coding: utf-8
# In[1]:
import tensorflow as tf
import os
from tensorflow import keras
from tensorflow.python.saved_model import builder as saved_model_builder
from tensorflow.python.saved_model import tag_constants, signature_constants, signature_def_utils_impl
from sklearn.feature_extraction.text import TfidfVec... |
# Content autogenerated. Do not edit.
syscalls_mips64n32 = {
"_newselect": 6022,
"_sysctl": 6152,
"accept": 6042,
"accept4": 6297,
"access": 6020,
"acct": 6158,
"add_key": 6243,
"adjtimex": 6154,
"alarm": 6037,
"bind": 6048,
"bpf": 6319,
"brk": 6012,
"cachectl": 6198... |
#!/usr/bin/env python
#
# Copyright 2001-2002 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright n... |
"""Tests for evaluator.py."""
import os
import unittest
from bfv.bfv_decryptor import BFVDecryptor
from bfv.bfv_encryptor import BFVEncryptor
from bfv.bfv_evaluator import BFVEvaluator
from bfv.bfv_key_generator import BFVKeyGenerator
from bfv.bfv_parameters import BFVParameters
from util.plaintext import Plaintext
f... |
from django.db import models
class Student(models.Model):
"""Model for Awana Students"""
MALE = 'M'
FEMALE = 'F'
GENDER_CHOICES = (
(MALE, 'Male'),
(FEMALE, 'Female'),
)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
gender =... |
# -*- coding: utf-8 -*-
"""
sphinxnotes.strike
~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2021 Shengyu Zhang.
:license: BSD, See LICENSE
"""
from __future__ import annotations
from os import path
from typing import TYPE_CHECKING, List, Dict, Tuple
from docutils import nodes, utils
if TYPE_CHECKING:
... |
# -*- coding: utf-8 -*-
from requests import Session
import json
from .storage import nodes
from time import sleep
from pprint import pprint
from itertools import cycle
class Http():
http = Session()
class RpcClient(Http):
""" Simple Steem JSON-RPC API
This class serves as an abstraction layer for easy use ... |
# ------------------------------------------------------------------------------
# Copyright 2020 Forschungszentrum Jülich GmbH
# "Licensed to the Apache Software Foundation (ASF) under one or more contributor
# license agreements; and to You under the Apache License, Version 2.0. "
#
# Forschungszentrum Jülich
# In... |
import numpy as np
import matplotlib.pyplot as plt
import astropy.constants as con
import utils as utl
import covariance as cov
import os
# Defining kappa
sol_lum = (con.L_sun*1e7).value
kap_uv = 2.2e-10/sol_lum
# Range of Luminosities (or absolute magnitudes) used
mags_all = np.linspace(-24, -13, 10)
lums_all = utl.... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Fieldset, Div, HTML
from dimagi.utils.decorators.memoized import memoized
from .models import (CustomDataFieldsDe... |
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from chat import views
from chat.serializers import MessageSerializerCreate
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.user = self.scope["user"]
self.room_name = self... |
# Initializers
import os
ON_HEROKU = 'ON_HEROKU' in os.environ
# Facebook App pymultiposter
# FACEBOOK_CLIENT_ID = "101206834030831"
# FACEBOOK_CLIENT_SECRET = "9be8d03bb48f86245d2bad7269831f51"
IMGUR_CLIENT_ID = "3f4360ea159fad4"
IMGUR_CLIENT_SECRET = "be5c53e8daf8645f2f33c3b9d8c8ac9488396fb6"
S3_BUCKET = "pymulti... |
from __future__ import unicode_literals, division
from django.db import models
from django.utils import timezone
from django.utils.timezone import utc
from django.contrib import auth
from datetime import datetime, timedelta, time
import colorsys
import math
import pytz
from autoslug import AutoSlugField
class Contex... |
from discord.ext import commands
from discord.utils import get
from datetime import datetime, timedelta
from unicodedata import normalize
from inspect import Parameter
from aiohttp import ClientSession
from typing import Union
async def get_json(link: str, headers: dict = None, json: bool = True) -> Union[dict, str]:... |
import numpy as np
import pandas as pd
import os
from cost_prophet.utils.evaluation import test_error
from cost_prophet.utils.linear_alebra import split_tests_sets, get_known_indices
from dask import delayed, compute
from time import time
from dotenv import dotenv_values
from collections import OrderedDict
from copy i... |
#! /usr/bin/env python3
# -*-coding:utf-8 -*-
# @Time : 2019/06/19 18:57:07
# @Author : che
# @Email : ch1huizong@gmail.com
import ZODB
import ZODB.FileStorage
import transaction
from account import Account
filestorage = ZODB.FileStorage.FileStorage("zodb_account.db")
db = ZODB.DB(filestorage)
conn = db.open(... |
"""
zoom.packages
Provide a simple shorthand way to include external components in projects.
"""
import json
import os
import zoom
default_packages = {
'c3': {
'libs': [
'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js',
'https://cdnjs.cloudflare.com/ajax/libs... |
import pcap
import dpkt
a=pcap.pcap()
a.setfilter('arp')
for i,j in a:
tem=dpkt.ethernet.Ethernet(j)
print ("%s %x",i,tem) |
"""
This examples loads a pre-trained model and evaluates it on the STSbenchmark, Sick-R and STS12-16 datasets.
Another function of this examples is to save the extracted word embeddings to `summary_path`
Usage:
python evaluation_stsbenchmark_save_embed.py --pooling aver --layer_index 1,12 --whitening --encoder_name b... |
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__author__ = "d01"
__email__ = "jungflor@gmail.com"
__copyright__ = "Copyright (C) 2015-16, Florian JUNG"
__license__ = "MIT"
__version__ = "0.1.0... |
# Areas list
areas = [ "hallway", 14.35,
"kitchen", 15.0,
"living room", 19.0,
"bedroom", 12.5,
"bathroom", 8.75 ]
#1 Print out second element
print(_________)
#2 Print out bathroom (using a negative index)
print(_________)
#3 Print out the kitchen area
print(_________) |
import requests
OH_BASE_URL = 'https://www.openhumans.org/'
def oh_get_member_data(token):
"""
Exchange OAuth2 token for member data.
"""
req = requests.get(
'{}api/direct-sharing/project/exchange-member/'.format(OH_BASE_URL),
params={'access_token': token})
if req.status_code == ... |
"""
OBJECT RECOGNITION USING A SPIKING NEURAL NETWORK.
* The data preparation module.
@author: atenagm1375
"""
import os
import numpy as np
import pandas as pd
from torch.utils.data import Dataset
import cv2
class CaltechDataset(Dataset):
"""
CaltechDataset class.
Attributes
----------
calt... |
import torch
class AccumulateKNN(torch.autograd.Function):
@staticmethod
def forward(ctx,
distances: torch.Tensor,
features: torch.Tensor,
indices: torch.Tensor,
n_moments: int = 1,
mean_and_max: bool = True):
output_f... |
# CS 545 Machine Learning
# Homework 3 SVMs and Feature Selection
# Haomin He
"""
References:
Lecture Slides
https://archive.ics.uci.edu/ml/datasets/Spambase
http://scikit-learn.org/stable/modules/preprocessing.html
https://github.com/paolo215/CS445-ML
https://github.com/asayles
https://github.com/ZPdesu/Spam-Message... |
import os
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from tqdm import tqdm
def binarize_batch(batch_tuple):
# We share randomness so that if x == y, they're binarized consistently
# You won't believe how much training time we saved by switching to this
# _blazingly fa... |
import pytest
from hyp3lib import DemError
from hyp3_autorift import geometry, io
from hyp3_autorift.process import DEFAULT_PARAMETER_FILE
def test_find_jpl_parameter_info():
lat_limits = (55, 56)
lon_limits = (40, 41)
polygon = geometry.polygon_from_bbox(x_limits=lat_limits, y_limits=lon_limits)
par... |
from pydub import AudioSegment as AS
import numpy as np
from numpy.fft import fft
import matplotlib.pyplot as plt
pfad = "/home/noah/Schreibtisch/Bachelorarbeit/speechcommandCorpus/marvin/0a7c2a8d_nohash_0.wav"
test = AS.from_wav(pfad)
rohDaten=test.raw_data
daten = np.frombuffer(rohDaten,dtype=np.int16)
fig = plt.fi... |
import pandas as pd
import numpy as np
from sklearn.metrics import silhouette_score
from itertools import combinations
import Levenshtein
def levenshtein_metric(X, min_samples=0):
""" Returns array of average levenshtein scores of each cluster by averaging the levenshtein scores of all pairwise strings in each clu... |
import os.path
import numpy as np
import cv2
import argparse
parser = argparse.ArgumentParser(description='Convert frames into a video')
parser.add_argument('--frames', default='/home/hteam/Documents/hao/Research/Detection/detectron2/result_images', type=str, help='video frames file')
parser.add_argument('--output', d... |
import urllib.request
import re
import os
import argparse
parser=argparse.ArgumentParser(description='Input Conference (C) and Year (Y)')
parser.add_argument('C',type=str,default='CVPR',
help='a name of CVPR, ICCV or ECCV')
parser.add_argument('Y',type=int,default=2020,
h... |
import hashlib
import pickle
import os
from ..algorithms import librosa_analysis
from track import Track
class Song(Track):
"""A :py:class:`radiotool.composer.Track`
subclass that wraps a music .wav file.
Allows access to a musical analysis of the song.
"""
def __init__(self, fn, name="Song name"... |
from django.contrib import admin
from .models import Message
# Register your models here.
@admin.register(Message)
class MessageAdmin(admin.ModelAdmin):
list_display = ('id', 'author', 'created', 'updated','content','is_public')
list_filter = ('author', 'created',)
search_fields = ('category', 'con... |
from flask import Flask
from voice_api.blueprints.fs_api.views import fs_api
from voice_api.blueprints.web_api.views import web_api
from voice_api.models import db
import logging
from logging.handlers import TimedRotatingFileHandler
def creat_app():
app=Flask(__name__)
app.config.from_object('config')
app.... |
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, generics
from rest_framework.pagination import CursorPagination
from app import models
from app import serializers
class ResultsPagination(CursorPagination):
page_size = 25
page_size_query_param = 'size'
max... |
""" Unit tests for the basis polynomial computations """
# -------------------------------------------------------------------------------------------------------------------- #
# Importing packages
# -------------------------------------------------------------------------------------------------------------------- #... |
import unittest
from lab.upscaling.worker.Algorithm import *
if __name__ == "__main__":
# Test code
gscalertest = GScalerAlgorithmTest()
unittest.main()
|
import sys
import os
import argparse
import shutil
import json
from riaps.gen.target.cpp import cppgen, sync_cpp
from riaps.gen.target.python import pygen, sync_python
from riaps.gen.target.capnp import capnpgen, sync_capnp
from multigen.jinja import JinjaTask, JinjaGenerator
def preprocess(model):
items={
... |
"""
Module with specialized instructions for matrix factorization, topic modeling and clustering activities.
By: Victor Pontes (victoraleff@gmail.com)
"""
from tqdm import tqdm
import numpy as np
import pandas as pd
from implicit.als import AlternatingLeastSquares
import faiss
from sklearn.metrics.pairwise imp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/CapabilityStatement) on 2020-02-03.
# 2020, SMART Health IT.
import sys
from dataclasses import dataclass, field
from typing import ClassVar, Optional, List
from .backboneelement import Bac... |
from typing import Optional, Tuple, Callable, Dict
import numpy as np
from pararealml.core.constrained_problem import ConstrainedProblem
from pararealml.core.constraint import apply_constraints_along_last_axis
from pararealml.core.differential_equation import Lhs
from pararealml.core.initial_value_problem import Init... |
from django import forms
from django.contrib.auth.models import User
from app.models import *
class LoginForm(forms.Form):
username = forms.CharField(max_length=32, min_length=5, label="用户名")
password = forms.CharField(max_length=32, min_length=5, label="密码", widget=forms.PasswordInput())
def clea... |
from .enet.enet import ENet
__all__ = ["ENet"]
|
# Generated by Django 3.1.3 on 2021-01-25 21:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('awward_app', '0004_auto_20210125_2054'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='profile... |
#!/usr/bin/env python2
import os
import re
import sys
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
ROOT = os.path.abspath(os.path.dirname(__file__))
VERSION_RE = re.compile(r'''__version__ = ['"]([0-9.]+)['"]''')
class PyTest(TestCommand):
user_options = [... |
import tempfile, shutil, os, datetime, resource, sys, time
from s3ts.treestore import TreeStore
from s3ts.filestore import LocalFileStore
from s3ts.config import TreeStoreConfig
class TransferStats:
def __init__(self):
self.bytesUploaded = 0
self.bytesCached = 0
self.rusage0 = resource.get... |
from tqdm import *
import numpy
import dataset
from nets import simpleNet
mnist = dataset.load_mnist()
nn = simpleNet(architecture=numpy.array([784 ,100, 10]))
for epoch in range(10):
success = numpy.zeros(shape=(mnist[0][0].shape[0],))
for example in tqdm(range(mnist[0][0].shape[0])): #
input = mnist[0][0... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 16 16:25:21 2021
@author: Andreas Traut
Problem:
Assume, ath we have a bag of capacity c. And assume, that we have n items, which
each has a weight and a profit. We have the choice to select items, to be filled
into this bag and the aim is to maximize the profit. At s... |
# -*- coding: utf-8 -*-
"""Query builder."""
import json
import logging
from collections import Iterable
from .exc import QueryMissingNetworksError
from .seeding import Seeding
from ...manager.models import Node
from ...struct.pipeline import Pipeline
__all__ = [
'Query',
]
log = logging.getLogger(__name__)
... |
"""Converts PubMed abstracts to a file with one abstract per line."""
import argparse
import datetime
import gzip
import logging
import multiprocessing
import os
import process
import time
import xml.etree.cElementTree as ET
from functools import partial
from typing import Tuple
logging.basicConfig(format="%(asctime... |
# --------------
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
# Code starts here
df = pd.read_csv(path)
cols = ['INCOME','HOME_VAL','BLUEBOOK','OLDCLAIM','CLM_AMT']
df[cols] = df[cols].replace({'\$': '', ',': ''}, rege... |
class Solution:
def numTeams(self, rating: List[int]) -> int:
"""
requirements:
3 elements
2 valid teams:
1. i < j < k
2. i > j < k
can reuse the same elements
Ideas:
1. Brute Force.
Fix i, j, move k....n-1
... |
from typing import List, Sequence
import itertools
import numpy as np
__all__ = ['voltage_to_uint16']
def voltage_to_uint16(voltage: np.ndarray, output_amplitude: float, output_offset: float, resolution: int) -> np.ndarray:
"""
:param voltage:
:param output_amplitude:
:param output_offset:
:par... |
############################################
# Semi-Adversarial Network #
# (convolutional autoencoder) #
# iPRoBe lab #
# #
############################################
import torch
import torch.nn as nn
class AutoEn... |
#!/usr/bin/python
import usb.core
import usb.util
import sys, struct
class WCHISP:
def __init__(self):
# find our device
dev = usb.core.find(idVendor=0x4348, idProduct=0x55e0)
if dev is None:
raise ValueError('Device not found')
dev.set_configuration()
... |
import os
import re
import logging
from consts import TIMEOUT_RC
from structs import TimedRunParams
from structs import ToolRunParams
from utils import get_tmp_file_name, execute_shell, readfile
from config import RUN_SOLVER_EXEC
class RunStats:
def __init__(self, cpu_time_sec:float=None,
wall_t... |
import unittest2
import sys
import os
sys.path.append(os.getcwd() + '/..')
import video_file_saver
class AuthTokenTests(unittest2.TestCase):
@classmethod
def tearDown(cls):
[os.remove(f) for f in os.listdir() if f.endswith('.mp4') or f.endswith('.txt')]
def test_record(self):
strea... |
#------------------------------------#
# Author: Yueh-Lin Tsou #
# Update: 7/20/2019 #
# E-mail: hank630280888@gmail.com #
#------------------------------------#
"""-----------------------------------------------------------------
Implement Template Matching by using Normalised Cross ... |
"""
jsnek_saved_games_dataset that returns flat (vectorized) data
"""
from .jsnek_base_dataset import JSnekBaseDataset
from .. import utils
class JSnekDataset(JSnekBaseDataset):
"""Represents a board state in the following way:
board_state: `torch.Tensor`
Board state in torch.Tensor format. Board st... |
from io import StringIO
from textwrap import dedent
from aiida.cmdline.utils.common import get_calcjob_report
from aiida.orm import FolderData
from aiida.plugins import ParserFactory
import pytest
def get_log():
return dedent(
"""\
units metal
final_energy: 2.0
final_cell: 0 1 0 0... |
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2022, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.