repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
MFTreeSearchCV
MFTreeSearchCV-master/utils/unittest_optimisers.py
""" Unit tests for optimers. -- [email protected] """ # pylint: disable=import-error # pylint: disable=no-member # pylint: disable=invalid-name # pylint: disable=relative-import # pylint: disable=abstract-class-not-used import os from argparse import Namespace import numpy as np import time # Local from base_t...
5,155
36.911765
87
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/ancillary_utils.py
""" A collection of utilities for ancillary purposes. -- [email protected] """ # pylint: disable=import-error # pylint: disable=no-member # pylint: disable=invalid-name # pylint: disable=relative-import import numpy as np # Print lists as strings def get_rounded_list(float_list, round_to_decimals=3): """ R...
1,795
27.507937
73
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/experimenters.py
""" Harness to run experiments and save results. -- [email protected] """ # pylint: disable=import-error # pylint: disable=no-member # pylint: disable=relative-import # pylint: disable=abstract-class-not-used from argparse import Namespace import random from time import time import numpy as np from scipy.io im...
3,830
34.472222
89
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/reporters.py
""" Monitors are used to monitor the progress of any algorithm. Here we implement the most basic monitor which will be inherited by monitors for specific processes. -- [email protected] """ import sys def get_reporter(reporter): """ Returns a reporter based on what was passed as argument. If reporter is al...
1,537
29.156863
87
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/base_test_class.py
""" Implements a base class for unit tests with some common utilities. """ import numpy as np import random import sys from time import time import unittest class BaseTestClass(unittest.TestCase): """ An abstract base class for unit tests. """ def __init__(self, *args, **kwargs): """ Constructor. """ ...
1,298
24.98
74
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/general_utils.py
""" A collection of very generic python utilities. -- [email protected] """ # pylint: disable=import-error # pylint: disable=no-member # pylint: disable=invalid-name # pylint: disable=relative-import import numpy as np def compare_dict(dict_1, dict_2): """ Compares two dictionaries. """ # N.B: Taken from...
3,506
33.048544
90
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/__init__.py
""" Some general utility functions we will need. -- [email protected] """
81
15.4
46
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/optimisers.py
""" A collection of wrappers for optimisng a function. -- [email protected] """ # pylint: disable=import-error # pylint: disable=no-member # pylint: disable=invalid-name # pylint: disable=relative-import # pylint: disable=superfluous-parens from argparse import Namespace from datetime import datetime import os...
6,624
37.517442
90
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/unittest_general_utils.py
""" Test cases for functions in general_utils.py -- [email protected] """ # pylint: disable=import-error # pylint: disable=no-member # pylint: disable=invalid-name # pylint: disable=relative-import import numpy as np import general_utils from base_test_class import BaseTestClass, execute_tests class GeneralU...
3,943
34.854545
83
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/direct_fortran/__init__.py
0
0
0
py
MFTreeSearchCV
MFTreeSearchCV-master/utils/direct_fortran/simple_direct_test.py
import numpy as np import direct def main(): """ Main function. """ obj = lambda x: (np.dot(x-0.1,x), 0) lower_bounds = [-1] * 4 upper_bounds = [1] * 4; dim = len(lower_bounds) eps = 1e-5 max_func_evals = 1000 max_iterations = max_func_evals algmethod = 0 # _log_file = 'dir_file_name' _log_file ...
1,367
22.586207
74
py
Tamanduatei_Vulnerability
Tamanduatei_Vulnerability-main/vulnerability.py
import igraph as ig import numpy as np import time import multiprocessing as mp f2 = open("screen.out", 'w') f = open("result.dat", "w") # Calculating the efficiency of a given network def eff_global(g, weights): N = g.vcount() eff = 0.0 sp = g.shortest_paths(weights=weights) for l i...
2,290
27.283951
108
py
uMatrix
uMatrix-master/tools/make-firefox-meta.py
#!/usr/bin/env python3 import os import json import re import sys if len(sys.argv) == 1 or not sys.argv[1]: raise SystemExit('Build dir missing.') proj_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], '..') build_dir = os.path.abspath(sys.argv[1]) version = '' with open(os.path.join(proj_dir, 'di...
1,077
29.8
84
py
uMatrix
uMatrix-master/tools/make-opera-meta.py
#!/usr/bin/env python3 import os import json import re import sys if len(sys.argv) == 1 or not sys.argv[1]: raise SystemExit('Build dir missing.') proj_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], '..') build_dir = os.path.abspath(sys.argv[1]) version = '' with open(os.path.join(proj_dir, 'di...
1,623
29.641509
90
py
uMatrix
uMatrix-master/tools/make-chromium-meta.py
#!/usr/bin/env python3 import os import json import re import sys if len(sys.argv) == 1 or not sys.argv[1]: raise SystemExit('Build dir missing.') proj_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], '..') build_dir = os.path.abspath(sys.argv[1]) version = '' with open(os.path.join(proj_dir, 'di...
1,140
27.525
80
py
uMatrix
uMatrix-master/dist/chromium/publish-beta.py
#!/usr/bin/env python3 import datetime import json import jwt import os import re import requests import shutil import subprocess import sys import tempfile import time import zipfile from distutils.version import StrictVersion from string import Template # - Download target (raw) uMatrix.chromium.zip from GitHub # ...
6,489
32.626943
118
py
uMatrix
uMatrix-master/dist/firefox/publish-signed-beta.py
#!/usr/bin/env python3 import datetime import json import jwt import os import re import requests import shutil import subprocess import sys import tempfile import time import zipfile from distutils.version import LooseVersion from string import Template # - Download target (raw) uMatrix.firefox.xpi from GitHub # ...
12,565
38.024845
189
py
oscimpDigital
oscimpDigital-master/doc/tutorials/plutosdr/2-PRN_on_PL/project_gps/app/top_block.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: Top Block # GNU Radio version: 3.7.13.5 ################################################## from distutils.version import StrictVersion if __name__ == '__main__': import ctypes ...
12,615
42.805556
163
py
oscimpDigital
oscimpDigital-master/doc/tutorials/plutosdr/99-gnuradio-audio/top_block.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: Top Block # Generated: Tue Feb 26 16:54:22 2019 ################################################## from gnuradio import analog from gnuradio import audio from gnuradio import eng_no...
2,691
31.433735
148
py
lydia
lydia-main/scripts/run-clang-format.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of Lydia. # # Lydia is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ...
12,277
29.926952
87
py
lydia
lydia-main/scripts/check_copyright_notice.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of Lydia. # # Lydia is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ...
4,260
36.052174
86
py
sciann-applications
sciann-applications-master/SciANN-LaplaceEq-Forward/sciann_datagenerator.py
# ============================================================================== # Copyright 2021 SciANN -- Ehsan Haghighat. # All Rights Reserved. # # Licensed under the MIT License. # # A guide for generating collocation points for PINN solvers. # # Includes: # - DataGeneratorX: # Generate 1D collo...
20,752
31.477308
98
py
sciann-applications
sciann-applications-master/SciANN-SolidMechanics/SciANN-SolidMechanics.py
""" SciANN-SolidMechanics.py Description: SciANN code for solution and discovery of solid mechanics from data. For additional details, please check our paper at: https://arxiv.org/abs/2003.02751 Created by Ehsan Haghighat on 2/14/20. """ import os, sys, time import numpy as np from sciann.utils.math impo...
13,624
39.19174
157
py
sciann-applications
sciann-applications-master/SciANN-ElastoPlasticity/plotting.py
""" Description: Plotting for von-Mises elasto-plasticity problem: https://arxiv.org/abs/2003.02751 Created by Ehsan Haghighat on 6/10/20. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm, Normalize import matplotlib.ticker as ticker import matplotlib.ticke...
1,102
29.638889
72
py
sciann-applications
sciann-applications-master/SciANN-ElastoPlasticity/utility_functions.py
""" Description: Utility functions for data preparation. Created by Ehsan Haghighat on 6/10/20. """ import os, time import sys import numpy as np import pandas as pd from scipy.interpolate import griddata RADI = 50.0 def eval_mu_sig(X): return X.mean(), X.std() def std(X, mu, sig): return (X-m...
3,014
27.714286
114
py
sciann-applications
sciann-applications-master/SciANN-Elasticity/sciann_datagenerator.py
# ============================================================================== # Copyright 2021 SciANN -- Ehsan Haghighat. # All Rights Reserved. # # Licensed under the MIT License. # # A guide for generating collocation points for PINN solvers. # # Includes: # - DataGeneratorX: # Generate 1D collo...
20,752
31.477308
98
py
sciann-applications
sciann-applications-master/SciANN-DataGenerator/sciann-datagenerator.py
# ============================================================================== # Copyright 2021 SciANN -- Ehsan Haghighat. # All Rights Reserved. # # Licensed under the MIT License. # # A guide for generating collocation points for PINN solvers. # # Includes: # - DataGeneratorX: # Generate 1D collo...
20,752
31.477308
98
py
sciann-applications
sciann-applications-master/SciANN-ConstitutiveModeling/vonMises_isotropic_stochastic.py
# Copyright 2022 SciANN -- Ehsan Haghighat. # All Rights Reserved. # # Licensed under the MIT License. # # vonMises_isotropic_stochastic.py # # Using transfer learning to perform material characterization # # Requirements: # - data/vonMisesGeneral-random.csv # - transfer_learning_weights/vonMises_isotropic_stochast...
10,430
26.377953
96
py
sciann-applications
sciann-applications-master/SciANN-ConstitutiveModeling/Tensor.py
# Copyright 2022 SciANN -- Ehsan Haghighat. # All Rights Reserved. # # Licensed under the MIT License. # # Tensor class: # Abstract 3x3 tensorial operations, on vectorized data (batch), # with elasto-plasticity applications in mind. # import numpy as np import sciann as sn class BaseTensor: """ BaseTenso...
3,280
22.775362
113
py
sciann-applications
sciann-applications-master/SciANN-ConstitutiveModeling/vonMises_isotropic_dimensionless.py
# Copyright 2022 SciANN -- Ehsan Haghighat. # All Rights Reserved. # # Licensed under the MIT License. # # vonMises_isotropic_dimensionless.py # # Main code characterizing vonMises model with isotropic hardening # # Requirements: # - data/vonMises.csv # import numpy as np import matplotlib.pyplot as plt from ...
10,131
26.911846
114
py
sciann-applications
sciann-applications-master/SciANN-ConstitutiveModeling/druckerPrager_dimensionless-biaxial.py
# Copyright 2022 SciANN -- Ehsan Haghighat. # All Rights Reserved. # # Licensed under the MIT License. # # druckerPrager_dimensionless-biaxial.py # # Main code for characterizing Drucker-Prager model for biaxial loading # # Requirements: # - data/druckerPrager-biaxial.csv # import numpy as np import matplotlib...
10,077
25.803191
114
py
sciann-applications
sciann-applications-master/SciANN-ConstitutiveModeling/druckerPrager_dimensionless-biaxial-undrained.py
# Copyright 2022 SciANN -- Ehsan Haghighat. # All Rights Reserved. # # Licensed under the MIT License. # # druckerPrager_dimensionless-biaxial-undrained.py # # Main code for characterizing Drucker-Prager model for undrained biaxial loading # # Requirements: # - data/druckerPrager-biaxial-undrained.csv # import...
10,126
25.862069
114
py
sciann-applications
sciann-applications-master/SciANN-SolidMechanics-BCs/SciANN-SolidMechanics-BCs.py
""" SciANN-SolidMechanics.py Description: SciANN code for solution and discovery of solid mechanics from data. For additional details, please check our paper at: https://arxiv.org/abs/2003.02751 Created by Ehsan Haghighat on 2/14/20. """ import os, sys, time import numpy as np from sciann.utils.math impo...
14,462
40.088068
157
py
sciann-applications
sciann-applications-master/SciANN-Vibrations/PlateVibration/membrane.py
import numpy as np import matplotlib.pyplot as plt import sciann as sn from sciann.utils.math import diff, sign, sin from gen_dataset import gen_grid from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter Lx =...
2,735
27.206186
115
py
sciann-applications
sciann-applications-master/SciANN-Vibrations/PlateVibration/membrane_inv.py
import numpy as np import matplotlib.pyplot as plt import sciann as sn from sciann.utils.math import diff, sign, sin from gen_dataset import gen_grid from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter from m...
3,060
25.617391
118
py
sciann-applications
sciann-applications-master/SciANN-Vibrations/PlateVibration/plate.py
import numpy as np import sciann as sn from sciann.utils.math import diff, sign, sin from gen_dataset import gen_grid import os os.environ["CUDA_VISIBLE_DEVICES"] = "-1" from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, Form...
2,749
24.462963
124
py
sciann-applications
sciann-applications-master/SciANN-Vibrations/PlateVibration/gen_dataset.py
import numpy as np def gen_grid(nx=5, ny=5, nt=10, Lx=1.0, Ly=1.0, T=1.0): # domain grids x_grid, y_grid, t_grid = np.meshgrid( np.linspace(0, Lx, nx)[1:-1], np.linspace(0, Ly, ny)[1:-1], np.linspace(0, T, nt)[1:], indexing='ij' ) x_grid, y_grid, t_grid = [x.reshape(...
2,634
27.641304
114
py
vampire
vampire-master/scripts/stat_plotter.py
#!/usr/bin/python # # see https://docs.google.com/document/pub?id=1vsmC80shh7qCpwgaNTrLzRyz61I0BZWJFvIqiE9yIG8 # for documentation # import sys import platform import subprocess import re import time import tempfile import os import math timeDataRE = re.compile("^(.* t[0-9]+) at ([0-9]+): (.*)$") labelRE = re.compil...
9,326
24.414169
115
py
vampire
vampire-master/scripts/determinism_checker.py
#!/usr/bin/python """ Will run two vampires in parallel and compare their output. Attempts to change the memory alignment of the second vampire by creating a lot of environment variables (this should make stack start from a different place in memory). Command line: [-p] [-a alternative_executable] executable arg1 ......
4,220
25.71519
90
py
vampire
vampire-master/scripts/infXpostFx.py
#!/usr/bin/python postfix = [] temp = [] operator = -10 operand = -20 leftparentheses = -30 rightparentheses = -40 space = -50 #convert a string into usable tokens def strToTokens(str): strArr = [] strArr = str tempStr = '' tokens = [] tokens_index = 0 count = 0 for x in strArr: co...
5,395
30.190751
101
py
vampire
vampire-master/scripts/proof_checker.py
#!/usr/bin/env python # @Author Giles import os import sys import subprocess if(len(sys.argv)<2): print "You should provide a command to proof_check i.e. ../vampire_rel_master -sa inst_gen TPTP/Problems/SYN/SYN001+1.p" sys.exit(0) TPTP='~/TPTP-v6.4.0/' VAMPIRE_ROOT = sys.argv[1]+' --include '+TPTP VAMPIRE_CHEC...
3,382
29.754545
270
py
vampire
vampire-master/scripts/annotateCode.py
#!/usr/bin/env python import sys, os, time, getopt from subprocess import Popen, list2cmdline import subprocess import argparse import insertInv import tempfile def cpu_count(): if sys.platform =="win32": try: num = int(os.environ['NUMBER_OF_PROCESORS']) except(ValueError, KeyError):...
13,937
36.069149
149
py
vampire
vampire-master/scripts/insertInv.py
#!/usr/bin/python import os import sys import re import string import infXpostFx def split_line(line): # return a tuple (loop invariant) , (![...] and the rest) s= line.split(",",1) s1 = s[1]...
6,403
45.405797
174
py
vampire
vampire-master/scripts/history_search.py
#!/opt/local/bin/python3.2 #!/usr/bin/python """ Will find a svn revision that is the last to give a specified output Command line: [-f first_revision] [-l last_revision] [-d regex] executable arg1 ... default first_revision is 1500 default last_revision is the current one default regex is "Refutation found." Looks ...
4,426
23.731844
78
py
vampire
vampire-master/scripts/generate_proof_checking_problems.py
import random import os import subprocess N=1000 VAMPIRE='../vampire_rel_master' TPTP='~/TPTP/TPTP-v6.1.0/' read_from='all_relevant_problems' directory='generated_proof_obligations' if not os.path.exists(directory): os.makedirs(directory) #randomly generate N problems for proof checking all_problems=set() with o...
1,714
24.220588
137
py
vampire
vampire-master/scripts/papers/compare_preproc_analyzer.py
#!/usr/bin/python import fileinput import os strategyCnt = None benchs = [] intInfty = 10000000000000000 def readInpVal(v): if v=="TO": return intInfty else: return int(v) class Rec: idx = 0 def __init__(self, idx, vals): ...
4,832
31.655405
94
py
vampire
vampire-master/scripts/papers/get_cpa_interpolant_results.py
#!/usr/bin/python import fileinput import os import re printLatex = os.getenv("PRINT_LATEX", "ON")=="ON" #if variable is set, benchmark names will be restricted only to those appearing in the specified file restrFName = os.getenv("RESTRICTING_FILE", "") reIgnoredLine = re.compile("(%)|(sh: line 1: .* Alarm clock)...
19,577
35.390335
145
py
vampire
vampire-master/scripts/papers/z3_interpolant_stat_analyzer.py
#!/usr/bin/python import fileinput import os import re reYicesGarbaggeLine = re.compile("sh: line 1: .* Alarm clock"); benchSep = re.compile("============#$") colorSep = re.compile("------#$") reName = re.compile("F: (.*)$") reRedStart = re.compile("Rq:$") reBlueStart = re.compile("Bq:$") reDerLocal = re.compile(...
17,818
38.774554
117
py
openslide
openslide-main/scripts/dist.py
#!/usr/bin/python3 import os from pathlib import Path import shutil import subprocess base = Path(os.getenv('MESON_DIST_ROOT')) subprocess.run(['meson', 'compile', 'doc/html'], check=True) shutil.copytree('doc/html', base / 'doc/html', symlinks=True)
254
20.25
61
py
neuralqa
neuralqa-master/setup.py
import os from importlib.machinery import SourceFileLoader from setuptools import setup, find_packages version = SourceFileLoader('neuralqa.version', os.path.join( 'neuralqa', 'version.py')).load_module().VERSION def package_files(directory): paths = [] for (path, _, filenames) in os.walk(directory): ...
1,762
27.435484
83
py
neuralqa
neuralqa-master/neuralqa/cli.py
import click from neuralqa.server import launch_server from neuralqa.utils import cli_args from neuralqa.utils import import_sample_data, ConfigParser import os from neuralqa.retriever import RetrieverPool import logging @click.group() @click.version_option() def cli(): pass # @cli.command() # @cli_args.HOST # ...
1,233
22.283019
75
py
neuralqa
neuralqa-master/neuralqa/version.py
VERSION = "0.0.31-alpha"
26
8
24
py
neuralqa
neuralqa-master/neuralqa/__init__.py
import logging from neuralqa.version import VERSION as __version__ from neuralqa.reader import BERTReader from neuralqa.utils import import_sample_data logging.getLogger("transformers").setLevel(logging.ERROR) logging.getLogger("tensorflow").setLevel(logging.ERROR) logging.getLogger("elasticsearch").setLevel(logging....
378
30.583333
61
py
neuralqa
neuralqa-master/neuralqa/expander/mlmexpander.py
from neuralqa.expander import Expander import logging from transformers import AutoTokenizer, TFBertForMaskedLM import tensorflow as tf import time import spacy logger = logging.getLogger(__name__) class MLMExpander(Expander): def __init__(self, index_type="mlm", model_path="bert-base-uncased", **kwargs): ...
4,286
41.87
217
py
neuralqa
neuralqa-master/neuralqa/expander/expander.py
class Expander: def __init__(self, expander_type, **kwargs): self.expander_type = expander_type
109
21
48
py
neuralqa
neuralqa-master/neuralqa/expander/__init__.py
from .expander import * from .mlmexpander import * from .expanderpool import *
79
19
27
py
neuralqa
neuralqa-master/neuralqa/expander/expanderpool.py
from neuralqa.expander import MLMExpander import logging logger = logging.getLogger(__name__) class ExpanderPool(): def __init__(self, expanders): self._selected_expander = expanders["selected"] self.expander_pool = {} for expander in expanders["options"]: if (expander["type"...
1,398
34.871795
182
py
neuralqa
neuralqa-master/neuralqa/reader/reader.py
import tensorflow as tf import numpy as np from transformers import AutoTokenizer, TFAutoModelForQuestionAnswering import time import logging logger = logging.getLogger(__name__) class Reader: def __init__(self, model_name, model_path, model_type, **kwargs): self.load_model(model_name, model_path, mod...
758
28.192308
71
py
neuralqa
neuralqa-master/neuralqa/reader/bertreader.py
from neuralqa.reader import Reader import tensorflow as tf import numpy as np import time import logging logger = logging.getLogger(__name__) class BERTReader(Reader): def __init__(self, model_name, model_path, model_type="bert", **kwargs): Reader.__init__(self, model_name, model_path, model_type) ...
10,473
42.641667
187
py
neuralqa
neuralqa-master/neuralqa/reader/readerpool.py
from neuralqa.reader import BERTReader import logging logger = logging.getLogger(__name__) class ReaderPool(): def __init__(self, models): self._selected_model = models["selected"] self.reader_pool = {} for model in models["options"]: if (model["type"] == "bert" or model["typ...
1,331
32.3
167
py
neuralqa
neuralqa-master/neuralqa/reader/__init__.py
from .reader import * from .bertreader import * from .readerpool import *
74
17.75
25
py
neuralqa
neuralqa-master/neuralqa/utils/config_utils.py
import yaml import os import logging import shutil logger = logging.getLogger(__name__) class ConfigParser: def __init__(self, config_path): module_file_path = os.path.dirname(os.path.abspath(__file__)) self.default_config_path = os.path.join( module_file_path, "../config_default.ya...
2,359
34.757576
85
py
neuralqa
neuralqa-master/neuralqa/utils/data_utils.py
from elasticsearch import Elasticsearch import os import zipfile import shutil import urllib.request import logging import lzma import json import tarfile import hashlib logger = logging.getLogger(__name__) # index settings with analyzer to automatically remove stop words index_settings = { "settings": { ...
6,518
32.260204
94
py
neuralqa
neuralqa-master/neuralqa/utils/file_utils.py
0
0
0
py
neuralqa
neuralqa-master/neuralqa/utils/__init__.py
from .config_utils import ConfigParser from .file_utils import * from .data_utils import import_sample_data, parse_field_content
129
31.5
63
py
neuralqa
neuralqa-master/neuralqa/utils/cli_args.py
""" Definitions of click options shared by several CLI commands. """ import click HOST = click.option("--host", "-h", default="127.0.0.1", help="The network address to listen on (default: 127.0.0.1). " "Use 0.0.0.0 to bind to all addresses if you want to access the trackin...
1,118
43.76
140
py
neuralqa
neuralqa-master/neuralqa/retriever/solrretriever.py
from neuralqa.retriever import Retriever from neuralqa.utils import parse_field_content import requests import logging logger = logging.getLogger(__name__) class SolrRetriever(Retriever): def __init__(self, index_type="solr", host="localhost", port=8983, protocol="http", ** kwargs): Retriever.__init__(s...
2,910
36.320513
138
py
neuralqa
neuralqa-master/neuralqa/retriever/elasticsearchretriever.py
from neuralqa.retriever import Retriever from neuralqa.utils import parse_field_content from elasticsearch import Elasticsearch, ConnectionError, NotFoundError import logging logger = logging.getLogger(__name__) class ElasticSearchRetriever(Retriever): def __init__(self, index_type="elasticsearch", host="localh...
3,559
34.959596
138
py
neuralqa
neuralqa-master/neuralqa/retriever/retriever.py
class Retriever: def __init__(self, index_type): self.index_type = index_type
92
14.5
36
py
neuralqa
neuralqa-master/neuralqa/retriever/__init__.py
from .retriever import * from .elasticsearchretriever import * from .solrretriever import * from .retrieverpool import *
121
23.4
37
py
neuralqa
neuralqa-master/neuralqa/retriever/retrieverpool.py
from neuralqa.retriever import ElasticSearchRetriever import logging logger = logging.getLogger(__name__) class RetrieverPool(): def __init__(self, retrievers): self.retriever_pool = {} for retriever in retrievers["options"]: if (retriever["value"] in self.retriever_pool): ...
1,751
37.086957
189
py
neuralqa
neuralqa-master/neuralqa/server/serve.py
from neuralqa.reader import BERTReader, ReaderPool from neuralqa.server.routehandlers import Handler from neuralqa.retriever import ElasticSearchRetriever, RetrieverPool from neuralqa.utils import ConfigParser from neuralqa.expander import ExpanderPool import os import logging import time import uvicorn from fastapi...
2,057
28.4
80
py
neuralqa
neuralqa-master/neuralqa/server/routemodels.py
from pydantic import BaseModel from typing import Optional class Document(BaseModel): max_documents: Optional[int] = 5 query: str = "what is a fourth amendment right violation?" fragment_size: int = 250 retriever: Optional[str] = None relsnip: Optional[bool] = True class Answer(BaseModel): ...
1,108
28.184211
127
py
neuralqa
neuralqa-master/neuralqa/server/server_app.py
import uvicorn import os def launch_server(host="127.0.0.1", port=5000, workers=1, reload=False): uvicorn.run("neuralqa.server.serve:app", host=host, port=port, workers=workers, log_level="info", reload=reload) if __name__ == "__main__": launch_server()
283
20.846154
83
py
neuralqa
neuralqa-master/neuralqa/server/__init__.py
from .server_app import launch_server
38
18.5
37
py
neuralqa
neuralqa-master/neuralqa/server/routehandlers.py
from neuralqa.utils import ConfigParser import time from fastapi import APIRouter from typing import Optional from neuralqa.server.routemodels import Document, Answer, Explanation, Expansion import logging logger = logging.getLogger(__name__) class Handler: def __init__(self, reader_pool, retriever_pool, expan...
5,890
40.485915
176
py
neuralqa
neuralqa-master/tests/expander/test_expander.py
from neuralqa.expander import MLMExpander def test_mlm_expander(): expander_kwargs = { # "model_path": "distilbert-base-uncased" } test_string = "Steve jobs created the apple computer in which year" expander = MLMExpander(**expander_kwargs) expansion = expander.expand_query(test_string) ...
400
24.0625
71
py
neuralqa
neuralqa-master/tests/reader/test_reader.py
0
0
0
py
neuralqa
neuralqa-master/tests/retriever/test_retriever.py
from neuralqa.retriever import ElasticSearchRetriever from neuralqa.utils import ConfigParser def test_elasticserch_retriever(): app_config = ConfigParser("config.yaml") rkwargs = app_config.config["retriever"]["options"][1]["connection"] retriever = ElasticSearchRetriever(**rkwargs) results = retriev...
452
29.2
72
py
neuralqa
neuralqa-master/docs/conf.py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
1,992
33.362069
79
py
LRMI
LRMI-main/feature/svm.py
import numpy as np from sklearn.model_selection import KFold from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC # data = np.loadtxt('dataset/waveform/waveform-+noise.data', dtype=np.float64, delimiter=',') # features = [ # [6, 10, 15, 9, 12, 11, 30, 37, 23, 29, ], # MRMI # [6, 10, 15, 9, 5,...
3,828
31.176471
93
py
LRMI
LRMI-main/feature/knn.py
import numpy as np from sklearn.model_selection import train_test_split, KFold from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import classification_report, confusion_matrix, mutual_info_score from sklearn.feature_selection import mutual_info_clas...
4,257
33.33871
86
py
BeatTheBookie
BeatTheBookie-master/src/Figure2A.py
import numpy as np import pandas as pd import matplotlib as mpl from scipy.stats import norm import random import bisect bet = 50 # money on each bet marg = 0.05 # margin odds above the mean. n_samples = 10 # number of returns to calculate (with replacement) for the random strategy #rand('seed',1) # use always the sa...
8,610
44.803191
150
py
BeatTheBookie
BeatTheBookie-master/src/collect.py
import os, fnmatch from itertools import cycle dest = open('odds_series.csv','w') # replace by 'odds_series_b.csv' for b dataset flatten = lambda l: [item for sublist in l for item in sublist] header_cols = ['match_id','match_date','match_time','score_home','score_away'] \ + flatten([[''.join(map(str,t)) for t in zi...
1,542
31.829787
181
py
BeatTheBookie
BeatTheBookie-master/src/unpack.py
import os source = open('../data/odds_series.csv','r') # replace path for '../data/odds_series_b.csv' for the other dataset path = "../data/odds_series/" # replace path for "../data/odds_series_b/" for the other dataset header = True for line in source.readlines(): if header: header = False continue...
727
41.823529
149
py
BeatTheBookie
BeatTheBookie-master/src/Figure1.py
import numpy as np import pandas as pd import matplotlib as mpl dir_path = '../data/' data = pd.read_csv(dir_path + "closing_odds.csv") #data = np.genfromtxt(dir_path + "closing_odds.csv", delimiter=',') # Fields: # 1. match_table_id: unique identifier of the game # 2. league of the game # 3. match date # 4. home tea...
4,908
36.473282
100
py
DeepAligned-Clustering
DeepAligned-Clustering-main/pretrain.py
from util import * from model import * from dataloader import * class PretrainModelManager: def __init__(self, args, data): set_seed(args.seed) self.model = BertForModel.from_pretrained(args.bert_model, cache_dir = "", num_labels = data.n_known_cls) if args.freeze_bert_parameters: ...
4,907
40.59322
129
py
DeepAligned-Clustering
DeepAligned-Clustering-main/DeepAligned.py
from model import * from init_parameter import * from dataloader import * from pretrain import * from util import * class ModelManager: def __init__(self, args, data, pretrained_model=None): if pretrained_model is None: pretrained_model = BertForModel.from_pretrained(args.bert_mod...
10,443
36.3
136
py
DeepAligned-Clustering
DeepAligned-Clustering-main/dataloader.py
from util import * def set_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) class Data: def __init__(self, args): set_seed(args.seed) max_seq_lengths = {'clinc':30, 'stackoverflow':45,'banking':55} args.max_seq_length = max_seq_lengths[args.da...
13,724
44.598007
175
py
DeepAligned-Clustering
DeepAligned-Clustering-main/model.py
from util import * class BertForModel(BertPreTrainedModel): def __init__(self,config,num_labels): super(BertForModel, self).__init__(config) self.num_labels = num_labels self.bert = BertModel(config) self.dense = nn.Linear(config.hidden_size, config.hidden_size) self...
1,273
42.931034
169
py
DeepAligned-Clustering
DeepAligned-Clustering-main/util.py
import itertools import subprocess import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import copy import torch.nn.functional as F import random import csv import sys from torch import nn from tqdm import tqdm_notebook, trange, tqdm from pytorch_pretrained_bert.optimization imp...
1,544
31.87234
110
py
DeepAligned-Clustering
DeepAligned-Clustering-main/init_parameter.py
from argparse import ArgumentParser def init_model(): parser = ArgumentParser() parser.add_argument("--data_dir", default='data', type=str, help="The input data dir. Should contain the .csv files (or other data files) for the task.") parser.add_argument("--save_results_pat...
3,278
46.521739
151
py
lm-intervention
lm-intervention-master/experiment_num_agreement.py
import torch # import torch.nn as nn import torch.nn.functional as F import numpy as np # import random from functools import partial from tqdm import tqdm # from tqdm import tqdm_notebook import math import statistics from utils_num_agreement import batch, convert_results_to_pd from transformers import ( GPT2LMH...
37,950
44.724096
129
py
lm-intervention
lm-intervention-master/aggregate_total_effect_bar_plot.py
import pandas as pd import matplotlib.pyplot as plt import sys import seaborn as sns sns.set() PATH = sys.argv[1] FIGURES_PATH = sys.argv[2] MODELS = ['Distil', 'Small', 'Medium', 'Large', 'XL'] EXAMPLE_TYPES = ['None', 'Distractor', 'Plural attractor', 'Singular attractor'] FORMAT = '.pdf' def save_aggrega...
1,324
31.317073
77
py
lm-intervention
lm-intervention-master/attention_utils.py
import torch import matplotlib.pyplot as plt import seaborn as sns; sns.set() from tqdm import tqdm import pandas as pd import numpy as np from scipy.stats import ttest_ind def perform_intervention(intervention, model, effect_types=('indirect', 'direct')): """Perform intervention and return results for specified ...
9,550
44.265403
142
py
lm-intervention
lm-intervention-master/attention_figures3.py
"""Creates figures showing attention for specific examples, based on JSON files""" import json import math from operator import itemgetter import numpy as np import seaborn as sns import torch from matplotlib import pyplot as plt from transformers import GPT2Model, GPT2Tokenizer BLACK = '#000000' GRAY = '#303030' d...
8,088
38.847291
128
py
lm-intervention
lm-intervention-master/generate_sentences.py
import os import csv from vocab_utils import get_nouns, get_verbs PATH = "vocab/" def get_nouns2(): noun2_list = [] with open(os.path.join(PATH, "noun2.txt"), "r") as noun2_file: for noun2 in noun2_file: noun2s, noun2p = noun2.split() noun2_list.append((noun2s, noun2p)) ret...
3,852
37.148515
102
py
lm-intervention
lm-intervention-master/attention_figures4.py
"""Creates summary figure of various effects for attention intervention from JSON file""" import json import matplotlib as mpl import numpy as np import seaborn as sns from matplotlib import pyplot as plt sns.set() import pandas as pd import os def main(): #models = ['distilgpt2', 'gpt2', 'gpt2-medium', 'gpt2-...
3,438
35.2
125
py
lm-intervention
lm-intervention-master/neuron_experiment_multiple_templates_num_agreement.py
from datetime import datetime import os import sys import random from utils_num_agreement import convert_results_to_pd from experiment_num_agreement import Intervention, Model from transformers import ( GPT2Tokenizer, TransfoXLTokenizer, XLNetTokenizer, BertTokenizer ) from vocab_utils import get_nouns, get_nouns...
6,895
42.64557
123
py
lm-intervention
lm-intervention-master/vocab_utils.py
#!/usr/bin/env python # coding: utf-8 import pandas as pd PATH = 'vocab/' simple = pd.read_csv(PATH + 'simple.txt', sep=' |\t', engine='python', names=['The','noun','verb','number', 'grammaticality','id']) nounpp = pd.read_csv(PATH + 'nounpp.tx...
4,098
32.876033
80
py