repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
bruceravel/xraylarch
lib/__init__.py
#!/usr/bin/env python """ Larch: a scientific data processing macro language based on python """ # import sys ## require that numpy be available right away!! import numpy major, minor = sys.version_info[0], sys.version_info[1] if major < 2 or (major == 2 and minor < 6): raise EnvironmentError('requires python ...
bruceravel/xraylarch
tests/utils.py
<gh_stars>0 #!/usr/bin/env python """ Basic unit testing utilities for larch """ import unittest import time import os import sys import numpy as np from tempfile import NamedTemporaryFile from larch import Interpreter, InputText def nullfunction(*args, **kwargs): pass class LarchSession(object): def __init...
bruceravel/xraylarch
plugins/xrmmap/xrf_netcdf.py
#!/usr/bin/python """ support for netcdf file output files containing MCA spectra from Epics Mapping Mode with XIA xMXAP electronics """ import numpy as np import time import sys import os try: import scipy.io.netcdf netcdf_open = scipy.io.netcdf.netcdf_file except ImportError: raise ImportError('cannot fi...
bruceravel/xraylarch
lib/version.py
#!/usr/bin/env python __date__ = '22-Nov-2016' __version__ = '0.9.31' import sys import numpy import scipy import matplotlib try: import wx wxversion = wx.__version__ except: wxversion = 'not available' def make_banner(extra=None): lines = ('=' * 72) fmt = """Larch %s (%s) <NAME>ville and Larc...
bruceravel/xraylarch
plugins/io/__init__.py
from .fileutils import (increment_filename, new_filename, new_dirname, fix_filename, fix_varname, pathOf, unixpath, winpath, nativepath, strip_quotes, get_timestamp) from .columnfile import read_ascii, write_ascii, write_group, iso8601_time from .xdi import read_xdi, XD...
bruceravel/xraylarch
plugins/wx/xrddisplay.py
#!/usr/bin/env python """ GUI Frame for XRD display """ import sys import os import time import copy from functools import partial from threading import Thread import socket from functools import partial import wx import wx.lib.mixins.inspection import wx.lib.scrolledpanel as scrolled try: from wx._core import P...
bruceravel/xraylarch
plugins/io/save_restore.py
<reponame>bruceravel/xraylarch import json import numpy as np import h5py from larch import Group, Parameter, isParameter from larch import ValidateLarchPlugin from larch.utils import fixName from larch_plugins.io import fix_varname class H5PySaveFile(object): def __init__(self, fname, _larch=None): self....
bruceravel/xraylarch
plugins/epics/xrf_detectors.py
import time import numpy as np from functools import partial try: import epics from epics.devices.mca import MultiXMAP from epics.devices.struck import Struck from epics.devices.xspress3 import Xspress3 from epics.wx import EpicsFunction, DelayedEpicsCallback HAS_EPICS = True except (NameError...
bruceravel/xraylarch
lib/utils/strutils.py
#!/usr/bin/env python """ utilities for larch """ from __future__ import print_function import re import sys if sys.version[0] == '3': maketrans = str.maketrans def bytes2str(s): if isinstance(s, str): return s elif isinstance(s, bytes): return s.decode(sys.stdout.encodi...
bruceravel/xraylarch
examples/io/mdaconverter.py
from mda import mda2ascii fname = 'SampleScan.mda' mda2ascii(fname)
bruceravel/xraylarch
plugins/xray/__init__.py
<gh_stars>0 # # from .chemparser import chemparse from .physical_constants import (R_ELECTRON_CM, AVOGADRO, BARN, PLANCK_HC, RAD2DEG) from .xraydb import xrayDB from .xraydb_plugin import (atomic_mass, atomic_number, atomic_symbol, atomic_density, ...
bruceravel/xraylarch
plugins/xafs/fluo.py
<reponame>bruceravel/xraylarch<filename>plugins/xafs/fluo.py import numpy as np from larch import ValidateLarchPlugin, Make_CallArgs, parse_group_args from larch_plugins.xray import xray_line, xray_edge, material_mu from larch_plugins.xafs import preedge, set_xafsGroup MODNAME = '_xafs' @ValidateLarchPlugin def fluo...
bruceravel/xraylarch
plugins/math/spline.py
<gh_stars>0 #!/usr/bin/env python """ Splines for fitting to data within Larch """ from scipy.interpolate import splrep, splev from larch import (Parameter, Group, isgroup, isParameter, ValidateLarchPlugin) @ValidateLarchPlugin def spline_rep(x, y, group=None, name='spl1', _larch=None): """cre...
bruceravel/xraylarch
plugins/xray/xraydb.py
#!/usr/bin/env python """ SQLAlchemy wrapping of x-ray database for data from Elam et al, Chantler et al, Waasmaier and Kirfel Main Class for full Database: xrayDB """ import os import time import json import six import numpy as np from scipy.interpolate import interp1d, splrep, splev, UnivariateSpline from sql...
bruceravel/xraylarch
plugins/wx/xrfdisplay_utils.py
#!/usr/bin/env python """ utilities for XRF display """ import copy from functools import partial import time import numpy as np import wx import wx.lib.colourselect as csel from wxutils import (SimpleText, FloatCtrl, Choice, Font, pack, Button, Check, HyperText, HLine, GridPanel, CEN, LEFT, RIG...
bruceravel/xraylarch
plugins/xafs/feffit.py
<gh_stars>0 #!/usr/bin/env python """ feffit sums Feff paths to match xafs data """ from collections import Iterable from copy import copy import numpy as np from numpy import array, arange, interp, pi, zeros, sqrt, concatenate from scipy.optimize import leastsq as scipy_leastsq from larch import (Group, Parameter...
yxieca/sonic-mgmt
ansible/roles/test/files/ptftests/fdb_test.py
import fdb import json import logging import subprocess from collections import defaultdict from ipaddress import ip_address, ip_network import ptf import ptf.packet as scapy import ptf.dataplane as dataplane from ptf import config from ptf.base_tests import BaseTest from ptf.testutils import * class FdbTest(BaseTe...
yxieca/sonic-mgmt
ansible/library/port_alias.py
#!/usr/bin/env python import re import os import traceback import subprocess from operator import itemgetter from itertools import groupby from collections import defaultdict DOCUMENTATION = ''' module: port_alias.py Ansible_version_added: 2.0.0.2 short_description: Find SONiC device port alias mapping if there is...
yxieca/sonic-mgmt
ansible/roles/test/files/acstests/lag_test.py
#----------------------------------- # A set of traffic-tests for checking LAGs functionality. #----------------------------------- import random import time import logging import ptf.packet as scapy import socket import ptf.dataplane as dataplane from ptf.testutils import * from ptf.mask import Mask import ipaddress...
yxieca/sonic-mgmt
ansible/roles/test/files/ptftests/fib.py
import re from ipaddress import ip_address, ip_network from lpm import LpmDict # These subnets are excluded from FIB test # reference: RFC 5735 Special Use IPv4 Addresses # RFC 5156 Special Use IPv6 Addresses EXCLUDE_IPV4_PREFIXES = [ '0.0.0.0/8', # "This" Network RFC 1122, Sectio...
yxieca/sonic-mgmt
ansible/library/switch_arptable.py
#!/usr/bin/python DOCUMENTATION = ''' --- module: switch_arptble version_added: "1.9" description: Ansible module retrieves arp table from SONiC switch Depends on /sbin/ip neigh output: arptable{ "v4":{ "10.10.1.3":{ "interface": "Ethernet68" "state": "ST...
yxieca/sonic-mgmt
ansible/roles/test/files/ptftests/dhcp_relay_test.py
<gh_stars>1-10 import ast import struct import ipaddress # Packet Test Framework imports import ptf import ptf.packet as scapy import ptf.testutils as testutils from ptf import config from ptf.base_tests import BaseTest from ptf.mask import Mask # Helper function to increment an IP address # ip_addr should be passed...
yxieca/sonic-mgmt
ansible/library/lag_facts.py
<gh_stars>0 #!/usr/bin/python import json from ansible.module_utils.basic import * DOCUMENTATION = ''' --- module: lag_facts Ansible_version_added: "2.0.0.2" Sonic_version: "2.0" short_description: Retrieve lag(LACP) information from a device description: - Retrieved facts will be inserted to: lag_facts:...
ruijieren98/SegmenTron
segmentron/utils/filesystem.py
<reponame>ruijieren98/SegmenTron """Filesystem utility functions.""" from __future__ import absolute_import import os import errno import torch import logging from ..config import cfg def save_checkpoint(model, epoch, optimizer=None, lr_scheduler=None, is_best=False): """Save Checkpoint""" directory = os.path...
ruijieren98/SegmenTron
test_mosaic/mosaic.py
from json import load import sys import os import random import numpy as np from torch.utils.data import Dataset import torch import torch.nn.functional as F import cv2 from path import Path from matplotlib import pyplot as plt def load_mosaic(index): """loads images in a mosaic Refer: https://github....
hilotter/dynamic-rendering-lambda-edge
doc/diagram.py
<filename>doc/diagram.py from diagrams import Cluster, Diagram, Edge from diagrams.aws.network import Cloudfront from diagrams.aws.storage import S3 from diagrams.onprem.client import Users, User from diagrams.aws.compute import Lambda from diagrams.aws.network import APIGateway from diagrams.onprem.compute import Serv...
hyattdrew11/Built-Budget-API
migrations/versions/bd4bdf990c64_initilize_base_schema.py
"""Initilize Base Schema Revision ID: bd4bdf990c64 Revises: Create Date: 2021-04-07 20:25:43.879239 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto gen...
hyattdrew11/Built-Budget-API
migrations/versions/1087a77c7911_budget_item_amount_integer_to_float.py
<filename>migrations/versions/1087a77c7911_budget_item_amount_integer_to_float.py """Budget Item Amount Integer to Float Revision ID: 1087a77c7911 Revises: <KEY> Create Date: 2021-04-08 09:25:12.631298 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, us...
hyattdrew11/Built-Budget-API
unit_tests/run_test.py
<gh_stars>0 #! TEST REST ENDPOINTS import pytest import requests api_base_url = 'http://localhost:5000' # test create and delete a customer def create_delete_customer(customer): post = requests.post(api_base_url + '/customer/details', json=customer) res_json = post.json() new_customer_id = str(res_json['data'...
hyattdrew11/Built-Budget-API
migrations/versions/cabbf5779d8b_customer_reference_email_field.py
<reponame>hyattdrew11/Built-Budget-API """Customer Reference - Email Field Revision ID: <KEY> Revises: <PASSWORD> Create Date: 2021-04-07 20:28:20.039074 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '<PASSWORD>' branch_labels = None d...
hyattdrew11/Built-Budget-API
config.py
<filename>config.py<gh_stars>0 #! import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config(object): SECRET_KEY = 'myprecious' # SQLALCHEMY_DATABASE_URI = 'mysql://root:''@localhost/builtapi' SQLALCHEMY_DATABASE_URI = 'mysql://drew:secret@db/builtapi' SQLALCHEMY_TRACK_MODIFICATIONS = F...
hyattdrew11/Built-Budget-API
app/models.py
from datetime import datetime from app import db, ma from marshmallow import Schema, fields, validate import random SEED = False class Customer(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) email = db.Column(db.String(255)) class BudgetItem(db.Model): id ...
hyattdrew11/Built-Budget-API
app/routes.py
#! ''' ..%%%%...%%%%%%..%%%%%%..........%%%%%...%%..%%..%%%%%%..%%......%%%%%%. .%%......%%........%%............%%..%%..%%..%%....%%....%%........%%... .%%.%%%..%%%%......%%............%%%%%...%%..%%....%%....%%........%%... .%%..%%..%%........%%............%%..%%..%%..%%....%%....%%........%%... ..%%%%...%%%%%%....%%...
New2World/paper-proj
src/train.py
import os import numpy as np from sklearn import datasets import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader import seaborn as sb import matplotlib.pyplot as plt from model import GCN def get_knn_graph(data, k): n_sampl...
New2World/paper-proj
src/test.py
<reponame>New2World/paper-proj<gh_stars>0 import numpy as np import seaborn as sb import matplotlib import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager import torch from torch.utils.data import DataLoader, Dataset from model import OurModel # class DataSet(Dataset): # def __init__(self,...
New2World/paper-proj
src/model.py
<reponame>New2World/paper-proj import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class GraphConvolutionLayer(nn.Module): def __init__(self, in_features, out_features, adj_matrix): super(GraphConvolutionLayer, self).__init__() self.adj_matrix = nn.Parameter(adj_ma...
indigo13love/bufu
setup.py
<gh_stars>0 import setuptools with open('README.md', 'r') as fh: long_description = fh.read() setuptools.setup( name='bufu', version='0.0.4', author='indigo13love', author_email='<EMAIL>', description='Minimal file uploader CLI for Snowflake internal stage', long_description=long_descripti...
indigo13love/bufu
bufu/bufu.py
import fire import snowflake.connector import configparser import secrets import pathlib class Bufu(): def connect(self): cp = configparser.ConfigParser() path = pathlib.Path('~/.snowsql/config') cp.read(path.expanduser()) conn = snowflake.connector.connect( user = cp['c...
oiqbal95/RL-Self-Exploration-Mapping
scripts/robot_simulation.py
from scipy import spatial from skimage import io import numpy as np import numpy.ma as ma import time import sys from scipy import ndimage import matplotlib.pyplot as plt sys.path.append(sys.path[0] + '/..') from build.inverse_sensor_model import * from build.astar import * from random import shuffle import os class...
oiqbal95/RL-Self-Exploration-Mapping
scripts/tf_networks.py
import tensorflow as tf tf.compat.v1.disable_eager_execution() def weight_variable(shape): initial = tf.compat.v1.random.truncated_normal(shape, stddev=0.01) return tf.compat.v1.Variable(initial) def bias_variable(shape): initial = tf.compat.v1.constant(0.01, shape=shape) return tf.compat.v1.Variabl...
cpetrich/rawdatx
tests/test_runs.py
import unittest import rawdatx.read_TOA5 as read_raw_data import rawdatx.process_XML as process_XML import glob, sys, os, hashlib, zipfile try: import ConfigParser as configparser # Python 2 except ImportError: import configparser # Python 3 cfg=""" [RawData] raw_data_path = ./raw_data/ mask = ...
cpetrich/rawdatx
examples/simple_example/process.py
<reponame>cpetrich/rawdatx<gh_stars>1-10 import rawdatx.read_TOA5 as read_raw_data import rawdatx.process_XML as process_XML config = './config.cfg' read_raw_data.main(config) process_XML.main(config)
cpetrich/rawdatx
src/rawdatx/__init__.py
<gh_stars>1-10 __version__ = "0.1" __title__ = "rawdatx" __description__ = "Generate Excel files from logger data files" __uri__ = "https://github.com/cpetrich/rawdatx" __author__ = "<NAME>" __email__ = "<EMAIL>" __license__ = "MIT" __copyright__ = "Copyright (C) 2015 <NAME>"
cpetrich/rawdatx
src/rawdatx/_xml_parser.py
<reponame>cpetrich/rawdatx import xml.etree.ElementTree as _ET # does the attribute decomposition # This module is used ONLY as a fall-back if lxml is not installed. # required functionality: # DTD().validate(tree) # tree=parse() # element=tree.getroot() # element.attrib[<attribute-name>] # element.tag # ...
cpetrich/rawdatx
src/rawdatx/process_XML.py
<reponame>cpetrich/rawdatx #!/usr/bin/env python3 from __future__ import division # used for function evaluator import xlsxwriter import numpy as np import datetime, re import sys, os, copy is_python_3 = sys.version_info[0] == 3 if is_python_3: from io import StringIO import configparser xrange=range ...
cpetrich/rawdatx
src/rawdatx/read_TOA5.py
#!/usr/bin/env python3 import datetime import numpy as np try: import ConfigParser as configparser # Python 2 except ImportError: import configparser # Python 3 import sys, glob, os try: dummy = xrange(3) # Python 2 except NameError: xrange=range # Python 3 # 25 Dec 2018: allow for string data # 19 Dec 2015: remove u...
alekseynp/stylegan2-pytorch
processing/test_blur.py
<filename>processing/test_blur.py from PIL import Image import torch import torch.autograd as autograd from torchvision import transforms import numpy as np from processing.blur import GaussianBlur, RandomGaussianBlur img = Image.open('blur.png').convert('RGB') def show_blur(size, sig): gb = GaussianBlur(size,...
alekseynp/stylegan2-pytorch
processing/colour.py
# Colour because we're Canadian, damn it! import numpy as np import torch import torch.nn as nn import torch.autograd as autograd # From http://docs.opencv.org/2.4/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html class BrightnessContrast(nn.Module): def __init__(self, gain_min=0.67, gain_max...
alekseynp/stylegan2-pytorch
processing/mirror.py
import numpy as np import torch import torch.nn as nn import torch.autograd as autograd class RandomMirror(nn.Module): def __init__(self, mirror_prob): super(RandomMirror, self).__init__() self.mirror_prob = mirror_prob self.inv_idx = None def forward(self, x): input_size = x....
alekseynp/stylegan2-pytorch
processing/blur.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class RandomGaussianBlur(nn.Module): def __init__(self, prob_blur, size, sigma, n_channels=None): super(RandomGaussianBlur, self).__init__() self.prob_blur = prob_blur self.gaussian_blur = GaussianBlur(si...
alekseynp/stylegan2-pytorch
processing/random_do.py
import torch import torch.nn as nn class RandomDo(nn.Module): def __init__(self, prob_do, thing): super(RandomDo, self).__init__() self.prob_do = prob_do self.thing = thing def forward(self, x): batch_size = x.size()[0] mask = torch.rand(batch_size) < self.prob_do ...
nevermined-io/metadata-driver-filecoin
tests/integration/test_estuary.py
<reponame>nevermined-io/metadata-driver-filecoin # THIS FILE IMPLEMENTS AN INTEGRATION TEST USING A REMOTE ESTUARY GATEWAY import os import tempfile import pytest from metadata_driver_interface.exceptions import DriverError from metadata_driver_filecoin.data_plugin import Plugin plugin = Plugin() def test_upload_d...
nevermined-io/metadata-driver-filecoin
tests/test_plugin.py
from metadata_driver_filecoin.data_plugin import Plugin plugin = Plugin() def test_url_parser(): filecoin_url = plugin.parse_url('cid://USER_TOKEN:DEAL_ID@ESTUARY_GATEWAY/CID_HASH') assert filecoin_url.user_token == 'USER_TOKEN' assert filecoin_url.deal_id == 'DEAL_ID' assert filecoin_url.gateway_url...
nevermined-io/metadata-driver-filecoin
metadata_driver_filecoin/data_plugin.py
<filename>metadata_driver_filecoin/data_plugin.py import json import os import tempfile import time import requests from metadata_driver_interface.data_plugin import AbstractPlugin from metadata_driver_interface.exceptions import DriverError from requests import HTTPError from requests_toolbelt.multipart import encode...
nevermined-io/metadata-driver-filecoin
setup.py
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.md') as readme_file: readme = readme_file.read() with open('HISTORY.md') as history_file: history = history_file.read() # Installed by pip install metadata-driver-...
mckev/pyweb
pyweb/util.py
<filename>pyweb/util.py def get_int(val, default=None): assert default is None or type(default) is int try: return int(val) except ValueError: return default except TypeError: # When val is None, list, tuple, set, dict, etc. return default
mckev/pyweb
controller/errors/404.py
<filename>controller/errors/404.py import pyweb class WebController(pyweb.Controller): def index(self, environ, start_response): registry = self.registry response = registry.response # Response response.set_status('404 Not Found') response.set_header('Content-Type', 'text/p...
mckev/pyweb
pyweb/library/config.py
<filename>pyweb/library/config.py import configparser class Config: """ Read configuration file """ def __init__(self, filename): self._config = configparser.ConfigParser() self._config.read(filename) def get(self, key, section='general'): # Notes on https://docs.python.org/3/lib...
mckev/pyweb
pyweb/engine/controller.py
<gh_stars>0 class Controller: """ Base class for all controllers """ def __init__(self, registry): self.registry = registry
mckev/pyweb
controller/q/tests/db_concurrent01.py
<filename>controller/q/tests/db_concurrent01.py import pyweb class WebController(pyweb.Controller): def index(self, environ, start_response): # How to test: # - Open 3 browser windows: # http://192.168.10.163:9090/q/tests/db_concurrent01 # http://192.168.10.163:9...
mckev/pyweb
controller/q/tests/session.py
<reponame>mckev/pyweb import pyweb import re class WebController(pyweb.Controller): def test_page_one(self): # Required behaviours: # - Browser (client) doesn't send sessid cookie. # - Server tells browser (client) to set a new sessid cookie. It always gives a unique session id. ...
mckev/pyweb
model/user.py
<reponame>mckev/pyweb import pyweb class User(pyweb.Model): def get_attributes(self, user_id): registry = self.registry result = {'name': '<NAME>', 'address': 'Pune, India'} return result
mckev/pyweb
pyweb/engine/routing.py
import importlib import os import re class Routing: """ URL Dispatch mechanism Every .py files in "controller" directory and its sub-directory is accessible and can be called directly by client. Note that only one routing object exists for all client connections! """ def __init__(self): ...
mckev/pyweb
pyweb/library/db.py
<reponame>mckev/pyweb<gh_stars>0 import psycopg2 import psycopg2.extensions import psycopg2.extras import time class DB: """ Database connection """ def __init__(self, log): self._log = log self._error_code = None self._error_desc = None def connect(self, database, user, password...
mckev/pyweb
controller/q/tests/url.py
<filename>controller/q/tests/url.py import pyweb class WebController(pyweb.Controller): def index(self, environ, start_response): registry = self.registry response = registry.response # Extended URL # Example: # http://192.168.10.163:9090/q/tests/url/johny?q=abc # ...
mckev/pyweb
pyweb/library/response.py
import html import http.cookies import time class Response: """ Handle HTTP output """ def __init__(self): # Ref: http://legacy.python.org/dev/peps/pep-3333/ # HTTP status code: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes self._status = '200 OK' self._headers = {} ...
mckev/pyweb
test.py
#!/usr/bin/python3 import json import model.user import os import pyweb import pyweb.util import re # Util tests def test_util(): assert pyweb.util.get_int(3) == 3 assert pyweb.util.get_int(3, -1) == 3 assert pyweb.util.get_int(3.99, -1) == 3 assert pyweb.util.get_int([3], -1) == -1 assert pyweb....
mckev/pyweb
pyweb/library/cache.py
import json import redis class Cache: """ Cache mechanism that is able to store a value for a particular key for a given period of time """ def __init__(self, host, port=6379): self._redis = redis.Redis(host=host, port=port) def set(self, key, value, ttl): """ Set the value of a ...
mckev/pyweb
start.py
<reponame>mckev/pyweb import psycopg2.pool import pyweb log = pyweb.Log() log.log('Starting up WSGI application...', log.INFO) # Controller routing = pyweb.Routing() # View view = pyweb.View() # Database Pool # Ref: http://www.slideshare.net/petereisentraut/programming-with-python-and-postgresql page 62 # Note: max...
mckev/pyweb
pyweb/library/log.py
<gh_stars>0 import logging import traceback class Log: """ Log events """ # Error level DEBUG = logging.DEBUG INFO = logging.INFO WARNING = logging.WARNING ERROR = logging.ERROR CRITICAL = logging.CRITICAL def __init__(self, filename=None): self._logger = logging.getLogger('m...
mckev/pyweb
pyweb/library/session.py
import hashlib import os import string import time class Session: """ Manage user session """ # Tips: # - Protecting cookie should be taken as the same priority as protecting password. # Knowing a user's cookie would make you able to log in as that user. # - Do not pass session id thro...
mckev/pyweb
pyweb/__init__.py
from pyweb.engine.controller import Controller from pyweb.engine.model import Model from pyweb.engine.registry import Registry from pyweb.engine.routing import Routing from pyweb.engine.view import View from pyweb.library.cache import Cache from pyweb.library.config import Config from pyweb.library.db import DB from py...
mckev/pyweb
controller/q/tests/sleep01.py
import pyweb import time class WebController(pyweb.Controller): def index(self, environ, start_response): # How to test: # - Open 3 browser windows: # http://192.168.10.163:9090/q/tests/sleep01 # http://192.168.10.163:9090/q/tests/sleep02 # http:/...
mckev/pyweb
pyweb/engine/view.py
<gh_stars>0 import contextlib import io import os import re class View: """ Class to generate dynamic view We are using PHP-style <?py ... ?> to insert Python codes in between HTML. Note that this object lives for a long time because it stores the view templates that have been compiled. """ d...
mckev/pyweb
pyweb/library/request.py
<reponame>mckev/pyweb import http.cookies import urllib.parse class Request: """ Handle HTTP input """ def __init__(self, environ): self._environ = environ def get_var(self, key): """ Return GET value as string :param key: the name of the get variable :return: the...
mckev/pyweb
pyweb/engine/registry.py
class Registry: """ Global variables accessible by all model and controllers """ def __init__(self): pass
mckev/pyweb
pyweb/engine/model.py
<gh_stars>0 class Model: """ Base class for all models """ def __init__(self, registry): self.registry = registry
ccubed/Shosetsu
Shosetsu/errors.py
<gh_stars>1-10 class Error(Exception): pass class VNDBOneResult(Error): """ This exception is raised when we search for an item but only get on result so VNDB passes us directly to that content. Attributes: expression - The input name that returned only one result vnid - The ID...
ccubed/Shosetsu
unitTests.py
<filename>unitTests.py<gh_stars>1-10 import unittest import asyncio import random from Shosetsu import Shosetsu, errors class ShosetsuTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.loop = asyncio.get_event_loop() cls.setsu = Shosetsu() # Search for proper responses from p...
ccubed/Shosetsu
Shosetsu/__init__.py
from .VNDB import *
ccubed/Shosetsu
Shosetsu/Parsing.py
from bs4 import NavigableString async def parse_vn_results(soup): """ Parse Visual Novel search pages. :param soup: The BS4 class object :return: A list of dictionaries containing a name and id. """ soup = soup.find_all('td', class_='tc1') vns = [] for item in soup[1:]: vns.ap...
ccubed/Shosetsu
setup.py
from setuptools import setup setup( name='Shosetsu', version='1.2.0', packages=['Shosetsu'], url='https://github.com/ccubed/Shosetsu', license='MIT', author='<NAME>', author_email='<EMAIL>', description='Python 3 Aiohttp VNDB Scraper', long_description='Shosetsu is a Python 3 Asynci...
ccubed/Shosetsu
Shosetsu/VNDB.py
<gh_stars>1-10 import aiohttp import asyncio from bs4 import BeautifulSoup from bs4 import NavigableString from .errors import * from .Parsing import * class Shosetsu: def __init__(self, loop=None): self.session = aiohttp.ClientSession() self.base_url = "https://vndb.org" self.headers = {"U...
cormacpayne/Oryx
tests/SampleApps/python/tweeter3/tweeter3/settings/development.py
from tweeter3.settings.base import * # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = <KEY>' # SECURITY WARNING: don't run with debug turned on in prod...
ImNimboss/uberduck
uberduck/classes.py
""" Copyright 2022-present ImNimboss 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 use, copy, modify, merge, publish, distribute, ...
ImNimboss/uberduck
setup.py
<gh_stars>1-10 from setuptools import setup with open('.github/README.md') as file: long_description = file.read() with open('uberduck/__init__.py') as file: lines = file.readlines() for line in lines: if line.startswith('__version__: str = '): version = line[20:-2] break setup( name...
ImNimboss/uberduck
uberduck/main.py
<filename>uberduck/main.py """ Copyright 2022-present ImNimboss 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 use, copy, modify, m...
ImNimboss/uberduck
uberduck/__init__.py
<reponame>ImNimboss/uberduck<filename>uberduck/__init__.py<gh_stars>1-10 """ A synchronous and asynchronous API wrapper for the [UberDuck](https://uberduck.ai) text-to-speech service with 100% coverage and top-notch utilities. Copyright 2022-present ImNimboss Permission is hereby granted, free of charge, to any perso...
HyperStandard/py-flask
links.py
<filename>links.py __author__ = 'nonex_000' class Link: """A simple link implementation""" def __init__(self, name, url, image=None): self._name = name self._url = url if image is None: self._image = "" else: self._image = image @property def n...
HyperStandard/py-flask
database.py
from __future__ import with_statement import datetime __author__ = 'nonex_000' import sqlite3 class DataBase: def __init__(self): DATABASE_NAME = "assets/databases/chats.db3" # self.connection = sqlite3.connect(DATABASE_NAME) self.connection = sqlite3.connect(':memory:') self....
HyperStandard/py-flask
api.py
<gh_stars>0 #from asyncio import Lock from flask import render_template __author__ = 'nonex_000' class PyFlaskApi: def GetData(data): return "got data" + data def get_data(data): return "data got " + data def get_user(user): return "user got " + user def get_page(page): ...
HyperStandard/py-flask
flaskapp.py
<gh_stars>0 import os from datetime import datetime from flask import Flask, render_template, send_from_directory, g, request import sqlite3 from api import PyFlaskApi from database import DataBase from links import Link from collections import OrderedDict app = Flask(__name__) ON_OPENSHIFT = False if 'OPENSHIFT_R...
Praveenpk-vpk/api-openapi-samples
validator.py
<gh_stars>10-100 #!/usr/bin/env python3 import collections import logging import sys from argparse import ArgumentParser from os import getcwd, path import jsonschema import yaml from colors import color from jsonschema.exceptions import RefResolutionError from openapi_spec_validator import openapi_v3_spec_validator f...
OSSystems/meta-updatehub-ti
conf/setup-environment.d/updatehub-ti.py
<filename>conf/setup-environment.d/updatehub-ti.py def __after_init_updatehub_ti(): PLATFORM_ROOT_DIR = os.environ['PLATFORM_ROOT_DIR'] append_layers([ os.path.join(PLATFORM_ROOT_DIR, 'sources', p) for p in [ 'meta-ti', 'meta-updatehub-ti', ...
smartcommunitylab/sco.mobilitycovid
batch/06_batch_compute_user_clusters-v5.py
import io import os import sys import time import azure.batch.batch_service_client as batch import azure.batch.batch_auth as batch_auth import azure.batch.models as batchmodels from datetime import datetime, timedelta, timezone from dotenv import load_dotenv load_dotenv() # # Batch credentials # BATCH_ACCOUNT_NAME ...
smartcommunitylab/sco.mobilitycovid
scripts/stop_user_clusters-v5.py
from __future__ import print_function from sklearn.cluster import DBSCAN import argparse import hashlib import os import time from datetime import date, datetime, timedelta from functools import reduce from math import degrees from concurrent.futures import ThreadPoolExecutor import concurrent.futures from azure.st...
jasondegraw/STADIC
export.py
<filename>export.py import os import shutil import subprocess import argparse import datetime # # Set up optional arguments # parser = argparse.ArgumentParser() parser.add_argument("--destination", default = '../stadic-export', help="directory to write exported files to") parser...
tarunkathuria1/p124
app.py
from flask import Flask,jsonify, request app = Flask(__name__) datas = [ { 'id': 1, 'contact': '9987644456', 'name': 'Raju', 'done': False }, { 'id': 2, 'contact': ' 9876543222', 'name': 'Rahul', 'done': False } ] @app.route("/") def h...
Rohith04MVK/Pokedex-website
stats.py
<filename>stats.py<gh_stars>1-10 import requests def get_stats(): r = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon}").json() # abilities abilities = r["abilities"] for ability in abilities: Ability = ability['ability']['name'] Hidden = ability['is_hidden'] Slot = ...
Rohith04MVK/Pokedex-website
app.py
<reponame>Rohith04MVK/Pokedex-website from flask import Flask, url_for, redirect from flask.templating import render_template from flask_wtf import FlaskForm from wtforms import StringField from wtforms.validators import InputRequired import requests def get_stats(): r = requests.get( f"https://pokeapi.co...