repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
BotMaid/BotMaid
plugins/update.py
class pluginClass: """更新 BotMaid""" registCommand = "update", listenPlainMessage = False listenChatAction = False async def onCommandMessageReceivedListener(self, client, event, command, args): import os os.system("git pull") await client.edit_message(event.message, "更新完成,正在...
BotMaid/BotMaid
plugins/autokick.py
import configparser class pluginClass: """自动删除新加用户,管理员手动添加(非邀请链接)不会删除""" registCommand = "autoKick", listenPlainMessage = False listenChatAction = True autoKickList = [] def __init__(self): try: import os if not os.path.exists("configs/autoKick"): ...
BotMaid/BotMaid
plugins/re.py
<filename>plugins/re.py class pluginClass: """~~复读机~~ 用法 re <次数>""" registCommand = "re", listenPlainMessage = False listenChatAction = False async def onCommandMessageReceivedListener(self, client, event, command, args): if event.reply_to_msg_id: await client.delete_message...
kusalavanguhan/Adv-Auto-Filter-Bot
bot/translation.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (c) @Tamil_Tentkotta class Translation(object): START_TEXT = """ <i>Sorry, This Bot Can Only Be Used In @Tamil_Tentkotta..!</i>""" HELP_TEXT = """<i><u>Usage Guide</u></i> <i>Sorry, I Can't Help You!</i> """ ABOUT_TEXT = """...
kusalavanguhan/Adv-Auto-Filter-Bot
bot/bot.py
<filename>bot/bot.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- # (c) @Tamil_Tentkotta from pyrogram import Client, __version__ from . import API_HASH, APP_ID, LOGGER, \ BOT_SESSION, BOT_TOKEN from .user import User class Bot(Client): USER: User = None USER_ID: int = None de...
kusalavanguhan/Adv-Auto-Filter-Bot
bot/user.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # (c) @Tamil_Tentkotta from pyrogram import Client, __version__ from . import API_HASH, APP_ID, LOGGER, \ USER_SESSION class User(Client): def __init__(self): super().__init__( USER_SESSION, api_hash=API_HASH, ...
giangnguyen2412/Contcap
prepro/statistics.py
import os import matplotlib.pyplot as plt import numpy as np DATASET = 'MSCOCO' PARENT_PATH = '../dataset/processed' NUM_PER_IMG = 80 FONT_SIZE = 7 def cal_num(path): """ Calculate the number of each class: path - the directory where contains the images divided into classes return: a dictionary with ...
Waliwe/Python
dicionario_teste.py
<reponame>Waliwe/Python<gh_stars>0 person1={'nome': 'Mateus', 'idade': '35', 'sexo': 'masculino', 'sobrenome': 'Henrique', 'contato': '3333'} for x in person1: ## define que o person1 é o x e mostra as chaves print(x, end=" ") print('') print(50*'-') print('') for x in person1.values(): print(x, end=" ") #p...
Waliwe/Python
dicionario.py
#Dicionario person1={"nome":"Mateus","idade":"33","sexo":"masculino"} #usado para acessar a atribuição dada a um item person2={"nome":"Larissa","idade":"22","sexo":"feminino"} print(f'Nome: {person1["nome"]}') print(f'Idade: {person1["idade"]}') print(f'Sexo: {person1["sexo"]},{person2["sexo"]}') print('') print(50*...
Waliwe/Python
lista_tupla.py
<filename>lista_tupla.py lista=['banana', 'café', 'nescal'] print(lista) lista.append('Abacaxi') # adiciona um item print(lista) lista.insert(0,'Abacaxi') #adiciona um item na lista na posição escolhida print(lista) lista.remove('nescal') #remove um item print(lista) lista.pop(0) #remove o item da casa print(lista) p...
FroshOU/manga
docs/conf.py
# -- Setup Django -- from os import environ as env from os.path import dirname, join from sys import path path.insert(0, dirname(dirname(__file__))) path.insert(1, join(dirname(__file__), '_ext')) env['DJANGO_SETTINGS_MODULE'] = 'MangAdventure.tests.settings' __import__('django').setup() # -- Project information --...
FroshOU/manga
groups/admin.py
<reponame>FroshOU/manga<gh_stars>10-100 """Admin models for the groups app.""" from typing import Optional from django.contrib import admin from django.db.models.functions import Lower # XXX: cannot be resolved under TYPE_CHECKING from django.forms.models import BaseInlineFormSet, ModelForm from django.forms.widgets ...
FroshOU/manga
reader/migrations/0005_managers.py
from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('reader', '0004_aliases'), ] operations = [ migrations.AddField( model_name='se...
FroshOU/manga
reader/admin.py
<reponame>FroshOU/manga """Admin models for the reader app.""" from hashlib import blake2b from typing import Optional, Tuple, Type from django.contrib import admin from django.contrib.contenttypes.admin import GenericStackedInline from django.db.models import Q, QuerySet # XXX: cannot be resolved under TYPE_CHECKING...
FroshOU/manga
users/admin.py
<filename>users/admin.py<gh_stars>10-100 """Admin models for the users app.""" from typing import List, Tuple, Type from django.contrib import admin from django.contrib.auth import models from django.db.models.functions import Concat as C from django.db.models.query import QuerySet, Value as V from django.forms.field...
FroshOU/manga
docs/_ext/mangadventure_patches.py
from typing import get_type_hints, Any, List, Optional, Type, Tuple from django.db.models.base import Model from django.db.models.enums import Choices from django.db.models.fields import AutoField from django.db.models.fields.related_descriptors import ( ForeignKeyDeferredAttribute, ReverseManyToOneDescriptor,...
FroshOU/manga
users/tests/test_admin.py
from django.contrib.admin.sites import AdminSite from django.http import HttpRequest from users.admin import ( OAuthApp, OAuthAppAdmin, User, UserAdmin, UserForm, UserTypeFilter ) from . import UsersTestBase class TestUserTypeFilter(UsersTestBase): def setup_method(self): super().setup_method() ...
FroshOU/manga
reader/migrations/0006_file_limits.py
from django.db import migrations, models from MangAdventure import validators class Migration(migrations.Migration): dependencies = [('reader', '0005_managers')] operations = [ migrations.AlterField( model_name='chapter', name='file', field=models.FileField( ...
FroshOU/manga
groups/tests/test_admin.py
from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import User from django.http import HttpRequest from MangAdventure.tests.utils import get_test_image from groups.admin import GroupAdmin, MemberAdmin from groups.models import Group, Member from . import GroupsTestBase class GroupsAdm...
FroshOU/manga
MangAdventure/tests/settings.py
<filename>MangAdventure/tests/settings.py """The project's test settings.""" import re from importlib.util import find_spec from os import environ as env from pathlib import Path from secrets import token_urlsafe from MangAdventure import __version__ as VERSION from MangAdventure.bad_bots import BOTS BASE_DIR = Path...
FroshOU/manga
groups/migrations/0002_managers.py
from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('groups', '0001_squashed'), ] operations = [ migrations.AddField( model_name='g...
FroshOU/manga
users/__init__.py
<gh_stars>10-100 """The app that handles users.""" # XXX: Can't add type hint due to circular import. def get_user_display(user) -> str: """ Display the name of the user. :param user: A ``User`` model instance. :type user: :class:`~django.contrib.auth.models.User` :return: The user's full name i...
FroshOU/manga
reader/__init__.py
<reponame>FroshOU/manga """The app that handles configuration."""
FroshOU/manga
users/forms.py
"""Form models for the users app.""" from django import forms from django.contrib.auth.models import User from MangAdventure.validators import FileSizeValidator from .models import UserProfile class UserProfileForm(forms.ModelForm): """Form used for editing a :class:`~users.models.UserProfile` model.""" #:...
datascienceslugs/dss-disastertweets
setup.py
from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='Labeling disaster tweets as real or not', author='<NAME>', license='MIT', )
csstree/SublimeLinter-contrib-csstree
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by <NAME> # Copyright (c) 2016 <NAME> # # License: MIT # """This module exports the CssTree plugin class.""" from SublimeLinter.lint import Linter, util class CssTree(Linter): """Provides an interface to csstree ...
giammi56/iminuit
src/iminuit/cost.py
<filename>src/iminuit/cost.py """ Standard cost functions to minimize. """ from .util import describe, make_func_code import numpy as np def _safe_log(x): # does not return NaN for x >= 0 log_const = 1e-323 return np.log(x + log_const) def _sum_log_x(x): return np.sum(_safe_log(x)) def _sum_n_log...
giammi56/iminuit
doc/plots/bench.py
<reponame>giammi56/iminuit<gh_stars>0 import numpy as np from numpy.random import default_rng from matplotlib import pyplot as plt import matplotlib as mpl from matplotlib.ticker import LogLocator import os import pickle mpl.rcParams.update(mpl.rcParamsDefault) class TrackingFcn: def __init__(self, rng, npar): ...
giammi56/iminuit
src/iminuit/repr_text.py
<reponame>giammi56/iminuit from .pdg_format import _round, _strip import numpy as np import re def pdg_format(value, *errors): if value is None: strings, nexp = _round((0, *errors), None, None) strings = strings[1:] else: strings, nexp = _round((value, *errors), None, None) strings...
giammi56/iminuit
src/iminuit/info.py
<filename>src/iminuit/info.py import warnings from iminuit.version import __version__ # noqa: F401 warnings.warn("import iminuit.version instead", DeprecationWarning, stacklevel=2)
giammi56/iminuit
.ci/release_check.py
<gh_stars>0 import requests from pkg_resources import parse_version import sys version_fn, changelog_fn = sys.argv[1:] with open(version_fn) as f: version = {} exec(f.read(), version) # this loads __version__ version = version["__version__"] # make sure that changelog was updated with open(changelog_fn)...
giammi56/iminuit
src/iminuit/tests/test_util.py
from iminuit import util import pytest def test_fitarg_rename(): fitarg = {"x": 1, "limit_x": (2, 3), "fix_x": True, "error_x": 10} def ren(x): return "z_" + x newfa = util.fitarg_rename(fitarg, ren) assert "z_x" in newfa assert "limit_z_x" in newfa assert "error_z_x" in newfa as...
giammi56/iminuit
src/iminuit/color.py
from iminuit._deprecated import deprecated __all__ = ["Gradient"] class Gradient: """Color gradient. """ _steps = None def __init__(self, *steps): self._steps = steps @classmethod @deprecated("use Gradient(...)(...)") def color_for( cls, v, min=0.0, max=1.0, startcolor=...
giammi56/iminuit
src/iminuit/latex.py
<reponame>giammi56/iminuit from iminuit.color import Gradient __all__ = ["LatexTable"] class LatexTable: """Latex table output. """ float_format = "%10.5g" int_format = "%d" latex_kwd = [ "alpha", "beta", "gamma", "delta", "epsilon", "zeta", ...
giammi56/iminuit
doc/plots/loss.py
from matplotlib import pyplot as plt import numpy as np def soft_l1(z): return 2 * ((1 + z) ** 0.5 - 1) x = np.linspace(-3, 3) z = x ** 2 plt.plot(x, z, label="linear $\\rho(z) = z$") plt.plot(x, soft_l1(z), label="soft L1-norm $\\rho(z) = 2(\\sqrt{1+z} - 1)$") plt.xlabel("studentized residual") plt.ylabel("cos...
giammi56/iminuit
src/iminuit/tests/test_minimize.py
<gh_stars>0 import pytest from iminuit import minimize import numpy as np from numpy.testing import assert_allclose opt = pytest.importorskip("scipy.optimize") def func(x, *args): c = args[0] if args else 1 return c + x[0] ** 2 + (x[1] - 1) ** 2 + (x[2] - 2) ** 2 def grad(x, *args): return 2 * (x - (0,...
giammi56/iminuit
src/iminuit/tests/__init__.py
<reponame>giammi56/iminuit """IMinuit tests."""
giammi56/iminuit
.ci/install_pypy36.py
<filename>.ci/install_pypy36.py import sys from urllib.request import urlopen import tarfile import subprocess as subp from pathlib import Path import tempfile import shutil if Path("pypy36/pypy3/bin/activate").exists(): raise SystemExit plat = {"darwin": "osx64", "linux": "linux64"}[sys.platform] filename = "pyp...
giammi56/iminuit
src/iminuit/util.py
"""iminuit utility functions and classes.""" import re from collections import OrderedDict, namedtuple from . import repr_html from . import repr_text import warnings import inspect from ._deprecated import deprecated inf = float("infinity") class IMinuitWarning(RuntimeWarning): """iminuit warning. """ cla...
giammi56/iminuit
src/iminuit/iminuit_warnings.py
<gh_stars>0 from . import util as _util import warnings from sys import version_info as pyver warnings.warn( "importing iminuit.iminuit_warnings is deprecated, " "import warnings from iminuit.util instead", DeprecationWarning, ) deprecated_names = ["IMinuitWarning", "InitialParamWarning", "HesseFailedWarn...
giammi56/iminuit
.ci/download_azure_artifacts.py
<reponame>giammi56/iminuit<filename>.ci/download_azure_artifacts.py<gh_stars>0 import requests import json import shutil from urllib.request import urlopen from pathlib import Path import zipfile import tempfile organization = "scikit-hep" project = "iMinuit" def get(url): return json.loads(requests.get(url).con...
giammi56/iminuit
src/iminuit/_deprecated.py
<reponame>giammi56/iminuit import warnings class deprecated(object): def __init__(self, reason): self._reason = reason def __call__(self, func): def decorated_func(*args, **kwargs): warnings.warn( "{0} is deprecated: {1}".format(func.__name__, self._reason), ...
giammi56/iminuit
src/iminuit/_minuit_methods.py
<reponame>giammi56/iminuit from warnings import warn from iminuit.util import InitialParamWarning import numpy as np def pedantic(self, parameters, kwds, errordef): def w(msg): warn(msg, InitialParamWarning, stacklevel=3) for vn in parameters: if vn not in kwds and "limit_%s" % vn not in kwds...
JoshuaBragg/PTIR
ptir/__init__.py
from PIL import Image import numpy as np import os def _print_error(e): print (u'\u001b[31mERROR: \u001b[33m' + str(e) + u'\u001b[0m') def render(image_path, width=100, height=100, interp_method='bilinear', only8Bit=False, only24Bit=False): if (width <= 0 or height <= 0 or (width // 1 != width) or (height // 1 != h...
gim-/tiny-projects
TwitterHomeFeed/setup.py
# -*- coding: utf-8 -*- # # Copyright (c) 2014 <NAME> <<EMAIL>> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
gim-/tiny-projects
TwitterHomeFeed/twitter_feed.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2014 <NAME> <<EMAIL>> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
rmlarose/vls
pauli/test_vls.py
""" Unit tests for PauliSystem. """ # ============================================================================= # imports # ============================================================================= import numpy as np from vls_pauli import PauliSystem # =======================================================...
rmlarose/vls
ibmq/plot_ibmqx4_results.py
""" Script for reading in 2-variable linear systems solver data on ibmqx4 and plotting. """ # ============================================================================= # imports # ============================================================================= import matplotlib.pyplot as plt import numpy as np impor...
rmlarose/vls
pauli/vls_pauli.py
<gh_stars>0 """ Classes and functions for running VLS where the matrix A is assumed to be a sum of pauli operators. written by <NAME> <<EMAIL>> at LANL 11-14-2018 """ # ============================================================================= # imports # ==========================================================...
rmlarose/vls
ibmq/run_ibmq.py
<reponame>rmlarose/vls """Code for running a small instance of VLS on IBMQ and simulator. Script is currently set to run in two modes: MODE == "grid_search" perform a grid search of the cost function over all angles. MODE == "optimize" Use an optimization algorithm to find the minimum of the cost. w...
rmlarose/vls
vls.py
""" vls.py Class for variational linear systems code. """ # ============================================================================= # imports # ============================================================================= import numpy as np import cirq # =====================================================...
rmlarose/vls
pauli/run_vls.py
<filename>pauli/run_vls.py """ Main script for running vls with pauli operators. written by <NAME> <<EMAIL>> at LANL 11-14-2018 """ # ============================================================================= # imports # ============================================================================= from time impor...
power-edge/PySBR
pysbr/queries/openinglines.py
<filename>pysbr/queries/openinglines.py from typing import List, Union from pysbr.queries.lines import Lines from pysbr.queries.query import Query import pysbr.utils as utils class OpeningLines(Lines): """Get the opening lines offered by a sportsbook for a number of events and markets. The date and time tha...
power-edge/PySBR
tests/test_config.py
<filename>tests/test_config.py import pytest from pytest import mark from pytest_lazyfixture import lazy_fixture class TestConfig: @mark.parametrize( "league", [ lazy_fixture("nfl"), lazy_fixture("ncaaf"), lazy_fixture("epl"), lazy_fixture("mlb"), ...
power-edge/PySBR
pysbr/queries/query.py
from string import Template import copy import typing from typing import Callable, Any, Dict, Optional, List, Union from functools import wraps from gql import Client, gql from gql.transport.requests import RequestsHTTPTransport import pandas as pd from fake_useragent import UserAgent import pysbr.utils as utils from...
power-edge/PySBR
pysbr/queries/sportsbooks.py
<filename>pysbr/queries/sportsbooks.py<gh_stars>10-100 from typing import List, Union from pysbr.queries.query import Query import pysbr.utils as utils class Sportsbooks(Query): """Get information about a number of sportsbooks from their system ids. Note that the id returned from lines-related queries is ca...
power-edge/PySBR
pysbr/queries/leaguemarkets.py
from pysbr.queries.query import Query class LeagueMarkets(Query): """Get the betting markets available for a particular league. Only market ids are returned by the query, without market names. For some leagues, this query returns many more market ids than the markets found on SBR. Args: leag...
power-edge/PySBR
pysbr/config/config.py
<filename>pysbr/config/config.py<gh_stars>10-100 import pysbr.utils as utils from typing import Dict class Config: """Base config class to be subclassed by other config classes.""" def __init__(self): self._translations = utils.load_yaml(utils.build_yaml_path("dictionary")) def _translate_dict(s...
power-edge/PySBR
pysbr/queries/eventsbyeventids.py
from typing import List, Union from pysbr.queries.query import Query import pysbr.utils as utils class EventsByEventIds(Query): """Get events from a list of event ids. All event queries return information about matching events including date and time, location, participants, and associated ids. Arg...
power-edge/PySBR
pysbr/queries/bestlines.py
from typing import List, Union from pysbr.queries.lines import Lines from pysbr.queries.query import Query import pysbr.utils as utils class BestLines(Lines): """Get the best lines offered by any sportsbook for a number of events and markets. For each event, participant and market combination, the best line...
power-edge/PySBR
pysbr/queries/consensusHistory.py
<filename>pysbr/queries/consensusHistory.py from typing import List, Union from pysbr.queries.lines import Lines from pysbr.queries.query import Query import pysbr.utils as utils class ConsensusHistory(Lines): """Get the consensus amongst SBR members for selected markets on an event. For events in some leag...
power-edge/PySBR
pysbr/queries/eventsbyparticipantsrecent.py
<filename>pysbr/queries/eventsbyparticipantsrecent.py from typing import List, Union from pysbr.queries.query import Query import pysbr.utils as utils class EventsByParticipantsRecent(Query): """Get the 5 most recent events for a number of participants. 5 is an arbitrary number enforced by the query on the ...
power-edge/PySBR
pysbr/queries/eventsbydate.py
from datetime import datetime from typing import List, Union from pysbr.queries.query import Query import pysbr.utils as utils class EventsByDate(Query): """Get events for selected leagues on a certain date. All event queries return information about matching events including date and time, location, pa...
power-edge/PySBR
pysbr/queries/eventgroupsbyleague.py
from pysbr.queries.query import Query class EventGroupsByLeague(Query): """Get the event groups available on a particular league. Event groups refer to things like Week 1 of the NFL season, or the US Open, so you can use this in conjunction with EventsByEventGroups to get information about a group of...
power-edge/PySBR
pysbr/queries/team.py
<gh_stars>10-100 from pysbr.queries.query import Query class Team(Query): """Get information about a team from its team id. The team's name, location, conference, division, league, and associated ids are among the values returned from the query. Args: team_id: SBR team id. """ @Quer...
power-edge/PySBR
pysbr/queries/eventmarkets.py
from pysbr.queries.query import Query class EventMarkets(Query): """Get the event markets available on a particular event. The response contains only the market ids, not their names. Args: event_id: SBR event id. """ @Query.typecheck def __init__(self, event_id: int): super(...
power-edge/PySBR
pysbr/queries/marketsbymarketids.py
from typing import List, Union from pysbr.queries.query import Query import pysbr.utils as utils class MarketsByMarketIds(Query): """Get information about a number of leagues from their league ids. Market name, description, and market type id are included in the response. Args: market_ids: SBR ...
power-edge/PySBR
pysbr/queries/searchsports.py
<reponame>power-edge/PySBR<gh_stars>10-100 from pysbr.queries.query import Query class SearchSports(Query): """Get up to 5 sports matching a given search term. Case is ignored. The max number of upcoming events returned is enforced by the server. The query response includes sport name and id. A...
power-edge/PySBR
pysbr/utils.py
import json from inspect import cleandoc from textwrap import indent from datetime import datetime from pathlib import Path import pathlib from typing import Dict, Any, List from pytz import timezone, utc import yaml def dump_json(d, path: str): """Write json to file specified by path. Raises: FileN...
power-edge/PySBR
pysbr/queries/leaguehierarchy.py
from pysbr.queries.query import Query class LeagueHierarchy(Query): """Get the league hierarchy for a particular league. The query returns a list of dicts, each representing a team in the league. Each dict contains the team id, and information about what conference and division the team belongs to. ...
power-edge/PySBR
pysbr/queries/eventsbymatchup.py
from pysbr.queries.query import Query class EventsByMatchup(Query): """Get events where two participants matched up against one another. This query returns up to n previous head-to-head matches between two participants, where n is equal to the count argument. It works with teams or individuals. Exam...
power-edge/PySBR
tests/test_integration.py
<filename>tests/test_integration.py<gh_stars>10-100 from pysbr.config.sport import NFL, NCAAF, ATP from datetime import datetime class TestIntegration: def test_last_year_group_nfl( self, events_by_date, event_groups_by_league, events_by_event_group, current_lines, ): ...
power-edge/PySBR
pysbr/queries/linehistory.py
<reponame>power-edge/PySBR<filename>pysbr/queries/linehistory.py from typing import List, Union from pysbr.queries.lines import Lines from pysbr.queries.query import Query import pysbr.utils as utils class LineHistory(Lines): """Get the line history of an event and market for a particular sportsbook. The co...
power-edge/PySBR
pysbr/queries/leaguesbyleagueids.py
<reponame>power-edge/PySBR from typing import List, Union from pysbr.queries.query import Query import pysbr.utils as utils class LeaguesByLeagueIds(Query): """Get information about a number of leagues from their league ids. League name, abbreviation, and sport id are included in the response. Args: ...
power-edge/PySBR
pysbr/queries/searchevents.py
<gh_stars>10-100 import json import copy from pysbr.queries.query import Query # only returns five first results, and only for upcoming events # cannot search by location, league etc. Only by event participants class SearchEvents(Query): """Get up to 5 upcoming events matching a given search term. The searc...
power-edge/PySBR
tests/test_utils.py
from datetime import datetime from pytz import timezone from pytest import mark from tzlocal import get_localzone import pysbr.utils as utils class TestUtils: @mark.parametrize( ("dt_str", "tz", "expected"), [ ("2020-10-20, 9:00", "Canada/Pacific", 1603209600), ("2020-10-...
power-edge/PySBR
pysbr/queries/currentlines.py
from typing import List, Union from pysbr.queries.lines import Lines from pysbr.queries.query import Query import pysbr.utils as utils class CurrentLines(Lines): """Get the current lines offered by sportsbooks for a number of events and markets. For each sportsbook, event, participant and market combination...
power-edge/PySBR
pysbr/queries/eventsbydaterange.py
from datetime import datetime from typing import List, Union from pysbr.queries.query import Query import pysbr.utils as utils class EventsByDateRange(Query): """Get events for selected leagues over a range of dates. All event queries return information about matching events including date and time, loc...
power-edge/PySBR
pysbr/queries/eventsbyparticipants.py
<reponame>power-edge/PySBR<filename>pysbr/queries/eventsbyparticipants.py from typing import Optional, List, Union, Tuple, Dict from datetime import datetime from pysbr.queries.query import Query import pysbr.utils as utils class EventsByParticipants(Query): """Get events for a number of participants over a give...
power-edge/PySBR
pysbr/queries/eventsbyeventgroup.py
<gh_stars>10-100 from pysbr.queries.query import Query class EventsByEventGroup(Query): """Get events for a particular league and event group. All event queries return information about matching events including date and time, location, participants, and associated ids. season_id is a required argum...
power-edge/PySBR
pysbr/__init__.py
<reponame>power-edge/PySBR<gh_stars>0 from pysbr.queries.bestlines import BestLines from pysbr.queries.consensusHistory import ConsensusHistory from pysbr.queries.currentlines import CurrentLines from pysbr.queries.eventgroupsbyleague import EventGroupsByLeague from pysbr.queries.eventmarkets import EventMarkets from p...
benjaminbrinkman/fun-translator
fun-translator.py
<reponame>benjaminbrinkman/fun-translator sorta_japanese = { "a": "ka", "b": "zu", "c": "mi", "d": "te", "e": "ku", "f": "lu", "g": "ji", "h": "ri", "i": "ki", "j": "zus", "k": "me", "l": "ta", "m": "rin", "n": "to", "o": "mo", "p": "no", "q": "ke", ...
chuter/wechat-requests
tests/test_mpauth.py
<reponame>chuter/wechat-requests # -*- encoding: utf-8 import pytest from wechat.result import build_from_response from wechat.auth import MpOuthApi, get_mp_access_token @pytest.mark.usefixtures('response_builder') class TestAuth: def test_mp_auth_params(self, mocker, mp_appid, mp_secret): patched_req...
chuter/wechat-requests
tests/test_mpapi.py
<gh_stars>1-10 # -*- encoding: utf-8 import time import pytest import mock from wechat import mpapi, RequestException from wechat import settings from .compat import parse_qsl, urlparse @pytest.fixture(scope="class") def base_mpapi(request, mp_access_token): mpapi_instance = mpapi.formp(mp_access_token) re...
chuter/wechat-requests
tests/test_oauth.py
# -*- encoding: utf-8 import pytest from wechat.compat import str, url_quote, unicode from wechat.result import build_from_response from wechat import web_auth from wechat.auth import _web_auth_api, WebAuth from wechat import settings @pytest.fixture def patch_request(mocker, mp_appid, mp_secret, fake_response): ...
chuter/wechat-requests
src/wechat/message/models.py
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup from wechat.compat import basestring class MessageTypes(object): def __init__(self): raise NotImplementedError() TEXT = u'text' LINK = u'link' IMAGE = u'image' EVENT = u'event' VOICE = u'voice' VIDEO = u'video' LOCATION ...
chuter/wechat-requests
setup.py
<reponame>chuter/wechat-requests #!/usr/bin/env python # -*- coding: utf-8 -*- import io import os import sys from setuptools import find_packages, setup DESCRIPTION = 'so eazy to interact with wechat api' URL = 'https://github.com/chuter/wechat-requests' EMAIL = '<EMAIL>' AUTHOR = 'chuter' VERSION = None # What pa...
chuter/wechat-requests
src/wechat/sign.py
#!/bin/python2 # -*- coding: utf-8 -*- import time import hmac import random import string import hashlib from . import settings from .compat import str, range, unicode __all__ = ['random_nonce_str', 'sign_for_pay', 'sign_for_jsapi'] def random_nonce_str(length): if length <= 0: raise ValueError('len...
chuter/wechat-requests
src/wechat/settings.py
# -*- encoding: utf-8 from .utils import build_user_agent # common DEFAULT_HEADERS = { 'User-Agent': build_user_agent() } TIMEOUT = 1 ENCODING = 'utf-8' RETRYS = 3 RETRY_BACKOFF_FACTOR = 0.1 RETRY_STATUS_FORCELIST = frozenset([500, 502, 504]) # auth OAUTH_HOST = 'open.weixin.qq.com' AUTH_EXPIRED_CODES = froz...
chuter/wechat-requests
src/wechat/auth.py
# -*- encoding: utf-8 import re from .compat import url_quote, bytes from .api import Api from . import settings __all__ = ['get_mp_access_token', 'web_auth'] class MpOuthApi(Api): IMMUTABLE_FIELDS = frozenset(['_appid', '_secret']) def __init__(self, appid, secret, **kwargs): if appid is None o...
chuter/wechat-requests
tests/conftest.py
<reponame>chuter/wechat-requests # -*- encoding: utf-8 import pytest from wechat.compat import json from wechat import settings from .compat import urljoin, range @pytest.fixture(scope="session", autouse=True) def mp_access_token(request): return 'dummy_mp_account_access_token' @pytest.fixture(scope='session'...
chuter/wechat-requests
tests/test_utils.py
<reponame>chuter/wechat-requests<gh_stars>1-10 # -*- encoding: utf-8 from wechat.compat import json from wechat import utils class TestXmlSerialize: def test_empty_kwargs(self): xml_text = utils.serialize_dict_to_xml() assert xml_text == u'<xml>\n</xml>' def test_kwargs_onlywith_base_type(...
chuter/wechat-requests
src/wechat/pay.py
# -*- encoding: utf-8 import re import time from copy import copy from .api import Api from . import settings from . import sign from . import utils __all__ = ['for_merchant', 'build_jspay_params'] """ WxPay Api Requests ============================== ** all api will auto sign ** Api return RequestResult instan...
chuter/wechat-requests
tests/test_pay.py
# -*- encoding: utf-8 import pytest import mock from bs4 import BeautifulSoup from wechat import pay, settings from wechat.result import build_from_response """ Use `sandbox <https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=23_4>`_ to text """ # noqa @pytest.fixture(scope='module', autouse=True) def ...
chuter/wechat-requests
src/wechat/result.py
<reponame>chuter/wechat-requests<filename>src/wechat/result.py # -*- encoding: utf-8 import logging from bs4 import BeautifulSoup from .compat import json, JSONDecodeError, bytes, str from .settings import ENCODING __all__ = ['build_from_response', 'build_from'] class RequestResult(object): _XML_SUCCESS_COD...
chuter/wechat-requests
tests/__init__.py
# -*- encoding: utf-8 import logging logging.getLogger('wechat').setLevel(logging.DEBUG)
chuter/wechat-requests
src/wechat/compat.py
<reponame>chuter/wechat-requests<gh_stars>1-10 # -*- coding: utf-8 -*- # flake8: noqa import sys _ver = sys.version_info is_py2 = (_ver[0] == 2) is_py3 = (_ver[0] == 3) try: import simplejson as json except ImportError: import json JSONDecodeError = None else: JSONDecodeError = json.errors.JSONDec...
chuter/wechat-requests
tests/message/test_context.py
# -*- encoding: utf-8 from wechat.message.context import Context class TestContext: def test_set(self): ctx = Context.new(name='wechat', version='1.0.0') ctx.set('name', 'wechat-requests') assert ctx.get('name') == 'wechat-requests' def test_defaults(self): ctx = Context.ne...
chuter/wechat-requests
src/wechat/message/exceptions.py
# -*- coding: utf-8 -*- class MessageProcessException(Exception): def __init__(self, *args, **kwargs): self.handler = kwargs.pop('handler', None) self.raw_message = kwargs.pop('raw_message', None) super(MessageProcessException, self).__init__(*args, **kwargs) class MessageCryptoProcessE...
chuter/wechat-requests
src/wechat/utils.py
# -*- encoding: utf-8 from six import iteritems from .compat import json, str, bytes from .__version__ import __version__, __name__ __all__ = ['build_user_agent', 'serialize_dict_to_xml'] _USER_AGENT = None def build_user_agent(): global _USER_AGENT if _USER_AGENT is None: _USER_AGENT = '{}{}'...