text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
"""
PyTorch Dataset loader for 360-degree video saliency prediction.
"""
import os
import pickle
import numbers
from random import Random
from typing import Optional, Callable, Tuple, Union, List
import numpy as np
from PIL import Image
from scipy import signal
from tqdm import tqdm
import tor... | vhchuong/Saliency-prediction-for-360-degree-video | src/saliency360/datasets/vr_video.py | .py | 1695a61d0d325fdc | 7.39 | 5 |
# -*- coding: utf-8 -*-
"""
Spherical Mean Squared Error (SphereMSE) loss function for omnidirectional saliency prediction.
"""
import math
import numpy as np
import torch
import torch.nn as nn
class SphereMSE(nn.Module):
"""
Spherical Mean Squared Error Loss.
Weights each pixel's squared error by t... | vhchuong/Saliency-prediction-for-360-degree-video | src/saliency360/losses/sphere_mse.py | .py | b4c545fe60132b56 | 7.39 | 5 |
# -*- coding: utf-8 -*-
"""
Spherical U-Net architecture for 360-degree video saliency prediction.
"""
import torch
import torch.nn as nn
from saliency360.utils.torch_support import preprocess
# Compatibility fix for legacy PyTorch checkpoints
try:
torch._utils._rebuild_tensor_v2
except AttributeError:
def _r... | vhchuong/Saliency-prediction-for-360-degree-video | src/saliency360/models/spherical_unet.py | .py | 1ae2f2fc354cdcee | 7.39 | 5 |
# -*- coding: utf-8 -*-
"""
Coordinate generation utilities for mapping surrounding pixels of arbitrary center coordinates
in equirectangular projection (ERP) 360-degree panoramas.
Based on Appendix A ("The process of creating the dictionaries") from:
"Saliency prediction for 360-degree video", IEEE GTSD 2020.
"""
im... | vhchuong/Saliency-prediction-for-360-degree-video | src/saliency360/utils/coordinates.py | .py | 42af09033be45085 | 7.39 | 5 |
# -*- coding: utf-8 -*-
"""
Inference and evaluation script for 360-degree video saliency prediction.
Usage:
python test.py --checkpoint ./checkpoints/spherical_unet_20epoch.pth.tar
"""
import os
import sys
import argparse
from pathlib import Path
# Add src to python path for standalone execution
sys.path.insert... | vhchuong/Saliency-prediction-for-360-degree-video | test.py | .py | 5b1506c8c0b53e68 | 7.89 | 5 |
#Date: 12/09/2020
#Class: CS6821
#Project: A Information Retrieval System
#Author(s): Mohammad Jaminur Islam
import base64
import io
import matplotlib.pyplot as plot
import numpy as np
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
RECALL_LEVELS = np.array([0., 0.1, 0... | mohammadjaminur/InformationRetrieval | evaluation/evaluation.py | .py | f4ae5c8e3e4c2fe4 | 7 | 0 |
#Date: 12/09/2020
#Class: CS6821
#Project: A Information Retrieval System
#Author(s): Mohammad Jaminur Islam
import nltk
from nltk import PorterStemmer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import numpy as np
from num2words import num2words
def _ensure_nltk_data():
"""Download ... | mohammadjaminur/InformationRetrieval | processor/processor.py | .py | 283dd939c9ad8ba2 | 7 | 0 |
"""
search_engine.py — thin orchestration layer used by app.py (the Flask UI).
This module owns application state (the loaded CISI collection, the built
inverted index, and the precomputed TF-IDF table) and exposes two plain
functions, `search()` and `evaluate()`, that the web layer calls. The actual
ranking math (BM2... | mohammadjaminur/InformationRetrieval | search_engine.py | .py | c48c81cb2160634b | 7 | 0 |
"""
PyFi: Fast, lightweight file sharing over a local WiFi network.
Author: Vubon Roy
"""
import os
import sys
import logging
import argparse
from PyFi.server import FileServer
class PyFi:
"""PyFi application controller managing the local file server."""
def __init__(self):
self.file_server = FileSe... | vubon/pyfi | PyFi/pyfi.py | .py | 6bd5962d5e01f75a | 7.24 | 2 |
import os
import re
import sys
import time
import logging
import threading
import urllib.parse
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from typing import Optional
from PyFi.utils.util import (
render_terminal_card,
get_available_port,
get_ip_addres... | vubon/pyfi | PyFi/server/server.py | .py | 09290e7d79e83747 | 7.24 | 2 |
import io
import sys
import socket
import shutil
from subprocess import run, PIPE, CalledProcessError
import segno
__all__ = [
"qr_generator",
"render_terminal_card",
"get_available_port",
"get_ip_address",
"command_processor",
"format_bytes",
"format_duration",
"render_progress_bar",
]... | vubon/pyfi | PyFi/utils/util.py | .py | 025f14b9281d1d98 | 7.24 | 2 |
"""Model objects used to model data for the db.
Attributes:
DB_DIALECT: A str representing the dialect of the db
DB_HOST: A str representing the host of the db
DB_PORT: An int representing the port the db is running on
DB_NAME: A str representing the db in which to connect to
DB_PATH: A str represe... | danrneal/bookshelf-app | backend/models.py | .py | 239a9bb609bf2743 | 7 | 0 |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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 ... | fabric-testbed/ControlFramework | fabric_cf/actor/boot/inventory/aggregate_resource_model_creator.py | .py | 69195606ae38ee34 | 7.24 | 2 |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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 ... | fabric-testbed/ControlFramework | fabric_cf/actor/core/apis/abc_broker_reservation.py | .py | 386ec1dade3659fc | 7.24 | 2 |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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 ... | fabric-testbed/ControlFramework | fabric_cf/actor/core/apis/abc_client_policy.py | .py | f647da27eb1120d7 | 7.24 | 2 |
"""
북마크릿 요소 클릭 자동화 — 셀렉터 후보 순회.
JS_BOOKMARKLET_AUTO_CLICK은 셀렉터 후보 목록을 순서대로 시도해 처음
매칭되는 요소에 MouseEvent('click')을 dispatchEvent로 발생시키는
북마크릿이다. try_selectors()는 같은 "후보 순회 → 첫 매칭 채택" 로직을
파이썬 쪽에서 재현한 헬퍼로, 실제 DOM 대신 가짜 페이지(dict)로 검증한다.
"""
from collections.abc import Callable
JS_BOOKMARKLET_AUTO_CLICK = """
(function () {... | TaewonyNet/taewonynet.github.io | src/bookmarklet_auto_click.py | .py | 5f01a58978d4d095 | 7.15 | 1 |
"""
가장 단순한 북마크릿 — 원리 데모.
JS_CODE는 현재 페이지의 title을 console.log로 출력하는 최소 스니펫이다.
build_bookmarklet_url()이 이를 `javascript:` URL로 인코딩한다. 즐겨찾기의
URL 칸에 이 결과를 붙여넣으면 북마크릿이 완성된다.
"""
from urllib.parse import quote
JS_CODE = """
(function () {
console.log("현재 페이지 title:", document.title);
})();
""".strip()
def build_bookm... | TaewonyNet/taewonynet.github.io | src/bookmarklet_basic.py | .py | 203a722115907155 | 7.15 | 1 |
"""
북마크릿 SPA 페이지 전환 감시 — history.pushState 몽키패치.
JS_BOOKMARKLET_SPA_MONITOR는 history.pushState/replaceState를 감싸
호출될 때마다 커스텀 이벤트(locationchange)를 발생시키고, 리스너가
Beacon으로 URL 변경을 서버에 전송하는 북마크릿이다. 브라우저 없이는
직접 실행할 수 없으므로, 이 파일은 문자열 구조를 정적으로 검증한다 —
필수 API 호출이 모두 포함됐는지, 괄호가 짝이 맞는지 확인한다.
"""
JS_BOOKMARKLET_SPA_MONITOR = """
(f... | TaewonyNet/taewonynet.github.io | src/bookmarklet_spa_monitor.py | .py | 0926e8fa563f7207 | 7.15 | 1 |
import os
import yaml
import base64
import requests
from pathlib import Path
from abc import ABC, abstractmethod
# 설정 로드
with open(Path(__file__).parent.parent / ".config.yaml") as f:
config = yaml.safe_load(f)
class BaseChatAPI(ABC):
"""Chat API의 기본 추상 클래스 - OpenAI 호환 메시지 형식 사용"""
@abstractmethod
d... | TaewonyNet/taewonynet.github.io | src/chat.py | .py | 5116250146df39c3 | 7.15 | 1 |
from collections import OrderedDict
from keras.layers import InputLayer, BatchNormalization, Dense, Conv2D, Deconv2D, Activation, Flatten, Reshape
import numpy as np
import pymc3 as pm
from theano import shared, config, function, clone, pp
import theano.tensor as tt
import keras
import matplotlib
import matplotlib.pypl... | js0823/RobustBNN | src/VAE.py | .py | a207fc62aab9d528 | 7 | 0 |
#!/usr/bin/env python
"""
Converts a pickle file containing CudaNdarraySharedVariables into
a pickle file containing only TensorSharedVariables.
Usage:
gpu_pkl_to_cpu_pkl.py <gpu.pkl> <cpu.pkl>
Loads gpu.pkl, replaces cuda shared variables with numpy ones,
and saves to cpu.pkl.
If you create a model while using GPU and... | js0823/RobustBNN | src/gpu_pkl_to_cpu_pkl.py | .py | d186417b6dbbc74b | 7 | 0 |
"""Console script for sked_parser."""
import argparse
import logging
import os
import sys
from pathlib import Path
import yaml
from sked_parser import app
log = logging.getLogger("sked_parser")
def load_yaml_conf(yaml_file):
"""Helper function to load the configuration yaml files"""
with open(yaml_file, "... | SplusEins/sked_parser | sked_parser/__main__.py | .py | 24f7669c8faea90d | 7 | 0 |
import json
import logging
from time import sleep
from sked_parser import scraper
log = logging.getLogger("sked_parser")
def write_timetable_json(tables, file_path):
with open(file_path, "w") as f:
json.dump(tables, f, indent=2, ensure_ascii=False)
f.write("\n")
def raise_for_duplicated_ids(di... | SplusEins/sked_parser | sked_parser/app.py | .py | fb635d46e6b04441 | 7 | 0 |
import logging
import re
from urllib.parse import unquote, urljoin
import requests
from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth
log = logging.getLogger("sked_parser")
# Install request cache with 10 minute expiration time to avoid spamming requests
# import requests_cache
# requests_cache.i... | SplusEins/sked_parser | sked_parser/scraper.py | .py | 84397a9df87d16e6 | 7 | 0 |
from sked_parser.scraper import (
create_id,
extract_semester,
optimize_label,
guess_degree,
)
def test_extract_semester_normal():
"""Test normal/default string"""
sem_str = "Angewandte Informatik - 1. Semester"
assert extract_semester(sem_str, "") == 1
def test_extract_semester_multiple... | SplusEins/sked_parser | tests/test_scraper.py | .py | e6728bccbc37694e | 7.5 | 0 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Publishes AWS VM burn rate
"""
from decisionengine.framework.modules import Publisher
from decisionengine_modules.AWS.publishers.AWS_generic_publisher import AWSGenericPublisher as publisher
@publisher.consumes_dat... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/publishers/AWS_burn_rate.py | .py | c0e000185504a694 | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Publishes figure of merit data
"""
from decisionengine.framework.modules import Publisher
from decisionengine_modules.AWS.publishers.AWS_generic_publisher import AWSGenericPublisher as publisher
@publisher.consumes... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/publishers/AWS_figure_of_merit.py | .py | 24d5849e34de1bf1 | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Generic AWS publisher
"""
import abc
import pandas
import decisionengine_modules.graphite_client as graphite
from decisionengine.framework.modules import Publisher
DEFAULT_GRAPHITE_HOST = "fermicloud399.fnal.gov"... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/publishers/AWS_generic_publisher.py | .py | d2e5f70430103a9b | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Publishes price / performance data
"""
import decisionengine_modules.graphite_client as graphite
from decisionengine.framework.modules import Publisher
from decisionengine_modules.AWS.publishers.AWS_generic_publishe... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/publishers/AWS_price_performance.py | .py | 313eca3fd712b7cc | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Fill in data from Instance Performance CSV file
"""
import pandas as pd
from decisionengine.framework.modules import Source
from decisionengine.framework.modules.Source import Parameter
@Source.supports_config(Para... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/sources/AWSInstancePerformance.py | .py | 56cfee6a5143bc66 | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Fill in data from Job Limits CSV file
"""
import os
import time
import pandas as pd
from decisionengine.framework.modules import Source
from decisionengine.framework.modules.Source import Parameter
_RETRIES = 5
_TO... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/sources/AWSJobLimits.py | .py | 3e53e764df043524 | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Get AWS capacity (running instances) information.
"""
import boto3
import pandas as pd
import decisionengine_modules.load_config as load_config
from decisionengine.framework.modules import Source
from decisionengine... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/sources/AWSOccupancy.py | .py | 9cb35b4b2c26a04b | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Get AWS spot price information
"""
import datetime
import time
import boto3
import pandas as pd
import decisionengine_modules.load_config as load_config
from decisionengine.framework.modules import Source
from dec... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/sources/AWSSpotPrice.py | .py | 79376223e5bf51b0 | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import datetime
import time
import pandas as pd
from bill_calculator_hep.AWSBillAnalysis import AWSBillCalculator
from decisionengine.framework.modules import Source
from decisionengine.framework.modules.Source import ... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/sources/BillingInfo.py | .py | e9b199c0abe31ffa | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
This data is taken from billing and arranged as dictionary of
AccountConstants instead of separate class for each billing class.
This way is more convenient to use in programs.
"""
EXPECTED_NAMES = [
"accountName... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/sources/DEAccountContants.py | .py | f5ebaaf1d87ae533 | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
import pandas
from decisionengine.framework.modules import Source
from decisionengine.framework.modules.Source import Parameter
_SAMPLE_CONFIG = {
"target_aws_vm_burn_rate": [9.0],
"target_aws_bill_burn_rate": [... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/sources/FinancialParameters.py | .py | 0833f6737fbdad7e | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Get AWS capacity (running instances) information.
"""
import boto3
import pandas as pd
from decisionengine.framework.modules import Transform
class OccupancyData:
"""
Occupancy data element
"""
def... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/transforms/AWSOccupancy.py | .py | 30ab2f4d393969bb | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Get AWS spot price information
"""
import datetime
import time
import boto3
import pandas as pd
from decisionengine.framework.modules import Transform
# default values
REGION = "us-west-2"
INSTANCE_TYPES = ["m3.2x... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/transforms/AWSSpotPrice.py | .py | 7ba4966e0043b07e | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Calculates real time burn rate for AWS
"""
import pandas as pd
from decisionengine.framework.modules import Transform
@Transform.consumes(provisioner_resource_spot_prices=pd.DataFrame, AWS_Occupancy=pd.DataFrame)
... | HEPCloud/decisionengine_modules | src/decisionengine_modules/AWS/transforms/AwsBurnRate.py | .py | 318e25e8fae37acc | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Publishes GCE VM Burn Rates
"""
from decisionengine.framework.modules import Publisher
from decisionengine_modules.graphite.publishers.generic_publisher import GenericPublisher as publisher
@publisher.consumes_dat... | HEPCloud/decisionengine_modules | src/decisionengine_modules/GCE/publishers/GCEBurnRatePublisher.py | .py | 631d13eddd729f7b | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Publishes price / performance data
"""
import decisionengine_modules.graphite_client as graphite
from decisionengine.framework.modules import Publisher
from decisionengine_modules.graphite.publishers.generic_publis... | HEPCloud/decisionengine_modules | src/decisionengine_modules/GCE/publishers/GCEFigureOfMerit_publisher.py | .py | 72280e4c2cb7d960 | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Publishes price / performance data
"""
import decisionengine_modules.graphite_client as graphite
from decisionengine.framework.modules import Publisher
from decisionengine_modules.graphite.publishers.generic_publish... | HEPCloud/decisionengine_modules | src/decisionengine_modules/GCE/publishers/GCEPricePerformance_publisher.py | .py | 40de42e70a651d5f | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
# standard library imports
import pandas as pd
# related third party imports
from bill_calculator_hep.GCEBillAnalysis import GCEBillCalculator
# local application/library specific imports
from decisionengine.framework.m... | HEPCloud/decisionengine_modules | src/decisionengine_modules/GCE/sources/GCEBillingInfo.py | .py | ac53d0dc6dd0c8f5 | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
This source takes input from instance_performance_gce.csv
and adds it to data block
"""
import pandas as pd
from decisionengine.framework.modules import Source
from decisionengine.framework.modules.Source import Para... | HEPCloud/decisionengine_modules | src/decisionengine_modules/GCE/sources/GCEInstancePerformance.py | .py | 6c6b04818951032d | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Calculates real time burn rate for GCE
"""
import pandas as pd
from decisionengine.framework.modules import Transform
@Transform.consumes(GCE_Instance_Performance=pd.DataFrame, GCE_Occupancy=pd.DataFrame)
@Transfo... | HEPCloud/decisionengine_modules | src/decisionengine_modules/GCE/transforms/GceBurnRate.py | .py | afa2b13cbff95a44 | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Calculates price / performance and figure of merit and
saves it into the output file according to design document.
"""
import sys
import numpy as np
import pandas as pd
from decisionengine.framework.modules import ... | HEPCloud/decisionengine_modules | src/decisionengine_modules/GCE/transforms/GceFigureOfMerit.py | .py | 753e143761333a0d | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Publishes price / performance data
"""
import decisionengine_modules.graphite_client as graphite
from decisionengine.framework.modules import Publisher
from decisionengine_modules.graphite.publishers.generic_publis... | HEPCloud/decisionengine_modules | src/decisionengine_modules/NERSC/publishers/NerscFigureOfMerit_publisher.py | .py | eaee5f15b76c3ffa | 7.24 | 2 |
# SPDX-FileCopyrightText: 2017 Fermi Research Alliance, LLC
# SPDX-License-Identifier: Apache-2.0
"""
Get allocation info from Nersc
"""
import contextlib
import pandas as pd
from decisionengine.framework.modules import Source
from decisionengine.framework.modules.Source import Parameter
from decisionengine_modules.... | HEPCloud/decisionengine_modules | src/decisionengine_modules/NERSC/sources/NerscAllocationInfo.py | .py | 7264056538bdbbf9 | 7.24 | 2 |
#!/usr/bin/env python
#
# Copyright (C) Jean-Paul Calderone 2008-2015, All rights reserved
#
"""
Installation script for the OpenSSL package.
"""
import os
import re
from setuptools import find_packages, setup
HERE = os.path.abspath(os.path.dirname(__file__))
META_PATH = os.path.join("src", "OpenSSL", "version.py")... | sailfishos-mirror/pyopenssl | setup.py | .py | ae46fe2fed3da9e7 | 7 | 0 |
from __future__ import annotations
import os
import sys
import warnings
from typing import Any, Callable, NoReturn, Union
from cryptography.hazmat.bindings.openssl.binding import Binding
StrOrBytesPath = Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]
binding = Binding()
ffi = binding.ffi
lib: Any = binding... | sailfishos-mirror/pyopenssl | src/OpenSSL/_util.py | .py | 8b9b3442fdbdf00c | 7 | 0 |
"""
PRNG management routines, thin wrappers.
"""
from __future__ import annotations
import warnings
from OpenSSL._util import lib as _lib
warnings.warn(
"OpenSSL.rand is deprecated - you should use os.urandom instead",
DeprecationWarning,
stacklevel=3,
)
def add(buffer: bytes, entropy: int) -> None:
... | sailfishos-mirror/pyopenssl | src/OpenSSL/rand.py | .py | b52c5d03de484ce4 | 7 | 0 |
# Copyright (c) The pyOpenSSL developers
# See LICENSE for details.
import pathlib
from tempfile import mktemp
import pytest
from OpenSSL.SSL import OPENSSL_VERSION, SSLeay_version
is_awslc = b"AWS-LC" in SSLeay_version(OPENSSL_VERSION)
def pytest_report_header(config: pytest.Config) -> str:
import cryptograp... | sailfishos-mirror/pyopenssl | tests/conftest.py | .py | edea15b228291401 | 7.5 | 0 |
# Copyright (c) Frederick Dean
# See LICENSE for details.
"""
Unit tests for `OpenSSL.rand`.
"""
from __future__ import annotations
import pytest
from OpenSSL import rand
class TestRand:
@pytest.mark.parametrize("args", [(b"foo", None), (None, 3)])
def test_add_wrong_args(self, args: tuple[object, object]... | sailfishos-mirror/pyopenssl | tests/test_rand.py | .py | 4ed656a08e189870 | 7.5 | 0 |
import pytest
from OpenSSL._util import exception_from_error_queue, lib
class TestErrors:
"""
Tests for handling of certain OpenSSL error cases.
"""
def test_exception_from_error_queue_nonexistent_reason(self) -> None:
"""
:func:`exception_from_error_queue` raises ``ValueError`` when... | sailfishos-mirror/pyopenssl | tests/test_util.py | .py | d442688701d6684f | 7.5 | 0 |
from django.shortcuts import render
from django.views.generic import View
import requests
API_KEY = 'XXXXXXXXXXXXXXXXXXXX'
BASE_URL = 'https://api.openweathermap.org/data/2.5/forecast'
def top(request):
return render(request, 'playaibo/index.html')
class ForecastView(View):
"""API実行結果の表示
"""
templa... | shonan-py/django_practice | playaibo/views.py | .py | e3b3e099d15dd9f9 | 7.24 | 2 |
import datetime
import logging
from collections.abc import Iterator
from typing import Self
import pydantic
from mosura.schemas.issue import Issue
from mosura.schemas.issue import IssueCreate
from mosura.schemas.issue import IssueTransition
from mosura.schemas.issue import Status
logger = logging.getLogger(__name__... | TheKevJames/mosura | mosura/schemas/timeline.py | .py | b3ae534096f2aeb6 | 7.15 | 1 |
import asyncio
import datetime
import logging
from collections.abc import Iterator
from typing import Any
import fastapi
import requests
from . import database
from . import models
from . import schemas
logger = logging.getLogger(__name__)
# Network hiccups the poll loop should ride out rather than treat as fatal
... | TheKevJames/mosura | mosura/tasks.py | .py | 5c5ad083c1e3c6af | 7.15 | 1 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
from collections import defaultdict
import os
from pathlib import Path
from colcon_core.environment_variable import EnvironmentVariable
from colcon_core.location import get_config_path
from colcon_core.logging import colcon_logger
impo... | colcon/colcon-mixin | colcon_mixin/mixin/__init__.py | .py | a687cdc16c7ec955 | 7.35 | 4 |
# Copyright 2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
import argparse
import os
from pathlib import Path
import sys
import warnings
from colcon_core.argument_default import is_default_value
from colcon_core.argument_default import unwrap_default_value
from colcon_core.argument_default import w... | colcon/colcon-mixin | colcon_mixin/mixin/mixin_argument.py | .py | 0afa099549469450 | 7.35 | 4 |
# Copyright 2026 Innocent Pious
# Licensed under the Apache License, Version 2.0
"""Compute the order in which mixins referencing other mixins are applied."""
class CircularMixinError(Exception):
"""Raised when the mixin reference graph contains a cycle."""
class MissingMixinError(Exception):
"""Raised whe... | colcon/colcon-mixin | colcon_mixin/mixin/order.py | .py | 11c245c132d61536 | 7.35 | 4 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
import os
import socket
import sys
import time
from urllib.error import HTTPError
from urllib.error import URLError
from urllib.request import urlopen
import warnings
from colcon_core.location import get_config_path
from colcon_core.lo... | colcon/colcon-mixin | colcon_mixin/mixin/repository.py | .py | 872004924407f9ea | 7.35 | 4 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
from colcon_core.logging import colcon_logger
from colcon_core.plugin_system import instantiate_extensions
from colcon_core.plugin_system import order_extensions_by_name
logger = colcon_logger.getChild(__name__)
class MixinSubverbExt... | colcon/colcon-mixin | colcon_mixin/subverb/__init__.py | .py | 7bb5812c11fecd9d | 7.35 | 4 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
from argparse import ArgumentTypeError
from colcon_core.plugin_system import satisfies_version
from colcon_mixin.mixin.repository import get_repositories
from colcon_mixin.mixin.repository import set_repositories
from colcon_mixin.subv... | colcon/colcon-mixin | colcon_mixin/subverb/add.py | .py | 34035fc1eb3fc087 | 7.35 | 4 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
from colcon_core.plugin_system import satisfies_version
from colcon_mixin.mixin import get_mixin_files
from colcon_mixin.mixin.repository import get_repositories
from colcon_mixin.mixin.repository import get_repository_mixin_files
from ... | colcon/colcon-mixin | colcon_mixin/subverb/list.py | .py | 08e88044a2314ba7 | 7.35 | 4 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
from colcon_core.plugin_system import satisfies_version
from colcon_mixin.mixin.repository import get_repositories
from colcon_mixin.mixin.repository import set_repositories
from colcon_mixin.subverb import MixinSubverbExtensionPoint
... | colcon/colcon-mixin | colcon_mixin/subverb/remove.py | .py | 7fc20c6d920e8e17 | 7.35 | 4 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
from colcon_core.plugin_system import satisfies_version
from colcon_mixin.mixin import get_mixins
from colcon_mixin.subverb import MixinSubverbExtensionPoint
def _get_mixin_name_completer(verb_key, mixins_by_verb):
def mixin_name_... | colcon/colcon-mixin | colcon_mixin/subverb/show.py | .py | 98ba5f200b14107b | 7.35 | 4 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
import os
import sys
from colcon_core.plugin_system import satisfies_version
from colcon_mixin.mixin import get_mixin_files
from colcon_mixin.mixin import get_mixin_path
from colcon_mixin.mixin.repository import get_repositories
from c... | colcon/colcon-mixin | colcon_mixin/subverb/update.py | .py | 4305f87a80622fe8 | 7.35 | 4 |
# Copyright 2016-2018 Dirk Thomas
# Licensed under the Apache License, Version 2.0
from colcon_core.command import add_subparsers
from colcon_core.plugin_system import satisfies_version
from colcon_core.verb import VerbExtensionPoint
from colcon_mixin.subverb import get_subverb_extensions
class MixinVerb(VerbExtensi... | colcon/colcon-mixin | colcon_mixin/verb/mixin.py | .py | af7c8593e5d8376d | 7.35 | 4 |
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
class EmailAuthBackend(ModelBackend):
"""
Authenticate using e-mail or username
"""
def authenticate(self, request, username=None, password=None, **kwargs):
if n... | delitamakanda/fanfiction | api/authentication.py | .py | 2a6a7e2eda0a96c7 | 7.35 | 4 |
#https://stackoverflow.com/questions/28036404/django-rest-framework-upload-image-the-submitted-data-was-not-a-file/28036805#28036805
from django.db import IntegrityError
from rest_framework import serializers, fields
class Base64ImageField(serializers.ImageField):
"""
A Django REST framework field for handling imag... | delitamakanda/fanfiction | api/customserializer.py | .py | 68b3e51e363756a9 | 7.35 | 4 |
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from django.urls import resolve
from rest_framework.fields import Field
from rest_framework.reverse import reverse
class OrderField(models.PositiveIntegerField):
def __init__(self, for_fields=None, *args, **kwargs):
self.fo... | delitamakanda/fanfiction | api/fields.py | .py | de0b4efec78e174a | 7.35 | 4 |
#!/usr/bin/env python3
"""Tests for Semantic Scholar rate-limit handling in scripts/fetch_stream.py.
The free Semantic Scholar API 429s routinely; these tests simulate that and
check that (a) requests retry with backoff and (b) a run that stays
rate-limited preserves the scholar data already in _data/stream.json inste... | pizzato/pizzato.github.io | tests/test_fetch_stream.py | .py | e8750b9ea5f71622 | 7.5 | 0 |
import os
import time
import requests
import logging
from typing import Optional, Dict, Any
from hubmap_commons import file_helper as commons_file_helper
import mysql.connector
from flask import Flask
logger = logging.getLogger(__name__)
# Only using Flask for config importing
app = Flask(
__name__,
insta... | hubmapconsortium/ingest-api | src/bulk_register.py | .py | 93d561b1e0cb5b2c | 7 | 0 |
from os.path import join, dirname
from jsonschema import validate, ValidationError, SchemaError
import jsonref
import json
def assert_valid_schema(data, schema_file):
""" Checks whether the given data matches the schema """
schema = _load_json_schema(schema_file)
return validate(data, schema)
def _load... | hubmapconsortium/ingest-api | src/json_schema_validator.py | .py | 58f0955590b67a7f | 7 | 0 |
# import XML libraries
import os
import sys
import shutil
import tarfile
import argparse
import datetime as dt
from typing import Final
import xml.etree.ElementTree as ET
instructions = """
To use:
python3 SetOraDeadlines.py (-d deadline) (-s start) path/to/course/tarball
Opens an edX course export, sets ORA dates, a... | Colin-Fredericks/hx-xml | SetOraDeadlines.py | .py | ab1f9ec11b531dec | 7.3 | 3 |
"""
Python Markdown
A Python implementation of John Gruber's Markdown.
Documentation: https://python-markdown.github.io/
GitHub: https://github.com/Python-Markdown/markdown/
PyPI: https://pypi.org/project/Markdown/
Started by Manfred Stienstra (http://www.dwerg.net/).
Maintained for a few years by Yuri Takhteyev (ht... | Colin-Fredericks/hx-xml | markdown/__main__.py | .py | 32954adf397043ee | 7.3 | 3 |
"""
Python Markdown
A Python implementation of John Gruber's Markdown.
Documentation: https://python-markdown.github.io/
GitHub: https://github.com/Python-Markdown/markdown/
PyPI: https://pypi.org/project/Markdown/
Started by Manfred Stienstra (http://www.dwerg.net/).
Maintained for a few years by Yuri Takhteyev (ht... | Colin-Fredericks/hx-xml | markdown/blockparser.py | .py | 2690613a890ea015 | 7.3 | 3 |
"""
Python Markdown
A Python implementation of John Gruber's Markdown.
Documentation: https://python-markdown.github.io/
GitHub: https://github.com/Python-Markdown/markdown/
PyPI: https://pypi.org/project/Markdown/
Started by Manfred Stienstra (http://www.dwerg.net/).
Maintained for a few years by Yuri Takhteyev (ht... | Colin-Fredericks/hx-xml | markdown/extensions/__init__.py | .py | 9f0d95b5a7c87f9c | 7.3 | 3 |
"""
Python Markdown
A Python implementation of John Gruber's Markdown.
Documentation: https://python-markdown.github.io/
GitHub: https://github.com/Python-Markdown/markdown/
PyPI: https://pypi.org/project/Markdown/
Started by Manfred Stienstra (http://www.dwerg.net/).
Maintained for a few years by Yuri Takhteyev (ht... | Colin-Fredericks/hx-xml | markdown/extensions/legacy_attrs.py | .py | d84695424c50a0d9 | 7.3 | 3 |
# Copyright 2019-2025 Simon Zigelli
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | zigellsn/StagyBee | app/StagyBee/consumers.py | .py | 258cffc8cfcb7fd2 | 7 | 0 |
from fastmcp import FastMCP
import datetime
from node_listener.storage.storage import Storage
from node_listener.service.config import Config
from mcp_server.weather import weather
from mcp_server.air import air_quality
from mcp_server.home import home_data
mcp = FastMCP("sensor_listener")
config = Config('config.ini'... | bkosciow/sensor_listener | mcp_server.py | .py | 5ad74991b4fab1f4 | 7 | 0 |
import logging
import flask
from flask import jsonify
logger = logging.getLogger(__name__)
def init_api(app, cfg, storage):
@app.route("/api/keys")
def get_keys():
"""
"""
data = storage.get_all()
return jsonify({"keys": list(data.keys())})
@app.route("... | bkosciow/sensor_listener | node_api/api/routes.py | .py | fd9c5a43cbecc36a | 7 | 0 |
import logging
import boto3
import yaml
logger = logging.getLogger(__name__)
def config_load(config_file):
c = yaml.safe_load(config_file)
c["instance_list"] = list(c["instances"].keys())
logger.debug(f"Found these instances in config.yaml: {c['instance_list']}")
return c
def config_get_account_na... | ombu/stackedup | src/stacks/config.py | .py | ea9c62160663f9bf | 7 | 0 |
import datetime
import logging
import os
import subprocess
from typing import AnyStr, Dict
import boto3
import botocore.exceptions
import yaml
from tabulate import tabulate
logger = logging.getLogger(__name__)
class Stack:
def __init__(
self,
project_name: AnyStr,
stack_type: AnyStr,
... | ombu/stackedup | src/stacks/stack.py | .py | 0cb8d418c98e9f91 | 7 | 0 |
#!/usr/bin/env python
import sys
import time
from typing import Any
import schedule
from pvoutput import PVOutput
from pvoutput.exceptions import InvalidRegexpError
from pvoutput.parameters import ADDSTATUS_PARAMETERS
from pygoodwe import SingleInverter
from goodwe2pvoutput import LOGGER, Config
def add_soc(
c... | yaleman/goodwe2pvoutput | goodwe2pvoutput/__main__.py | .py | 037143e20385fb9f | 7.24 | 2 |
"""Core tools to build simple interfaces to complex data sources and bend the interface to your will (and need)"""
import os
# from contextlib import suppress
file_sep = os.path.sep
def kvhead(store, n=1):
"""Get the first item of a kv store, or a list of the first n items"""
if n == 1:
for k in st... | i2mint/dol | dol/__init__.py | .py | 3a6ba45b8108c969 | 7.39 | 5 |
"""Dependency-free core of dol's key-path *write* machinery.
This leaf module holds the pieces that both :mod:`dol.paths` and :mod:`dol.trans`
need for setting (and deleting) values through key-paths, including optional
*write-through autovivification* — creating missing intermediate levels on write
(GitHub issue #16)... | i2mint/dol | dol/_paths_core.py | .py | 28cffa48fd613fbf | 7.39 | 5 |
"""Content references and content-addressed storage — the flat "blob" layer.
Many apps split their data into two concerns (the *content-metadata bifurcation*;
see ``misc/docs/dol_content_metadata_bifurcation.md``):
- **records / metadata** — small, queryable rows (a ``MutableMapping`` of dicts, a DB);
- **content / b... | i2mint/dol | dol/content.py | .py | 82e638acca760045 | 7.39 | 5 |
"""Layers introspection"""
from functools import partial
# TODO: Make a generator and a index getter for keys and vals (and both).
# Point is to be able to get views from any level.
not_found = type("NotFound", (), {})()
no_default = type("NoDefault", (), {})()
def get_first_attr_found(store, attrs, default=no_de... | i2mint/dol | dol/dig.py | .py | 3880b7685b6e0626 | 7.39 | 5 |
"""Error objects and utils"""
from collections.abc import Mapping
from inspect import signature
# TODO: More on wrapped_callback: Handle *args too. Make it work with builtins (no signature!)
# TODO: What about traceback?
# TODO: Make it a more general and useful store decorator. Trans store into an getitem exception... | i2mint/dol | dol/errors.py | .py | 84922f1a2c89653f | 7.39 | 5 |
"""Ideas for a new store wrapping setup"""
from typing import KT, VT
from collections.abc import MutableMapping, Mapping, Iterable, Callable
from dol.util import inject_method
# Note: See dol.base.Store (and complete MappingWrap)
# TODO: Complete with wrap hooks (those of dol.base.Store and more)
class MappingWrap:
... | i2mint/dol | dol/scrap/new_store_wrap.py | .py | b0ff1f4610fd270a | 7.39 | 5 |
"""Utils to make stores"""
from typing import KT, VT, Any, NewType
from collections.abc import Mapping, Callable, Iterator, Collection
import dataclasses
from dataclasses import dataclass
import operator
from functools import partial
from contextlib import suppress
from dol.base import KvReader
Getter = NewType("Gett... | i2mint/dol | dol/scrap/store_factories.py | .py | 32e518ad0a304b8f | 7.39 | 5 |
"""
Tests for appendable.py
"""
from dol.appendable import Extender, read_add_write
def test_extender():
store = {"a": "pple"}
# test normal extend
a_extender = Extender(store, "a")
a_extender.extend("sauce")
assert store == {"a": "pplesauce"}
# test creation (when key is not in store)
b_... | i2mint/dol | dol/tests/test_appendable.py | .py | aa6e56057536d9c2 | 7.89 | 5 |
from dol.base import Store
import pytest
@pytest.mark.skip(reason="edge case that we will try to address later")
def test_simple_store_wrap_unbound_method_delegation():
# What does Store.wrap do? It wraps classes or instances in such a way that
# mapping methods (like __iter__, __getitem__, __setitem__, __del... | i2mint/dol | dol/tests/test_edge_cases.py | .py | 27d8c58788f7da35 | 7.89 | 5 |
"""Tests for dol.errors module"""
import pytest
from dol.errors import (
items_with_caught_exceptions,
_assert_condition,
NotValid,
KeyValidationError,
NoSuchKeyError,
NotAllowed,
OperationNotAllowed,
ReadsNotAllowed,
WritesNotAllowed,
DeletionsNotAllowed,
IterationNotAllowe... | i2mint/dol | dol/tests/test_errors.py | .py | 79c07a43226ab69d | 7.89 | 5 |
"""Test tools.py module."""
from dol.kv_codecs import ValueCodecs
import inspect
def test_kvcodec_user_story_01():
# See https://github.com/i2mint/dol/discussions/44#discussioncomment-7598805
# Say you have a source backend that has pickles of some lists-of-lists-of-strings,
# using the .pkl extension,
... | i2mint/dol | dol/tests/test_kv_codecs.py | .py | 9fac118e9802afb6 | 7.89 | 5 |
"""Combinatorial regression tests for ``mk_dirs_if_missing`` (Issue #14).
Issue #14 reported two fragilities, both of which are resolved on current dol; these
tests lock the behavior in (the issue explicitly asked for "more combinatorial wrapper
testing"):
1. **Read ops on a fresh store whose root dir does not exist ... | i2mint/dol | dol/tests/test_mk_dirs_if_missing.py | .py | ff5e007226ee53cd | 7.89 | 5 |
"""Packaging and test-configuration hygiene checks for the ``dol`` distribution.
``dol`` sits at the bottom of a large dependency tree, so a few "boring"
packaging properties are worth asserting explicitly instead of trusting by
inspection:
- The :pep:`561` ``py.typed`` marker must be present *and shipped*. Without i... | i2mint/dol | dol/tests/test_packaging_hygiene.py | .py | 550e67143c5ae6f8 | 7.89 | 5 |
"""Tests for paths.py"""
from dol.paths import KeyTemplate, path_get
import pytest
def test_path_get():
# NOTE: The following examples test the current default behavior, but that doesn't
# mean that this default behavior is the best behavior. I've made the choice of
# aligning (though not completely) wit... | i2mint/dol | dol/tests/test_paths.py | .py | faf51e387073665a | 7.89 | 5 |
"""Regression test for Issue #3: the recursive file walk must skip unreadable dirs.
``FileBytesReader(gettempdir())`` used to raise ``PermissionError`` because ``os.listdir``
hits OS-protected subdirectories (e.g. macOS's ``.../com.apple.*/TemporaryItems/``). The
walk now skips directories it cannot read instead of cr... | i2mint/dol | dol/tests/test_walk_permissions.py | .py | a29c6488fe9f1bd6 | 7.89 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.