repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
dvdhrm/manifestdb
src/mpp/__main__.py
"""OSBuild Manifest Pre-Processor""" import sys from .mpp import Mpp as Main if __name__ == "__main__": with Main(sys.argv) as global_main: sys.exit(global_main.run())
dvdhrm/manifestdb
src/test/test_pylint.py
"""Run `pylint` on all python sources.""" import subprocess import unittest class TestPylint(unittest.TestCase): """Testcases of this unittest""" # pylint: disable=no-self-use def test_pylint(self): """Run pylint on all python sources""" files = subprocess.check_output( [ ...
dvdhrm/manifestdb
src/mpp/mpp.py
<reponame>dvdhrm/manifestdb """osbuild-mpp - OSBuild Manifest-Pre-Processor The Manifest-Pre-Processor processes annotated osbuild manifests and produces manifests ready to be consumed by osbuild. In its basic form, it takes a valid osbuild manifest on standard-input and produces a copy on standard output. A set of pr...
dvdhrm/manifestdb
src/mdb/mdb.py
<gh_stars>0 #!/usr/bin/python3 """osbuild-mdb - OSBuild Manifest Database This tool provides access to the OSBuild Manifest DB, performs maintenance tasks on the database, and provides external access to the manifests. """ # pylint: disable=invalid-name,too-few-public-methods import argparse import contextlib impo...
dvdhrm/manifestdb
src/mdb/__main__.py
"""OSBuild Manifest Database""" import sys from .mdb import Mdb as Main if __name__ == "__main__": with Main(sys.argv) as global_main: sys.exit(global_main.run())
dvdhrm/manifestdb
src/mdb/__init__.py
"""OSBuild Manifest Database""" from .mdb import Mdb __all__ = ["Mdb"]
dvdhrm/manifestdb
src/mpp/__init__.py
"""OSBuild Manifest Pre-Processor""" from .mpp import Mpp __all__ = ["Mpp"]
RmDr/logistic-regressions
python_pytorch.py
<reponame>RmDr/logistic-regressions import numpy as np import torch from collections import defaultdict def log_loss(predicted_probs, true_labels, implementation='lib'): '''Log loss implementation in pytorch.''' if implementation == 'lib': loss_value = torch.nn.modules.BCEWithLogitsLoss()(predicted_pr...
IlyaGusev/purano
purano/annotator/processors/tfidf_keywords.py
<reponame>IlyaGusev/purano<filename>purano/annotator/processors/tfidf_keywords.py from typing import List from purano.annotator.processors import Processor from purano.models import Document from purano.proto.info_pb2 import Info as InfoPb from purano.training.models.tfidf import load_idfs, get_tfidf_vector @Process...
IlyaGusev/purano
purano/clusterer/clusterer.py
<reponame>IlyaGusev/purano import json import itertools from typing import Optional from collections import defaultdict import numpy as np from _jsonnet import evaluate_file as jsonnet_evaluate_file from nltk.stem.snowball import SnowballStemmer from scipy.special import expit from sklearn.cluster import Agglomerative...
IlyaGusev/purano
purano/training/distil_embeddings.py
<reponame>IlyaGusev/purano import argparse import copy import json import itertools import os import random from typing import List from _jsonnet import evaluate_file as jsonnet_evaluate_file from tqdm import tqdm import torch from torch.utils.data import DataLoader, RandomSampler from pytorch_lightning import Trainer...
IlyaGusev/purano
purano/training/train_text2title.py
import argparse import copy import json import os import random from _jsonnet import evaluate_file as jsonnet_evaluate_file from fasttext import load_model as ft_load_model from torch.utils.data import DataLoader, RandomSampler from pytorch_lightning import Trainer, seed_everything from pytorch_lightning.callbacks imp...
IlyaGusev/purano
purano/viewer/views/index.py
<reponame>IlyaGusev/purano<gh_stars>1-10 from flask import Blueprint, render_template bp = Blueprint('index', __name__) @bp.route('/') def hello_world(): return render_template("index.html")
IlyaGusev/purano
purano/training/models/tfidf.py
from collections import Counter from sklearn.feature_extraction.text import TfidfVectorizer from torch import nn from purano.util import tokenize_to_lemmas def build_idf_vocabulary(texts, max_df=0.2, min_df=20): print("Building TfidfVectorizer...") vectorizer = TfidfVectorizer(tokenizer=tokenize_to_lemmas, ...
IlyaGusev/purano
purano/io/parsers_csv.py
import csv from urllib.parse import urlsplit from dateutil.parser import parse as parse_datetime from purano.io.parse_dir import parse_dir def read_parsers_csv(file_name): with open(file_name, "r", encoding="utf-8") as r: header = next(r).strip().split(",") for line in r: line = line....
IlyaGusev/purano
purano/training/datasets/embeddings_as_target.py
<filename>purano/training/datasets/embeddings_as_target.py from typing import List, Dict import torch from torch.utils.data import Dataset from transformers import AutoTokenizer class EmbeddingsAsTargetDataset(Dataset): def __init__( self, records: List[Dict], url2num: Dict[str, int], ...
IlyaGusev/purano
purano/annotator/processors/tfidf.py
<filename>purano/annotator/processors/tfidf.py from typing import List, Optional import numpy as np import torch from purano.annotator.processors import Processor from purano.models import Document from purano.proto.info_pb2 import Info as InfoPb from purano.training.models.tfidf import load_idfs, get_tfidf_vector, S...
IlyaGusev/purano
purano/io/__init__.py
from purano.io.markup_tsv import read_markup_tsv, write_markup_tsv from purano.io.parsers_csv import read_parsers_csv, read_parsers_csv_dir from purano.io.tg_jsonl import read_tg_jsonl, read_tg_jsonl_dir from purano.io.tg_html import read_tg_html, read_tg_html_dir from purano.io.threads_json import read_threads_json
IlyaGusev/purano
purano/training/fasttext_hnsw.py
import numpy as np from hnswlib import Index as HnswIndex from purano.util import tokenize class FasttextHnsw: def __init__(self, model): self.model = model self.vector_dim = model.get_dimension() self.hnsw = HnswIndex(space='l2', dim=self.vector_dim * 3) def words_to_embeddings(self...
IlyaGusev/purano
purano/run_parse.py
<gh_stars>1-10 import argparse import os import json from typing import Optional from _jsonnet import evaluate_file as jsonnet_evaluate_file from fasttext import load_model as ft_load_model from pandas import DataFrame from pyonmttok import Tokenizer from sqlalchemy import create_engine from sqlalchemy.orm import sess...
IlyaGusev/purano
purano/training/models/distil_bert.py
from typing import Dict import torch from torch import nn from transformers import DistilBertModel, DistilBertConfig, AdamW, get_linear_schedule_with_warmup from pytorch_lightning import LightningModule class DistilEmbeddingBertLightning(LightningModule): def __init__(self, config: Dict): super().__init_...
IlyaGusev/purano
purano/training/train_tfidf.py
import argparse import json from _jsonnet import evaluate_file as jsonnet_evaluate_file from sklearn.decomposition import TruncatedSVD from scipy.sparse import csr_matrix import torch from tqdm import tqdm from purano.io import read_tg_jsonl from purano.training.models.tfidf import build_idf_vocabulary, get_tfidf_vec...
IlyaGusev/purano
purano/run_clustering.py
import argparse from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from pyinstrument import Profiler from purano.clusterer.clusterer import Clusterer def cluster( input_file: str, nrows: int, sort_by_date: bool, start_date: str, end_date: str, config: str, outpu...
IlyaGusev/purano
purano/tests/test_io.py
import unittest import os from datetime import datetime from purano.io import read_tg_html_dir, read_tg_jsonl_dir, read_parsers_csv_dir TESTS_DIR = os.path.dirname(os.path.abspath(__file__)) TESTS_DATA_DIR = os.path.join(TESTS_DIR, "data") def assert_document(case, document): url = document.get("url") host...
IlyaGusev/purano
purano/run_fit_param.py
import argparse import copy import os import neptune from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from hyperopt import Trials, fmin, hp, tpe from purano.clusterer.clusterer import Clusterer from purano.clusterer.metrics import calc_metrics from purano.io import parse_tg_jsonl, parse_cl...
IlyaGusev/purano
purano/run_evaluate.py
import argparse import json import os from purano.clusterer.metrics import calc_metrics from purano.io import read_tg_jsonl, read_markup_tsv, read_threads_json def evaluate( clustering_markup_tsv, original_jsonl, threads_json, output_json, include_errors ): assert os.path.isfile(clustering_ma...
IlyaGusev/purano
competition/scoring_program/evaluate.py
<gh_stars>1-10 #!/usr/bin/env python import argparse import sys import os def evaluate(input_dir, output_dir): submit_dir = os.path.join(input_dir, 'res') truth_dir = os.path.join(input_dir, 'ref') if not os.path.isdir(submit_dir): print "%s doesn't exist" % submit_dir return if not...
IlyaGusev/purano
purano/util/registrable.py
# Based on https://github.com/allenai/allennlp/blob/master/allennlp/common/registrable.py from collections import defaultdict class Registrable: _registry = defaultdict(dict) @classmethod def register(cls, name): registry = Registrable._registry[cls] def add_subclass_to_registry(subclass...
IlyaGusev/purano
purano/training/datasets/__init__.py
from purano.training.datasets.text2title import Text2TitleDataset from purano.training.datasets.gen_title import GenTitleDataset
IlyaGusev/purano
parsers/parsers/pipelines.py
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import datetime import csv class ParsersPipeline(object): def open_spider(self, spider): self.file = open(spider....
IlyaGusev/purano
purano/annotator/annotator.py
<reponame>IlyaGusev/purano import json import time import copy from typing import List, Iterable from _jsonnet import evaluate_file as jsonnet_evaluate_file from purano.models import Document, Info from purano.proto.info_pb2 import Info as InfoPb from purano.annotator.processors import Processor class Annotator: ...
IlyaGusev/purano
purano/io/tg_html.py
<filename>purano/io/tg_html.py import json from dateutil.parser import parse as parse_datetime from urllib.parse import urlsplit from xml.etree.cElementTree import parse as parse_xml from purano.io.parse_dir import parse_dir def read_tg_html(file_name): tree = parse_xml(file_name) root = tree.getroot() h...
IlyaGusev/purano
purano/util/hg_evaluate.py
<filename>purano/util/hg_evaluate.py<gh_stars>1-10 #!/usr/bin/env python3 import razdel from rouge_metric import PyRouge from nltk.translate.bleu_score import corpus_bleu import argparse import os import json from collections import defaultdict def calc_metrics(refs, hyps, metric="all"): metrics = dict() met...
IlyaGusev/purano
purano/annotator/processors/__init__.py
from purano.annotator.processors.processor import Processor from purano.annotator.processors.fasttext import FasttextProcessor from purano.annotator.processors.transformers import TransformersProcessor from purano.annotator.processors.elmo import ElmoProcessor from purano.annotator.processors.ner_slovnet import NerSlov...
IlyaGusev/purano
purano/viewer/views/document.py
<filename>purano/viewer/views/document.py from flask import Blueprint, render_template from purano.viewer.app import db from purano.models import Document bp = Blueprint('document', __name__) @bp.route('/', methods=["GET"]) def list(): documents = db.session.query(Document).all() return render_template("doc...
IlyaGusev/purano
parsers/parsers/settings.py
# -*- coding: utf-8 -*- # Scrapy settings for parsers project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://doc.scrapy.org/en/latest/topics/settings.html # https://doc.scrapy.org/en/latest/topic...
IlyaGusev/purano
purano/annotator/processors/transformers.py
<filename>purano/annotator/processors/transformers.py from typing import List import numpy as np import torch from transformers import AutoTokenizer, AutoModel, logging from purano.annotator.processors import Processor from purano.models import Document from purano.proto.info_pb2 import Info as InfoPb @Processor.re...
IlyaGusev/purano
parsers/parsers/spiders/base.py
from urllib.parse import urlsplit from datetime import datetime import scrapy from scrapy.loader import ItemLoader from parsers.items import Document class NewsSpiderConfig: def __init__(self, title_path, summary_path, date_path, date_format, text_path, topics_path, authors_path): self....
IlyaGusev/purano
purano/annotator/processors/ner_slovnet.py
<reponame>IlyaGusev/purano<gh_stars>1-10 from typing import List from navec import Navec from slovnet import NER from purano.annotator.processors import Processor from purano.models import Document from purano.proto.info_pb2 import Info as InfoPb, EntitySpan as EntitySpanPb @Processor.register("ner_slovnet") class ...
IlyaGusev/purano
purano/io/threads_json.py
<reponame>IlyaGusev/purano<gh_stars>1-10 import json def read_threads_json(file_name): threads = [] with open(file_name, "r") as r: threads = json.load(r) labels = dict() for label, thread in enumerate(threads): thread_urls = {url for url in thread["articles"]} for url in threa...
IlyaGusev/purano
purano/run_annotate.py
<gh_stars>1-10 import os import argparse from shutil import copyfile from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from purano.models import Document from purano.annotator.annotator import Annotator def annotate(config: str, batch_size: int, input_file: str, ...
IlyaGusev/purano
parsers/parsers/items.py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class Document(scrapy.Item): title = scrapy.Field() summary = scrapy.Field() text = scrapy.Field() date = scrapy.Field() url = scra...
IlyaGusev/purano
purano/util/__init__.py
<reponame>IlyaGusev/purano<gh_stars>1-10 import os import shutil from purano.util.tokenization import tokenize, tokenize_to_lemmas def get_true_file(file_path): if file_path.endswith(".tar.gz"): true_file_path = file_path.replace(".tar.gz", "") if not os.path.exists(true_file_path): d...
IlyaGusev/purano
purano/convert_to_codalab_data.py
import argparse import csv from purano.io import read_markup_tsv def convert( input_file, output_file, answers_only, data_only ): assert answers_only and not data_only or data_only and not answers_only records = read_markup_tsv(input_file) fields = tuple() if answers_only: fi...
IlyaGusev/purano
purano/annotator/processors/fasttext.py
from typing import List import numpy as np import fasttext import pyonmttok import torch from purano.annotator.processors import Processor from purano.models import Document from purano.proto.info_pb2 import Info as InfoPb from purano.util import tokenize @Processor.register("fasttext") class FasttextProcessor(Proc...
IlyaGusev/purano
purano/clusterer/metrics.py
<reponame>IlyaGusev/purano from sklearn.metrics import classification_report def calc_metrics(markup, url2record, labels): not_found_count = 0 for record in markup: first_url = record["first_url"] second_url = record["second_url"] not_found_in_labels = first_url not in labels or second...
IlyaGusev/purano
purano/io/parse_dir.py
<gh_stars>1-10 import os def parse_dir(directory, ext, parse_file_func, print_interval=None): documents_count = 0 for r, d, f in os.walk(directory): for file_name in f: file_name = os.path.join(r, file_name) if not file_name.endswith(ext): continue t...
IlyaGusev/purano
purano/util/tokenization.py
import string from pyonmttok import Tokenizer from pymorphy2 import MorphAnalyzer tokenizer = Tokenizer("conservative", joiner_annotate=False) morph = MorphAnalyzer() def tokenize(text, lower=True): text = str(text).strip().replace("\n", " ").replace("\xa0", " ") if lower: text = text.lower() to...
IlyaGusev/purano
purano/form_sbs_titles_markup.py
import argparse import copy import json import itertools import random from purano.io import read_markup_tsv, write_markup_tsv def main( original_jsonl, threads_json, honey_tsv, current_markup_tsv, output_tsv, clustering_markup_tsv, include_bad_samples, randomize=False ): url2reco...
IlyaGusev/purano
purano/training/datasets/gen_title.py
import torch from torch.utils.data import Dataset class GenTitleDataset(Dataset): def __init__( self, records, tokenizer, max_tokens_text=200, max_tokens_title=40 ): self.records = records self.tokenizer = tokenizer self.max_tokens_text = max_tok...
IlyaGusev/purano
purano/annotator/processors/elmo.py
<filename>purano/annotator/processors/elmo.py from typing import List import numpy as np import torch import pyonmttok from purano.annotator.processors import Processor from purano.models import Document from purano.proto.info_pb2 import Info as InfoPb @Processor.register("elmo") class ElmoProcessor(Processor): ...
IlyaGusev/purano
purano/io/tg_jsonl.py
<reponame>IlyaGusev/purano import json from datetime import datetime from urllib.parse import urlsplit from purano.io.parse_dir import parse_dir def read_tg_jsonl(file_name): with open(file_name, "r", encoding="utf-8") as f: for line in f: record = json.loads(line) assert "title" ...
IlyaGusev/purano
purano/run_to_jsonl.py
<reponame>IlyaGusev/purano<gh_stars>1-10 import json import os import argparse from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from purano.models import Document def entity_to_tuple(e, text): result = (e.begin, e.end, e.tag, text[e.begin: e.end]) return result def to_jsonl(inp...
IlyaGusev/purano
purano/aggregate_clustering_toloka.py
<reponame>IlyaGusev/purano import argparse from collections import Counter from collections import defaultdict from sklearn.metrics import cohen_kappa_score from purano.io import write_markup_tsv def main(answers_file_name, min_proba, target_file_name): with open(answers_file_name, "r") as r: header = tu...
IlyaGusev/purano
purano/training/train_gen_title.py
<filename>purano/training/train_gen_title.py import argparse import json import random from _jsonnet import evaluate_file as jsonnet_evaluate_file from transformers import AutoTokenizer, EncoderDecoderModel, Trainer, TrainingArguments, logging from purano.io import read_tg_jsonl from purano.training.datasets import G...
IlyaGusev/purano
purano/form_clustering_markup.py
<reponame>IlyaGusev/purano<filename>purano/form_clustering_markup.py import argparse import json import random from purano.io import read_markup_tsv, write_markup_tsv def main( original_jsonl, threads_json, honey_tsv, current_markup_tsv, output_tsv, true_prob, random_prob ): url2recor...
IlyaGusev/purano
parsers/parsers/spiders/gazeta.py
<gh_stars>1-10 # From https://github.com/ods-ai-ml4sg/proj_news_viz/ # blob/master/scraping/newsbot/newsbot/spiders/gazeta.py # Main contributor: https://github.com/Teoretic6 from datetime import datetime from scrapy import Request, Selector from parsers.spiders.base import NewsSpider, NewsSpiderConfig class Gazet...
IlyaGusev/purano
purano/annotator/processors/processor.py
<gh_stars>1-10 from typing import List from purano.util.registrable import Registrable from purano.proto.info_pb2 import Info as InfoPb from purano.models import Document class Processor(Registrable): def __call__(self, docs: List[Document], infos: List[InfoPb]): raise NotImplementedError("Base Processor...
IlyaGusev/purano
purano/training/models/__init__.py
from purano.training.models.text2title import Text2TitleModel from purano.training.models.bottleneck_encoder_decoder import BottleneckEncoderDecoderModel
IlyaGusev/purano
purano/training/models/bottleneck_encoder_decoder.py
<reponame>IlyaGusev/purano from typing import Optional import torch from transformers import EncoderDecoderModel, PreTrainedModel, PretrainedConfig class BottleneckEncoderDecoderModel(EncoderDecoderModel): def __init__( self, config: Optional[PretrainedConfig] = None, encoder: Optional[Pr...
IlyaGusev/purano
purano/make_submission.py
<filename>purano/make_submission.py import argparse import csv import os from purano.io import read_markup_tsv, read_threads_json def make_submission( clustering_markup_tsv, threads_json, output_file ): assert os.path.isfile(clustering_markup_tsv) assert clustering_markup_tsv.endswith(".tsv") ...
IlyaGusev/purano
purano/io/markup_tsv.py
<filename>purano/io/markup_tsv.py import csv def read_markup_tsv(file_name, clean_header=True): with open(file_name, "r") as r: header = tuple(next(r).strip().split("\t")) if clean_header: header = tuple((h.split(":")[-1] for h in header)) reader = csv.reader(r, delimiter='\t',...
IlyaGusev/purano
purano/models.py
from sqlalchemy import Column, String, Text, DateTime, ForeignKey, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from purano.proto.info_pb2 import Info as InfoPb Base = declarative_base() class Document(Base): __tablename__ = "document" id = Column(I...
IlyaGusev/purano
purano/training/datasets/text2title.py
import random import numpy as np import torch from torch.utils.data import Dataset from purano.util import tokenize from purano.training.fasttext_hnsw import FasttextHnsw class Text2TitleDataset(Dataset): def __init__(self, data, ft_model, min_words=2, max_words=150): self.ft_hnsw = FasttextHnsw(ft_mode...
IlyaGusev/purano
purano/viewer/app.py
<reponame>IlyaGusev/purano<filename>purano/viewer/app.py import os import argparse from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--port", type=int, help="Port", default="5001") parser.add...
IlyaGusev/purano
purano/training/models/text2title.py
<filename>purano/training/models/text2title.py import torch import torch.nn as nn from pytorch_lightning import LightningModule class Embedder(nn.Module): def __init__(self, embedding_dim=384, hidden_dim=50): super().__init__() self.mapping_layer = nn.Linear(embedding_dim, hidden_dim) def for...
nanobioSE/bnsl
bin/test/bnsl_test.py
import testbook import os from datetime import datetime import subprocess DEFAULT_E2K2RATIO = 1 DEFAULT_SALT = 0.175 @testbook.testbook('bnsl-frontend.ipynb', execute=True) def test_runPreprocessor(tb): t0 = datetime.now() func = tb.ref("runPreprocessor") func(DEFAULT_E2K2RATIO, DEFAULT_SALT) logf = "...
navi25/VQA
app/server/app.py
from flask import Flask, request, jsonify, send_from_directory, redirect from flask.ext.cors import CORS import redis from time import sleep from datetime import datetime import pickle import uuid app = Flask(__name__) CORS(app) redis_obj = redis.Redis() @app.route('/q', methods=['GET']) def get_query(): if len(r...
navi25/VQA
app/server/job.py
<reponame>navi25/VQA from keras.models import model_from_json from keras.preprocessing.sequence import pad_sequences from nltk.tokenize import word_tokenize from time import sleep import numpy as np import h5py import json import redis import pickle redis_obj = redis.Redis() model_filename = 'resources/model.json' mo...
navi25/VQA
models.py
<reponame>navi25/VQA from keras.models import Sequential from keras.layers import Dense, Activation, Dropout, LSTM, Flatten, Embedding, Merge from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D import h5py def Word2VecModel(embedding_matrix, num_words, embedding_dim, seq_length, dropout_r...
0xProject/p2p_incentives
test/data_processing/test_find_best_worst_lists.py
<reponame>0xProject/p2p_incentives """ This module contains unit tests of find_best_worst_lists(). """ from typing import List, Tuple import pytest from data_processing import find_best_worst_lists from data_types import BestAndWorstLists, InvalidInputError, SpreadingRatio from .__init__ import RATIO_LIST # test nor...
0xProject/p2p_incentives
test/node/test_del_neighbor.py
<filename>test/node/test_del_neighbor.py """ This module contains unit tests of del_neighbor(). Note: we also need to test the "remove_order" option here. However, in order to test it we will need to use functions receive_order_internal() and store_orders(). Thus, the test cases with "remove_oder" option turned on dep...
0xProject/p2p_incentives
test/performance_candidates/test_single_peer_satisfaction_neutral.py
""" This module contains unit tests of single_peer_satisfaction_neutral(). """ import copy from typing import List, NamedTuple import pytest from scenario import Scenario from engine import Engine import performance_candidates from ..__init__ import SCENARIO_SAMPLE, ENGINE_SAMPLE # The arrange helper function needed...
0xProject/p2p_incentives
test/engine/test_tit_for_tat.py
<filename>test/engine/test_tit_for_tat.py """ This module contains unit tests of tit_for_tat(). """ import random from typing import NamedTuple, Tuple, List import pytest import engine_candidates from scenario import Scenario from engine import Engine from node import Peer from ..__init__ import ( SCENARIO_SAMPLE...
0xProject/p2p_incentives
test/node/test_store_orders.py
<filename>test/node/test_store_orders.py """ This module contains unit tests of store_orders(). We should have these tests before testing receive_order_internal() because store_order() will be used during the test of receive_order_internal(). """ from typing import List import pytest from node import Peer from messag...
0xProject/p2p_incentives
test/data_processing/test_calculate_density.py
""" This module contains unit tests of calculate_density(). """ from typing import List, Tuple import pytest from data_processing import calculate_density from data_types import InvalidInputError from .__init__ import SATISFACTORY_LIST # test normal cases CASES_CALCULATE_DENSITY: List[Tuple[List[List[float]], float...
0xProject/p2p_incentives
test/single_and_multi_run/test_order_arrival.py
""" This module contains unit tests of order_arrival(). """ import pytest from scenario import Scenario from engine import Engine from performance import Performance from node import Peer from data_types import ConcaveParameters, RandomParameter from single_run import SingleRun from ..__init__ import ( SCENARIO_...
0xProject/p2p_incentives
test/single_and_multi_run/test_group_of_orders_arrival_helper.py
<reponame>0xProject/p2p_incentives """ This module contains unit tests of group_of_orders_arrival_helper(). """ import random import pytest from single_run import SingleRun from engine import Engine from performance import Performance from scenario import Scenario from ..__init__ import SCENARIO_SAMPLE, ENGINE_SAMPLE...
0xProject/p2p_incentives
test/single_and_multi_run/test_add_new_links_helper.py
""" This module contains unit tests of add_new_links_helper(). """ from typing import List, Tuple import pytest from single_run import SingleRun from node import Peer from scenario import Scenario from engine import Engine from performance import Performance from ..__init__ import SCENARIO_SAMPLE, ENGINE_SAMPLE, PERF...
0xProject/p2p_incentives
test/single_and_multi_run/__init__.py
<reponame>0xProject/p2p_incentives """ This __init__.py file contains specific mock/fake functions for this sub-module. """ from typing import List def mock_random_choice(candidates: List, weights: List[float], *, k: int) -> List: """ This is a mock function for random.choice(). It generates a deterministic ...
0xProject/p2p_incentives
single_run.py
<gh_stars>1-10 """ This module contains the SingleRun class only. """ import random from typing import Dict, Set, List, TYPE_CHECKING, cast, Tuple, Optional import numpy from message import Order from node import Peer from data_types import ( SingleRunPerformanceResult, PeerTypeName, OrderTypeName, Pee...
0xProject/p2p_incentives
test/single_and_multi_run/test_group_of_peers_arrival_helper.py
""" This module contains unit tests of group_of_peers_arrival_helper(). """ import random from typing import Dict, cast import pytest from single_run import SingleRun from engine import Engine from performance import Performance from scenario import Scenario from data_types import PeerTypeName from ..__init__ import...
0xProject/p2p_incentives
example.py
""" This module contains one test case by generating a point in engine, scenario, and performance. """ from typing import List import numpy from engine import Engine from scenario import Scenario from performance import Performance from data_types import ( Distribution, OrderProperty, ConcaveProperty, ...
0xProject/p2p_incentives
test/node/test_scoring_system.py
<reponame>0xProject/p2p_incentives """ This module tests the scoring system for neighbors to contribute. Score changes happen in receive_order_internal() and store_orders(), but it is difficult to cover all cases when tests of these two functions are focused on other perspectives. So we decided to have an individual te...
0xProject/p2p_incentives
performance_candidates.py
""" This module contains possible implementations for performance measurement functions. """ # NOTE: the attribute "max_age_to_track" in all functions means that orders whose age is less # than this value will be considered; orders whose age is exactly this value will be excluded. import statistics from typing import...
0xProject/p2p_incentives
test/performance_candidates/test_single_peer_order_receipt_ratio.py
""" This module contains unit tests of single_peer_order_receipt_ratio(). """ import copy from typing import List, NamedTuple, Set, Tuple import pytest from node import Peer from message import Order from scenario import Scenario from engine import Engine import performance_candidates from data_types import SpreadingR...
0xProject/p2p_incentives
test/__init__.py
""" This module contains test functions. We also put some constants and helper functions in this __init__ file for unit tests to use. """ from typing import List, Set, Tuple import numpy from message import Order from node import Peer from performance import Performance from data_types import ( OrderProperty, ...
0xProject/p2p_incentives
test/single_and_multi_run/test_generate_events.py
""" This module contains unit tests of generate_events_during_whole_process(). """ from typing import List import pytest from single_run import SingleRun from ..__init__ import SCENARIO_SAMPLE, ENGINE_SAMPLE, PERFORMANCE_SAMPLE def generate_fake_events(rate: float, length: int) -> List[int]: """ This is a f...
0xProject/p2p_incentives
test/node/test_add_neighbor.py
<reponame>0xProject/p2p_incentives """ This module contains unit tests of add_neighbor(). """ import collections from typing import List, Deque import pytest from node import Peer, Neighbor from ..__init__ import ( ENGINE_SAMPLE, SCENARIO_SAMPLE, create_a_test_peer, create_test_peers, ) @pytest.mar...
0xProject/p2p_incentives
test/node/test_receive_external.py
<reponame>0xProject/p2p_incentives """ This module contains unit tests of receive_order_external(). """ import pytest from node import Peer from message import Order from ..__init__ import ( SCENARIO_SAMPLE, ENGINE_SAMPLE, create_a_test_peer, create_a_test_order, ) @pytest.mark.parametrize("scenario,...
0xProject/p2p_incentives
test/single_and_multi_run/test_operations_in_a_time_round.py
<reponame>0xProject/p2p_incentives """ This module contains unit tests of operations_in_a_time_round(). """ import random import pytest from single_run import SingleRun from scenario import Scenario from engine import Engine from performance import Performance from ..__init__ import ( SCENARIO_SAMPLE, ENGINE_...
0xProject/p2p_incentives
performance.py
<filename>performance.py """ This module contains the class Performance only. """ from typing import TYPE_CHECKING, Set, List, Optional import performance_candidates from data_types import ( PerformanceParameters, PerformanceOptions, PerformanceExecutions, SpreadingOption, SatisfactionOption, ...
0xProject/p2p_incentives
test/single_and_multi_run/test_reorganize_performance_results.py
""" This module contains unit tests of reorganize_performance_results(). """ from data_types import SingleRunPerformanceResult, MultiRunPerformanceResult from multi_run_in_parallel import MultiRunInParallel SINGLE_RESULT_1 = SingleRunPerformanceResult( order_spreading=[0.2, 0.5, 0.7, 0.9, None], normal_peer_...
0xProject/p2p_incentives
test/performance_candidates/test_peer_order_stat_on_window.py
<gh_stars>1-10 """ This module contains unit tests of peer_order_stat_on_window(). """ import copy from typing import List, NamedTuple, Tuple import pytest from node import Peer from message import Order from scenario import Scenario from engine import Engine import performance_candidates from ..__init__ import ( ...
0xProject/p2p_incentives
test/engine/test_remove_lazy.py
""" This module contains unit tests of remove_lazy(). """ from typing import List from collections import deque import pytest from node import Peer import engine_candidates from scenario import Scenario from engine import Engine from ..__init__ import ENGINE_SAMPLE, SCENARIO_SAMPLE from .__init__ import create_a_peer...
0xProject/p2p_incentives
scenario_candidates.py
""" This module contains contains all possible realizations for functions in Scenario. """ import random import math from typing import List, TYPE_CHECKING from data_types import HawkesArrivalRate if TYPE_CHECKING: from message import Order def hawkes(rate: HawkesArrivalRate, max_time: int) -> List[int]: "...
0xProject/p2p_incentives
node.py
<gh_stars>1-10 """ This module contains Neighbor and Peer classes. They are both representatives of nodes. Note that sometimes we use "node" and "peer" interchangeably in the comment. """ import collections import copy from typing import Deque, Set, Dict, List, Tuple, TYPE_CHECKING from message import OrderInfo, Order...
0xProject/p2p_incentives
test/scenario/test_settle_concave.py
<reponame>0xProject/p2p_incentives """ This module contains unit tests of settle_concave(). """ import math from typing import NamedTuple, List import pytest from scenario_candidates import settle_concave from scenario import Scenario from engine import Engine from message import Order from node import Peer from .._...
0xProject/p2p_incentives
test/node/test_del_order.py
""" This module contains unit tests of del_order(). """ from typing import List import pytest from node import Peer from message import Order from ..__init__ import ( SCENARIO_SAMPLE, ENGINE_SAMPLE, create_test_peers, create_test_orders, create_a_test_peer, create_a_test_order, ) @pytest.ma...
0xProject/p2p_incentives
scenario.py
""" This module contains class Scenario only. """ from typing import TYPE_CHECKING, List, cast import numpy import scenario_candidates from data_types import ( ScenarioParameters, ScenarioOptions, OrderTypePropertyDict, PeerTypePropertyDict, EventOption, EventArrivalRate, PoissonArrivalRate...