repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
lijun99/altar | models/cudalinear/cudalinear/cudaLinear.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
import altar.cuda
from altar.cuda import cublas
from altar.cuda import libcuda
from altar.cuda.models.cudaBayesian import cud... |
lijun99/altar | models/cdm/cdm/__init__.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# the package
import altar
# access to the CDM source
from .Source import Source as source
# and the layout of the input file
from .Data import Data as... |
lijun99/altar | cuda/cuda/bayesian/cudaMetropolisVaryingSteps.py | <filename>cuda/cuda/bayesian/cudaMetropolisVaryingSteps.py
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# externals
import math
# the package
import altar
import altar.cuda
from altar.cuda import c... |
lijun99/altar | altar/altar/data/DataL2.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
# my protocol
from .DataObs import DataObs as data
# declaration
class DataL2(altar.component, family="altar.data.datal2", i... |
lijun99/altar | models/cdm/tests/sanity.py | <filename>models/cdm/tests/sanity.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
def test():
# get the model
from altar.models import cdm
# and publish it
return cdm
# boo... |
lijun99/altar | cuda/cuda/models/__init__.py | <filename>cuda/cuda/models/__init__.py
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
import altar.cuda
# the base
from altar.models.Model import Model as model
from altar.... |
lijun99/altar | models/cdm/cdm/libcdm.py | <gh_stars>1-10
# -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2018-2021 jet propulsion laboratory
# (c) 2018-2021 california institute of technology
# all rights reserved
#
# United States Government Sponsorship acknowledged. Any commercial use must be negotiated with
# the Office of Technology T... |
lijun99/altar | cuda/cuda/norms/__init__.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
import altar.cuda
# publish the protocol for norms
from altar.norms.Norm import Norm as norm
# implementations
@altar.fo... |
lijun99/altar | altar/altar/actions/Forward.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
# Author(s): <NAME>
#
# get the package
import altar
# get my model package
import altar.models.seismic
# declaration
class Forward(altar.panel(), famil... |
lijun99/altar | altar/altar/models/__init__.py | <filename>altar/altar/models/__init__.py<gh_stars>1-10
# -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# the package
import altar
# the protocols
from .Model import Model as model
from .ParameterSe... |
lijun99/altar | altar/altar/shells/Application.py | <reponame>lijun99/altar
# -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# support
import altar
# the simple application shell
class Application(altar.application, family="altar.shells.application"):... |
lijun99/altar | altar/altar/bayesian/Recorder.py | <gh_stars>1-10
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>. aïvázis, <NAME>
# the package
import altar
# an implementation of the archiver protocol
class Recorder(
altar.componen... |
lijun99/altar | cuda/cuda/data/cudaDataL2.py | <gh_stars>1-10
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
import altar.cuda
from altar.cuda import libcuda
from altar.cuda import cublas as cublas
import numpy
# my p... |
lijun99/altar | altar/altar/bayesian/Controller.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# get the package
import altar
# the controller protocol
class Controller(altar.protocol, family="altar.controllers"):
"""
The protocol that a... |
lijun99/altar | cuda/cuda/__init__.py | <reponame>lijun99/altar<filename>cuda/cuda/__init__.py<gh_stars>1-10
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# export my parts
from . import (
# norms
norms,
# probability distribu... |
lijun99/altar | models/reverso/reverso/Source.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME>
#
# (c) 2018-2021 california institute of technology
# all rights reserved
#
#
# framework
import altar
# externals
import numpy
from math import sqrt, pi as π
# library
from .libreverso import Reverso
# declaration
class Source:
"""
The source response fo... |
lijun99/altar | cuda/cuda/ext/__init__.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# pull the extension module; this must exist, so let import errors bubble up
from . import cudaaltar as libcudaaltar
# end of file
|
lijun99/altar | altar/altar/bayesian/CUDAAnnealing.py | <reponame>lijun99/altar<filename>altar/altar/bayesian/CUDAAnnealing.py
# -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# superclass
from .AnnealingMethod import AnnealingMethod
import altar.cuda
# d... |
lijun99/altar | altar/altar/shells/AlTar.py | <gh_stars>1-10
# -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# support
import altar
# the plexus
class AlTar(altar.plexus, family="altar.shells.altar", namespace="altar"):
"""
The main act... |
lijun99/altar | altar/altar/bayesian/Solver.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
# <NAME>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# get the package
import altar
# the scheduler protocol
class Solver(altar.protocol, family="altar.bayesian.solvers"):
"""
The proto... |
lijun99/altar | models/seismic/seismic/Static.py | <reponame>lijun99/altar
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
# declaration
class Static(altar.models.bayesian, family="altar.models.seismic.static"):
"""
... |
lijun99/altar | altar/altar/data/__init__.py | <filename>altar/altar/data/__init__.py
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
# publish the protocol for norms
from .DataObs import DataObs as data
from .DataL2 ... |
lijun99/altar | models/cudalinear/examples/PInversion.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
#! /usr/bin/env python3
import numpy
import h5py
def PseudoInverse(gf_file, data_file):
"""
Use pseudo inverse to solve linear inversion proble... |
lijun99/altar | models/seismic/seismic/cuda/cudaKinematicG.py | <filename>models/seismic/seismic/cuda/cudaKinematicG.py
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
import altar.cuda
# my base
from altar.cuda.models.cudaBayesian impor... |
lijun99/altar | altar/altar/models/ParameterSet.py | <reponame>lijun99/altar
# -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# the package
import altar
# the parameter set protocol
class ParameterSet(altar.protocol, family="altar.models.parameterset"... |
lijun99/altar | models/seismic/seismic/Moment.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# get the package
import altar
# get the protocol
from altar.distributions import distribution
# and my base class
from altar.distributions.Uniform impor... |
lijun99/altar | models/seismic/seismic/cuda/cudaMoment.py | <gh_stars>1-10
# -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> (<EMAIL>)
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# get the package
import altar
import altar.cuda
# get the protocol
# and my base class
from altar.cuda.distributions.cudaUniform impor... |
lijun99/altar | models/seismic/examples/utils/checkDataPrediction.py | #!/usr/bin/env python3
# -*- python -*-
# -*- coding: utf-8 -*-
#
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
import h5py
import numpy
import sys
def checkDataDiff():
"""
Check the difference between data predictions and observat... |
lijun99/altar | cuda/cuda/distributions/cudaPreset.py | <reponame>lijun99/altar
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# get the package
import altar
import altar.cuda
# get the base
from .cudaDistribution import cudaDistribution
# the declaratio... |
lijun99/altar | altar/altar/models/Contiguous.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# the package
import altar
# the protocol
from .ParameterSet import ParameterSet as parameters
# component
class Contiguous(altar.component,
... |
lijun99/altar | models/reverso/reverso/libreverso.py | #!/usr/bin/env python3
# The Two-Reservoir Model
# This model assumes an elastic half-space and incompressible magma. The two magma
# reservoirs comprise a deep reservoir connected to a shallow reservoir by an
# hydraulic pipe ["A two-magma chamber model as a source of deformation at Grimvsvotn
# Volcano, Iceland by R... |
lijun99/altar | altar/altar/bayesian/MPIAnnealing.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# externals
import mpi
import journal
# the framework
import altar
# superclass
from .AnnealingMethod import AnnealingMethod
# declaration
class MPIA... |
lijun99/altar | altar/altar/simulations/Archiver.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# the package
import altar
# the archiver protocol
class Archiver(altar.protocol, family="altar.simulations.archivers"):
"""
The protocol that ... |
lijun99/altar | models/seismic/seismic/StaticCp.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
from .Static import Static
# declaration
class StaticCp(Static, family="altar.models.seismic.staticCp"):
"""
Linear M... |
lijun99/altar | altar/altar/norms/L2.py | # -*- python -*-
# -*- coding: utf-8 -*-
#
# <NAME> <<EMAIL>>
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# the package
import altar
# my protocol
from .Norm import Norm
# declaration
class L2(altar.component, family="altar.norms.l2", implements=Norm):
... |
lijun99/altar | models/seismic/seismic/cuda/cudaStaticCp.py | <gh_stars>1-10
# -*- python -*-
# -*- coding: utf-8 -*-
#
# (c) 2013-2021 parasim inc
# (c) 2010-2021 california institute of technology
# all rights reserved
#
# Author(s): <NAME>
# the package
import altar
import altar.cuda
from altar.cuda import cublas
from altar.cuda import libcuda
from .cudaStatic import cudaSta... |
IvanAgafonov/get-all-chat-members | bot.py | <reponame>IvanAgafonov/get-all-chat-members
# importing all required libraries
from boto.s3.connection import S3Connection
import os
from telethon.sync import TelegramClient
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.types import InputPeerUser, InputPeerChannel, ChannelParticipan... |
pogginicolo98/start2impact_python_project | main.py | # Start2Impact: Python project
# Cryptocurrency reporting system
import json
import os
from password import COINMARKETCAP_API_KEY
import requests
import time
class CoinmarketcapHandler:
""" Coinmarketcap APIs handler. Connect and fetch data from Coinmarketcap APIs """
def __init__(self):
self.url = ... |
maurcz/studying | discord-bot/using_bot.py | import os
import random
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
# interesting - with `Client` you get more flexibility, with `commands.Bot` you're
# bound to the well-known pattern of using prefixes.
# update - there's actually ... |
maurcz/studying | blockchain/blockchain.py | import hashlib
import json
from time import time
from urllib.parse import urlparse
import requests
class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
self.nodes = set() # nodes must be unique
# Genesis block
self.add_block(previo... |
maurcz/studying | blockchain/api.py | from uuid import uuid4
from flask import Flask, jsonify, request
from blockchain import Blockchain
app = Flask(__name__)
node_id = str(uuid4()).replace("-", "")
blockchain = Blockchain()
@app.route("/mine", methods=["GET"])
def mine():
last_block = blockchain.last_block
last_proof = last_block["proof"]
... |
maurcz/studying | discord-bot/using_client.py | <filename>discord-bot/using_client.py
import os
import random
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
# -------
# Example - Responding to events with subclasses
# class CustomClient(discord.Client):
# async def on_ready(... |
steveroch-rs/MCRcon | mcrcon.py | import argparse
import getpass
import os
import socket
import ssl
import select
import struct
import time
import platform
if platform.system() != "Windows":
import signal
class MCRconException(Exception):
pass
def timeout_handler(signum, frame):
raise MCRconException("Connection timeout error")
class... |
keystonetowersystems/fuzzyfloat | fuzzyfloat/types.py | from .meta import FuzzyFloatMeta
class rel_fp(metaclass=FuzzyFloatMeta):
pass
class abs_fp(metaclass=FuzzyFloatMeta, rel_tol=0.0, atol=1e-07):
pass
|
keystonetowersystems/fuzzyfloat | tests/test_fp_rel.py | import pytest
from fuzzyfloat import rel_fp
def expect_fp(value, expected):
assert type(value) == rel_fp
assert value == expected
def test_cmp_eq():
value = rel_fp(100.5)
assert value == 100.5
assert value == 100.5000001
assert value == 100.4999999
value = rel_fp(1e-20)
assert val... |
keystonetowersystems/fuzzyfloat | fuzzyfloat/meta.py | def eq_with_tolerances(ftype, rel_tol=1e-09, abs_tol=0.0):
def fp_eq(a, b):
return ftype.__le__(abs(a - b), max(rel_tol * max(abs(a), abs(b), 1), abs_tol))
return fp_eq
class FuzzyFloatMeta(type):
def __new__(metaclass, name, bases, clsdict, ftype=float, rel_tol=1e-09, atol=0.0):
bases =... |
keystonetowersystems/fuzzyfloat | setup.py | from setuptools import setup, find_packages
def readme():
with open('README.md') as f:
return f.read()
setup(
name='fuzzyfloat',
version='1.0.3',
description='Utility library that provides a floating point type with tolerance for equality comparisons',
long_description=readme(),
long_d... |
keystonetowersystems/fuzzyfloat | fuzzyfloat/__init__.py | """
"""
from .types import rel_fp, abs_fp
|
damm89/zgw-auth-backend | zgw_auth_backend/apps.py | <filename>zgw_auth_backend/apps.py
from django.apps import AppConfig, apps
class ZgwAuthBackendConfig(AppConfig):
name = "zgw_auth_backend"
def ready(self):
register_spectacular_extensions()
def register_spectacular_extensions():
if not apps.is_installed("drf_spectacular"):
return
... |
damm89/zgw-auth-backend | zgw_auth_backend/__init__.py | <reponame>damm89/zgw-auth-backend
default_app_config = "zgw_auth_backend.apps.ZgwAuthBackendConfig"
|
damm89/zgw-auth-backend | zgw_auth_backend/migrations/0001_initial.py | <reponame>damm89/zgw-auth-backend
# Generated by Django 2.2.13 on 2020-12-15 15:31
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="ApplicationCredentials",
fiel... |
damm89/zgw-auth-backend | zgw_auth_backend/admin.py | from django.contrib import admin
from .models import ApplicationCredentials
@admin.register(ApplicationCredentials)
class ApplicationCredentialsAdmin(admin.ModelAdmin):
list_display = ("client_id",)
search_fields = ("clien_id",)
|
damm89/zgw-auth-backend | zgw_auth_backend/models.py | <filename>zgw_auth_backend/models.py<gh_stars>0
from django.db import models
from django.utils.translation import gettext_lazy as _
class ApplicationCredentials(models.Model):
client_id = models.CharField(
_("client ID"),
max_length=50,
unique=True,
help_text=_(
"Client... |
damm89/zgw-auth-backend | zgw_auth_backend/contrib/drf_spectacular.py | <reponame>damm89/zgw-auth-backend
from drf_spectacular.extensions import OpenApiAuthenticationExtension
class ZGWAuthenticationScheme(OpenApiAuthenticationExtension):
target_class = "zgw_auth_backend.authentication.ZGWAuthentication"
name = "ZGWAuthentication"
def get_security_definition(self, auto_schem... |
damm89/zgw-auth-backend | tests/test_authentication.py | <reponame>damm89/zgw-auth-backend
from django.contrib.auth import get_user_model
from django.test import override_settings
from django.urls import path
from rest_framework import permissions, status
from rest_framework.response import Response
from rest_framework.test import APITestCase
from rest_framework.views impor... |
damm89/zgw-auth-backend | zgw_auth_backend/zgw.py | <reponame>damm89/zgw-auth-backend
import logging
from typing import Any, Dict, Optional
from django.utils.translation import gettext_lazy as _
import jwt
from rest_framework import exceptions
from .models import ApplicationCredentials
logger = logging.getLogger(__name__)
ALG = "HS256"
class ZGWAuth:
def __i... |
damm89/zgw-auth-backend | zgw_auth_backend/authentication.py | # Mostly taken from https://github.com/VNG-Realisatie/vng-api-common/blob/master/vng_api_common/middleware.py
#
# We can't use vng-api-common at the moment because of the hard pinned dependencies on
# DRF 3.10 and drf-yasg 1.16.0
import logging
from django.contrib.auth import get_user_model
from django.utils.translati... |
genaforvena/street_art_nn_api | tests/test_street_art_nn.py | <reponame>genaforvena/street_art_nn_api
#!flask/bin/python
import os
import tempfile
import pytest
from street_art_nn import street_art_nn
@pytest.fixture
def client(request):
db_fd, street_art_nn.app.config['DATABASE'] = tempfile.mkstemp()
street_art_nn.app.config['TESTING'] = True
client = street_art_n... |
genaforvena/street_art_nn_api | street_art_nn/__init__.py | from .street_art_nn import app
|
genaforvena/street_art_nn_api | street_art_nn/street_art_nn.py | #!flask/bin/python
import json
import sqlite3
import os
from geopy.distance import vincenty
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, jsonify
DATABASE = 'art_nn.db'
app = Flask(__name__)
app.config.update(dict(
DATABASE=os.path.join(app.root_path, DAT... |
jbuenof45401/ProyectoProgramacionCorte120191 | funciones.py | def calcular_precio_producto(coste_producto):
'''
(num) -> float: valor del producto
calcular el coste del producto aumentando el 50% de su valor como comision
>>> calcular_precio_producto(5000)
7500.0
>>> calcular_precio_producto(1000)
1500.0
:param coste_producto: representa el cos... |
jbuenof45401/ProyectoProgramacionCorte120191 | pruebas.py | import unittest
import funciones as f
class pruebas(unittest.TestCase):
def test_calcular_precio_producto(self):
self.assertEqual(f.calcular_precio_producto(1000), 1500)
self.assertEqual(f.calcular_precio_producto(0), 0)
def test_calcular_precio_servicio(self):
self.assertEqual(f.calc... |
crusaderky/pshell | pshell/tests/test_call.py | <reponame>crusaderky/pshell<gh_stars>1-10
import io
import os
import sys
import tempfile
import time
import pytest
import pshell as sh
from . import DATADIR, StubError, unix_only, windows_only
if os.name == "nt":
HELLO_CMD = [os.path.join(DATADIR, "hello.bat")]
EXIT1_CMD = [os.path.join(DATADIR, "exit1.bat"... |
crusaderky/pshell | pshell/tests/test_env.py | <reponame>crusaderky/pshell
import os
import pytest
import pshell as sh
from . import DATADIR, StubError, unix_only
@unix_only
def test_source(str_or_path):
os.environ.pop("UNITTEST_DATA_1", None)
os.environ["UNITTEST_DATA_2"] = "old"
# Also test variable name resolution
os.environ["UNITTEST_DATAD... |
crusaderky/pshell | pshell/tests/test_search.py | import os
import pickle
from pathlib import Path
import pytest
import pshell as sh
def test_glob_iglob(str_or_path, tmpdir):
os.environ["UNITTEST_BASH"] = str(tmpdir)
# Create sample data
results = [
str_or_path(os.path.join(str(tmpdir), f"test{i}.txt")) for i in (1, 2, 3)
]
for fname i... |
crusaderky/pshell | pshell/manipulate.py | """Functions for manipulating files
"""
from pathlib import Path
from typing import Sequence, Union
from . import log
from .open import pshell_open
__all__ = ("concatenate",)
PathLike = Union[str, Path]
def concatenate(
input_fnames: Sequence[PathLike], output_fname: PathLike, mode: str = "w", **kwargs
) -> No... |
crusaderky/pshell | pshell/tests/test_open.py | import bz2
import gzip
import io
import lzma
import os
import psutil
import pytest
import pshell as sh
compression_param = pytest.mark.parametrize(
"openfunc,ext,compression",
[
(open, "", "auto"),
(gzip.open, ".gz", "auto"),
(bz2.open, ".bz2", "auto"),
(lzma.open, ".xz", "aut... |
crusaderky/pshell | pshell/search.py | <reponame>crusaderky/pshell<filename>pshell/search.py
"""Search and file system traversal functions
"""
import glob as _glob
from pathlib import Path
from typing import Iterator, List, Optional, Union, overload
from . import log
from .env import resolve_env
__all__ = ("FileMatchError", "glob", "iglob")
class FileMa... |
crusaderky/pshell | pshell/tests/data/sleep20_sigterm_ignore.py | <gh_stars>1-10
#!/usr/bin/env python
"""Simple script that executes for 20s and ignores SIGTERM.
"""
import os
import signal
import time
def _handler(signum, _frame):
"""Print the incoming signal, then do nothing."""
print("Receive signal {signum}".format(signum=signum))
def main():
"""Register signal h... |
crusaderky/pshell | pshell/tests/test_procs.py | <filename>pshell/tests/test_procs.py<gh_stars>1-10
import getpass
import multiprocessing
import os
import socket
import subprocess
import sys
import time
import psutil
import pytest
import pshell as sh
from . import DATADIR
def spawn_test_proc():
"""Start a long-running process
"""
if os.name == "nt":
... |
crusaderky/pshell | pshell/file.py | <gh_stars>1-10
"""Functions for handling files and directories
"""
import datetime
import errno
import os
import shutil
import stat
from contextlib import contextmanager
from pathlib import Path
from typing import Iterator, Optional, Union, overload
from . import log
from .env import resolve_env
__all__ = (
"remo... |
crusaderky/pshell | pshell/tests/test_log.py | <reponame>crusaderky/pshell
import logging
import pshell as sh
from pshell import log
def test_log(caplog):
caplog.set_level(10)
log.debug("%d", 1)
assert sh.get_logger().name == "pshell"
sh.set_global_logger(logging.getLogger("g1"))
log.info("%d", 2)
assert sh.get_logger().name == "g1"
s... |
crusaderky/pshell | pshell/log.py | """Functions and global variables related to logging
"""
from contextvars import ContextVar
from logging import Logger, getLogger
from typing import Optional, Union
_global_logger: Optional[Logger] = None
context_logger: ContextVar[Optional[Logger]] = ContextVar(
"context_logger", default=None
)
def set_global_... |
crusaderky/pshell | pshell/__init__.py | <reponame>crusaderky/pshell
"""Convenience aggregator for all submodules
"""
from subprocess import CalledProcessError, TimeoutExpired # noqa: F401
import pkg_resources
from .call import call, check_call, check_output, real_fh # noqa: F401
from .env import override_env, putenv, resolve_env, source # noqa: F401
fr... |
crusaderky/pshell | pshell/tests/test_file.py | import getpass
import glob
import os
import subprocess
import pytest
import pshell as sh
from . import StubError, unix_only
def test_remove(str_or_path, tmpdir):
os.environ["UNITTEST_BASH"] = str(tmpdir)
testpath = str_or_path(f"{tmpdir}/test_remove")
testpath_env = str_or_path("$UNITTEST_BASH/test_rem... |
crusaderky/pshell | pshell/tests/__init__.py | import os
import pytest
DATADIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "data"))
class StubError(Exception):
"""Phony exception used to test that the cleanup in context managers always
happens
"""
pass
unix_only = pytest.mark.skipif(os.name == "nt", reason="Unix only")
windows_o... |
crusaderky/pshell | pshell/procs.py | <filename>pshell/procs.py<gh_stars>1-10
"""Utilities to manage running processes
"""
import getpass
import os
import time
from pathlib import Path
from typing import Collection, List, Union
import psutil
from . import log
from .env import resolve_env
__all__ = ("find_procs_by_cmdline", "kill")
def find_procs_by_cm... |
crusaderky/pshell | pshell/env.py | """Functions related to environment variables
"""
import os
import string
from contextlib import contextmanager
from pathlib import Path
from typing import IO, Iterator, Union, overload
from . import log
from .call import check_output
__all__ = ("source", "putenv", "override_env", "resolve_env")
def source(bash_fil... |
crusaderky/pshell | pshell/tests/test_manipulate.py | <reponame>crusaderky/pshell
import pytest
import pshell as sh
@pytest.mark.parametrize("newline", ["\n", "\r\n"])
def test_concatenate_t1(str_or_path, tmpdir, newline):
# Output file already exists and is non-empty. Files end without a newline.
# Test compression.
out = str_or_path(f"{tmpdir}/out.gz")
... |
crusaderky/pshell | pshell/tests/conftest.py | from pathlib import Path
import pytest
@pytest.fixture(params=[str, Path])
def str_or_path(request):
"""Run a test that uses this fixture twice, with and without pathlib
Usage::
def test_open(str_or_path):
sh.open(str_or_path("foo/bar/baz"))
"""
return request.param
|
crusaderky/pshell | pshell/call.py | <gh_stars>1-10
"""Functions to execute shell commands in a subprocess
"""
import io
import os
import subprocess
import threading
from contextlib import contextmanager
from typing import IO, List, Optional, Tuple, Union
from . import log
__all__ = ("real_fh", "call", "check_call", "check_output")
_BASH_INIT = "set -o... |
crusaderky/pshell | pshell/open.py | """Functions to open file descriptors
"""
import os.path
from pathlib import Path
from typing import IO, BinaryIO, Callable, Union
from . import log
from .env import resolve_env
__all__ = ("pshell_open",)
# When importing in __init__, we're going to rename pshell_open to just open
def pshell_open(
file: Union[s... |
OverEuro/swarmtools | src/SwarmTools.py | <reponame>OverEuro/swarmtools
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 18:46:11 2019
@author: EuroBrother
"""
import numpy as np
def func(x):
y = np.sum(x**2)
return y
class BasicPSO:
def __init__(self, num_params,
lbound,
ubound,
... |
OverEuro/swarmtools | src/exp_training_nn4rl/swarmtools.py | <filename>src/exp_training_nn4rl/swarmtools.py<gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
def func(x):
# y = np.sum(x**2)
y = 100 * np.sum((x[:-1]**2-x[1:])**2) + np.sum((x[:-1]-1)**2)
return y
'''Optimizers Class'''
class Optimizer(object):
def __init__(self, obj, eps... |
OverEuro/swarmtools | src/training.py | <reponame>OverEuro/swarmtools
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
class con_bandit():
'''stationary bandit problem'''
def __init__(self):
self.state = 0
self.bandits = np.array([[.9,.9,.6,-5],[.7,-5,1,.8],... |
OverEuro/swarmtools | src/ver03.py | import numpy as np
import matplotlib.pyplot as plt
def testfun(x):
# loss = np.sum((x - np.ones(len(x))*10)**2)
loss = 100 * np.sum((x[:-1]**2-x[1:])**2) + np.sum((x[:-1]-1)**2)
return loss
def GetExp(pop, popf, xnes, sigma, dim):
sp = np.ones((len(popf), dim))
for i in range(len(popf)):
... |
OverEuro/swarmtools | src/exp_training_nn4rl/training_nes.py | <reponame>OverEuro/swarmtools
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
import swarmtools as sts
class con_bandit():
'''stationary bandit problem'''
def __init__(self):
self.state = 0
self.bandits = np.array([[.... |
ZHUchichi/TSP_GA | TSP_GA.py | <gh_stars>1-10
# ^(* ̄(oo) ̄)^
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import random
import operator
import csv
N_CITIES = 48 #城市数
POP_SIZE = 200 #每一代个体数
ELITE_SIZE = 100 #保留的精英个体数量
MUTATE_RATE = 0.002 #基因变异概率
N_GENERATIONS = 1000 #生成子代数量
#勾股定理求两城市间距离
def dista... |
pouyatafti/gmailcli | gmailcli.py | import argparse
import sys
import csv
import os
from gmail import gmail
def parse_args():
parser = argparse.ArgumentParser(description="gmailcli.py")
parser.add_argument("-c", "-cred", dest="cred_fn", required=True, help="credential file")
parser.add_argument("-t", "-tok", dest="tok_fn", required=True, help="tok... |
pouyatafti/gmailcli | gmail/gmail.py | <filename>gmail/gmail.py
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from collections import namedtuple
import base64
import email
import os
def mime_header_item(msg, item):
hi = msg.get(item)
hid = email.header.decode_header(hi)[0]
if isinst... |
parnedo/medicaments.france | code/pharmacien_parser.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from pharmacien import pharmacien
import xml.etree.ElementTree as ET
from HTMLParser import HTMLParser
from BeautifulSoup import BeautifulSoup
import HTMLParser
import re
class pharmacien_parser:
def __init__(self, data):
self.removeHTMLTags = re.compile(r'<.*?>')
... |
parnedo/medicaments.france | code/pharmacy.py | <gh_stars>1-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
class pharmacy:
def __init__(self):
self.idx =''
self.commercial=''
self.social =''
self.addresse =''
self.postalcode=''
self.city =''
self.telephone =''
self.fax =''
d... |
parnedo/medicaments.france | code/medicament_main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
class main:
def __init__(self):
self.mMedicament_list = []
self.mBaseUrl = 'base-donnees-publique.medicaments.gouv.fr'
def fetchMedicaments(self, filename):
from medicament_parser import medicament_parser
for upperCase in map(chr, range... |
parnedo/medicaments.france | code/csv2sql.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from pharmacy import pharmacy
if __name__ == "__main__":
import sys
for l in open (sys.argv[1], "r").readlines():
print pharmacy.fromCsv(l).sql()
|
parnedo/medicaments.france | code/pharmacy_parser.py | <reponame>parnedo/medicaments.france
#!/usr/bin/python
# -*- coding: utf-8 -*-
from pharmacy import pharmacy
import xml.etree.ElementTree as ET
from HTMLParser import HTMLParser
from BeautifulSoup import BeautifulSoup
import HTMLParser
import re
class pharmacy_parser:
def __init__(self, data):
self.removeH... |
parnedo/medicaments.france | code/medicament.py | <reponame>parnedo/medicaments.france
#!/usr/bin/python
# -*- coding: utf-8 -*-
class medicament :
def __init__(self):
self.mTitle = None
self.mCodeCIS = None
self.mCodeCIP13 = None
self.mTherapy = None
self.mGenericGroup = None
self.mComposit... |
parnedo/medicaments.france | code/pharmacien.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
class pharmacien:
def __init__(self):
self.name = None
self.familyname= None
self.title = None
self.nRPPS = None
def __str__(self):
return str(self.name) + "|" +\
str(self.familyname) + "|" +\
... |
parnedo/medicaments.france | code/pharmacy_main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
class main:
def __init__(self):
self.mPharmacy_list = []
self.mBaseUrl = 'http://www.ordre.pharmacien.fr/annuaire/etablissement'
def fetchFarmacies(self, filename):
from pharmacy_parser import pharmacy_parser
import urlp... |
DjalelBBZ/ramp-board | ramp-database/ramp_database/model/tests/test_event.py | <filename>ramp-database/ramp_database/model/tests/test_event.py
import datetime
import shutil
import pytest
from ramp_utils import read_config
from ramp_utils.utils import encode_string
from ramp_utils.testing import database_config_template
from ramp_utils.testing import ramp_config_template
from rampwf.prediction_... |
DjalelBBZ/ramp-board | ramp-utils/ramp_utils/tests/test_ramp.py | import os
import pytest
from ramp_utils.testing import ramp_config_template
from ramp_utils import read_config
from ramp_utils import generate_ramp_config
@pytest.mark.parametrize(
"config",
[ramp_config_template(),
read_config(ramp_config_template()),
read_config(ramp_config_template(), filter_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.