content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
"""
This module contains a subroutine for spectrally accurate interpolation of
data that is known on a uniform grid in a periodic domain.
"""
import numpy as np
#from numba import njit
# Get machine precision
eps = np.finfo(float).eps
#@njit
def fourier_interpolation(fk, x):
"""
I... |
# Generated by Django 3.0.6 on 2020-05-17 18:14
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('disease', '0003_auto_20200517_1739'),
]
operations = [
migrations.AddFie... |
import json
import sys
from typing import Dict, List
from aito.schema import AitoTableSchema
from aito.utils.data_frame_handler import DataFrameHandler
from .sub_command import SubCommand
from ..parser import PathArgType, InputArgType, ParseError, try_load_json
class ConvertFromFormatSubCommand(SubCommand):
def ... |
# Copyright 2017, Inderpreet Singh, All rights reserved.
import pickle
import sys
import argparse
# my libs
from system import SystemScanner, SystemFile, SystemScannerError
if __name__ == "__main__":
if sys.hexversion < 0x03050000:
sys.exit("Python 3.5 or newer is required to run this program.")
pa... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@version: ??
@author: xiaoming
@license: MIT Licence
@contact: xiaominghe2014@gmail.com
@site:
@software: PyCharm
@file: base_define.py
@time: 2017/12/19 下午12:11
"""
import const as xreg
xreg.repeat_0_or_more = '*'
xreg.repeat_1_or_more = '+'
xreg.repeat_0_or_1 = '?'
x... |
'''
@author Tian Shi
Please contact tshi@vt.edu
'''
import itertools
import os
import shutil
import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from LeafNATS.data.utils import create_batch_memory
from LeafNATS.utils.utils import show_progress
from nltk.corpus import st... |
## Script to help generate caterogy information
words_HP = ['harry', 'said', 'ron', 'hermione', 'professor', 'lupin', 'back', 'black', 'one', 'around', 'like', 'looked', 'could', 'see', 'got', 'snape', 'hagrid', 'didnt', 'get', 'know', 'well', 'harrys', 'still', 'eyes', 'go', 'would', 'dont', 'time', 'though', 'face',... |
#%% from all the dataset extract the raw rows that respect some conditions
import bz2
import subprocess
import os
from datetime import datetime
from utils import utils
dataset = '/home/gandelli/dev/data/it/sorted_by_pages.tsv.bz2'
dump_in = bz2.open(dataset, 'r')
line = dump_in.readline()
reverted_user = ''
curren... |
def quicksort(x):
if len(x) == 1 or len(x) == 0:
return x
else:
pivot = x[0]
i = 0
for j in range(len(x) - 1):
if x[j + 1] < pivot:
x[j + 1], x[i + 1] = x[i + 1], x[j + 1]
i += 1
x[0], x[i] = x[i], x[0]
first_part = quic... |
#!/usr/bin/env python2
"""
This script performs trail finding for a given species.
Retrieval of metabolic pathways, genomic information and EC numbers associations
is also handled, as needed.
Version: 1.0 (May 2018)
License: MIT
Author: Alexandra Zaharia (contact@alexandra-zaharia.org)
"""
import multiprocessing
im... |
import unittest
class Solution:
def isValid(self, s: str) -> bool:
token = {
')': '(',
'}': '{',
']': '[',
}
stack = []
for i in range(len(s)):
char = s[i]
if char in token:
if len(stack) == 0:
... |
from datetime import datetime
from test.base import ClientBaseCase
from linode_api4.objects import Config, Image, Instance, Type
from linode_api4.objects.base import MappedObject
class LinodeTest(ClientBaseCase):
"""
Tests methods of the Linode class
"""
def test_get_linode(self):
"""
... |
import unittest
from unittest import mock
from service.app import create_app
class TestApp(unittest.TestCase):
def test1(self):
_app = create_app()
with _app.test_client() as client:
with mock.patch('service.views.stories.get_users_s') as get_user_mock:
with mock.patch... |
# converts a csv file with set info to an Euler permutation list
# also checks for duplicate row names
# defines the CSV data filenames
inFile = "input.csv"
outFile = "output.csv"
# necessary imports
import csv
import time
# start timer
start = time.time()
# number of redundant iterations
iter = 0
# get the CSV da... |
""" Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +, -, *, /
operators , open ( and closing parentheses ) and empty spaces . The integer
division should truncate toward zero.
You may assume that the given expression ... |
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('requirements.txt') as req_file:
requires = [req for req in req_file.read().split('\n') if req]
with open('requirements-dev.txt') as req_file:
requires_dev = [req for req in req_file.... |
# Copyright (c) 2019 PaddlePaddle 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 appli... |
#!/usr/bin/env python
"""
libRst
======
This module is intended to provide compilation support for rst. The intention
is to keep the required libraries all in one place to provide a deployable,
python 2.6/2.7 compatible, rst compiler.
RST Constructs to be supported:
- paragraph
- heading
- list (unordere... |
import itertools
from typing import Dict, List, Tuple
import numpy as np
from sklearn.metrics import (
classification_report,
precision_score,
recall_score,
precision_recall_fscore_support,
)
from imagededup.utils.logger import return_logger
logger = return_logger(__name__)
def _get_unique_ordered_... |
from bitarray import bitarray
from copy import deepcopy
from functools import wraps
import math
import random
import unittest
length_prefix = 2
def bitarray_to_bytes(bitarr):
return bitarr.length().to_bytes(length_prefix, byteorder='big') + bitarr.tobytes()
def bitarray_from_bytes(bites):
length = int.from_b... |
"""
the C source files and headers in this directory were copied from
https://github.com/devonmpowell/r3d at git revision `6ddcdfa` on
4/22/2019 by MRB.
"""
from . import _r2d
|
# -*- coding:utf-8 -*-
import numpy as np
import pylab as plt
class Damper(object):
'''ダンパークラス'''
def __init__(self,angle_radian:float,coefficient:float,alpha:float):
self.rad = angle_radian
self.coeff = coefficient
self.alpha = alpha
@property
def direction_vector(self):
return np.array([np... |
# build RF extension
# run in RF
import os
from mojo.extensions import ExtensionBundle
# get current folder
basePath = os.path.dirname(__file__)
# folder with python files
libPath = os.path.join(basePath, 'extensionLib')
# folder with html files
htmlPath = os.path.join(basePath, 'html')
if not os.path.exists(htmlPat... |
# Copyright 2016 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 l... |
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPalette
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
MainWindow.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
MainWind... |
""" Build a neural machine translation model based on the transformer architecture. """
import os
import sys
import json
import time
import logging
import argparse
import tempfile
import subprocess
import numpy as np
import tensorflow as tf
from datetime import datetime
from collections import OrderedDict
from tran... |
# Copyright 2020-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 django.http import JsonResponse
from shop.models import ProductSKU
import json
class DataIntegrityCheckMixin:
def dispatch(self, request, *args, **kwargs):
# validate data
try:
data = json.loads(request.body.decode())
except:
return JsonResponse({'res': 0, 'err... |
import asyncio
import logging
import typing
from typing import Optional
from aiohttp.web import Request
from lbry.error import ResolveError, DownloadSDTimeoutError, InsufficientFundsError
from lbry.error import ResolveTimeoutError, DownloadDataTimeoutError, KeyFeeAboveMaxAllowedError
from lbry.error import InvalidStrea... |
import QUANTAXIS as QA
from QUANTAXIS.QAFetch.QAhuobi import FIRST_PRIORITY
from scipy.signal import butter, lfilter
import numpy as np
import matplotlib.pyplot as plt
from QUANTAXIS.QAIndicator.talib_numpy import *
if __name__ == '__main__':
codelist = ['BCHUSDT', 'BSVUSDT', 'BTCUSDT', 'EOSUSDT', 'ETHUSDT', 'ETCU... |
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
requirements = [
]
setup(
name='timecheck',
version='0.1.0',
license='MIT',
author='Jeeseung Han',
author_email='jinh574@naver.com',
url='https://hashbox.github.io',
description='Check elapsed time',
packages=find_pac... |
import os
import unittest
from datetime import datetime
from intuitquickbooks.auth import Oauth1SessionManager
from intuitquickbooks.client import QuickBooks
from intuitquickbooks.objects.trackingclass import Class
class ClassTest(unittest.TestCase):
def setUp(self):
self.session_manager = Oauth1SessionM... |
import time, datetime
import pandas as pd
import numpy as np
import json
from NLP.SVM.svm import Svm
from NLP.PREPROCESSING.preprocessor import Preprocessor
class SdgSvm(Svm):
"""
Concrete class to classify SDGs for modules and publications using the Svm model.
"""
def __init__(self):
sup... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class History(object):
"""Hold the training history"""
def __init__(self):
self.hist = pd.DataFrame(columns=['train loss', 'train acc', 'val loss', 'val acc'])
formatters = {
'train loss': "{:0.8f}".format, ... |
import json
import redis
from django.conf import settings
from tulius.websockets import consts
def publish_message(channel, message):
redis_client = redis.Redis(
settings.REDIS_CONNECTION['host'],
settings.REDIS_CONNECTION['port'],
db=settings.REDIS_CONNECTION['db']
)
redis_clien... |
import math
from typing import List
if __name__ == '__main__':
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
temp = math.inf
result = None
if len(nums) <3:
return []
else:
for i in range(len(... |
# pylint: disable=unused-import
# noinspection PyUnresolvedReferences
from scooter.models import rentals # noqa: F401
# noinspection PyUnresolvedReferences
from scooter.models import locations # noqa: F401
# noinspection PyUnresolvedReferences
from scooter.models import scooters # noqa: F401
# noinspection PyUnre... |
"""
Tests of dit.example_dists.dependencies
"""
from __future__ import division
import pytest
from dit.example_dists.dependencies import mixed, stacked
from dit.multivariate import coinformation, intrinsic_mutual_information
def test_mixed1():
"""
Test against known values.
"""
i = coinformation(mi... |
from patternpieces import PatternPieces
class Piece:
def __init__(self, idpiece, left=PatternPieces.EDGE, up=PatternPieces.EDGE,
right=PatternPieces.EDGE, down=PatternPieces.EDGE):
self.id = idpiece
self.leftEdge = left
self.upEdge = up
self.rightEdge = right
... |
"""Flashpoint Test File."""
import demistomock as demisto
import pytest
import json
import io
import datetime
import unittest
from unittest.mock import patch
from CommonServerPython import arg_to_datetime
from Flashpoint import Client, MESSAGES, MAX_PRODUCT, FILTER_DATE_VALUES, IS_FRESH_VALUES, MAX_PAGE_SIZE, \
SOR... |
# Задача 6. Вариант 32
# Создайте игру, в которой компьютер загадывает название одного из двадцати восьми стран, входящих в Европейский союз, а игрок должен его угадать.
# 24.03.2016
# Ширлин Вячеслав Викторович
import random
print ("Программа загадывает название одного из двадцати восьми стран, входящих в Европейски... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
from django.views import View
from django.core import serializers
from .models import RiskType, Field, NumberField, DateField, TextField
import json
from django.http import JsonResponse
import datetime
class IndexView(View):
... |
from .config import Config as StreamsConfig
|
l=[1,2,3,4,5]
print(list(filter(lambda x:x%2,l)))
|
import os
from platform import uname
from typing import Any, Dict
from cpuinfo import get_cpu_info
from GPUtil import getGPUs
from psutil import cpu_count, cpu_freq, virtual_memory
NUM_CPU = os.cpu_count() or 1
def get_machine_info() -> Dict[str, Any]:
sys = uname()
cpu = get_cpu_info()
svmem = virtual_... |
#
# Copyright 2011-2012 Ning, Inc.
#
# Ning licenses this file to you 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 compute_distance_and_align.compute_levenshtein_distance as compute_dist
def align_strings(seq1, seq2):
'''
Calculates minimum edit distance between str1 and str2
and saves backpointers to retrieve the allignments
:param srt seq1: from this s®tring
:param srt seq2: into this string
:ret... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
#admin.autodiscover() #drop this line for Django 1.8
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hiren.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.ur... |
# Copyright (c) 2017-2018 {Flair Inc.} WESLEY PENG
#
# 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 agre... |
from typing import List, Any
import cv2
import numpy as np
from Constants import Constants
from Vison.MathHandler import MathHandler
if __name__ == '__main__':
# Create instances of MathHandler class and Constants classes. These will keep all of the numbers
# and calculations of of this class so that this ... |
import logging
import sys
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
from application.main.config import settings
from application.main.utility.config_loader import ConfigReaderInstance
logging_config = ConfigReaderInstance.yaml.read_config_from_file(
settings.LOG_CONFIG_FILENA... |
#Pair up NPOL UF files and combine to create single cfradial file
import numpy as np
import os
import logging as log
# Inputs
inDir = '/home/disk/bob/olympex/raw/npol_qc2/rhi'
paramFile = '../params/RadxConvert.npol_rhi_west'
binDir = '/home/disk/meso-home/meso/lrose/bin'
#dates = ['20151105','20151112','20151113','2... |
from datetime import datetime
import numpy as np
from aidapy import event_search
# Time interval
start_time = datetime(2017, 7, 15, 7, 0, 0)
end_time = datetime(2017, 7, 15, 12, 0, 0)
# Input settings to look for dipolarization fronts on MMS1 probe
settings = {
"criteria": lambda dc_mag_z, mag_elangle, sc_pos_x, ... |
from django.urls import path
from . import views
urlpatterns = [
path('allstudents/', views.student_list, name='student_list'),
path('<int:student_id>/', views.single_student, name='single_student'),
path('registration/', views.student_regi, name='student_regi'),
path('edit/<int:pk>', views.edit_studen... |
"""
MIT License
Copyright (c) 2016 Ionata Digital
Copyright (c) 2009-2014 Joshua Roesslein
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rig... |
# Generated by Django 3.2.5 on 2021-08-14 17:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('character', '0006_auto_20210814_1738'),
]
operations = [
migrations.RemoveField(
model_name='bo... |
#coding=utf-8
import json
import io
import urllib.request
import time
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/49.0.2')]
# 根据 t_company_logo.json、t_company.json文件内容,
# 将t_company_logo文件中的公司logo 与 t_company文件同名公司的logo
# 打印 带有公司logo url地址的t_company信息
# ******************** ... |
# Description:
'''This is the demo code for all the functions of UPS Plus.
Advanced users can select the functions they need through the function options provided in the code below to customize and develop them to meet their needs.
'''
import time
import smbus2
import logging
from ina219 import INA219,DeviceRangeError... |
import os
import os.path
import pydicom
import shutil
from multiprocessing import Process
import time
# set initial values
src_path = "dicom file directory"
des_path = "destination directory"
process_count = 10 # number of process you use
def sd_form(str): # Series Description
str = str.replace(' ', '_')
... |
# encoding: UTF-8
"""
Implement phylib command line application.
"""
from __future__ import print_function
import sys
__USAGE__ = """usage: phylib <command> [<args>]
The support commands are:
cfutil-export export channel data to file or Channel Finder Service
impact-lattice generate IMPACT lattice file ... |
'''
This builds up the interface for the proof search module.
'''
import gen_model_beam_search
import gen_model_beam_search_torch
import pred_model as pred_model_run
import payout_model_5_train as payout_model_run
from models import *
from beam_search import *
import os
import sys
import numpy as np
import pickle as p... |
import pylibimport
# Downloaded whl
filename = "./sub/import_dir/opencv_python-4.5.1.48-cp38-cp38-win_amd64.whl"
imp = pylibimport.VersionImporter(install_dir='./sub/target_dir')
# imp.install(filename, 'cv2', '4.5.1') # Install with name cv2
# cv2_4_5_1 = imp.import_module('cv2', '4.5.1')
# Use import chain if imp... |
#!/usr/bin/env python3
"""
Copyright 2019 Johns Hopkins University (Author: Phani Sankar Nidadavolu)
Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""
from __future__ import print_function
import os
import sys
import argparse
from collections import OrderedDict
from scipy.io import wavfile
from nump... |
import pytest
from test_tube.argparse_hopt import HyperOptArgumentParser
from test_tube.hpc import SlurmCluster
def test_slurm_time_to_seconds():
parser = HyperOptArgumentParser()
parsed = parser.parse_args()
cluster = SlurmCluster(log_path='/home/travis', hyperparam_optimizer=parsed)
assert cluster... |
# -*- coding: utf-8 -*-
'''
@author: kebo
@contact: kebo0912@outlook.com
@version: 1.0
@file: trainer.py
@time: 2021/05/12 01:09:57
这一行开始写关于本文件的说明与解释
'''
import tensorflow as tf
from functools import wraps
from cybo.data.dataloader import Dataloader
from cybo.models.model import Model
from cybo.training.utils impo... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from backbone import (res32_cifar,res32_cifar_group, res50,res50_group, res10, res10_group, res152,res152_group)
from modules import GAP, FCNorm, FCGroupNorm, Identity, SEN, GMP, LWS, LWS_bias
import copy
import numpy as np
import cv2
class ... |
from enum import Enum
class Feature(str, Enum):
MINIMUM = "MINIMUM"
MAXIMUM = "MAXIMUM"
VARIANCE = "VARIANCE"
ABS_ENERGY = "ABS_ENERGY"
MEAN = "MEAN"
MEDIAN = "MEDIAN"
SKEWNESS = "SKEWNESS"
KURTOSIS = "KURTOSIS" |
from floodsystem.stationdata import build_station_list
from floodsystem.stationdata import update_water_levels
from floodsystem.flood import stations_level_over_threshold
stations = build_station_list()
update_water_levels(stations)
print(stations_level_over_threshold(stations, 0.8))
|
import re
from nltk.util import ngrams, pad_sequence, everygrams
from nltk.tokenize import word_tokenize
from nltk.lm import MLE, WittenBellInterpolated
import numpy as np
import plotly.graph_objects as go
from scipy.ndimage import gaussian_filter
# Training data file
train_data_file = ""
# read training data
with op... |
import csv
from ..base import BaseDataset
from ..utils import image_loader
from .schemas import MultiClassClassificationDatasetSchema
"""
The format of the multiclass classification dataset is:
image_path1,label1
image_path2,label2
...
"""
class MultiClassClassificationDataset(BaseDataset):
schema = MultiClassC... |
''' nio_pe.py: A specialization of the PE class, for use with Nick's Accelerator
'''
from core.defines import Operator
from core.pe import PE
from core.pipeline import Stage
from core.messaging import Message
from core.utils import *
class NioPE(PE):
def __init__(self, system_clock_ref, message_router):
... |
'''
Pure python implementation of a connect 4 terminal game object.
Optimizations applied allow computation of one move and one check in approx. 100us.
---Still kinda slow... see connect4tf.py for a (hopefully) faster implementation.---nvm, this is all i got
'''
import numpy as np
class Connect4Board(object):
def ... |
from src.infra.db.setup import Session
def get_db():
db = Session()
try:
yield db
finally:
db.close()
|
#!/usr/bin/python2.5
# Copyright (C) 2007 Google 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 la... |
"""Configuration for kalufs-kepubify.
May be overridden by instance/config.py.
"""
import os
# The log folder location
LOG_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "logs")
# Set log level to debug
DEBUG = True
TEMPLATES_AUTO_RELOAD = True
# Generate with os.urandom(24)
SECRET_KEY = "SUPERSEC... |
import atexit
import collections
import dataclasses
import functools
from math import log
import more_itertools
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def _fmt_permitted(permitted):
return "\n".join("".join(c if c in p else " " for c in ALPHABET) for p in permitted)
@dataclasses.dataclass(frozen=True)
class ... |
from __future__ import print_function
from __future__ import absolute_import
from builtins import range
from .tesisfunctions import Plotim,overlay
import cv2
import numpy as np
from .tesisfunctions import brightness, IMAGEPATH,graphpolygontest,thresh_biggestCnt,\
CircleClosure,twoMaxTest,graphDeffects,extendedSep... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
#
# RFID Read
#
import os,sys
import time
import json
import rfidiot
import CHIP_IO.GPIO as GPIO
from colorama import init
init(strip=not sys.stdout.isatty()) # strip colors if stdout is redirected
from termcolor import cprint
from pyfiglet import figlet_format
from... |
import unittest
from problem_322 import path_steps
class Problem322TestCase(unittest.TestCase):
number_1 = 10
number_2 = 11
start = 0
step = 0
def test_path_steps_1(self):
self.assertEqual(4, path_steps(self.start, self.step, self.number_1))
def test_path_steps_2(self):
self.... |
# coding=utf-8
# Copyright 2021 The HuggingFace Team. 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 requir... |
import os
from six.moves import xrange
from pymt.portprinter.port_printer import VtkPortPrinter
from pymt.testing.ports import UniformRectilinearGridPort
def test_one_file(tmpdir):
port = UniformRectilinearGridPort()
with tmpdir.as_cwd():
printer = VtkPortPrinter(port, "landscape_surface__elevation... |
class NoPubSubDriver(Exception):
pass
|
import numpy as np
a = np.array([-100, -10, 0, 10, 100])
print(a)
# [-100 -10 0 10 100]
print(np.sign(a))
# [-1 -1 0 1 1]
print(type(np.sign(a)))
# <class 'numpy.ndarray'>
print(np.sign(a).dtype)
# int64
a_float = np.array([-1.23, 0.0, 1.23])
print(a_float)
# [-1.23 0. 1.23]
print(np.sign(a_float))
... |
#!/usr/bin/env python3
import re
from setuptools import setup, find_packages
INIT_FILE = 'orbital/__init__.py'
init_data = open(INIT_FILE).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_data))
AUTHOR_EMAIL = metadata['author']
VERSION = metadata['version']
LICENSE = metadata['license']
DESCRIPT... |
from latex import build_pdf, LatexBuildError
from latex.errors import parse_log
import pytest
def test_generates_something():
min_latex = r"""
\documentclass{article}
\begin{document}
Hello, world!
\end{document}
"""
pdf = build_pdf(min_latex)
assert pdf
def test_raises_correct_exception_on_fail():
... |
#! python3
import re
import cloudconvert
def get_thumbnail_url(youtube_url, thumbnail_res):
youtube_url = youtube_url.rstrip()
youtube_id = ""
# Get YouTube video ID
search_pattern = re.search("(?:\/|%3D|v=|vi=)([0-9A-z-_]{11})(?:[%#?&]|$)", youtube_url)
if search_pattern:
youtube_id = sea... |
"""Helper classes for formulating game outcome measure"""
import numpy as np
import scipy.stats
import scipy.optimize
try:
import matplotlib.pyplot as plt
except:
pass
class GameOutcomeMeasure:
"""Base class for game outcome measure
Derived class must implement __call__ method, which accepts array
... |
from flask import Flask
from flask import jsonify
from flask import abort
from card import Card
import maker
import json
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
app.config['JSON_AS_ASCII'] = False
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
# 名刺一覧を作る
cards = maker.make()
@app.route('/')
def ro... |
# coding=utf-8
import json
import time
import sys
from functools import wraps
python_version = sys.version[0]
if python_version == '3':
basestring = str
def fn_timer(function):
"""
元素查找计时器
"""
@wraps(function)
def function_timer(*args, **kwargs):
t0 = time.time()
result = fun... |
import os
import json
import inspect
from datetime import date
import numpy as np
from typing import List, Tuple
import matplotlib.pyplot as plt
from ReinLife.World.entities import Agent
class Saver:
""" Class for saving the results of an experiment
If directories do not currently exist, it will create them... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
"""A few checks at the CASIA_FASD database.
"""
import os, sys
import unittest
from . import Database
from nose.plugins.skip import SkipTest
class FASDDatabaseTest(unittest.TestCase):
"""Performs various tests on the CASIA_FASD spoofing attack database."""
... |
# -*- coding: utf8 -*-
import json
from typing import List
from console.models import TaskIntra, task_intra_repo
from console.exceptions import NotFound, AlreadyExist
from console.user import UserService
from console.project import ProjectService
from console.utils import get_time_version
class TaskIntraService:
... |
import time
import machine, neopixel
np = neopixel.NeoPixel(machine.Pin(33), n=10,bpp=3,timing=1)
def demo(np):
n = np.n
# cycle
for i in range(4 * n):
for j in range(n):
np[j] = (0, 0, 0)
np[i % n] = (255, 255, 255)
np.write()
time.sleep_ms(25)
# bounce
for i in range(4 * n):
for j in range(n):
... |
import re
from collections import namedtuple
import attr
from automat import MethodicalMachine
from .conversion import Converter
from .messages import Notice, Error
_convert_to_underscores_lmao = re.compile(r"(?<!^)(?=[A-Z])")
def _get_last_collector(results):
try:
from twisted.internet.defer import D... |
from django.apps import AppConfig
class DjangoConohaObjstorageConfig(AppConfig):
name = 'django_conoha_objstorage'
|
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
"""Make task_group_id nullable
Revision ID: 1a4241cfd4cd
Revises: 44047daa31a9... |
from .matrix_factorization import MFExplicitSGD
from .matrix_factorization_prep import MFExplicitPrepSGD
__all__ = [
"MFExplicitSGD",
"MFExplicitPrepSGD"
]
|
import numpy as np
import pickle
import glob
import copy
from l96 import l96
from l96 import l96_jacobian
#import ipdb
########################################################################################################################
# Non-linear model vectorized for ensembles
def l96V(x, f):
""""This desc... |
######################################################################################################################
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
import requests
print("key = ")
key = raw_input()
print("id = ")
yt = raw_input()
r = requests.get('https://www.googleapis.com/youtube/v3/videos?id=' + yt + '&key=' + key + '&part=statistics').json()
like = int(r['items'][0]['statistics']['likeCount'])
dislike = int(r['items'][0]['statistics']['dislikeCount'])
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.