content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
""" Unit tests for FeatureNormalizer """
import nose.tools
import sys
import numpy
sys.path.append('..')
from dcase_framework.features import FeatureNormalizer, FeatureContainer, FeatureExtractor
import os
def test_accumulate_finalize():
FeatureExtractor(store=True, overwrite=True).extract(
audio_file=os... | python |
"""A package for computing Pfaffians"""
import cmath
import math
import numpy as np
import scipy.linalg as la
import scipy.sparse as sp
def householder_real(x):
"""(v, tau, alpha) = householder_real(x)
Compute a Householder transformation such that
(1-tau v v^T) x = alpha e_1
where x and v a real v... | python |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.template import loader
from django.utils.safestring import mark_safe as _S
from django.utils.six.moves.urllib.parse import urlparse
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import get_permission_c... | python |
"""
Evaluate the true Fourier coefficients of a given function x(1-x),
generate the domain based on that and define the model Q:\Lambda \to D
"""
import sympy
from inversefuns.utilities import get_coef, coef_domain, fourier_exp_vec
import numpy as np
param_len = 5
t=np.array((0.1,0.2,0.4,0.5,0.7))
period0 = 1.0
def t... | python |
"""Base Class for a Solver. This class contains the different methods that
can be used to solve an environment/problem. There are methods for
mini-batch training, control, etc...
The idea is that this class will contain all the methods that the different
algorithms would need. Then we can simply call this class in the ... | python |
import re
mystring='My ip address is 10.10.10.20 and by subnet mask is 255.255.255.255'
if (re.search("ip address",mystring)):
ipaddregex=re.search("ip address is \d+.\d+.\d+.\d+",mystring)
ipaddregex=ipaddregex.group(0)
ipaddress=ipaddregex.replace("ip address is ","")
print ("IP address is :",ipaddre... | python |
import sys
import PyFBA.metabolism
class Reaction:
"""
A reaction is the central concept of metabolism and is the conversion of substrates to products.
The reaction describes what we know. At a bare minimum we need a a name for the reaction. The name can either be the
reaction id (e.g. modelSEED or ... | python |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import paddle
from mmdet.models.utils import interpolate_as
def test_interpolate_as():
source = paddle.rand((1, 5, 4, 4))
target = paddle.rand((1, 1, 16, 16))
# Test 4D source and target
result = interpolate_as(source, target)
as... | python |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
"""
class Punto:
"""Representación de un punto en coordenadas polares.
:param x: coordenada x del punto.
:x type: int
:param y: coordenada y del punto.
:y type: int
"""
def __init__(self, x: int = 0, y: int = 0) -> None:
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pdb import set_trace
import re
def check_entitys(text):
ptrn = r"(&{1})([\w-]+)([;]{0,1})"
lst = []
for m in re.finditer(ptrn, text):
s = m.group()
g2 = m.groups()[2]
t = 0 if g2 == ';' else 1
lst.append({'s': s, 't': t})
... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2017-07-30 15:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0011_auto_20170718_2027'),
]
operations = [
migrations.AlterField... | python |
import json, pdb, os, numpy as np, cv2, threading, math, io
import torch
from torch.autograd import Variable
def open_image(fn):
""" Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normal... | python |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we a... | python |
from queue import PriorityQueue as PQueue
N = int(input())
C = int(input())
V = int(input())
S = list(map(lambda x: int(x)-1, input().split()))
T = list(map(lambda x: int(x)-1, input().split()))
Y = list(map(int, input().split()))
M = list(map(int, input().split()))
E = [[] for _ in range(N)]
for f, t, cost, time in zi... | python |
import datetime
from django.conf import settings
from django.db import models
BLOOD_GROUP_STATUSES = (
('U', 'Urgente'),
('S', 'Stabile'),
('Z', 'Emergenza'),
('E', 'Eccedenza'),
('F', 'Fragile'),
)
class BloodGroup(models.Model):
groupid = models.CharField(max_length=3, unique=True) # AB+... | python |
from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField
from backend.blog.models import BlogCategory, Tag, Post
class BlogCategorySerializer(serializers.ModelSerializer):
"""Сериализация модели категорий"""
children = serializers.ListField(source='get_children', read... | python |
#!/usr/bin/env python
# encoding: utf-8
# dit gedeelte zorgt ervoor dat stdout, stderr = subprocess.Popen werkt.
import subprocess
# tussen word = "" kun je de tekst typen die de koe moet uitspreken.
# cowsay staat voor een koe, maar als je een ander karakter wilt zul je de code moeten aanpassen.
# van 'cowsay', naar... | python |
"""Functions for generating interactive visualizations of 3D models of
trees."""
import os
import numpy as np
import pandas as pd
import geopandas as gpd
import seaborn as sns
import ipyvolume as ipv
from ipywidgets import FloatSlider, VBox, HBox, Accordion, Text, Layout
from forest3d.geometry import make_tr... | python |
from js9 import j
def init_actions_(service, args):
dependencies = {
'list_disks': ['init'],
'get_consumption': ['install']
}
return dependencies
def init(job):
service = job.service
if 'g8client' not in service.producers:
raise j.exceptions.AYSNotFound("No producer g8cli... | python |
import math
n = input()
r = list(map(int,n))
lastNum = r[-1]
l = r[:-1]
newArray = list(map(int,l))
#print(newArray)
print(lastNum)
print(newArray)
| python |
from __future__ import absolute_import
import logging
import time
from django.contrib.auth.models import User
from django.http import HttpResponse, StreamingHttpResponse
from django.shortcuts import get_object_or_404, render, render_to_response
import elasticapm
class MyException(Exception):
pass
class Ignor... | python |
"""empty message
Revision ID: 878f67285c72
Revises: 122dd6a5c035
Create Date: 2019-05-29 12:57:36.544059
"""
# revision identifiers, used by Alembic.
revision = '878f67285c72'
down_revision = '122dd6a5c035'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
def upgrade():
... | python |
import numpy as np
import trimesh
from pdb import set_trace as bp
def write_off(file_path, verts, faces=None):
"""Export point cloud into .off file.
Positional arguments:
file_path: output path
verts: Nx3 array (float)
Kwargs:
faces: Mx3 array (int)
"""
off = open(file_path, 'w')
... | python |
from PyQt5 import QtWidgets, QtCore, QtGui
import os
#from gui.export_widget import Ui_Form
from editable_list_widget import list_widget
from gui import build
from wizard.vars import defaults
from wizard.tools import log
from wizard.prefs.main import prefs
import options_widget
import dialog_comment
from wizard.tools.... | python |
"""
PYTHON NUMBER SEQUENCE
"""
__author__ = 'Sol Amour - amoursol@gmail.com'
__twitter__ = '@solamour'
__version__ = '1.0.0'
# SYNTAX: [ value * step for value in range( amount ) ]
# Step = This is the value we will multiply our range by
# Amount = How many total values we want
# NOTES:
# All parameters ... | python |
# based on https://github.com/pypa/sampleproject
# MIT License
# Always prefer setuptools over distutils
from setuptools import setup, find_namespace_packages
from os import path
from io import open
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, ... | python |
from __future__ import unicode_literals
import datetime
from django.core.urlresolvers import reverse
from tracpro.polls.models import Answer, PollRun, Response
from tracpro.test.cases import TracProDataTest
from ..models import BaselineTerm
class TestBaselineTermCRUDL(TracProDataTest):
def setUp(self):
... | python |
# Copyright (c) 2020 Spanish National Research Council
#
# 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 ... | python |
# flake8: noqa
# Copyright (c) 2015 - 2017 Holger Nahrstaedt
# Copyright (c) 2016-2017 The pyedflib Developers
# <https://github.com/holgern/pyedflib>
# See LICENSE for license details.
from __future__ import division, print_function, absolute_import
from ._extensions._pyedflib import *
from ... | python |
"""
Holds functions responsible for objects validation across FAT-Forensics.
"""
# Author: Kacper Sokol <k.sokol@bristol.ac.uk>
# License: new BSD
import warnings
from typing import Union
import numpy as np
import fatf.utils.tools as fut
__all__ = ['is_numerical_dtype',
'is_textual_dtype',
'i... | python |
'''Validação de URL com POO
Pontos de Obsevação em uma URL: caracteres padrões → "?", "&", "https://", "http://", "www." '''
import re
class ExtratorURL:
def __init__(self, url):
self.url = self.clear_url(url)
self.url_validation()
def clear_url(self, url):
if type(url) == str:
... | python |
#!/usr/bin/env python3
project = "stories"
copyright = "2018, Artem Malyshev"
author = "Artem Malyshev"
version = "0.9"
release = "0.9"
templates_path = ["templates"]
source_suffix = ".rst"
master_doc = "index"
language = None
exclude_patterns = ["_build"]
pygments_style = "sphinx"
html_theme = "alabaster"
... | python |
from transformers import AutoModelWithLMHead, AutoTokenizer
def run_gpt2(gpt2_input):
tokenizer = AutoTokenizer.from_pretrained('gpt2')
model = AutoModelWithLMHead.from_pretrained('gpt2')
sequence = gpt2_input
input = tokenizer.encode(sequence, return_tensors='pt')
generated = model.generate(inpu... | python |
# coding=utf-8
# Copyright 2018 The TF-Agents 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... | python |
import numpy as np
from protosc.model.utils import train_xvalidate, create_clusters, select_features
from protosc.model.filter import FilterModel
from protosc.simulation import create_correlated_data, create_independent_data
from protosc.feature_matrix import FeatureMatrix
def get_test_matrix(n_row=100, n_col=50):
... | python |
# -*- coding: utf-8 -*-
import base64
import hashlib
import math
import time
from datetime import datetime
# from ccxt.base.errors import AuthenticationError, InvalidOrder
from ccxt.base.errors import ExchangeError
from ccxt.base.exchange import Exchange
class qtrade (Exchange):
def describe(self):
ret... | python |
import os
from typing import List
#
# get next filename under the [exchange directory]. if there is no folder for filename - the folder will be created
#
def get_next_report_filename(dir, filename_mask):
filename_mask2 = filename_mask % (dir, 0)
directory = os.path.dirname(filename_mask2)
try:
o... | python |
#!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Challenge Notebook
# ## Problem: Implement Fizz Buzz.
#
# * [Constraints](#Constraints)
# * ... | python |
#IP Address of the SQL server
host = "157.230.209.171"
#MySql username
user = "easley_1267"
#MySQL password
password = "ROY7iOUUQAt18r8qnsXf5jO3foUHgAbp" | python |
import pandas as pd
def convert_jh_global_time_series_to_long(df, name):
"""Converts JH global time series data from wide to long format"""
df = df.melt(id_vars=['Province/State', 'Country/Region', 'Lat', 'Long'],
var_name='date',
value_name=name)
# Convert to datetime
... | python |
import time
def example(seconds):
print('Starting task')
for i in range(seconds):
print(i)
time.sleep(1)
print('Task completed')
if __name__ == '__main__':
example(10)
| python |
"""The wireless version of a connection"""
from Connection import Connection
class Wireless_Connection(Connection):
type = "Wireless_Connection"
def __init__(self, source, dest):
"""
Create a connection between wireless devices.
"""
Connection.__init__(self, source,... | python |
from celery import shared_task
@shared_task
def add(a, b):
return (a+b)
| python |
# This file is part of the History Store (histore).
#
# Copyright (C) 2018-2021 New York University.
#
# The History Store (histore) is released under the Revised BSD License. See
# file LICENSE for full license details.
"""Writer for archives that are materialized as Json files on the file
system.
"""
from typing im... | python |
#!/usr/bin/env python
from ALU import *
import numpy as np
import pandas as pd
import pickle
class Dataset():
def __init__(self, data_bits, path, label_bit_msk=None):
if label_bit_msk is None:
label_bit_msk = [True for _ in range(data_bits)]
elif(len(label_bit_msk) > data_bits):
... | python |
'''
Regrid the GBT data to match the VLA HI data.
'''
from spectral_cube import SpectralCube
from astropy.utils.console import ProgressBar
import numpy as np
import os
from cube_analysis.io_utils import create_huge_fits
from paths import fourteenB_HI_data_path, data_path
# Load the non-pb masked cube
vla_cube = S... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class TX():
def __init__(self):
self.txid = ''
self.inputs = []
self.outputs = []
self.block_height = 0
self.confirmations = 0
def print_tx(self):
print '\nblock ', str(self.block_height), "(" + str(self.confirmatio... | python |
from series import fibonacci, lucas, sum_series
# Fibonacci tests"
# Expected Outcome
def test_zero():
expected = 0
actual = fibonacci(0)
assert actual == expected
def test_one():
expected = 1
actual = fibonacci(1)
assert actual == expected
def test_15n():
expected = 610
actual = fib... | python |
from django.urls import path
from . import views
app_name = 'orders'
urlpatterns = [
path('create/', views.order_create, name='order_create'),
path(
'order_list/<str:username>/',
views.orderlist,
name='order_list'
),
path(
'order_list/<int:id>/detail/',
views.o... | python |
'''
Python 3.6
This script contains functions to clean the text in the tweets.
Methods here are not called directly.
Instead, they are called from either "NLTK_clean_tweet_testing.py" or "TextBlob_clean_tweet_testing.py"
'''
print("Importing tweetCleaner...")
from bs4 import BeautifulSoup
import re
from nltk.stem im... | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import json
import torch
import torch.nn.functional as F
from fairseq import metrics, utils
from fairseq.criterions import Fairse... | python |
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import MyModel
def mymodel_list(request):
paginate_by = 24
qs = MyModel.objects.all()
paginator = ... | python |
import tkinter as tk
from sudokuUI import SudokuUI
root = tk.Tk()
#p = [ [0,i,i+1] for i in range(9) ] + [ [1,(i+3)% 9, i + 1] for i in range(9)] + [ [2,(i+6) % 9, i+1] for i in range(9)] + [[3,(i+1)%9,i+1] for i in range(9)] + [[4,(i+4)%9,i+1] for i in range(9)] + [[5, (i+7)% 9, i + 1] for i in range(9)] + [[6,(... | python |
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 scmanjarrez. All rights reserved.
# This work is licensed under the terms of the MIT license.
from contextlib import closing
import sqlite3 as sql
DB = 'diptico.db'
def setup_db():
with closing(sql.connect(DB)) as db:
with closing(db.cursor()) as cur... | python |
########
# Copyright (c) 2019 Cloudify Platform 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/LICENSE-2.0
#
# Unless requi... | python |
# Generated by Django 2.2.3 on 2019-07-30 13:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0002_auto_20190730_0034'),
('profiles', '0002_profile_follows'),
]
operations = [
migrations.AddField(
model_n... | python |
import numpy as np
import warnings
from time import sleep
from main import get_prediction
from example_data_base import save_historical_data, get_historical_data
prediction_rates = {}
def get_random_array(n):
return np.random.randint(0, 10, n).tolist()
def convert_to_db_format(predictions):
cars = predicti... | python |
# Ivan Carvalho
# Solution to https://www.urionlinejudge.com.br/judge/problems/view/2057
#!/usr/bin/env python2.7
# encoding : utf-8
numero = sum([int(i) for i in raw_input().split(" ")])
if numero < 0:
print numero + 24
elif numero < 24:
print numero
else:
print numero-24
| python |
"""Centralized setup of logging for the service."""
import logging.config
import sys
from os import path
def setup_logging(conf):
"""Create the services logger."""
if conf and path.isfile(conf):
logging.config.fileConfig(conf)
print("Configure logging, from conf:{}".format(conf), file=sys.std... | python |
import setuptools
setuptools.setup(
name='pytorch-nce2',
version='0.0.1',
author='Kaiyu Shi',
author_email='skyisno.1@gmail.com',
description='An NCE implementation in pytorch',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
url='https://githu... | python |
import os
import errno
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
DATA_PATH = 'raw_data'
SAMPLE_RATE = 16000
DURATION = 2.5
OFFSET = 0.5
HOP_LENGTH = 512
# MFCC -> (n_mfcc, t)
# t = sample_rate * time / hop_length
MAX... | python |
#
# Copyright (c) 2013-2018 Quarkslab.
# This file is part of IRMA project.
#
# 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 in the top-level directory
# of this distribution and at:
#
# http:... | python |
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
def __str__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=128)
ur... | python |
#!/usr/bin/env python
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# mock, just outputs empty .h/.cpp files
import os
import sys
if len(sys.argv) == 2:
basename, ext = os.path.splitext(sys.argv[1])
wit... | python |
from .unigram import UniGramModel
| python |
import os
import pandas as pd
jaea_fns_175 = pd.read_csv(os.path.join(__path__[0], "JAEA_FNS_175.csv")).set_index("E")
| python |
import torch
import torch.nn as nn
from utils import split_data,read_json_file, get_text
from dataset import my_dataset,my_collate_fn
from model import my_model,weights_init
from engine import train_fn,eval_fn
import cv2
from sklearn import model_selection
import pandas as pd
vocab="- !#$%&'()*+,./0123456789:;<=>?@AB... | python |
# creating a tupples
#empty tupple
s1=()
print('s1 : ',s1)
#tupple with multiple elements and accessing it
s2=(2782,'thakur',99)
print('s2 : ',s2)
#another way to create tupples and access them
S3=(82,85,96,56,70,99)
print('S3 : ',S3)
s4=74,'sandeep',90
print('s4 : ',s4)
s3=(82)
print('s3=(82): ',s3)
#cre... | python |
P = 10
objects = [(5, 18),(2, 9), (4, 12), (6,25)]
print("Items available: ",objects)
print("***********************************")
objects = filter(lambda x: x[0]<=P, objects)
objects = sorted(objects, key=lambda x: x[1]/x[0], reverse=True)
weight, value, subset = 0, 0, []
print("Items filtered and sorted: ",obj... | python |
from setuptools import setup, find_packages
setup(
name="JsonDataManager",
license="MIT",
version="1.0",
author="PieSignal",
author_email="leeon@insiro.me",
url="https://github.com/PieSignal/JsonDataManager",
requires=["typing >= 3.7.4.1, <4"],
packages=find_packages(),
)
| python |
import json
import re
import sys
from math import sin, cos, sqrt, atan2, radians
def main():
LAT_ORIGIN = radians(39.103119) # YOUR LOCATION LATITUDE IN ( )
LON_ORIGIN = radians(-84.512016) # YOUR LOCATION LONGITUDE IN ( )
radius_of_earth = 6378.0
results = []
with open("list.txt") as airpor... | python |
import vcf
import argparse
from record import Record, PhaseSet, ChromosomoHaplotype
from stats import PhaseSetStats, HapStats
def get_phase_set_stats(template_phase_set:PhaseSet, phase_set:PhaseSet):
prev_record: Record
record: Record
t_record: Record
t_prev_record: Record
record_count = 0
s... | python |
# File that prepares the transcripts into CSV for insertion into the database
# Created by Thomas Orth
import pandas as pd
import sys
# CHANGE THESE VALUES DEPENDING ON THE TRANSCRIPT
name = "Charles Terry"
summary = "Charles Terry is interviewed about his life in old trenton and other aspects such as working for t... | python |
from __future__ import print_function
import numpy as np
from collections import defaultdict
import matplotlib.pyplot as plt
import matplotlib.patches as patches
class PQTNode:
"""PQT Node class"""
def __init__(self, bounds=[[0., 1.], [0., 1.]]):
self.children = []
self.bounds = bounds
... | python |
''' '''
'''
ISC License
Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all c... | python |
class Matrix(object):
def __init__(self, matrix_string):
self.__matrix = [[int(el) for el in line.split()]
for line in matrix_string.splitlines()]
def row(self, index):
return self.__matrix[index-1].copy()
def column(self, index):
return [el[index-1] for el... | python |
def texto(num):
cores = {'Vermelho': '\033[31;1m', 'Azul': '\033[1;34m', 'Limpa': '\033[m'}
print(f'{cores["Vermelho"]}ERRO! "{cores["Azul"]}{num}{cores["Vermelho"]}" não é um valor válido!{cores["Limpa"]}')
def leiadinheiro(msg):
while True:
resp = str(input(msg)).strip()
resp1 = resp.rep... | python |
# Copyright 2010 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 law or a... | python |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
------------------------------------------... | python |
# Copyright (C) 2018 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Cycle Task Entry RBAC Factory."""
from ggrc.models import all_models
from integration.ggrc import Api
from integration.ggrc.access_control.rbac_factories import base
from integration.ggrc.models import fa... | python |
from simplecv.data import test_transforms as ttas
from albumentations import Compose, OneOf, Normalize
from albumentations import HorizontalFlip, VerticalFlip, RandomRotate90, RandomCrop
from simplecv.api.preprocess import albu
from albumentations.pytorch import ToTensorV2
import torch.nn as nn
config = dict(
mode... | python |
from .logit_lens import LogitLens
| python |
"""
@author Huaze Shen
@date 2019-07-19
"""
def combination_sum_2(candidates, target):
results = []
if candidates is None or len(candidates) == 0:
return results
candidates = sorted(candidates)
combination = []
helper(results, combination, candidates, 0, target)
return results
def he... | python |
from django.test import TestCase
from django.urls import reverse
from user.forms import (AssociatedEmailChoiceForm, AddEmailForm,
LoginForm, ProfileForm, RegistrationForm)
from user.models import User
class TestForms(TestCase):
def create_test_forms(self, FormClass, valid_dict, invalid_dict, user=None):
... | python |
# Copyright (c) 2015-2017 The Switch Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0, which is in the LICENSE file.
"""
This file should only include the version. Do not import any packages or
modules here because this file needs to be executed before SWITCH is
installed and executed in e... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .dependency import Dependency
from ..config import Configuration
from ..util.process import Process
from ..util.color import Color
import os
class Hashcat(Dependency):
dependency_required = False
dependency_name = 'hashcat'
dependency_url = 'https://has... | python |
from PyQt5.QtWidgets import QWidget, \
QHBoxLayout,\
QVBoxLayout,\
QDialog,\
QLineEdit,\
QLabel,\
QPushButton
from PyQt5.QtCore import Qt
class NewFile(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.name = QLineEdit()
self.name.setText("Un... | python |
'''
Base class for RTE test suite
'''
import abc
import numpy as np
class BaseTestRTE(object):
'''
base class to test all interfaces
'''
__metaclass__ = abc.ABCMeta
@property
@abc.abstractmethod
def _interface(self):
return None
def test_apply_bc_0(self):
'''
a... | python |
"""A client for Team Foundation Server."""
from __future__ import unicode_literals
import logging
import os
import re
import sys
import tempfile
import xml.etree.ElementTree as ET
from six.moves.urllib.parse import unquote
from rbtools.clients import RepositoryInfo, SCMClient
from rbtools.clients.errors import (Inv... | python |
########### IMPORTING THE REQURIED LIBRARIES ###########
from __future__ import print_function
from bs4 import BeautifulSoup as soup
from random import choice
from terminaltables import AsciiTable
from .proxy import _proxy
from .utils import *
import requests
######## DECLARING THE CLASS FOR GETTING COVID-19 DATA ###... | python |
#!/usr/bin/env python3
import sys
import re
# www.hackerrank.com
# http://www.hackerrank.com
# Regex_Pattern = r'^\w{3}\W{1}\w+\W{1}\w{3}$'
Regex_Pattern = r'^\d{1}\w{4}\.$'
print(str(bool(re.search(Regex_Pattern, input()))).lower())
| python |
#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
import os,re
from waflib import Utils,Options,Context
gnuopts='''
bindir, user commands, ${EXEC_PREFIX}/bin
sbindir, system binaries, ${EXEC_PREFIX}/sbin
libexecdir, program-specific binaries, ${EXEC... | python |
import logging
import numpy
import parse_cif_file
import os
import sys
from operator import itemgetter
def get_dihedral_angle1(p0,p1,p2,p3):
"""http://stackoverflow.com/q/20305272/1128289"""
p = [p0, p1, p2, p3]
b = p[:-1] - p[1:]
b[0] *= -1
v = numpy.array( [ v - (v.dot(b[1])/b[1].dot(b[1])) * b[1... | python |
# -*- coding: utf-8 -*-
"""
cdeweb.errors
~~~~~~~~~~~~~
Error views.
:copyright: Copyright 2016 by Matt Swain.
:license: MIT, see LICENSE file for more details.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
imp... | python |
from setuptools import setup
setup(
name='zipf',
version='0.1',
author='Amira Khan',
packages=['zipf'],
install_requires=[
'matplotlib',
'pandas',
'scipy',
'pyyaml',
'pytest'],
entry_points={
'console_scripts': [
'countwords = zipf.co... | python |
from abc import ABC, abstractmethod
import ccxt
from PySide6 import QtWidgets
# import ccxt.async_support as ccxt
from XsCore import xsIni
from ccxt import Exchange
class PluginBase(ABC):
name: str = ""
display_name: str = ""
info: str = ""
help_doc = "" # 不重写为没有文档 使用文档说明,为md文件,存放database的plugin_help... | python |
# Copyright 2014 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 law or ... | python |
# link:https://leetcode.com/problems/design-browser-history/
class BrowserHistory:
def __init__(self, homepage: str):
self.forw_memo = [] # forw_memo stores the future url
self.back_memo = [] # back_memo stores the previous url
self.curr_url = homepage
def visit(self, url: str... | python |
'''
Models utility module.
'''
import tensorflow as tf
def dense(input_size,output_size,depth,size):
'''Create a dense model with specific input_size,output_size,depth and number of neuros.'''
layers = [tf.keras.layers.Flatten(input_shape=(input_size,input_size,3))]
for i in range(depth):
... | python |
# -*- coding: utf-8 -*-
"""
@file
@brief
"""
import timeit
import pandas
def unit(x):
"""
Optimizes the rendering of time.
.. runpython::
:showcode:
from jupytalk.benchmark.mlprediction import unit
print(unit(34))
print(unit(3.4))
print(unit(0.34))
print(... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.