text stringlengths 2 999k |
|---|
import random
from locust import HttpLocust, TaskSet, task
class UserBehavior(TaskSet):
def on_start(self):
""" on_start is called when a Locust start before any task is scheduled """
self.url = "/predictions/fizbuz_package"
self.headers = {"Content-Type": "application/json"}
@task(10... |
import numpy as np
from tensorflow.keras import Input
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from cond_rnn import ConditionalRNN
# This is an example with dummy to explain how to use CondRNN.
# _______________________________________... |
model = "mobilenet_thin"
image = "/data/drone_filming/images/forest_person_far_0.jpg"
to_write_path = "human_pose.txt"
import argparse
import logging
import sys
import time
from tf_pose import common
import cv2
import os, glob
import numpy as np
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks imp... |
# 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... |
from Models.StudentPageModel import StudentPageModel
class ChangeStudentPasswordController:
def __init__(self, master, model, view):
self._view = view
self._master = master
self._model = model
def BackToStudentPage(self):
from Views.StudentPage import StudentPage
self.... |
###########################################################################
# Created by: CASIA IVA
# Email: jliu@nlpr.ia.ac.cn
# Copyright (c) 2018
###########################################################################
import os
import argparse
import torch
class Options():
def __init__(self):
par... |
import itertools
import random
from typing import Any
import numpy as np
import pytest
import cirq
from cirq.optimizers.two_qubit_to_fsim import (
_decompose_two_qubit_interaction_into_two_b_gates,
_decompose_xx_yy_into_two_fsims_ignoring_single_qubit_ops,
_sticky_0_to_1,
)
UNITARY_OBJS = [
cirq.Iden... |
from typing import List
from pathlib import Path
from dataclasses import dataclass
import requests
@dataclass
class PackageLocation:
url: str
name: str
def fetch_packages(
locations: List[PackageLocation], save_dir: Path, quiet: bool = False
) -> List[Path]:
outfiles = []
for loc in locations:
... |
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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 ... |
import asyncio
import json
import os
from glob import glob
from aiogithubapi import GitHub
from scripts.changed.repo import get_repo
TOKEN = os.getenv("GITHUB_TOKEN")
async def check():
print("Information: https://hacs.xyz/docs/publish/include#check-repository")
repo = get_repo()
issues = []
async w... |
import pytest
import torch
import torch.nn.functional as F
from d3rlpy.models.encoders import DefaultEncoderFactory
from d3rlpy.models.torch.imitators import (
ConditionalVAE,
DeterministicRegressor,
DiscreteImitator,
ProbablisticRegressor,
)
from .model_test import DummyEncoder, check_parameter_updat... |
# pylint: disable=no-value-for-parameter
"""Evaluate MovieLens."""
import logging
from dataclasses import dataclass
from typing import List, Union, Optional
import numpy as np
import deepr as dpr
from deepr.utils import mlflow
try:
import faiss
except ImportError as e:
print(f"Faiss needs to be installed fo... |
from . import models, rekit_db, postman
from pyorgtex import convert, generate, orgexport
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
import pytz, time
from datetime import datetime
def generate_manual_single(stuid,db_url,manualORGname,dirname='./',exportformat='pdf',dependencylist=[]):
newdict={... |
# -*- coding: utf-8 -*-
import logging
import random
import time
from collections import namedtuple, defaultdict
import gevent
from gevent.queue import Empty
from ethereum import slogging
from ethereum.utils import sha3
from raiden.tasks import Task
from raiden.messages import (
MediatedTransfer,
RefundTransf... |
import argparse
import os
import torch
import torchvision.transforms as transforms
from torch import nn
from torch import optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from models import E1
from models import E2
from models import Disc
from models import Decoder
from models import ... |
# Firewall Rule Anomaly Resolver for Ryu restfull firewall
# https://github.com/osrg/ryu/blob/master/ryu/app/rest_firewall.py
import logging
import logging.handlers
import itertools
import ctypes
from netaddr import IPSet, IPRange, IPNetwork, IPGlob
from netaddr import cidr_merge, valid_ipv4, valid_glob, glob_to_cidrs... |
#
# 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
# ... |
import math
class BezierCurve():
@staticmethod
def binomial(n, k):
"""Returns the binomial coefficient "n choose k" """
return math.factorial(n) / float(math.factorial(k) * math.factorial(n - k))
@staticmethod
def bernsteinPolynomialPoint(x, i, n):
"""Calculate the i-th compone... |
from datetime import datetime
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
tz_now = timezone.now
def friendly_datetime(date_time):
"""
Given a datetime object or an int() Unix timestamp, return a friendly
string like 'an hour ago', 'yesterday', '3 months ago'... |
# (c) 2016, Dag Wieers <dag@wieers.com>
#
# This file is part of Ansible
#
# Ansible 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 of the License, or
# (at your option) any later version.
#
... |
import os
import json
from wsgiref import simple_server
import falcon
from distutils.version import StrictVersion
class HelloWorldResource(object):
def on_get(self, req, resp):
resp.body = json.dumps({'text': 'Hello World!!!'})
if StrictVersion(falcon.__version__) < StrictVersion('3.0.0'):
app = fa... |
from unittest.mock import mock_open, patch
from transformer.transform import Transform
class TestTransform:
@staticmethod
def pass_through(rdr, wr, *params):
while True:
b = rdr.read()
wr(b)
if not b:
break
@staticmethod
def fcopy_pass_thro... |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('C6A', ['C8pro'])
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C3ub')
Monomer('C3A', ['Xiap', 'ParpU', 'C6pro'])
Mo... |
'''
@docstring
'''
from django.urls import path
from . import views
urlpatterns = [
# @route /api/
path('diary/', views.DiaryPagesList.as_view(), name="diarypagesapi"),
path('diary/<int:id>/', views.DiaryPageView.as_view(), name="diarypageapi"),
# @route /diary/
path('<int:postid>/', views.Diary... |
import random
import numpy as np
import pandas as pd
# make dataset function
def load_dataset(index_range: int = 10000, id_range: int = 5000) -> pd.DataFrame:
"""
make growth hacking dataset
:param index_range: (int)
make index random information
:param id_range: (int)
... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoApscheduler.settings')
try:
from django.core.management import execute_from_command_line
e... |
import math
import torch
import torch.nn as nn
from deepke.model import BasicModule, Embedding
class DotAttention(nn.Module):
'''
\text {Attention }(Q, K, V)=\operatorname{softmax}\left(\frac{Q K^{T}}{\sqrt{d_{k}}}\right) V
'''
def __init__(self, dropout=0.0):
super(DotAttention, self).__init_... |
def test_1a():
import day_1a
answer = day_1a.read_and_solve()
assert(3412531 == answer)
def test_1b():
import day_1b
answer = day_1b.read_and_solve()
assert(5115927 == answer)
def test_2a():
import day_2a
answer = day_2a.read_and_solve()
assert(3224742 == answer)
def test_2b... |
class Demo:
def mymethod1(self):
mynum1 = 10
print("The local variable mynum1 value is", mynum1)
def mymethod2(self):
mynum2 = 120
print("The local variable mynum2 value is", mynum2)
myobj = Demo()
myobj.mymethod1()
myobj.mymethod2()
|
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C8A', ['BidU', 'C3pro'])
Monomer('SmacM', ['BaxA'])
Monomer('BaxM', ['BidM', '... |
from __future__ import print_function
import os
import sys
import time
import logging
import tempfile
import traceback
import subprocess
from shutil import disk_usage, rmtree
try:
import pathlib
import importlib.util
except ImportError:
pass
class GIT(object):
@classmethod
def works(cls):
... |
"""
Create train from bronze data
Example call:
$ python3 create_train.py --bronze_file /mounts/work/ayyoob/results/gnn_align/yoruba/POSTgs_hin-x-bible-bsi_15lngs-POSFeatTruealltgts_trnsfrmrTrue6LResTrue_trainWEFalse_mskLngTrue_E1_traintgt0.8_TypchckTrue_TgBsdSlctTrue_tstamtall_20220502-155236_ElyStpDlta0-GA-chnls1024... |
# Copyright 2015 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 sys
import psycopg2
"""
A very simple ETL pipeline: reading a local file and pushing to Redshift
To install psycopg2, run the following command (after installing Anaconda
conda install -c anaconda psycopg2=2.6.2
"""
def extract(filename):
"""
extract portion of ETL
- In this case it is simply... |
import json
from typing import Any, Callable, Dict, List, Optional, Union
import requests
from meilisearch.config import Config
from meilisearch.errors import (
MeiliSearchApiError,
MeiliSearchCommunicationError,
MeiliSearchTimeoutError,
)
class HttpRequests:
def __init__(self, config: Config) -> None:... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse, sys, subprocess, textwrap, threading, signal
def shell_escape(s):
return "'" + s.replace("'", "'\"'\"'") + "'"
def run(cmd):
try:
subprocess.check_call(cmd, shell=True)
except subprocess.CalledProcessError as e:
print(e, file=... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Time : 2019-09-21 19:54
@Author : Wang Xin
@Email : wangxin_buaa@163.com
@File : __init__.py.py
""" |
from splinter import Browser
from bs4 import BeautifulSoup as bs
import requests
import pandas as pd
import time
def scrape():
py_dict = {}
# %%
# URL of page to be scraped
url = 'https://mars.nasa.gov/news/'
# %%
# Retrieve page with the requests module
response = requests.get(url)
# %%
# Create a Be... |
import logging
from unittest import mock
from django.test import TestCase
from django.contrib.auth.models import User
from uploadedfiles.models import UploadedFile, uploaded_file_path
class UploadedFileModelTests(TestCase):
def setUp(self):
# avoid cluttered console output (for instance logging all the... |
s = input("Please enter a string: ")
z = s[::-1]
if s == z:
print("The string is a palindrome")
else:
print("The string is not a palindrome")
|
# Copyright (c) 2010-2012 OpenStack Foundation
#
# 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 agree... |
#!/usr/bin/env python
import logging
import datetime
from collections import namedtuple
import pytz
import json
import iso8601
from lxml import etree
from lxml.etree import XMLSyntaxError
from Evtx.Evtx import Evtx
from Evtx.Views import evtx_file_xml_view
g_logger = logging.getLogger("process-forest.global")
de... |
#!/usr/bin/env python
from distutils.core import setup
setup(
name="gym_logger",
version="0.0.1",
author="koshmaar",
author_email="koshmaar@poczta.onet.pl",
packages=["gym"],
)
|
# How to add a test:
# Copy this file
# Rename TestTemplate to TestWhatever in line 9
# Rename machine path and config file in lines 11 and 14
from mpfmc.tests.MpfMcTestCase import MpfMcTestCase
class TestTemplate(MpfMcTestCase):
def get_machine_path(self):
return 'tests/machine_files/test_template'
... |
""" Run all the stages of the Deep Colony Tracking pipeline
Functions:
* :py:func:`log_method`: Wrap methods in a logging and timing calls
Classes:
* :py:class:`ImagePipeline`: The actual pipeline steps
"""
# Standard lib
import sys
import time
import shutil
import pathlib
import datetime
import functools
import ... |
import sys, os, socket, shutil
import tempfile
import logging
import urllib, urllib2, urlparse
from django.core.files.storage import default_storage
from django.conf import settings
from django.core.mail import send_mail
logger = logging.getLogger(__name__)
def splitpath(raw):
store_path = urlparse.urlsplit(ra... |
#!/usr/bin/env python
"""
setup.py file for WarpX
"""
import sys
import argparse
from setuptools import setup
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('--with-libwarpx', type=str, default=None, help='Install libwarpx with the given value as DIM. This option is only used by the make... |
import subprocess
command = ['ffmpeg',
'-i', '"CHR.mp4"',
'-ss', 288,
'-t', 10,
'-c:v', 'libx264', '-c:a', 'copy',
'-threads', '1',
'-loglevel', 'panic',
'"chr.mp4"']
command = ' '.join(command)
try:
output = subprocess.check_output(comm... |
from pytest_check import check
import jax
from jax.config import config
import jax.numpy as np
import numpy as onp
import fenics
import fenics_adjoint as fa
import ufl
import fdm
from jaxfenics_adjoint import build_jax_fem_eval
config.update("jax_enable_x64", True)
mesh = fa.UnitSquareMesh(3, 2)
V = fenics.Functio... |
from typing import List
BÉCHAMEL = "Béchamel"
VELOUTÉ = "Velouté"
ESPAGNOLE = "Espagnole"
TOMATO = "Tomato"
HOLLANDAISE = "Hollandaise"
MOTHER_SAUCES = (BÉCHAMEL, VELOUTÉ, ESPAGNOLE, TOMATO, HOLLANDAISE)
assert MOTHER_SAUCES[2] == "Espagnole"
def create_daughter_sauce(mother_sauce: str,
ex... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# https://codereview.stackexchange.com/questions/5196/grouping-consecutive-numbers-into-ranges-in-python-3-2
# https://stackoverflow.com/questions/2361945/detecting-consecutive-integers-in-a-list
from itertools import groupby, count
from operator import itemgetter
# import ... |
"""
Mask R-CNN
The main Mask R-CNN model implementation.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla
"""
import os
import random
import datetime
import re
import math
import logging
from collections import OrderedDict
import multiprocessing
im... |
import logging
import os.path
import networkx as nx
import numpy as np
import re
import selfies as sf
import sys
import time
import torch
from rdkit import Chem
from torch.utils.data import Dataset
from typing import Dict, List, Tuple
from utils.chem_utils import ATOM_FDIM, BOND_FDIM, get_atom_features_sparse, get_bon... |
# Copyright 2021. FastyBird s.r.o.
#
# 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... |
import string
import re
from pedal.report.imperative import MAIN_REPORT
from pedal.sandbox.result import SandboxResult
from pedal.sandbox.exceptions import SandboxException
from pedal.sandbox.sandbox import DataSandbox
from pedal.assertions.setup import _setup_assertions, AssertionException
_MAX_LENGTH = 80
def saf... |
"""empty message
Revision ID: 8b477c4e904
Revises: 6ae3f450df3
Create Date: 2015-02-12 21:16:15.970509
"""
# revision identifiers, used by Alembic.
revision = '8b477c4e904'
down_revision = '6ae3f450df3'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - plea... |
"""Abstract Transport class."""
from asyncio import compat
__all__ = ['BaseTransport', 'ReadTransport', 'WriteTransport',
'Transport', 'DatagramTransport', 'SubprocessTransport',
]
class BaseTransport:
"""Base class for transports."""
def __init__(self, extra=None):
if extra i... |
"""
This script keeps a timer that will cause an update to happen
on a weekly basis. Things we'll be updating are counting votes
for players, and processes for Dominion.
"""
import traceback
from collections import defaultdict
from datetime import datetime, timedelta
from django.db.models import Q, F
from evennia.ob... |
import chainer
import matplotlib.pyplot as plt
import numpy as np
from brancher.variables import RootVariable, RandomVariable, ProbabilisticModel
from brancher.standard_variables import NormalVariable, LogNormalVariable, BetaVariable
from brancher import inference
import brancher.functions as BF
# Probabilistic model... |
#!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import KoobitTestFramework
from test_framework.util import *
from test_fram... |
"""
# Mobius Software LTD
# Copyright 2015-2018, Mobius Software LTD
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later ve... |
# (C) Datadog, Inc. 2021-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
# This file is autogenerated.
# To change this file you should edit assets/configuration/spec.yaml and then run the following commands:
# ddev -x validate config -s <INTEGRATION_NAME>
# ddev -x va... |
#!/bin/python3
import sys
# Complete the hourglassSum function below.
def hourglassSum(arr):
max = -1000
for i in range(0, 6 - 2): # Last omitted
for j in range(0, 6 - 2):
sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + \
... |
"""Utilities"""
import time
import logging
import os
import random
import re
import string
import sys
from datetime import timedelta, datetime, date
import yaml
import elasticsearch
from voluptuous import Schema
from curator import exceptions
from curator.defaults import settings
from curator.validators import SchemaCh... |
"""This file can be marked for removal..."""
import requests
__author__ = "Swanand Rao"
__copyright__ = ""
__credits__ = ["Swanand Rao"]
__license__ = ""
__version__ = "0.1"
__maintainer__ = "Swanand Rao"
__email__ = "swanand.rao@gmail.com"
__status__ = "pre-alpha"
__basedir=''
__ecaaf... |
#!/usr/bin/env python3
from IPython import embed
import struct
lines = []
with open("ip_addresses.txt") as f:
lines = [x.strip().split(".") for x in f.readlines()]
coords = []
for line in lines:
coords.append(''.join([hex(int(y))[2:].zfill(2) for y in line]))
coords2 = [struct.unpack(">f", bytes.fromhex(x))[0... |
import os
import sys
import unittest
from tests.tests_validation.test_validator_kfold import KFoldValidatorTest
if __name__ == "__main__":
unittest.main()
|
"""
@brief test tree node (time=15s)
"""
import sys
import os
import unittest
from pyquickhelper.loghelper import fLOG, run_cmd
from pyquickhelper.pycode import get_temp_folder
from pyquickhelper.pycode.py3to2 import py3to2_convert_tree
class TestPy3to2(unittest.TestCase):
def test_py3to2(self):
... |
# -*- coding: utf-8 -*-
"""
Money class unittests
"""
import unittest
from money import Money
from . import mixins
class TestMoneyInstantiation(mixins.InstantiationMixin, unittest.TestCase):
def setUp(self):
self.MoneyClass = Money
class TestMoneyClass(mixins.ClassMixin, unittest.TestCase):
def set... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
##
# @file
# This script creates Nios II BSPs and code projects for each CPU in a given basic system description using the <TT>name</TT> tag of the CPU.
#
# @copyright BSD New
# @author Marcus Mikulcak
#
# @param sopc_file The SOPC Builder file.
# @param input_xml The basic... |
from custom_gym.envs.env import IslandEnv |
#!/usr/bin/env python3
import glob
from os.path import realpath, exists
def globr(regexp):
return glob.glob('lib/' + regexp, recursive=True) \
+ glob.glob('src/' + regexp, recursive=True) \
+ glob.glob('include/' + regexp, recursive=True)
def titlecase(s):
return s[0].upper() + s[1:]
... |
# This file is part of the ISIS IBEX application.
# Copyright (C) 2012-2020 Science & Technology Facilities Council.
# All rights reserved.
#
# This program is distributed in the hope that it will be useful.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License... |
from dataclasses import dataclass
from venidium.types.blockchain_format.sized_bytes import bytes32
from venidium.util.ints import uint32
from venidium.util.streamable import Streamable, streamable
@dataclass(frozen=True)
@streamable
class FarmNewBlockProtocol(Streamable):
puzzle_hash: bytes32
@dataclass(frozen... |
"""Extension to execute code outside the Python shell window.
This adds the following commands:
- Check module does a full syntax check of the current module.
It also runs the tabnanny to catch any inconsistent tabs.
- Run module executes the module's code in the __main__ namespace. The window
must have been sa... |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.4.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# ## ... |
from flask import Flask,render_template,request
import requests
import cv2
import re
import pyttsx3
from gtts import gTTS
rgb2hex = lambda r, g, b: '#%02x%02x%02x' % (r, g, b)
app = Flask(__name__)
def text_to_speech_gTTS(mytext,gender,file):
language="en"
slow = False
#creating audio obj from gTTS en... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-12-04 20:06
from __future__ import unicode_literals
from django.db import migrations
import localflavor.us.models
import wellsfargo.core.fields
import oscar.models.fields
class Migration(migrations.Migration):
dependencies = [
('wellsfargo', '... |
def aumentar(preco=0, taxa=0, formato=False):
"""
-> Calcula o aumento de um determinado preço,
retornando o resultado com ou sem formatação.
:param preco: o preço que se quer reajustar.
:param taxa: qual é a porcentagem do aumento.
:param formato: quer a saída formatada ou não?
:return: o v... |
import secrets
import os
from flask import render_template, url_for, flash, redirect, request
from flask_login import login_user, current_user, logout_user, login_required
from ems import app, bcrypt, db
from ems.forms import RegistrationForm, LoginForm, AccountForm, AddNewForm, UpdateDetailsForm
from ems.models import... |
# Copyright 2007-2017 by Peter Cock. All rights reserved.
# Revisions copyright 2010 by Uri Laserson. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Internal code for parsin... |
import os
import sys
from . import defaults, helpers
def get_valid_cwd():
try:
if os.name == "nt":
cwd = os.getcwd()
else:
cwd = os.getenv("PWD") or os.getcwd()
except Exception:
helpers.warn("Invalid current working directory!")
sys.stdou... |
import numpy as np
np.random.seed(10)
from data_splitter import collect_snapshots
from sklearn.metrics.pairwise import rbf_kernel
import matplotlib.pyplot as plt
import tensorflow as tf
num_components = 4
# http://fourier.eng.hmc.edu/e161/lectures/kernelPCA/node4.html
def centerK(K):
''' Returns centered K matri... |
import json
from hdmf.spec import GroupSpec, DatasetSpec, AttributeSpec, DtypeSpec, RefSpec
from hdmf.testing import TestCase
class DatasetSpecTests(TestCase):
def setUp(self):
self.attributes = [
AttributeSpec('attribute1', 'my first attribute', 'text'),
AttributeSpec('attribute2... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0007_auto_20160112_2055'),
]
operations = [
migrations.AlterField(
model_name='averagecrossover',
... |
def hamming_distance(text1, text2):
distance = 0
for i in range(len(text1)):
if text1[i] != text2[i]:
distance = distance + 1
return distance
############################################################
text = 'TTGTCACATCCGAAGAGTTCCCGTTTTCAGGATGTCCAGTATAAGAATAAGAGAGAAAGCGGGTTGCTTA... |
__version__ = "2.0.2"
|
# -*- coding: utf-8 -*-
"""Untitled38.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1D8Trl4wwfawf_9i_HM6zq7lHgGVmKLTv
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
dataset=pd.read_csv('winequality-red.csv')
dataset... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Dylan Hamel"
__version__ = "0.1"
__email__ = "dylan.hamel@protonmail.com"
__status__ = "Prototype"
# Default value used for exit()
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
HEADER = "[CumulusDevice -"
######################################################
#
# Impo... |
# -*- coding: utf-8 -*-
"""
Example of use Elman recurrent network
=====================================
Task: Detect the amplitudes
"""
import neurolab as nl
import numpy as np
# Create train samples
i1 = np.sin(np.arange(0, 20))
i2 = np.sin(np.arange(0, 20)) * 2
t1 = np.ones([1, 20])
t2 = np.ones([1, 20]) * 2
... |
#
#
# configuration data
# configuration.py
#
# Note configuration takes data from files and various sources and creates object
# data for various external processes
#
server_1_serial_interfaces = {}
#server_1_serial_interfaces[ "rtu_1" ] = { "type":"rs485_modbus", "interface_parameters":{ "interface":None, "tim... |
from typing import Callable, List, TypeVar
import cadquery as cq
def applyToEachFace(
wp: cq.Workplane,
f_workplane_selector: Callable[[cq.Face], cq.Workplane],
f_draw: Callable[[cq.Workplane, cq.Face], cq.Workplane],
) -> cq.Workplane:
"""
Basically equivalent to `Workplane.each(..)` but
app... |
# -*- coding: utf-8 -*-
# Copyright (C) 2020. 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 License at
#
# http://www.apache.org/licenses/LICENS... |
import time
import tkinter
import tkinter.messagebox
def download():
time.sleep(10)
tkinter.messagebox.showinfo('提示', '下载完成')
def show_about():
tkinter.messagebox.showinfo('关于', 'weishaodaren')
def main():
top = tkinter.Tk()
top.title('单线程')
top.geometry('200x150')
top.wm_attributes('-... |
import hashlib
import requests
import uuid
from server_config import LOCKED_URL,MAX_PORT_COUNT
import random
def hashify(password,mapped_email,num):
thorax = hashlib.sha256(bytes(password+mapped_email+str(num),encoding='utf-8')).hexdigest()
return thorax
def getNumber(username,password):
port = random.rand... |
"""Build starCraft agent with SCC algorithm."""
from functools import partial
from time import time
from xt.agent import Agent
from xt.algorithm.qmix.episode_buffer_np import EpisodeBatchNP
from xt.algorithm.qmix.transforms import OneHotNp
from zeus.common.ipc.message import message, set_msg_info
from zeus.common.uti... |
from contextlib import contextmanager
import inspect
import os
import random as py_random
from typing import Iterable
import numpy as np
from timeserio.externals import tensorflow as tf, keras
def iterlayers(model: keras.layers.Layer) -> Iterable[keras.layers.Layer]:
"""
Return iterable over all layers (and... |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
# -*- coding: utf-8 -*-
"""
@author: Daniel Jiménez-Caminero Costa
"""
import numpy as np
def segmentation_blocks(band_pass_signal_hr, sb, sh, dim):
""" Function used for the segmentation of the signal into smaller parts of audio (blocks). This has been implemented
as described in Formula 16 (secti... |
container_digests = {
"cuda9.0-cudnn7-ubuntu14.04": "sha256:c26138f4c38c754da2bad44a8a068523abf7fbd71d58a57ce92e5342c5431bf5",
"cuda10.0-cudnn7-ubuntu14.04": "sha256:7737d770599de8435115bfdf56977002319316a6735ab081f82506cb51443f9d",
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.