text stringlengths 2 999k |
|---|
from django.db import models
from ..helpers import wallpapers_dir
class Listino(models.Model):
nome = models.CharField(max_length=200)
def __str__(self):
return f"Listino {self.nome}"
class Meta:
verbose_name = "Listino"
verbose_name_plural = "Listini"
|
#-*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
#import ipdb
#batchnormalize:看
def batchnormalize(X, eps=1e-8, g=None, b=None):
if X.get_shape().ndims == 4:
mean = tf.reduce_mean(X, [0,1,2])
std = tf.reduce_mean( tf.square(X-mean), [0,1,2] )
X = (X-mean) / tf.sqrt(std+eps)... |
"""
Provides functionality to interact with lights.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/light/
"""
import logging
import os
import csv
import voluptuous as vol
from homeassistant.components import (
group, discovery, wemo, wink, isy994,... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import json
import logging
import warnings
from builtins import str
from typing import Text, Optional, List, Tuple
from rasa_core import utils, evaluate... |
# _*_ coding: utf-8 _*_
"""
install script: python3 setup.py install
"""
from setuptools import setup, find_packages
setup(
name="spider",
version="1.5.2",
author="xianhu",
keywords=["spider", "crawler", "multi-threads", "proxies"],
packages=find_packages(exclude=("test.*",)),
package_data={
... |
# Copyright 2015 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
#
# 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 not... |
import unittest
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
class AssertionsTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome('C:/Users/nicol/Documents/ProyectoPython/Selenium-Python/chromed... |
from . import decode
from .core import *
from .model import Crepe
from . import convert
from . import filter
from . import load
from . import loudness
from . import threshold
|
from Model import NER
from Model.WordEmbeddings.WordEmbedding import EmbeddingModel
#**** TAG SENTENCE ****
w2v_class = EmbeddingModel(r'C:\Path\To\W2V\Model' ,lower=True, binary=True)
test_sentence = 'John Wick really liked his dog Chester. They went to New York together to support the Help Orphan Puppies organizat... |
import re
from datetime import datetime
from city_scrapers_core.constants import BOARD, COMMITTEE
from city_scrapers_core.items import Meeting
from city_scrapers_core.spiders import CityScrapersSpider
class ChiPoliceRetirementSpider(CityScrapersSpider):
name = "chi_police_retirement"
agency = "Policemen's An... |
# from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
# import plotly.graph_objs as go
import os
import matplotlib
# matplotlib.use('TkAgg') # noqa
import seaborn # noqa
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa
import pandas as pd
try:
imp... |
# -*- coding: utf-8 -*-
"""
These URL routings are used by the example `polymorphic` as found in the django-SHOP's tutorials.
The difference here is that we added a special serializer class to add smart phones with their
variations to the cart.
"""
from __future__ import unicode_literals
from django.conf.urls import u... |
#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# 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
... |
import os
import json
import datetime
from themis.util import timeseries, aws_common
from themis.util.common import *
THIS_FOLDER = os.path.realpath(os.path.dirname(__file__))
def test_cloudwatch_timeseries():
cw = load_json_file(os.path.join(THIS_FOLDER, 'data', 'cloudwatch_kinesis_response.json'))
series =... |
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from set_style import set_style
set_style('default', w=1, h=3.3)
fig = plt.figure()
gs = gridspec.GridSpec(8,6)
ax00 = plt.subplot(gs[0:2,0:2])
ax0 = plt.subplot(gs[0:2,2:4])
ax1... |
"""Base UptimeRobot entity."""
from __future__ import annotations
from pyuptimerobot import UptimeRobotMonitor
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from .const import ATTR_TARGET, ATTRIBUT... |
# Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 Isaku Yamahata <yamahata at private email ne jp>
#
# 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
#
# h... |
from io import StringIO
from itertools import chain, product
from typing import List, Tuple, Type
from unittest import TestCase, TextTestRunner, defaultTestLoader, mock
from parametrize import parametrize
from parametrize.parametrize import UnparametrizedMethod
def run_unittests(case: Type[TestCase]):
suite = de... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import scipy.integrate as integrate |
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from models import Base, MyParentModel, MyChildModel
import pytest
@pytest.fixture(scope='session')
def engine():
return create_engine('sqlite://')
@pytest.fixture(scope='session')
def tables(engine):
Base.metadata.create_all(engine)
... |
"""One-off script to import Footy Tipper predictions to the DB."""
import os
import sys
import json
import django
PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))
if PROJECT_PATH not in sys.path:
sys.path.append(PROJECT_PATH)
django.setup()
from server.models import Prediction #... |
# This file contains experimental modules
import numpy as np
import torch
import torch.nn as nn
from yolov5_models.common import Conv, DWConv
from yolov5_utils.google_utils import attempt_download
class CrossConv(nn.Module):
# Cross Convolution Downsample
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, sho... |
from numpy.core.numeric import nan
from requests import Session
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
from datetime import datetime
HEADERS = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '\
'AppleWebKit/537.36 (KHTML, like Gecko) '\
'... |
import numpy as np
import droneposelib as dpl
def pflat(x):
"""Divide by the last coordinate to get an inhomogenous representation."""
# Enfoce 2D
if x.ndim == 1:
x = np.expand_dims(x, 1)
return x / x[-1, :]
def skew(a):
a = np.squeeze(a)
"""Create skew-symmetric matrix corresponding... |
# Licensed to Elasticsearch under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except... |
from _shared import DISCORD_MESSAGE_END
from pink_accents import Accent
class Slav(Accent):
"""You feel drunk"""
WORDS = {
r"my": "our",
r"friend": "comrade",
r"(enemy|foe)": "american pig",
r"(fuck|shit)": (
"blyat",
"cyka",
),
r"usa": ... |
import sys
sys.path.append("..")
import streamlit as st
from reddit_analysis.app.templates.c_testing.subreddits.algo import tfidf, lstm, bert
# Define possible models in a dict.
# Format of the dict:
# option 1: model -> code
# option 2 – if model has multiple variants: model -> model variant -> code
MODELS = {
... |
from pathlib import Path
import pandas as pd
path = Path("src/samples.xlsx")
xls = pd.ExcelFile(path)
print(xls.sheet_names)
df = xls.parse(xls.sheet_names[0])
print(df.head())
|
import typing
import re
import random
import jk_json
import jk_utils
from .re import compactVerboseRegEx
def _isType(x) -> bool:
return type is type(x)
#
_compileSingleType = None
class AbstractGenerator(object):
#
# @param list _xParentalRequiredList The JSON list that holds the names of those... |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2019 Rapptz
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 u... |
# coding=utf-8
# Copyright 2019 The Google Research 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 applicab... |
"""Images Serializers."""
# OS
import os
# Django
from django.core.files import File
# Django REST Framework
from rest_framework import serializers
# Model
from .models import (
OriginalImage,
EnhancementImage,
)
# Scikit Image
from skimage import (
color,
io,
exposure,
)
import numpy as np
... |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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... |
# flake8: noqa
# pylint: disable
from __future__ import annotations
import dataclasses
import io
import pprint
import sys
from enum import Enum
from typing import Any, BinaryIO, Dict, List, Tuple, Type, Callable, Optional, Iterator
from blspy import G1Element, G2Element, PrivateKey
from ssdcoin.types.blockchain_form... |
import sys
import socket
import argparse
import threading
from queue import Queue
from datetime import datetime
from multiprocessing import cpu_count
DEFAULT_THREAD = 2 * cpu_count()
DEFAULT_TIMEOUT = 0.05
DEFAULT_RETRIES = 4
PRINT_LOCK = threading.Lock()
TCP_SCAN_METHOD = {
"DONTFRAG": (socket.IPV6_D... |
# Copyright 2012-2017 The Meson development team
# 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... |
import demistomock as demisto
from CommonServerPython import *
import traceback
import base64
import urllib3
# Disable insecure warnings
urllib3.disable_warnings()
ERROR_CODES_TO_SKIP = [
404
]
'''CLIENT CLASS'''
def build_body_request_for_update_user(old_user_data, new_user_data):
operations = []
for ... |
#!/usr/bin/env python
# Copyright 2019 Calico 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agr... |
from task1.LinkedList import LinkedList
def climbStairs(n):
if n == 1:
return 1
if n == 2:
return 2
return climbStairs(n - 1) + climbStairs(n - 2)
def climbStairs_v2(n):
stairs = LinkedList(size=n)
stairs[0] = 1
stairs[1] = 2
for i in range(2, n):
stairs[i] = sta... |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//td/span[@class='name']",
'price' : "//div[@class='productInfo fr']/table//td/span[@class='price']",
'category' : "//div[@class='... |
from . import exceptions, collection, utility
class JSONCodec(object):
media_types = ['application/json']
def decode(self, bytestring, **options):
def convert(data):
if isinstance(data, dict):
data = collection.RecursiveCollection(data)
elif isinstance(data,... |
import json
from collections import OrderedDict
from starlette.testclient import TestClient
from src.fastapi_quickcrud.crud_router import crud_router_builder
from src.fastapi_quickcrud.misc.type import CrudMethods
from tests.test_implementations.test_sqlalchemy_table.api_test import get_transaction_session, app, Unti... |
# Copyright (c) 2020 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... |
from graphene_file_upload.django import FileUploadGraphQLView
class SentryGraphQLView(FileUploadGraphQLView):
"""
Sets the Sentry transaction name to be that of the GraphQL operation.
This helps break down all the /graphql requests into more actionable
buckets within Sentry.
"""
def execute_g... |
from __future__ import annotations
from enum import Enum, EnumMeta
from typing import TYPE_CHECKING, Any, Iterable, Iterator, Pattern, TypeVar
import re
from .linereader import InputLocation
class TokenMeta(EnumMeta):
"""Metaclass for `TokenEnum`."""
if TYPE_CHECKING:
pattern: Pattern[str]
def... |
""" linmix -- A hierarchical Bayesian approach to linear regression with error in both X and Y.
"""
from __future__ import print_function
import numpy as np
def task_manager(conn):
chain = None
while True:
message = conn.recv()
if message['task'] == 'init':
chain = Chain(**messag... |
# Generated by Django 3.0.8 on 2020-07-22 22:03
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('letters', '0012_auto_20200626_0848'),
]
operations = [
migrations.AlterField(
model_name='letter',
... |
from collections import OrderedDict
import struct
import skywinder.communication.file_format_classes
import skywinder.communication.packet_classes
from skywinder.utils.struct_formats import format_description
import numpy as np
import logging
logger = logging.getLogger(__name__)
try:
import mdstat
except ImportE... |
"""Binary sensor platform for Home Assistant PyJU-Control."""
from homeassistant.components.binary_sensor import BinarySensorEntity
from .const import BINARY_SENSOR
from .const import BINARY_SENSOR_DEVICE_CLASS
from .const import DEFAULT_NAME
from .const import DOMAIN
from .entity import PyJuControlEntity
async def ... |
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. 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... |
#!/usr/bin/python
import yaml
campus='/apps/etds/apps/uc3-etds/config/campus.yml'
app='/apps/etds/apps/uc3-etds/config/app_config.yml'
with open(campus, 'r') as cmp_cfg:
campus_configs = yaml.load(cmp_cfg, Loader=yaml.FullLoader)
with open(app, 'r') as app_cfg:
app_configs = yaml.load(app_cfg, Loader=yaml.Full... |
from django import forms
from django.utils.safestring import mark_safe
from django.conf import settings
import json
class ImgerWidget(forms.Widget):
def __init__(self, attrs=None, **kwargs):
self.imger_settings = attrs['imger_settings']
super(ImgerWidget, self).__init__(**kwargs)
class Media... |
"""Module for graph traversal methods."""
from __future__ import absolute_import
from ._ffi.function import _init_api
from . import backend as F
from . import utils
from .heterograph import DGLHeteroGraph
__all__ = ['bfs_nodes_generator', 'bfs_edges_generator',
'topological_nodes_generator',
'df... |
#!/usr/bin/env
# -*- coding: utf-8 -*-
# Copyright (C) Victor M. Mendiola Lau - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by Victor M. Mendiola Lau <ryuzakyl@gmail.com>, February 2017
import pylab
from datasets.nir_sugarcane ... |
# coding: utf-8
"""
Aeternity Epoch
This is the [Aeternity](https://www.aeternity.com/) Epoch API. # noqa: E501
OpenAPI spec version: 0.7.0
Contact: apiteam@aeternity.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import datetime
... |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, print_function, unicode_literals, \
absolute_import
import os
import unittest
from pymatgen.core import Molecule
__author__ = 'Kiran Mathew'
__email__ = 'kmathew@lbl.gov'... |
# -*- coding: utf-8 -*-
import os
import sqlite3
from collections import namedtuple
from src.function.db.sqlite_abc import SqliteBasic
_author_ = 'luwt'
_date_ = '2021/11/12 16:56'
# item_name:打开的项目名称,在树结构中展示的名称,ext_info:一些其他信息,item_order:展示顺序,is_current:是否是当前项
# expanded:是否展开,parent_id:父id,level:在树结构中的级别,树结构:(0,1,2... |
from models.Pruneable import Pruneable
from models.networks.assisting_layers.ResNetLayers import resnet18
class ResNet18(Pruneable):
def __init__(self, device="cuda", output_dim=2, input_dim=(1, 1, 1), **kwargs):
super(ResNet18, self).__init__(device=device, output_dim=output_dim, input_dim=input_dim, **k... |
#! /usr/bin/env python
"""
scriptloris_sfspoof.py
A quick script to demonstrate how ScriptLoris could be used to spoof valid
downloads on SourceForge.net, in order to improve a project's ranking. Bonus
points for using TOR Switcher in conjunction with this script.
This script requires TOR to be setup and running on l... |
#! /usr/bin/env python3
import libcal, json
date = libcal.getDate(days_offset=3)
with open("settings.json") as json_file:
settings = json.load(json_file)
room = settings["roomId"]
startTime = settings["startTime"]
numSlots = settings["numSlots"]
libcal.submitBooking(room,date,startTime,numSlots)... |
from rest_framework import serializers
from .models import Vegetable, Harvest, Transaction, Merchandise
class VegetableSerializer(serializers.ModelSerializer):
class Meta:
model = Vegetable
fields = '__all__'
class HarvestSerializer(serializers.ModelSerializer):
class Meta:
model = H... |
"""
Overriding TestCase for exam tool.
"""
import re
import unittest
import importlib
from examiner.exceptions import TestFuncNameError, TestClassNameError
import examiner.helper_functions as hf
class ExamTestCase(unittest.TestCase):
"""
Override methods to help customize outputs of testcases.
"""
ASS... |
#! /usr/bin/env python
import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist
pub = None
def clbk_laser(msg):
regions = {
'right': min(min(msg.ranges[0:143]), 10),
'fright': min(min(msg.ranges[144:287]), 10),
'front': min(min(msg.ranges[288:431]), 10),
... |
import io
import json
import logging
import os
import re
from contextlib import contextmanager
from textwrap import indent, wrap
from typing import Any, Dict, Iterator, List, Optional, Sequence, Union, cast
from .fastjsonschema_exceptions import JsonSchemaValueException
_logger = logging.getLogger(__name__)
_MESSAGE... |
# -*- coding: utf-8 -*-
"""
==================
MTH5
==================
MTH5 deals with reading and writing an MTH5 file, which are HDF5 files
developed for magnetotelluric (MT) data. The code is based on h5py and
therefor numpy. This is the simplest and we are not really dealing with
large tables of data to warrant ... |
import numpy as np
# from numpy_ringbuffer import RingBuffer
import librosa
import librosa.display
import matplotlib.pyplot as plt
import noisereduce as nr
from tensorflow.keras.models import model_from_json
from sklearn.preprocessing import LabelEncoder
import pyaudio
import wave # for save audio file
import datetime
... |
# ===============================================================================
# Copyright 2015 Jake Ross
#
# 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... |
def test_AUPRC():
from utils.AUPRC import ptsort, AUPRC
assert ptsort([0,1,2]) == 0
assert AUPRC([(0,0),(1,1)]) == 1.0 |
from i3pystatus import Status
# Hardcoded gruvbox palette
color0 = "#282828"
color1 = "#cc241d"
color2 = "#98971a"
color3 = "#d79921"
color4 = "#458588"
color5 = "#b16286"
color6 = "#689d6a"
color7 = "#a89984"
color8 = "#928374"
color9 = "#fb4934"
color10 = "#b8bb26"
color11 = "#fabd2f"
color12 = "#83a598"
color13 = "... |
import os
import dgl
import torch
import numpy as np
import torch.nn as nn
from model import PGNN
from sklearn.metrics import roc_auc_score
from utils import get_dataset, preselect_anchor
import warnings
warnings.filterwarnings('ignore')
def get_loss(p, data, out, loss_func, device, get_auc=True):
edge_mask = np.... |
"""Function Introspection
Functions are first class objects
They have attributes __doc__ __annotations__
We can attach our own attributes
"""
def my_func(a, b):
return a + b
'''
my_func.category = 'math
my_func.sub_category = 'arithmetic'
print((()))
'''
|
from load_data import Data
import numpy as np
import torch
import time
from collections import defaultdict
from model import *
from torch.optim.lr_scheduler import ExponentialLR
import argparse
from tqdm import tqdm
import os
from prettytable import PrettyTable
class Experiment:
def __init__(self, learning_r... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [ ]
setup_requirements = ['pytest-run... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Wrapper to train and test a video classification model."""
import argparse
import sys
import torch
import pyvideoai.utils.multiprocessing_helper as mpu
from pyvideoai.train_multiprocess import train
from experiment_util... |
# vim: set fileencoding=utf-8 :
from __future__ import absolute_import, print_function, unicode_literals
import itertools
import json
import pprint
import logbook
import mock
import pytest
from twisted.internet import defer
import stethoscope.api.devices
import stethoscope.api.factory
import stethoscope.plugins.sou... |
#!/usr/bin/env python2.7
# Copyright (c) 2015, Dataent Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import os
import dataent
dataent.connect(site=os.environ.get("site")) |
import struct
import socket
import threading
import queue
import logging
from enum import Enum, auto
logger = logging.getLogger(__name__)
class PortState(Enum):
OPEN = auto()
CLOSED = auto()
FILTERED = auto()
class TCPScanner:
def __init__(self, host, ports, timeout=5):
self.host = host
... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: mac_farsi.py
""" Python Character Mapping Codec mac_farsi generated from 'MAPPINGS/VENDORS/APPLE/FARSI.TXT' with gencodec.py.
"""
import codecs
cla... |
#!/usr/bin/env
# Copyright 2012-2014 the authors (see 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 requi... |
'''
Console interface to the overall segeval package.
.. moduleauthor:: Chris Fournier <chris.m.fournier@gmail.com>
'''
#===============================================================================
# Copyright (c) 2012, Chris Fournier
# All rights reserved.
#
# Redistribution and use in source and binary forms, wi... |
import torch
from torch import nn
from torch.nn.functional import fold, unfold
from . import norms, activations
from .norms import GlobLN, CumLN
from ..utils import has_arg
class SingleRNN(nn.Module):
""" Module for a RNN block.
Inspired from https://github.com/yluo42/TAC/blob/master/utility/models.py
L... |
import boto3
def get_rds_client(access_key, secret_key, region):
"""
Returns the client object for AWS RDS
Args:
access_key (str): AWS Access Key
secret_key (str): AWS Secret Key
region (str): AWS Region
Returns:
obj: AWS RDS Object
"""
return boto3.client(
... |
# -*- coding: utf-8 -*-
# pylint: disable= too-many-lines, redefined-builtin
# Copyright © 2017 Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
"""SFrame Data Iterator."""
fro... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: symbol.py
"""Non-terminal symbols of Python grammar (from "graminit.h")."""
single_input = 256
file_input = 257
eval_input = 258
decorator = 259
deco... |
# Generated by Django 2.2.10 on 2020-05-27 13:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tatl', '0004_tatlpermflex'),
]
operations = [
migrations.AlterField(
model_name='tatlpermflex',
name='extra_context... |
import discord
# Make sure we're using the correct version of Discord.py
if discord.__author__ != "Rapptz":
print("Error: Please use the rewrite version of Discord.py.")
print("Check the README for instructions.")
exit()
import requests, asyncio, platform
from discord.ext.commands import Bot
# End imports... |
# coding: utf-8
import os
import sys
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from common.multi_layer_net import MultiLayerNet
from common.optimizer import SGD
(x_train, t_train), (x_test, t_test) = load_mnist(norma... |
from typing import Union
from sqlalchemy.ext.declarative import DeclarativeMeta
import mongosql
from mongosql.util.inspect import pluck_kwargs_from
from ..exc import DisabledError
class MongoQuerySettingsHandler:
""" Settings keeper for MongoQuery
This is essentially a helper which will feed the correc... |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
import warnings
from copy import copy
from typing import Callable, List, Union
import numpy as np
from continuum.datasets import _ContinuumDataset
from continuum.scenarios import _BaseScenario
class ClassIncremental(_BaseScenario):
"""Continual Loader, generating datasets for the consecutive tasks.
Scenari... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
from __future__ import annotations
import typing
from vuakhter.base.base_log import BaseLog
from vuakhter.utils.types import TimestampRange
if typing.TYPE_CHECKING:
from vuakhter.base.access_log import AccessLog
from vuakhter.metrics.base import StatisticsMetrics
from vuakhter.utils.types import DateOrDat... |
import numpy as np
import matplotlib.pyplot as plt
import mlmc_eig_grad.models as models
def convergence_with_path(paths_, inner_samples, labels, filename):
if len(paths_) == 1:
colors = [0]
else:
colors = np.arange(len(paths_)) * 0.8 / (len(paths_) - 1)
plt.figure(figsize=(13, 10))
... |
# Training script for tiny-imagenet.
# Again, this script has a lot of bugs everywhere.
import argparse
import datetime
import json
import os
import shutil
import numpy as np
import torch
import torch.utils.data as data
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.d... |
config = dict()
config["env"] = "SERVER" # change this to "FULL" if you want to run full
# config["mode"] = "TEST" # change this to "FULL" if you want to run full
config["mode"] = "FULL" # change this to "FULL" if you want to run full
config["data_folders"] = ["data_train", "data_valid"]
# change this if you want to... |
import base64
import re
from abc import ABCMeta, abstractmethod
from cryptoconditions import TypeRegistry
from cryptoconditions.condition import Condition
from cryptoconditions.crypto import base64_remove_padding, base64_add_padding
from cryptoconditions.exceptions import ParsingError
from cryptoconditions.lib import W... |
#!/usr/bin/env python3
import acsuite
import os
import vapoursynth as vs
core = vs.core
ac = acsuite.AC()
path = r"../bdmv/KIXA_90892/BDMV/STREAM/00006.m2ts"
src = core.lsmas.LWLibavSource(path)
ac.eztrim(src, [(0, -24)], os.path.splitext(path)[0] + ".wav", "ep10pv.wav")
|
from tools import *
import torch
import numpy as np
import sys
charcnn = torch.load('/var/www/html/flaskapp/charcnn.pth')
charcnn.train(False)
def predict(name):
from torch.autograd import Variable
name = encode_input(name)
name = Variable(torch.from_numpy(name).float())
name = name.view(1,-1,max_na... |
import logging
import math
import tkinter as tk
from tkinter import ttk
from typing import TYPE_CHECKING
from core.gui import appconfig, validation
from core.gui.dialogs.dialog import Dialog
from core.gui.themes import FRAME_PAD, PADX, PADY, scale_fonts
from core.gui.validation import LARGEST_SCALE, SMALLEST_SCALE
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.