repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
EugeneSqr/carrierx-python | carrierx/resources/core/sms/messages.py | <reponame>EugeneSqr/carrierx-python
from carrierx.resources.base import ItemResource, ListResource
class Message(ItemResource):
wrapper = False
endpoint_path = 'sms/messages'
create_fields = (
'from_did',
'to_did',
'message',
'media_urls',
)
retrieve_fields = (
... |
EugeneSqr/carrierx-python | carrierx/resources/core/storage/containers.py | from operator import itemgetter
from carrierx.resources.base import ItemResource, ListResource
class Container(ItemResource):
endpoint_path = 'storage/containers'
create_fields = (
'name',
'partner_sid',
'unique',
'parent_container_sid',
'quota_count',
'quota_b... |
EugeneSqr/carrierx-python | carrierx/resources/mediator/bindings.py | <reponame>EugeneSqr/carrierx-python
from carrierx.resources.base import ItemResource, ListResource
class Binding(ItemResource):
wrapper = True
endpoint_path = 'bindings'
create_fields = (
'name',
'account_sid',
'origination_did',
'redirect_did',
'reuse',
'de... |
EugeneSqr/carrierx-python | carrierx/resources/core/sms/__init__.py | from carrierx.resources.core.sms.messages import Message, Messages
|
EugeneSqr/carrierx-python | carrierx/base/rest_client.py | class RestConnection:
def __init__(self, username='', password='', token='', base_url=''):
self.auth = (username, password)
self.auth_token = token
self.base_url = base_url
self.headers = {'Content-type': 'application/json'}
if token:
self.headers['Authorization'... |
EugeneSqr/carrierx-python | carrierx/resources/core/endpoints.py | <gh_stars>0
from operator import itemgetter
from carrierx.resources.base import ItemResource, ListResource
class Endpoint(ItemResource):
TYPE_SYSTEM_GATEWAY = 'system_gateway'
TYPE_THIRD_PARTY = 'third_party'
TYPE_CONFERENCE = 'conference'
TYPE_FLEXML = 'flexml'
TYPE_MEDIATOR = 'mediator'
en... |
neckbosov/ghgist | ghgist/commands.py | import json
from typing import Any, Dict, List
import requests
from ghgist import gist_utils
GITHUB_API = 'https://api.github.com'
class Commands(object):
"""Commands for manipulatins GitHub Gists."""
api_headers: Dict[str, str]
def __init__(self, headers: Dict[str, str]) -> None:
"""Initiali... |
neckbosov/ghgist | tests/conftest.py | <filename>tests/conftest.py
import json
import pytest
from ghgist import commands
@pytest.fixture
def cmd() -> commands.Commands:
"""Produce Commands object with correct api headers."""
try:
with open('.ghgist', 'r') as ghgist_file:
token = json.load(ghgist_file)['ghgist']['settings']['t... |
neckbosov/ghgist | tests/test_commands.py | <gh_stars>0
import os
from ghgist import commands
def test_create_one_and_delete(cmd: commands.Commands):
"""Simple scenario of usage."""
gist_id = cmd.gist_create('setup.cfg')
assert len(cmd.gist_list()) == 1
cmd.gist_delete(gist_id)
def test_empty(cmd: commands.Commands):
"""Get zero gists.""... |
neckbosov/ghgist | ghgist/cli.py | <filename>ghgist/cli.py<gh_stars>0
import argparse
import json
from ghgist import commands
def create_parser() -> argparse.ArgumentParser: # noqa: 210
parser = argparse.ArgumentParser(prog='ghgist')
subparsers = parser.add_subparsers(title='Actions', dest='command')
subparsers.required = True
parse... |
neckbosov/ghgist | ghgist/gist_utils.py | <filename>ghgist/gist_utils.py
from typing import Any, Dict
def format_gist(num: int, gist: Dict[str, Any]) -> str: # type: ignore
"""Create well-formatted string representation of GitHub Gist.
>>> format_gist(0, {'id': 1,'files':{'kek':''},'url':'https://github.com'})
'1. <1> kek: https://github.com'
... |
jayvdb/scipy | scipy/_lib/deprecation.py | import functools
import warnings
__all__ = ["_deprecated"]
def _deprecated(msg, stacklevel=2):
"""Deprecate a function by emitting a warning on use."""
def wrap(fun):
@functools.wraps(fun)
def call(*args, **kwargs):
warnings.warn(msg, category=DeprecationWarning,
... |
jayvdb/scipy | scipy/signal/tests/test_peak_finding.py | from __future__ import division, print_function, absolute_import
import copy
import numpy as np
from numpy.testing import (
assert_,
assert_equal,
assert_allclose,
assert_array_equal
)
import pytest
from pytest import raises, warns
from scipy._lib.six import xrange
from scipy.signal._peak_finding imp... |
likun97/Low_quality_classification_with_mobilenetv3 | py_train/pth2onnx/mv3_large_test_1img.py | <filename>py_train/pth2onnx/mv3_large_test_1img.py
'''PyTorch CUB-200-2011 Training with VGG16 (TRAINED FROM SCRATCH).'''
from __future__ import print_function
import os
# import nni
import time
import torch
import logging
import argparse
import torchvision
import random
from PIL import Image
import torch.nn as nn
impo... |
likun97/Low_quality_classification_with_mobilenetv3 | py_train/pth2onnx/torch2onnx.py | # import sys
# import os
# sys.path.append(os.path.abspath(os.path.join(os.getcwd(), ".")))
# import onnx
import torch
# from mv3_resnet50_large_2 import mobilenetv3
# ############################
# model = mobilenetv3().cuda()
# checkpoint = torch.load("/search/odin/likun/zyresnet/A_onnx/model_large_2_transf... |
likun97/Low_quality_classification_with_mobilenetv3 | py_train/mv3_large_test.py | '''PyTorch CUB-200-2011 Training with VGG16 (TRAINED FROM SCRATCH).'''
from __future__ import print_function
import os
# import nni
import time
import torch
import logging
import argparse
import torchvision
import random
from PIL import Image
import torch.nn as nn
import numpy as np
import torch.optim as optim
import t... |
likun97/Low_quality_classification_with_mobilenetv3 | py_train/dataset.py | import json
import torch.utils.data as Data
import os
from PIL import Image
import random
import numpy as np
import torch
from torchvision.transforms import transforms
# from utils import load_images
# from utils import data_augmentation
# import glob
from PIL import ImageFilter
def read_json(json_path):
with ope... |
likun97/Low_quality_classification_with_mobilenetv3 | py_train/focalloss_related.py |
# https://github.com/yxdr/pytorch-multi-class-focal-loss/blob/master/FocalLoss.py
import torch
class FocalLoss:
def __init__(self, alpha_t=None, gamma=0):
"""
: alpha_t: A list of weights for each class
: gamma:
"""
self.alpha_t = torch.tensor(alpha_t) if alpha_t else None... |
likun97/Low_quality_classification_with_mobilenetv3 | py_train/my_pooling.py | <reponame>likun97/Low_quality_classification_with_mobilenetv3
import torch
import numpy as np
import random
from torch.autograd import Variable
from torch.nn.modules.module import Module
from torch.nn.modules.utils import _single, _pair, _triple
import torch.nn.functional as F
from torch.nn.parameter import Parameter
... |
likun97/Low_quality_classification_with_mobilenetv3 | py_train/pth2onnx/torch2onnx_test.py |
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), ".")))
import onnx
import torch
from mv3_resnet50_large_2 import mobilenetv3, MobileNetV3
import cv2
import onnxruntime
import numpy as np
session = onnxruntime.InferenceSession("./model_large_2_v2_softmax_dim1_V2_dropout2_300.onnx") #... |
fuellbie/aws-config-rules | python/EC2_INFRASTRUCTURE_TAG_MATCHING/EC2_INFRASTRUCTURE_TAG_MATCHING_test.py | <reponame>fuellbie/aws-config-rules<filename>python/EC2_INFRASTRUCTURE_TAG_MATCHING/EC2_INFRASTRUCTURE_TAG_MATCHING_test.py
# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may
# not use this file except in compliance ... |
acidbubbles/MeshSync | Editor/DCCInstallScripts/InstallBlenderPlugin_2.79.py | import bpy
bpy.ops.wm.addon_install(overwrite=True, filepath="{0}")
bpy.ops.wm.addon_enable(module='unity_mesh_sync')
bpy.ops.wm.save_userpref()
|
acidbubbles/MeshSync | Editor/DCCInstallScripts/UninstallBlenderPlugin_2.79.py | import bpy
bpy.ops.wm.addon_remove(module='unity_mesh_sync')
bpy.ops.wm.save_userpref()
|
HighMileage/lacrm | tests/test_api.py | <reponame>HighMileage/lacrm<gh_stars>1-10
" Tests for api.py "
import re
import pytest
from lacrm.api import Lacrm
import responses
try:
# Python 2.6/2.7
import httplib as http
# from mock import Mock, patch
except ImportError:
# Python 3
import http.client as http
# from unittest.mock import Mo... |
HighMileage/lacrm | setup.py | <gh_stars>1-10
"lacrm package setup"
import os
from setuptools import setup
def read_version():
path = os.path.join(
os.path.abspath(os.path.dirname(__file__)),
'lacrm',
'_version.py'
)
with open(path) as f:
exec(f.read())
return locals()['__version__']
def downloa... |
HighMileage/lacrm | lacrm/utils.py | "Utilities classes for lacrm module"
class BaseLacrmError(Exception):
"""Base Lacrm API Exception"""
message = u'Unknown error occured. Response content: {content}.'
def __init__(self, content):
self.content = content
def __str__(self):
return self.message.format(content=self.conten... |
HighMileage/lacrm | lacrm/api.py | "Core classes and exceptions for lacrm"
from __future__ import print_function
import logging
import requests
import json
from lacrm.utils import LacrmArgumentError, BaseLacrmError
from os.path import expanduser
LOGGER = logging.getLogger(__name__)
class Lacrm(object):
"""Less Annoying CRM Instance
An insta... |
HighMileage/lacrm | lacrm/__init__.py | <gh_stars>1-10
"lacrm package"
from lacrm.api import Lacrm # noqa
|
TaymonB/django-cas-dev-server | setup.py | from setuptools import find_packages, setup
setup(
name='django-cas-dev-server',
version='0.1.2',
description='Extends the Django development server to include a local CAS server.',
url='https://github.com/TaymonB/django-cas-dev-server',
author='<NAME>',
author_email='<EMAIL>',
license='MIT... |
TaymonB/django-cas-dev-server | cas_dev_server/management/commands/casdevmanage.py | import subprocess
import sys
from optparse import OptionParser
from django.core.management import LaxOptionParser
from django.core.management.base import BaseCommand, CommandError
from cas_dev_server.management import subprocess_environment
class Command(BaseCommand):
option_list = BaseCommand.option_list[1:]
... |
TaymonB/django-cas-dev-server | cas_dev_server/management/commands/runserver.py | import os
import subprocess
import sys
from optparse import make_option
from django.apps import apps
from cas_dev_server.management import subprocess_environment
if apps.is_installed('django.contrib.staticfiles'):
from django.contrib.staticfiles.management.commands.runserver import Command as RunserverCommand
el... |
TaymonB/django-cas-dev-server | cas_dev_server/management/__init__.py | import base64
import hashlib
import os
from django.conf import settings
from django.utils.encoding import force_bytes
from django.utils.six.moves.urllib.parse import urlencode
import environ
DB_SCHEMES_BY_BACKEND = {backend: scheme for scheme, backend in sorted(environ.Env.DB_SCHEMES.items(), reverse=True)}
def db_u... |
TaymonB/django-cas-dev-server | cas_dev_server/internal/settings.py | <reponame>TaymonB/django-cas-dev-server
import environ
env = environ.Env()
SECRET_KEY = env('SECRET_KEY')
DEBUG = env('DEBUG', bool)
TEMPLATE_DEBUG = env('TEMPLATE_DEBUG', bool)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions'... |
manandey/metadata | bsmetadata/preprocessing_tools/html_parser/__init__.py | from typing import List, Optional
from bsmetadata.preprocessing_tools.html_parser.filters_and_cleaners import TextAndMetadataCleaner
from bsmetadata.preprocessing_tools.html_parser.objects import TagToRemoveWithContent
def get_clean_text_and_metadata(
html_str,
tags_to_remove_with_content: Optional[List[TagT... |
manandey/metadata | tests/test_entity_preprocessor.py | <reponame>manandey/metadata<filename>tests/test_entity_preprocessor.py
import unittest
from datasets import Dataset
from bsmetadata.preprocessing_utils import EntityPreprocessor
class TestEntityPreprocessor(unittest.TestCase):
def test_extract_entities(self):
my_dict = {
"text": [
... |
manandey/metadata | bsmetadata/preprocessing_tools/html_parser/filters_and_cleaners.py | <reponame>manandey/metadata
from typing import DefaultDict, List, Optional, Tuple
import htmlmin
from lxml import etree
from lxml.html import fromstring
from bsmetadata.preprocessing_tools.html_parser.objects import HtmlTag, Metadata, TagToRemove, TagToRemoveWithContent
from bsmetadata.preprocessing_tools.html_parser... |
zanachka/os-scrapy-kafka-pipeline | os_scrapy_kafka_pipeline/pipelines.py | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import logging
import time
from functools import partial
from typing import List, Optional, Tuple
from scrapy import signals... |
zanachka/os-scrapy-kafka-pipeline | os_scrapy_kafka_pipeline/__init__.py | from .pipelines import KafkaPipeline
from .producer import AutoProducer
__all__ = [
"AutoProducer",
"KafkaPipeline",
]
|
zanachka/os-scrapy-kafka-pipeline | os_scrapy_kafka_pipeline/utils.py | import logging
def loglevel(name):
return logging._nameToLevel[name.upper()]
def max_str(s, max_len=100):
if len(s) > max_len:
s = s[0:max_len] + " ..."
return s
|
zanachka/os-scrapy-kafka-pipeline | os_scrapy_kafka_pipeline/exporter.py | import base64
from itemadapter import ItemAdapter, is_item
from scrapy.exporters import PythonItemExporter
from scrapy.item import _BaseItem
from scrapy.utils.python import to_unicode
def pre_join(pre, key):
if pre is None:
return None
if pre == "":
return key
return f"{pre}.{key}"
clas... |
jmao44/QueueCheck | lambda/hourly_report.py | <gh_stars>0
import boto3
import time
import datetime
aws_access_key_id = '<KEY>'
aws_access_key = '<KEY>'
aws_region_name = 'us-east-1'
client = boto3.client('dynamodb', region_name=aws_region_name,
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_acces... |
jmao44/QueueCheck | lambda/realtime_status.py | <gh_stars>0
import boto3
import time
import datetime
aws_access_key_id = '<KEY>'
aws_access_key = '<KEY>'
aws_region_name = 'us-east-1'
client = boto3.client('dynamodb', region_name=aws_region_name,
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_acces... |
JakeMakesStuff/Steam.py | cogs/utils.py | <reponame>JakeMakesStuff/Steam.py
import aiohttp
import asyncio
import async_timeout
class Utils:
async def vanitytosteamid(vanityurl):
"""Convert a vanity url to SteamID64"""
session = aiohttp.ClientSession()
async with session.get("http://api.steampowered.com/ISteamUser/ResolveVanityUR... |
JakeMakesStuff/Steam.py | cogs/gameinfo.py | import discord
from discord.ext import commands
from .utils import Utils
import requests
import time
class GameInfo:
"""My custom cog that does stuff!"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def gameinfo(self, *, gamename):
"""Convert game name to ID"""
... |
JakeMakesStuff/Steam.py | cogs/userinfo.py | from discord.ext import commands
from .utils import Utils
import aiohttp
import asyncio
class Userinfo:
"""User Related Commands"""
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True)
async def ownedgames(self, ctx, *, user):
"""Get games owned by a user (use... |
JakeMakesStuff/Steam.py | cogs/dotainv.py | <filename>cogs/dotainv.py
import discord
from discord.ext import commands
from .utils import Utils
class Dota:
"""Dota Things"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def dotainv(self, vanityurl):
"""Get Players Inventory for Dota 2"""
if not vani... |
JakeMakesStuff/Steam.py | cogs/steammain.py | <filename>cogs/steammain.py
import discord
from discord.ext import commands
import aiohttp
from .utils import Utils
import requests
class Steammain:
"""My custom cog that does stuff!"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def userinfo(self, vanityurl):
""... |
JakeMakesStuff/Steam.py | main.py | from discord.ext import commands
import discord
import logging
import asyncio
import traceback
import sys
from config import Config
description = '''Steam.py Alpha v2.1'''
# Set logging level
logging.basicConfig(level=logging.ERROR)
# this specifies what extensions to load when the bot starts up
startup_extensions = ... |
99991/alpha-matting-dataset-generator-tool | main.py | <gh_stars>0
import cv2
import numpy as np
import random, time, sys, os
from PIL import Image
def save_image(path, image, make_directory=True):
assert(image.dtype in [np.uint8, np.float32, np.float64])
if image.dtype in [np.float32, np.float64]:
image = np.clip(image*255, 0, 255).astype(np.uint8)
... |
DaAnIV/Quasiperiodic | Butterfly.py | #!/usr/bin/env python3
"""A script to create the Kohomoto butterfly plot.
usage: Butterfly.py [-h] [-l LINEWIDTH] [--driver DRIVER] [-d DPI] [-s SAVE_EVERY] [-v V]
[--merge] [--merge-prefix MERGE_PREFIX] [--merge-per MERGE_PER] n
Plot the Kohomoto butterfly and save as a PNG
positional arguments... |
DaAnIV/Quasiperiodic | continued_fraction.py | <reponame>DaAnIV/Quasiperiodic
import numpy as np
from sympy import Rational
from mpmath import mp
class CR:
def __init__(self, number):
self.number = number
def get_seq(self, n):
seq = np.zeros(n, dtype=np.longlong)
number = self.number
for i in range(n):
a = mp.f... |
DaAnIV/Quasiperiodic | main.py | <gh_stars>0
import numpy as np
import sympy as sp
import matplotlib.pyplot as plt
def contfrac_to_frac(seq):
''' Convert the simple continued fraction in `seq`
into a fraction, num / den
'''
num, den = 1, 0
for u in reversed(seq):
num, den = den + num*u, num
return num, den
class... |
huseyinozdemir/used_css_javascript | main.py | #!/usr/bin/env python3
import sys
from urllib import request
from app.css_process import CssProcess
ERROR_NO_TARGET = 'python main.py http://abc.com/page.html http://abc.com'
# debug 1
DEBUG = 0
def set_out(input_list):
result = ''
for il in input_list:
result += il
return result
if __name__ ... |
huseyinozdemir/used_css_javascript | app/css_process.py | <filename>app/css_process.py
import re
from functools import reduce
RE_ELEMENT = '<([a-zA-Z]+)'
RE_ELEMENT = re.compile(RE_ELEMENT, re.DOTALL)
RE_CLASS = 'class="(.*?)"'
RE_CLASS = re.compile(RE_CLASS, re.DOTALL)
RE_ID = 'id="(.*?)"'
RE_ID = re.compile(RE_ID, re.DOTALL)
RE_CSS_FILE = r'href="(.*?\.css).*?"'
RE_CSS_FI... |
billogram/tool-dump-dynamodb-to-s3 | dump.py | #!/usr/bin/env python3
import ctypes
import io
from queue import Empty
from datetime import datetime
from os import cpu_count, path
import sys
import json
import logging
from multiprocessing import Process, Queue, Value
from typing import Callable
import boto3
KB = 1024
MB = KB * KB
MEMORY_LIMIT = 500 * MB
def du... |
TheApacheCats/PyPDF2 | PyPDF2/filters.py | <filename>PyPDF2/filters.py
# vim: sw=4:expandtab:foldmethod=marker
#
# Copyright (c) 2006, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retai... |
Amarto/223 | convex_hull.py |
# cross product of vectors OA and OB.
# positive if ccw turn, negative if cw turn, 0 if collinear
def cross_product(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
# return (a1 - or_x) * (b1 - or_x) - (a2 - or_y) * (b2-or_y)
def convex_hull(points):
print points
... |
Amarto/223 | converter.py | <gh_stars>0
from PIL import Image
GRADATIONS = 15 # number of color bands to split image into
# print the size of the gradations arrays to make sure everything is working
def print_gradation_buckets(gradations_arr):
pixel_count = 0
for i in range(GRADATIONS):
print 'Bucket #' + str(i + 1) + ': ' + st... |
Amarto/223 | converter_tester.py | import converter
grad_buckets = converter.get_gradation_buckets('example.png')
converter.print_gradation_buckets(grad_buckets)
|
jesus-333/Dynamic-PyTorch-Net | Old file/DynamicNet_OLD.py | # -*- coding: utf-8 -*-
import torch
from torch import nn
from support_DynamicNet import getActivationList, getPoolingList, convOutputShape
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
class DynamicCNN(nn.Module):
def __init__(self, parameters, print_var = False, tracking_inpu... |
jesus-333/Dynamic-PyTorch-Net | Example/test 1_EEG NET.py | <reponame>jesus-333/Dynamic-PyTorch-Net
import numpy as np
import torch
from DynamicNet import DynamicCNN, convertArrayInTupleList
#%%
print_var = False
tracking_input_dimension = True
C = 32
T = 1024
F_1 = 8
D = 2
F_2 = 16
kernel_1 = (1, 64)
kernel_2 = (C, 1)
kernel_3 = (1, 16)
kernel_4 = (1, 1)
parameters = {... |
jesus-333/Dynamic-PyTorch-Net | DynamicNet.py | # -*- coding: utf-8 -*-
import torch
from torch import nn
import torch.onnx
from support_DynamicNet import getActivationList, getPoolingList, LinearCombinationForMatrix
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
from scipy.io import savemat, loadmat
import os
#%%
class DynamicCNN(nn... |
jesus-333/Dynamic-PyTorch-Net | Example 1_EEGNet.py | import numpy as np
import torch
from DynamicNet import DynamicCNN, convertArrayInTupleList
#%% Define the parameters
print_var = False
tracking_input_dimension = True
C = 32
T = 512
F_1 = 8
D = 2
F_2 = 16
kernel_1 = (1, 64)
kernel_2 = (C, 1)
kernel_3 = (1, 16)
kernel_4 = (1, 1)
parameters = {}
parameters["h"] ... |
jesus-333/Dynamic-PyTorch-Net | Example/test 2_sakhavi_CWCNN.py | # -*- coding: utf-8 -*-
"""
@author: <NAME> (Jesus)
@organization: University of Padua (Italy)
"""
#%% Add support function folder to path
import torch
from DynamicNet import DynamicCNN, convertArrayInTupleList
#%%
def getSubjectParameters(subject_number, activation_function = 0):
# print(subject_number)
i... |
jesus-333/Dynamic-PyTorch-Net | Example/test 4_random.py | import numpy as np
import torch
from DynamicNet import DynamicCNN, convertArrayInTupleList
import random
#%% SET 1
print_var = True
tracking_input_dimension = True
parameters = {}
parameters["h"] = random.randint(80, 100)
parameters["w"] = random.randint(80, 100)
parameters["layers_cnn"] = random.randint(1, 4)
... |
jesus-333/Dynamic-PyTorch-Net | Example/test 3_sakhavi_C2CM.py | # -*- coding: utf-8 -*-
"""
@author: <NAME> (Jesus)
@organization: University of Padua (Italy)
"""
#%% Add support function folder to path
import torch
from DynamicNet import DynamicCNN, convertArrayInTupleList
#%%
def getSubjectParameters(subject_number, activation_function = 0):
# print(subject_number)
i... |
jesus-333/Dynamic-PyTorch-Net | support_DynamicNet.py | <gh_stars>1-10
import torch
from torch import nn
import torch.utils.data as data
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Subset
import numpy as np
import math
import pickle
#%%
def getActivationList():
"""
Method that return a list with the activation function of pytorch
... |
nrgxtra/web_basics | django101/django101/urls.py |
from django.contrib import admin
from django.urls import path, include
from django101 import cities
from django101.cities.views import index, list_phones, test_index, create_person
urlpatterns = [
path('admin/', admin.site.urls),
path('test/', test_index),
path('create/', create_person, name='c... |
nrgxtra/web_basics | petstagram2/petstagram2/common/urls.py | from django.urls import path
from petstagram2.common.views import landing_page
urlpatterns = [
path('', landing_page, name='landing')
]
|
nrgxtra/web_basics | onlineLibrary/onlineLibrary/books_app/forms.py | from django import forms
from onlineLibrary.books_app.models import Book
class CreateBookForm(forms.ModelForm):
class Meta:
model = Book
fields = '__all__'
|
nrgxtra/web_basics | book/book/book_app/views.py | <reponame>nrgxtra/web_basics<filename>book/book/book_app/views.py
from django.shortcuts import render, redirect
# Create your views here.
from book.book_app.forms import BookForm
from book.book_app.models import Book
def show_books(request):
books = Book.objects.all()
context = {
'books': b... |
nrgxtra/web_basics | notes/notes/user_notes/apps.py | from django.apps import AppConfig
class UserNotesConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'notes.user_notes'
|
nrgxtra/web_basics | notes/notes/user_profile/views.py | <gh_stars>0
from django.shortcuts import render, redirect
from core.get_user_profile import get_profile
from notes.user_notes.models import Note
from notes.user_profile.forms import UserProfileForm
def show_home(request):
profile = get_profile()
if not profile:
if request.method == 'POST':
... |
nrgxtra/web_basics | onlineLibrary/onlineLibrary/user_app/urls.py | <reponame>nrgxtra/web_basics<gh_stars>0
from django.urls import path
from onlineLibrary.user_app.views import show_home, create_profile, show_profile, edit_profile, delete_profile
urlpatterns = [
path('', show_home, name='home'),
path('create_user', create_profile, name='create profile'),
path('pro... |
nrgxtra/web_basics | book/book/book_app/urls.py | <gh_stars>0
from django.urls import path
from book.book_app.views import show_books, create_book, edit_book
urlpatterns = [
path('', show_books, name='index'),
path('create/', create_book, name='create'),
path('edit/<int:pk>', edit_book, name='edit'),
] |
nrgxtra/web_basics | book/book/book_app/models.py | from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=20)
pages = models.IntegerField(
validators=(
MinValueVali... |
nrgxtra/web_basics | expenseTracker/expenseTracker/profiles/views.py | from django.shortcuts import render, redirect
from expenseTracker.core.profile_utils import get_profile
from expenseTracker.expenses.models import Expense
from expenseTracker.profiles.forms import ProfileForm
def profile_details(request):
profile = get_profile()
expenses = Expense.objects.all()
... |
nrgxtra/web_basics | todos/todos/todos_app/views.py | from django.shortcuts import render, redirect
# Create your views here.
from todos.todos_app.forms import TodoForm
from todos.todos_app.models import Todo
def show_todos(request):
todos = Todo.objects.all()
context = {
'todos': todos
}
return render(request, 'index.html', context)... |
nrgxtra/web_basics | lost_and_found/tests/objects_posts/validators/test_validate_max_value.py | from django.core.exceptions import ValidationError
from django.test import TestCase
from lost_and_found.objects_posts.validators import validate_max_value
class ValidateMaxValueTests(TestCase):
def test_WhenValueIsGreaterThanMax(self):
value = 5
validate_func = validate_max_value(value -... |
nrgxtra/web_basics | todos/todos/todos_app/admin.py | from django.contrib import admin
# Register your models here.
from todos.todos_app.models import Todo, Person, Category
class TodoAdmin(admin.ModelAdmin):
list_display = ['title', 'description', 'is_done', 'person_responsible',]
admin.site.register(Todo, TodoAdmin)
admin.site.register(Person)
admin... |
nrgxtra/web_basics | lost_and_found/lost_and_found/objects_posts/admin.py | <filename>lost_and_found/lost_and_found/objects_posts/admin.py<gh_stars>0
from django.contrib import admin
from lost_and_found.objects_posts.models import Post, Object
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
pass
@admin.register(Object)
class ObjectAdmin(admin.ModelAdmin):
pass... |
nrgxtra/web_basics | lost_and_found/lost_and_found/objects_posts/views.py | from django.shortcuts import render, redirect
from lost_and_found.objects_posts.models import Post
from lost_and_found.objects_posts.forms import PostCreateForm, ObjectForm, PostEditForm
def index(request):
context = {
'posts': Post.objects.all(),
}
return render(request, 'index.html'... |
nrgxtra/web_basics | notes/notes/user_notes/urls.py | from django.urls import path
from notes.user_notes.views import create_note, edit_note, delete_note, note_details
urlpatterns = [
path('add/', create_note, name='note create'),
path('edit/<int:pk>', edit_note, name='note edit'),
path('delete/<int:pk>', delete_note, name='note delete'),
path('d... |
nrgxtra/web_basics | expenseTracker/expenseTracker/urls.py | <filename>expenseTracker/expenseTracker/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('expenseTracker.expenses.urls')),
path('profile/', include('expenseTracker.profiles.urls')),
]
|
nrgxtra/web_basics | django101/django101/cities/urls.py | from django.urls import path
from django101.cities.views import index, list_phones, show_forms_demo
from django.views.generic import TemplateView
urlpatterns = [
path('', index),
path('phones/', list_phones),
path('phones2/', TemplateView.as_view(template_name='phones.html')),
path('forms/', sh... |
nrgxtra/web_basics | onlineLibrary/onlineLibrary/user_app/models.py | <filename>onlineLibrary/onlineLibrary/user_app/models.py
from django.db import models
class Profile(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
image_url = models.URLField()
|
nrgxtra/web_basics | todos/todos/todos_app/forms.py | <reponame>nrgxtra/web_basics
from django import forms
from todos.todos_app.models import Todo
class TodoForm(forms.ModelForm):
class Meta:
model = Todo
fields = '__all__'
|
nrgxtra/web_basics | onlineLibrary/onlineLibrary/user_app/views.py | <reponame>nrgxtra/web_basics
from django.shortcuts import render, redirect
from onlineLibrary.books_app.models import Book
from onlineLibrary.user_app.forms import UserForm, DeleteUser
from onlineLibrary.user_app.models import Profile
def show_home(request):
user = Profile.objects.first()
if not use... |
nrgxtra/web_basics | book/book/book_app/admin.py | from django.contrib import admin
# Register your models here.
from book.book_app.models import Book
class BookAdmin(admin.ModelAdmin):
list_display = ['title', 'pages', 'description', 'author']
admin.site.register(Book, BookAdmin)
|
nrgxtra/web_basics | lost_and_found/lost_and_found/objects_posts/migrations/0001_initial.py | # Generated by Django 3.0.4 on 2020-03-12 10:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Object',
f... |
nrgxtra/web_basics | onlineLibrary/onlineLibrary/books_app/views.py | <reponame>nrgxtra/web_basics
from django.shortcuts import render, redirect
from onlineLibrary.books_app.forms import CreateBookForm
from onlineLibrary.books_app.models import Book
from onlineLibrary.user_app.models import Profile
def add_book(request):
user = Profile.objects.first()
if request.metho... |
nrgxtra/web_basics | todos/todos/todos_app/models.py | from django.db import models
# Create your models here.
class Person(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return f'{self.id}: {self.name}'
class Meta:
verbose_name_plural = 'people'
class Category(models.Model):
name = models.CharF... |
nrgxtra/web_basics | lost_and_found/lost_and_found/objects_posts/models.py | from django.core.validators import MinValueValidator
from django.db import models
from lost_and_found.objects_posts.validators import validate_max_value
class Object(models.Model):
name = models.CharField(
max_length=10
)
image = models.URLField()
width = models.IntegerField(
... |
nrgxtra/web_basics | lost_and_found/lost_and_found/objects_posts/apps.py | <reponame>nrgxtra/web_basics
from django.apps import AppConfig
class LostAndFoundAppConfig(AppConfig):
name = 'lost_and_found.objects_posts'
|
nrgxtra/web_basics | lost_and_found/lost_and_found/objects_posts/validators.py | from django.core.exceptions import ValidationError
def validate_max_value(max_value):
def internal_validate(value):
if value > max_value:
raise ValidationError(f'{value} is greater than max {max_value}')
return internal_validate
|
nrgxtra/web_basics | petstagram/petstagram/pets/views.py | from django.shortcuts import render, redirect
from petstagram.common.forms import CommentForm
from petstagram.common.models import Comment
from petstagram.pets.forms import PetForm, EditPetForm
from petstagram.pets.models import Pet, Like
def list_pets(request):
all_pets = Pet.objects.all()
context... |
nrgxtra/web_basics | book/book/book_app/forms.py | from django import forms
from book.book_app.models import Book
class BootstrapFormMixin:
def _init_bootstrap(self):
for (_, field) in self.fields.items():
field.widget.attrs = {
'class': 'form-control',
}
class BookForm(forms.ModelForm, BootstrapForm... |
nrgxtra/web_basics | petstagram2/petstagram2/pets/admin.py | <filename>petstagram2/petstagram2/pets/admin.py
from django.contrib import admin
from petstagram2.pets.models import Pet
@admin.register(Pet)
class PetAdmin(admin.ModelAdmin):
list_display = ['name', 'type', 'age']
# admin.site.register(Pet, PetAdmin)
|
nrgxtra/web_basics | django101/django101/cities/views.py | <filename>django101/django101/cities/views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django101.cities.models import Person
def show_forms_demo(request):
return render(request, 'forms_demo.html')
def index(req):
context = {
'name': 'Kiril'... |
nrgxtra/web_basics | django101/django101/cities/admin.py | <gh_stars>0
from django.contrib import admin
from django101.cities.models import Person
admin.site.register(Person)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.