max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
scrp/statements.py
DanielJDufour/scrp
0
6615451
<filename>scrp/statements.py from re import IGNORECASE, MULTILINE, search, UNICODE flags = IGNORECASE|MULTILINE|UNICODE def findStatementsUrlsFromSoup(soup, domain): url = findStatementsUrlFromSoup(soup, domain) if url: return [url] def findStatementsUrlFromSoup(soup, domain): href = findStatementsHrefFromSoup(soup) if href: if href.startswith("http"): return href else: return domain + href """ # bas\\u0131n = press in Turkish # bildirisi = statement in Turkish # "b\\u0130ld\\u0130r\\u0130ler\\u0130" has capitalized I's, need to also add lowercase # bildirileri = statements in Turkish # a\\u00e7\\u0131klamalar\\u0131 = releases in Turkish # presse = press in French # \\u0627\\u0644\\u0628\\u064a\\u0627\\u0646\\u0627\\u062a = bayanaat """ def findStatementsHrefFromSoup(soup): terms = ("a\u00e7\u0131klamalar\u0131","bas\u0131n","bildirisi","b\u0130ld\u0130r\u0130ler\u0130","daxuyan\xee","press", "statements", "\u0628\u064a\u0627\u0646\u0627\u062a", "\u0627\u0644\u0635\u062d\u0641\u064a\u0629", "\u0627\u0644\u0635\u062d\u0641\u064a\u0629", "\u0627\u0644\u0628\u064a\u0627\u0646\u0627\u062a \u0627\u0644\u0631\u0633\u0645\u064a\u0629","speeches","\u0628\u064a\u0627\u0646\u0627\u062a \u0627\u0644\u0647\u064a\u0626\u0629", "\u0628\u064a\u0640\u0640\u0627\u0646\u0640\u0627\u062a \u0631\u0633\u0640\u0640\u0640\u0645\u064a\u0640\u0629","\u0052\u0065\u0073\u006d\u0069 \u0041\u00e7\u0131\u006b\u006c\u0061\u006d\u0061\u006c\u0061\u0072","resmi a\xe7\u0131klamalar", "\u0627\u0635\u062f\u0627\u0631\u062a", "\u0627\u0644\u0628\u064a\u0627\u0646\u0627\u062a", "bayanaat", "bayanat", "bayyanat", "comments", "\u062a\u0635\u0631\u064a\u062d\u0627\u062a") hrefs = [] for a in soup.findAll("a", href=True): href = a['href'] #print "href is", href href_lower = href.lower() href_length = len(href_lower) text = a.text.strip().lower() #print "text is", [text] text_length = len(text) if text: for term in terms: if (term in text and len(term) + 10 > text_length) or (term in href_lower and len(href_lower) < 50): if "wordpress" not in text and "wordpress" not in href_lower and href != "#": #print "term is ", [term] hrefs.append(href) #print "hrefs are now", hrefs break hrefs.sort(key=len) if hrefs: return hrefs[0] def findStatementsUrlFromDriver(driver): script = """ var terms = ["a\\u00e7\\u0131klamalar\\u0131","bas\\u0131n","bildirisi","b\\u0130ld\\u0130r\\u0130ler\\u0130","press", "statements", "\\u0627\\u0644\\u0635\\u062d\\u0641\\u064a\\u0629", "\\u0627\\u0644\\u0635\\u062d\\u0641\\u064a\\u0629"]; var a_tags = document.getElementsByTagName('a'); for (var i = 0; i < a_tags.length; i++) { var a_tag = a_tags[i]; var href = a_tag.href; if (href) { var text = a_tag.textContent; for (var t = 0; t < terms.length; t++) { var term = terms[t]; if (href.indexOf(term) + text.indexOf(term) != -2) { if (href.startsWith("http") > -1) { return href; } else { return document.location.origin + href } } } } } """ return driver.execute_script(script)
<filename>scrp/statements.py from re import IGNORECASE, MULTILINE, search, UNICODE flags = IGNORECASE|MULTILINE|UNICODE def findStatementsUrlsFromSoup(soup, domain): url = findStatementsUrlFromSoup(soup, domain) if url: return [url] def findStatementsUrlFromSoup(soup, domain): href = findStatementsHrefFromSoup(soup) if href: if href.startswith("http"): return href else: return domain + href """ # bas\\u0131n = press in Turkish # bildirisi = statement in Turkish # "b\\u0130ld\\u0130r\\u0130ler\\u0130" has capitalized I's, need to also add lowercase # bildirileri = statements in Turkish # a\\u00e7\\u0131klamalar\\u0131 = releases in Turkish # presse = press in French # \\u0627\\u0644\\u0628\\u064a\\u0627\\u0646\\u0627\\u062a = bayanaat """ def findStatementsHrefFromSoup(soup): terms = ("a\u00e7\u0131klamalar\u0131","bas\u0131n","bildirisi","b\u0130ld\u0130r\u0130ler\u0130","daxuyan\xee","press", "statements", "\u0628\u064a\u0627\u0646\u0627\u062a", "\u0627\u0644\u0635\u062d\u0641\u064a\u0629", "\u0627\u0644\u0635\u062d\u0641\u064a\u0629", "\u0627\u0644\u0628\u064a\u0627\u0646\u0627\u062a \u0627\u0644\u0631\u0633\u0645\u064a\u0629","speeches","\u0628\u064a\u0627\u0646\u0627\u062a \u0627\u0644\u0647\u064a\u0626\u0629", "\u0628\u064a\u0640\u0640\u0627\u0646\u0640\u0627\u062a \u0631\u0633\u0640\u0640\u0640\u0645\u064a\u0640\u0629","\u0052\u0065\u0073\u006d\u0069 \u0041\u00e7\u0131\u006b\u006c\u0061\u006d\u0061\u006c\u0061\u0072","resmi a\xe7\u0131klamalar", "\u0627\u0635\u062f\u0627\u0631\u062a", "\u0627\u0644\u0628\u064a\u0627\u0646\u0627\u062a", "bayanaat", "bayanat", "bayyanat", "comments", "\u062a\u0635\u0631\u064a\u062d\u0627\u062a") hrefs = [] for a in soup.findAll("a", href=True): href = a['href'] #print "href is", href href_lower = href.lower() href_length = len(href_lower) text = a.text.strip().lower() #print "text is", [text] text_length = len(text) if text: for term in terms: if (term in text and len(term) + 10 > text_length) or (term in href_lower and len(href_lower) < 50): if "wordpress" not in text and "wordpress" not in href_lower and href != "#": #print "term is ", [term] hrefs.append(href) #print "hrefs are now", hrefs break hrefs.sort(key=len) if hrefs: return hrefs[0] def findStatementsUrlFromDriver(driver): script = """ var terms = ["a\\u00e7\\u0131klamalar\\u0131","bas\\u0131n","bildirisi","b\\u0130ld\\u0130r\\u0130ler\\u0130","press", "statements", "\\u0627\\u0644\\u0635\\u062d\\u0641\\u064a\\u0629", "\\u0627\\u0644\\u0635\\u062d\\u0641\\u064a\\u0629"]; var a_tags = document.getElementsByTagName('a'); for (var i = 0; i < a_tags.length; i++) { var a_tag = a_tags[i]; var href = a_tag.href; if (href) { var text = a_tag.textContent; for (var t = 0; t < terms.length; t++) { var term = terms[t]; if (href.indexOf(term) + text.indexOf(term) != -2) { if (href.startsWith("http") > -1) { return href; } else { return document.location.origin + href } } } } } """ return driver.execute_script(script)
en
0.374364
# bas\\u0131n = press in Turkish # bildirisi = statement in Turkish # "b\\u0130ld\\u0130r\\u0130ler\\u0130" has capitalized I's, need to also add lowercase # bildirileri = statements in Turkish # a\\u00e7\\u0131klamalar\\u0131 = releases in Turkish # presse = press in French # \\u0627\\u0644\\u0628\\u064a\\u0627\\u0646\\u0627\\u062a = bayanaat #print "href is", href #print "text is", [text] #print "term is ", [term] #print "hrefs are now", hrefs var terms = ["a\\u00e7\\u0131klamalar\\u0131","bas\\u0131n","bildirisi","b\\u0130ld\\u0130r\\u0130ler\\u0130","press", "statements", "\\u0627\\u0644\\u0635\\u062d\\u0641\\u064a\\u0629", "\\u0627\\u0644\\u0635\\u062d\\u0641\\u064a\\u0629"]; var a_tags = document.getElementsByTagName('a'); for (var i = 0; i < a_tags.length; i++) { var a_tag = a_tags[i]; var href = a_tag.href; if (href) { var text = a_tag.textContent; for (var t = 0; t < terms.length; t++) { var term = terms[t]; if (href.indexOf(term) + text.indexOf(term) != -2) { if (href.startsWith("http") > -1) { return href; } else { return document.location.origin + href } } } } }
2.652176
3
setup.py
esparta/dbfkit
0
6615452
<reponame>esparta/dbfkit #!/usr/bin/env python # -*- coding: utf-8 -*- import sys from setuptools.command.test import test as TestCommand try: from setuptools import setup except ImportError: from distutils.core import setup README = open('README.rst').read() HISTORY = open('HISTORY.rst').read().replace('.. :changelog:', '') REQUIREMENTS = ['dbf', 'click', ] TEST_REQUIREMENTS = ['pytest', ] class PyTest(TestCommand): """ Mixin to integrate pytest with setup.py """ def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(self.test_args) sys.exit(errcode) setup( name='dbfkit', version='0.2.0', description='DBF for humans', long_description=README + '\n\n' + HISTORY, author='<NAME>', author_email='<EMAIL>', url='https://github.com/esparta/dbfkit', packages=[ 'dbfkit', ], package_dir={'dbfkit': 'dbfkit'}, include_package_data=True, install_requires=REQUIREMENTS, cmdclass={'test': PyTest}, license="Apache Software License", zip_safe=False, keywords='dbfkit', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Database', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities' ], test_suite='dbfkit.test_app', tests_require=TEST_REQUIREMENTS, entry_points=''' [console_scripts] dbf2csv=dbfkit.cli:dbfread ''', )
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from setuptools.command.test import test as TestCommand try: from setuptools import setup except ImportError: from distutils.core import setup README = open('README.rst').read() HISTORY = open('HISTORY.rst').read().replace('.. :changelog:', '') REQUIREMENTS = ['dbf', 'click', ] TEST_REQUIREMENTS = ['pytest', ] class PyTest(TestCommand): """ Mixin to integrate pytest with setup.py """ def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errcode = pytest.main(self.test_args) sys.exit(errcode) setup( name='dbfkit', version='0.2.0', description='DBF for humans', long_description=README + '\n\n' + HISTORY, author='<NAME>', author_email='<EMAIL>', url='https://github.com/esparta/dbfkit', packages=[ 'dbfkit', ], package_dir={'dbfkit': 'dbfkit'}, include_package_data=True, install_requires=REQUIREMENTS, cmdclass={'test': PyTest}, license="Apache Software License", zip_safe=False, keywords='dbfkit', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Database', 'Topic :: Scientific/Engineering :: Information Analysis', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities' ], test_suite='dbfkit.test_app', tests_require=TEST_REQUIREMENTS, entry_points=''' [console_scripts] dbf2csv=dbfkit.cli:dbfread ''', )
en
0.468143
#!/usr/bin/env python # -*- coding: utf-8 -*- Mixin to integrate pytest with setup.py [console_scripts] dbf2csv=dbfkit.cli:dbfread
1.638309
2
homework2/03.py
nosy0411/Object_Oriented_Programming
0
6615453
<reponame>nosy0411/Object_Oriented_Programming import turtle t3 = turtle.Turtle() def draw_triangle(level): # 문제의 조건에 맞게 triangle을 그리려다 보면 한변의 길이를 조정해줘야 해서 새로운 함수를 만들고 길이변수값을 넣어주었다. def draw_fractal(d, level): # 프랙탈 삼각형중 제일 작은 크기의 경우 : base if level == 1: # 채워진 삼각형 그리기 t3.begin_fill() # 밑변, 우변, 좌변의 순으로 그리고 오른쪽 방향으로 본 채 마무리 for i in range(3): t3.forward(d) t3.left(120) t3.end_fill() # leve1>1인 경우 else: # 작은 삼각형(한레벨 아래의 좌하단 삼각형) 부터 그리기(좌하단 작은 삼각형으로 재귀적으로 내려감. level이 하나씩 내려가면 길이는 반이됨.) draw_fractal(d/2, level-1) # 한레벨 아래의 좌하단 삼각형을 그리면 우하단 삼각형을 그리기 위해 좌하단 삼각형의 변만큼 오른쪽으로 이동. t3.forward(d/2) # 한레벨 아래의 우하단 삼각형 그리기. draw_fractal(d/2, level-1) # 좌하단 삼각형을 그린 위치로 돌아옴. t3.backward(d/2) # 중앙 위에 있는 삼각형을 그리기 위해 방향을 잡고 한레벨 아래의 삼각형의 변의 길이만큼 이동. t3.left(60) t3.forward(d/2) # 중앙 위 삼각형을 그리기 위해 우측으로 방향. t3.right(60) # 한레벨 아래의 중앙 위 삼각형 그리기 draw_fractal(d/2, level-1) # 한레벨 아래의 좌하단 삼각형을 그린 위치로 돌아오고 방향은 오른쪽을 바라보게 함. t3.right(120) t3.forward(d/2) t3.left(120) # 도형 크기 d = 300 # 길이 변수 포함한 프랙탈 삼각형 그리기 draw_fractal(d, level) # 함수호출 draw_triangle(level=5) # 일시정지 turtle.done()
import turtle t3 = turtle.Turtle() def draw_triangle(level): # 문제의 조건에 맞게 triangle을 그리려다 보면 한변의 길이를 조정해줘야 해서 새로운 함수를 만들고 길이변수값을 넣어주었다. def draw_fractal(d, level): # 프랙탈 삼각형중 제일 작은 크기의 경우 : base if level == 1: # 채워진 삼각형 그리기 t3.begin_fill() # 밑변, 우변, 좌변의 순으로 그리고 오른쪽 방향으로 본 채 마무리 for i in range(3): t3.forward(d) t3.left(120) t3.end_fill() # leve1>1인 경우 else: # 작은 삼각형(한레벨 아래의 좌하단 삼각형) 부터 그리기(좌하단 작은 삼각형으로 재귀적으로 내려감. level이 하나씩 내려가면 길이는 반이됨.) draw_fractal(d/2, level-1) # 한레벨 아래의 좌하단 삼각형을 그리면 우하단 삼각형을 그리기 위해 좌하단 삼각형의 변만큼 오른쪽으로 이동. t3.forward(d/2) # 한레벨 아래의 우하단 삼각형 그리기. draw_fractal(d/2, level-1) # 좌하단 삼각형을 그린 위치로 돌아옴. t3.backward(d/2) # 중앙 위에 있는 삼각형을 그리기 위해 방향을 잡고 한레벨 아래의 삼각형의 변의 길이만큼 이동. t3.left(60) t3.forward(d/2) # 중앙 위 삼각형을 그리기 위해 우측으로 방향. t3.right(60) # 한레벨 아래의 중앙 위 삼각형 그리기 draw_fractal(d/2, level-1) # 한레벨 아래의 좌하단 삼각형을 그린 위치로 돌아오고 방향은 오른쪽을 바라보게 함. t3.right(120) t3.forward(d/2) t3.left(120) # 도형 크기 d = 300 # 길이 변수 포함한 프랙탈 삼각형 그리기 draw_fractal(d, level) # 함수호출 draw_triangle(level=5) # 일시정지 turtle.done()
ko
1.00007
# 문제의 조건에 맞게 triangle을 그리려다 보면 한변의 길이를 조정해줘야 해서 새로운 함수를 만들고 길이변수값을 넣어주었다. # 프랙탈 삼각형중 제일 작은 크기의 경우 : base # 채워진 삼각형 그리기 # 밑변, 우변, 좌변의 순으로 그리고 오른쪽 방향으로 본 채 마무리 # leve1>1인 경우 # 작은 삼각형(한레벨 아래의 좌하단 삼각형) 부터 그리기(좌하단 작은 삼각형으로 재귀적으로 내려감. level이 하나씩 내려가면 길이는 반이됨.) # 한레벨 아래의 좌하단 삼각형을 그리면 우하단 삼각형을 그리기 위해 좌하단 삼각형의 변만큼 오른쪽으로 이동. # 한레벨 아래의 우하단 삼각형 그리기. # 좌하단 삼각형을 그린 위치로 돌아옴. # 중앙 위에 있는 삼각형을 그리기 위해 방향을 잡고 한레벨 아래의 삼각형의 변의 길이만큼 이동. # 중앙 위 삼각형을 그리기 위해 우측으로 방향. # 한레벨 아래의 중앙 위 삼각형 그리기 # 한레벨 아래의 좌하단 삼각형을 그린 위치로 돌아오고 방향은 오른쪽을 바라보게 함. # 도형 크기 # 길이 변수 포함한 프랙탈 삼각형 그리기 # 함수호출 # 일시정지
3.534841
4
pisa/scripts/scan_allsyst.py
wym109/pisa
0
6615454
<filename>pisa/scripts/scan_allsyst.py #!/usr/bin/env python """ Performs 1D scans over all of the systematics in a pipeline (or multiple pipelines) and saves the output. This is to check the their likelihood spaces. """ from __future__ import absolute_import from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from collections import OrderedDict from os.path import expanduser, expandvars, isfile, join from pisa.analysis.analysis import Analysis from pisa.core.distribution_maker import DistributionMaker from pisa.utils.fileio import from_file, to_file, mkdir from pisa.utils.log import logging, set_verbosity __author__ = '<NAME>, <NAME>, <NAME>' __license__ = '''Copyright (c) 2014-2017, The IceCube Collaboration 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 in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.''' def parse_args(): """Parse command line arguments and return as a dict. Returns ------- kwargs """ parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument( '--template-settings', metavar='CONFIGFILE', required=True, action='append', help='''Settings for generating template distributions; repeat this option to define multiple pipelines.''' ) parser.add_argument( '--steps', type=int, required=True, help='''Provide a number of steps to scan the likelihood space over.''' ) parser.add_argument( '--hypo-param-selections', type=str, nargs='+', required=False, help='''Selection of params to use in order to generate the hypothesised Asimov distributions.''' ) parser.add_argument( '--outdir', required=True, metavar='DIR', type=str, help='Directory into which to store results.' ) parser.add_argument( '--minimizer-settings', type=str, metavar='JSONFILE', required=True, help='''Settings related to the minimizer used in the LLR analysis.''' ) parser.add_argument( '--metric', type=str, choices=['llh', 'chi2', 'conv_llh', 'mod_chi2'], required=True, help='''Settings related to the minimizer used in the LLR analysis.''' ) parser.add_argument( '--debug-mode', type=int, choices=[0, 1, 2], required=False, default=1, help='''How much information to keep in the output file. 0 for only essentials for a physics analysis, 1 for more minimizer history, 2 for whatever can be recorded.''' ) parser.add_argument( '-v', action='count', default=None, help='set verbosity level' ) kwargs = vars(parser.parse_args()) set_verbosity(kwargs.pop('v')) return kwargs def scan_allsyst(template_settings, steps, hypo_param_selections, outdir, minimizer_settings, metric, debug_mode): """Scan (separately) all systematics (i.e., non-fixed params). Parameters ---------- template_settings steps hypo_param_selections outdir minimizer_settings metric debug_mode Returns ------- restults : dict Keys are param names, values are the scan results """ outdir = expanduser(expandvars(outdir)) mkdir(outdir, warn=False) hypo_maker = DistributionMaker(template_settings) hypo_maker.select_params(hypo_param_selections) data_dist = hypo_maker.get_outputs(return_sum=True) minimizer_settings = from_file(minimizer_settings) analysis = Analysis() results = OrderedDict() # pylint: disable=redefined-outer-name for param in hypo_maker.params: if param.is_fixed: continue logging.info('Scanning %s', param.name) nominal_value = param.value outfile = join( outdir, '{:s}_{:d}_steps_{:s}_scan.json'.format(param.name, steps, metric) ) if isfile(outfile): raise IOError('`outfile` "{}" exists, not overwriting.' .format(outfile)) results[param.name] = analysis.scan( data_dist=data_dist, hypo_maker=hypo_maker, hypo_param_selections=hypo_param_selections, metric=metric, param_names=param.name, steps=steps, only_points=None, outer=True, profile=False, minimizer_settings=minimizer_settings, outfile=outfile, debug_mode=debug_mode ) to_file(results[param.name], outfile) param.value = nominal_value logging.info('Done scanning param "%s"', param.name) logging.info('Done.') return results def main(): """Run scan_allsyst with arguments from command line""" return scan_allsyst(**parse_args()) if __name__ == '__main__': results = main() # pylint: disable=invalid-name
<filename>pisa/scripts/scan_allsyst.py #!/usr/bin/env python """ Performs 1D scans over all of the systematics in a pipeline (or multiple pipelines) and saves the output. This is to check the their likelihood spaces. """ from __future__ import absolute_import from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from collections import OrderedDict from os.path import expanduser, expandvars, isfile, join from pisa.analysis.analysis import Analysis from pisa.core.distribution_maker import DistributionMaker from pisa.utils.fileio import from_file, to_file, mkdir from pisa.utils.log import logging, set_verbosity __author__ = '<NAME>, <NAME>, <NAME>' __license__ = '''Copyright (c) 2014-2017, The IceCube Collaboration 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 in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.''' def parse_args(): """Parse command line arguments and return as a dict. Returns ------- kwargs """ parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument( '--template-settings', metavar='CONFIGFILE', required=True, action='append', help='''Settings for generating template distributions; repeat this option to define multiple pipelines.''' ) parser.add_argument( '--steps', type=int, required=True, help='''Provide a number of steps to scan the likelihood space over.''' ) parser.add_argument( '--hypo-param-selections', type=str, nargs='+', required=False, help='''Selection of params to use in order to generate the hypothesised Asimov distributions.''' ) parser.add_argument( '--outdir', required=True, metavar='DIR', type=str, help='Directory into which to store results.' ) parser.add_argument( '--minimizer-settings', type=str, metavar='JSONFILE', required=True, help='''Settings related to the minimizer used in the LLR analysis.''' ) parser.add_argument( '--metric', type=str, choices=['llh', 'chi2', 'conv_llh', 'mod_chi2'], required=True, help='''Settings related to the minimizer used in the LLR analysis.''' ) parser.add_argument( '--debug-mode', type=int, choices=[0, 1, 2], required=False, default=1, help='''How much information to keep in the output file. 0 for only essentials for a physics analysis, 1 for more minimizer history, 2 for whatever can be recorded.''' ) parser.add_argument( '-v', action='count', default=None, help='set verbosity level' ) kwargs = vars(parser.parse_args()) set_verbosity(kwargs.pop('v')) return kwargs def scan_allsyst(template_settings, steps, hypo_param_selections, outdir, minimizer_settings, metric, debug_mode): """Scan (separately) all systematics (i.e., non-fixed params). Parameters ---------- template_settings steps hypo_param_selections outdir minimizer_settings metric debug_mode Returns ------- restults : dict Keys are param names, values are the scan results """ outdir = expanduser(expandvars(outdir)) mkdir(outdir, warn=False) hypo_maker = DistributionMaker(template_settings) hypo_maker.select_params(hypo_param_selections) data_dist = hypo_maker.get_outputs(return_sum=True) minimizer_settings = from_file(minimizer_settings) analysis = Analysis() results = OrderedDict() # pylint: disable=redefined-outer-name for param in hypo_maker.params: if param.is_fixed: continue logging.info('Scanning %s', param.name) nominal_value = param.value outfile = join( outdir, '{:s}_{:d}_steps_{:s}_scan.json'.format(param.name, steps, metric) ) if isfile(outfile): raise IOError('`outfile` "{}" exists, not overwriting.' .format(outfile)) results[param.name] = analysis.scan( data_dist=data_dist, hypo_maker=hypo_maker, hypo_param_selections=hypo_param_selections, metric=metric, param_names=param.name, steps=steps, only_points=None, outer=True, profile=False, minimizer_settings=minimizer_settings, outfile=outfile, debug_mode=debug_mode ) to_file(results[param.name], outfile) param.value = nominal_value logging.info('Done scanning param "%s"', param.name) logging.info('Done.') return results def main(): """Run scan_allsyst with arguments from command line""" return scan_allsyst(**parse_args()) if __name__ == '__main__': results = main() # pylint: disable=invalid-name
en
0.781457
#!/usr/bin/env python Performs 1D scans over all of the systematics in a pipeline (or multiple pipelines) and saves the output. This is to check the their likelihood spaces. Copyright (c) 2014-2017, The IceCube Collaboration 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 in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Parse command line arguments and return as a dict. Returns ------- kwargs Settings for generating template distributions; repeat this option to define multiple pipelines. Provide a number of steps to scan the likelihood space over. Selection of params to use in order to generate the hypothesised Asimov distributions. Settings related to the minimizer used in the LLR analysis. Settings related to the minimizer used in the LLR analysis. How much information to keep in the output file. 0 for only essentials for a physics analysis, 1 for more minimizer history, 2 for whatever can be recorded. Scan (separately) all systematics (i.e., non-fixed params). Parameters ---------- template_settings steps hypo_param_selections outdir minimizer_settings metric debug_mode Returns ------- restults : dict Keys are param names, values are the scan results # pylint: disable=redefined-outer-name Run scan_allsyst with arguments from command line # pylint: disable=invalid-name
2.353683
2
loldib/getratings/models/NA/na_ornn/__init__.py
koliupy/loldib
0
6615455
<reponame>koliupy/loldib from .na_ornn_top import * from .na_ornn_jng import * from .na_ornn_mid import * from .na_ornn_bot import * from .na_ornn_sup import *
from .na_ornn_top import * from .na_ornn_jng import * from .na_ornn_mid import * from .na_ornn_bot import * from .na_ornn_sup import *
none
1
1.087073
1
basinmaker/addattributes/addgaugeattributesqgis.py
dustming/basinmaker
4
6615456
from basinmaker.func.grassgis import * from basinmaker.func.qgis import * from basinmaker.func.pdtable import * from basinmaker.func.rarray import * from basinmaker.utilities.utilities import * import sqlite3 def add_gauge_attributes( grassdb, grass_location, qgis_prefix_path, catinfo, input_geo_names, obs_attributes=[], ): outlet_pt_info = input_geo_names["outlet_pt_info"] snapped_obs_points = input_geo_names["snapped_obs_points"] obsname = "obs" # input_geo_names["obsname"] import grass.script as grass import grass.script.setup as gsetup from grass.pygrass.modules import Module from grass.pygrass.modules.shortcuts import general as g from grass.pygrass.modules.shortcuts import raster as r from grass.script import array as garray from grass.script import core as gcore from grass_session import Session os.environ.update( dict(GRASS_COMPRESS_NULLS="1", GRASS_COMPRESSOR="ZSTD", GRASS_VERBOSE="1") ) PERMANENT = Session() PERMANENT.open(gisdb=grassdb, location=grass_location, create_opts="") con = sqlite3.connect( os.path.join(grassdb, grass_location, "PERMANENT", "sqlite", "sqlite.db") ) grass.run_command( "v.what.rast", map=outlet_pt_info, raster=obsname, column="obsid_pour", ) grass.run_command( "v.out.ogr", input=outlet_pt_info, output=os.path.join(grassdb, outlet_pt_info + ".shp"), format="ESRI_Shapefile", overwrite=True, quiet="Ture", ) ### read catchment sqlstat = "SELECT SubId,obsid_pour FROM %s" % (outlet_pt_info,) outletinfo = pd.read_sql_query(sqlstat, con) outletinfo = outletinfo.fillna(-9999) outletinfo = outletinfo.loc[outletinfo["obsid_pour"] > 0] sqlstat = "SELECT %s,%s,%s,%s,%s FROM %s" % ( obs_attributes[0], obs_attributes[1], obs_attributes[2], obs_attributes[3], obs_attributes[0] + "n", snapped_obs_points, ) gaugeinfo = pd.read_sql_query(sqlstat, con) gaugeinfo = gaugeinfo.fillna(-9999) for i in range(0, len(outletinfo)): catid = outletinfo["SubId"].values[i] obsid = outletinfo["obsid_pour"].values[i] catrow = catinfo["SubId"] == catid subgaugeinfo = gaugeinfo.loc[gaugeinfo[obs_attributes[0] + "n"] == obsid] catinfo.loc[catrow, "Has_Gauge"] = obsid if obsid > 79000: continue if len(subgaugeinfo) > 0: catinfo.loc[catrow, "Has_Gauge"] = subgaugeinfo[obs_attributes[0]].values[0] catinfo.loc[catrow, "DA_Obs"] = subgaugeinfo[obs_attributes[2]].values[0] catinfo.loc[catrow, "Obs_NM"] = subgaugeinfo[obs_attributes[1]].values[0] catinfo.loc[catrow, "SRC_obs"] = subgaugeinfo[obs_attributes[3]].values[0] PERMANENT.close() return catinfo
from basinmaker.func.grassgis import * from basinmaker.func.qgis import * from basinmaker.func.pdtable import * from basinmaker.func.rarray import * from basinmaker.utilities.utilities import * import sqlite3 def add_gauge_attributes( grassdb, grass_location, qgis_prefix_path, catinfo, input_geo_names, obs_attributes=[], ): outlet_pt_info = input_geo_names["outlet_pt_info"] snapped_obs_points = input_geo_names["snapped_obs_points"] obsname = "obs" # input_geo_names["obsname"] import grass.script as grass import grass.script.setup as gsetup from grass.pygrass.modules import Module from grass.pygrass.modules.shortcuts import general as g from grass.pygrass.modules.shortcuts import raster as r from grass.script import array as garray from grass.script import core as gcore from grass_session import Session os.environ.update( dict(GRASS_COMPRESS_NULLS="1", GRASS_COMPRESSOR="ZSTD", GRASS_VERBOSE="1") ) PERMANENT = Session() PERMANENT.open(gisdb=grassdb, location=grass_location, create_opts="") con = sqlite3.connect( os.path.join(grassdb, grass_location, "PERMANENT", "sqlite", "sqlite.db") ) grass.run_command( "v.what.rast", map=outlet_pt_info, raster=obsname, column="obsid_pour", ) grass.run_command( "v.out.ogr", input=outlet_pt_info, output=os.path.join(grassdb, outlet_pt_info + ".shp"), format="ESRI_Shapefile", overwrite=True, quiet="Ture", ) ### read catchment sqlstat = "SELECT SubId,obsid_pour FROM %s" % (outlet_pt_info,) outletinfo = pd.read_sql_query(sqlstat, con) outletinfo = outletinfo.fillna(-9999) outletinfo = outletinfo.loc[outletinfo["obsid_pour"] > 0] sqlstat = "SELECT %s,%s,%s,%s,%s FROM %s" % ( obs_attributes[0], obs_attributes[1], obs_attributes[2], obs_attributes[3], obs_attributes[0] + "n", snapped_obs_points, ) gaugeinfo = pd.read_sql_query(sqlstat, con) gaugeinfo = gaugeinfo.fillna(-9999) for i in range(0, len(outletinfo)): catid = outletinfo["SubId"].values[i] obsid = outletinfo["obsid_pour"].values[i] catrow = catinfo["SubId"] == catid subgaugeinfo = gaugeinfo.loc[gaugeinfo[obs_attributes[0] + "n"] == obsid] catinfo.loc[catrow, "Has_Gauge"] = obsid if obsid > 79000: continue if len(subgaugeinfo) > 0: catinfo.loc[catrow, "Has_Gauge"] = subgaugeinfo[obs_attributes[0]].values[0] catinfo.loc[catrow, "DA_Obs"] = subgaugeinfo[obs_attributes[2]].values[0] catinfo.loc[catrow, "Obs_NM"] = subgaugeinfo[obs_attributes[1]].values[0] catinfo.loc[catrow, "SRC_obs"] = subgaugeinfo[obs_attributes[3]].values[0] PERMANENT.close() return catinfo
en
0.371981
# input_geo_names["obsname"] ### read catchment
1.914943
2
python/spinn/rae_spinn.py
woojinchung/lms
3
6615457
import itertools import copy import numpy as np from spinn import util # PyTorch import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import torch.optim as optim from spinn.util.blocks import Reduce from spinn.util.blocks import LSTMState, Embed, MLP from spinn.util.blocks import bundle, unbundle, to_cpu, to_gpu, treelstm, lstm from spinn.util.blocks import get_h, get_c from spinn.util.misc import Args, Vocab, Example from spinn.fat_stack import BaseModel as _BaseModel from spinn.fat_stack import SPINN from spinn.data import T_SHIFT, T_REDUCE, T_SKIP, T_STRUCT def build_model(data_manager, initial_embeddings, vocab_size, num_classes, FLAGS): model_cls = BaseModel use_sentence_pair = data_manager.SENTENCE_PAIR_DATA return model_cls(model_dim=FLAGS.model_dim, word_embedding_dim=FLAGS.word_embedding_dim, vocab_size=vocab_size, initial_embeddings=initial_embeddings, num_classes=num_classes, mlp_dim=FLAGS.mlp_dim, embedding_keep_rate=FLAGS.embedding_keep_rate, classifier_keep_rate=FLAGS.semantic_classifier_keep_rate, tracking_lstm_hidden_dim=FLAGS.tracking_lstm_hidden_dim, transition_weight=FLAGS.transition_weight, encode_style=FLAGS.encode_style, encode_reverse=FLAGS.encode_reverse, encode_bidirectional=FLAGS.encode_bidirectional, encode_num_layers=FLAGS.encode_num_layers, use_sentence_pair=use_sentence_pair, lateral_tracking=FLAGS.lateral_tracking, use_tracking_in_composition=FLAGS.use_tracking_in_composition, predict_use_cell=FLAGS.predict_use_cell, use_lengths=FLAGS.use_lengths, use_difference_feature=FLAGS.use_difference_feature, use_product_feature=FLAGS.use_product_feature, num_mlp_layers=FLAGS.num_mlp_layers, mlp_bn=FLAGS.mlp_bn, predict_leaf=FLAGS.predict_leaf, ) class RAESPINN(SPINN): def __init__(self, args, vocab, predict_use_cell, use_lengths, predict_leaf): super(RAESPINN, self).__init__(args, vocab, predict_use_cell, use_lengths) model_dim = args.size * 2 self.decompose = nn.Linear(model_dim, model_dim * 2) # Predict whether a node is a leaf or not. self.predict_leaf = predict_leaf if self.predict_leaf: self.leaf = nn.Linear(model_dim, 2) def reduce_phase_hook(self, lefts, rights, trackings, reduce_stacks): if len(reduce_stacks) > 0: for left, right, stack in zip(lefts, rights, reduce_stacks): new_stack_item = stack[-1] new_stack_item.isleaf = False new_stack_item.left = left new_stack_item.right = right if not hasattr(left, 'isleaf'): left.isleaf = True if not hasattr(right, 'isleaf'): right.isleaf = True def reconstruct(self, roots): """ Recursively build variables for Reconstruction Loss. """ if len(roots) == 0: return [], [] LR = F.tanh(self.decompose(torch.cat(roots, 0))) left, right = torch.chunk(LR, 2, 1) lefts = torch.chunk(left, len(roots), 0) rights = torch.chunk(right, len(roots), 0) done = [] new_roots = [] extra = [] for L, R, root in zip(lefts, rights, roots): done.append((L, root.left.data)) done.append((R, root.right.data)) if not root.left.isleaf: new_roots.append(root.left) if not root.right.isleaf: new_roots.append(root.right) if self.predict_leaf: extra.append((L, root.left.isleaf)) extra.append((R, root.right.isleaf)) child_done, child_extra = self.reconstruct(new_roots) return done + child_done, extra + child_extra def leaf_phase(self, inp, target): inp = torch.cat(inp, 0) target = Variable(torch.LongTensor(target), volatile=not self.training) outp = self.leaf(inp) logits = F.log_softmax(outp) self.leaf_loss = nn.NLLLoss()(logits, target) preds = logits.data.max(1)[1] self.leaf_acc = preds.eq(target.data).sum() / float(preds.size(0)) def loss_phase_hook(self): if self.training: # only calculate reconstruction loss during train time. done, extra = self.reconstruct([stack[-1] for stack in self.stacks if not stack[-1].isleaf]) inp, target = zip(*done) inp = torch.cat(inp, 0) target = Variable(torch.cat(target, 0), volatile=not self.training) similarity = Variable(torch.ones(inp.size(0)), volatile=not self.training) self.rae_loss = nn.CosineEmbeddingLoss()(inp, target, similarity) if self.predict_leaf: leaf_inp, leaf_target = zip(*extra) self.leaf_phase(leaf_inp, leaf_target) class BaseModel(_BaseModel): def __init__(self, predict_leaf=None, **kwargs): self.predict_leaf = predict_leaf super(BaseModel, self).__init__(**kwargs) def build_spinn(self, args, vocab, predict_use_cell, use_lengths): return RAESPINN(args, vocab, predict_use_cell, use_lengths, self.predict_leaf)
import itertools import copy import numpy as np from spinn import util # PyTorch import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import torch.optim as optim from spinn.util.blocks import Reduce from spinn.util.blocks import LSTMState, Embed, MLP from spinn.util.blocks import bundle, unbundle, to_cpu, to_gpu, treelstm, lstm from spinn.util.blocks import get_h, get_c from spinn.util.misc import Args, Vocab, Example from spinn.fat_stack import BaseModel as _BaseModel from spinn.fat_stack import SPINN from spinn.data import T_SHIFT, T_REDUCE, T_SKIP, T_STRUCT def build_model(data_manager, initial_embeddings, vocab_size, num_classes, FLAGS): model_cls = BaseModel use_sentence_pair = data_manager.SENTENCE_PAIR_DATA return model_cls(model_dim=FLAGS.model_dim, word_embedding_dim=FLAGS.word_embedding_dim, vocab_size=vocab_size, initial_embeddings=initial_embeddings, num_classes=num_classes, mlp_dim=FLAGS.mlp_dim, embedding_keep_rate=FLAGS.embedding_keep_rate, classifier_keep_rate=FLAGS.semantic_classifier_keep_rate, tracking_lstm_hidden_dim=FLAGS.tracking_lstm_hidden_dim, transition_weight=FLAGS.transition_weight, encode_style=FLAGS.encode_style, encode_reverse=FLAGS.encode_reverse, encode_bidirectional=FLAGS.encode_bidirectional, encode_num_layers=FLAGS.encode_num_layers, use_sentence_pair=use_sentence_pair, lateral_tracking=FLAGS.lateral_tracking, use_tracking_in_composition=FLAGS.use_tracking_in_composition, predict_use_cell=FLAGS.predict_use_cell, use_lengths=FLAGS.use_lengths, use_difference_feature=FLAGS.use_difference_feature, use_product_feature=FLAGS.use_product_feature, num_mlp_layers=FLAGS.num_mlp_layers, mlp_bn=FLAGS.mlp_bn, predict_leaf=FLAGS.predict_leaf, ) class RAESPINN(SPINN): def __init__(self, args, vocab, predict_use_cell, use_lengths, predict_leaf): super(RAESPINN, self).__init__(args, vocab, predict_use_cell, use_lengths) model_dim = args.size * 2 self.decompose = nn.Linear(model_dim, model_dim * 2) # Predict whether a node is a leaf or not. self.predict_leaf = predict_leaf if self.predict_leaf: self.leaf = nn.Linear(model_dim, 2) def reduce_phase_hook(self, lefts, rights, trackings, reduce_stacks): if len(reduce_stacks) > 0: for left, right, stack in zip(lefts, rights, reduce_stacks): new_stack_item = stack[-1] new_stack_item.isleaf = False new_stack_item.left = left new_stack_item.right = right if not hasattr(left, 'isleaf'): left.isleaf = True if not hasattr(right, 'isleaf'): right.isleaf = True def reconstruct(self, roots): """ Recursively build variables for Reconstruction Loss. """ if len(roots) == 0: return [], [] LR = F.tanh(self.decompose(torch.cat(roots, 0))) left, right = torch.chunk(LR, 2, 1) lefts = torch.chunk(left, len(roots), 0) rights = torch.chunk(right, len(roots), 0) done = [] new_roots = [] extra = [] for L, R, root in zip(lefts, rights, roots): done.append((L, root.left.data)) done.append((R, root.right.data)) if not root.left.isleaf: new_roots.append(root.left) if not root.right.isleaf: new_roots.append(root.right) if self.predict_leaf: extra.append((L, root.left.isleaf)) extra.append((R, root.right.isleaf)) child_done, child_extra = self.reconstruct(new_roots) return done + child_done, extra + child_extra def leaf_phase(self, inp, target): inp = torch.cat(inp, 0) target = Variable(torch.LongTensor(target), volatile=not self.training) outp = self.leaf(inp) logits = F.log_softmax(outp) self.leaf_loss = nn.NLLLoss()(logits, target) preds = logits.data.max(1)[1] self.leaf_acc = preds.eq(target.data).sum() / float(preds.size(0)) def loss_phase_hook(self): if self.training: # only calculate reconstruction loss during train time. done, extra = self.reconstruct([stack[-1] for stack in self.stacks if not stack[-1].isleaf]) inp, target = zip(*done) inp = torch.cat(inp, 0) target = Variable(torch.cat(target, 0), volatile=not self.training) similarity = Variable(torch.ones(inp.size(0)), volatile=not self.training) self.rae_loss = nn.CosineEmbeddingLoss()(inp, target, similarity) if self.predict_leaf: leaf_inp, leaf_target = zip(*extra) self.leaf_phase(leaf_inp, leaf_target) class BaseModel(_BaseModel): def __init__(self, predict_leaf=None, **kwargs): self.predict_leaf = predict_leaf super(BaseModel, self).__init__(**kwargs) def build_spinn(self, args, vocab, predict_use_cell, use_lengths): return RAESPINN(args, vocab, predict_use_cell, use_lengths, self.predict_leaf)
en
0.890637
# PyTorch # Predict whether a node is a leaf or not. Recursively build variables for Reconstruction Loss. # only calculate reconstruction loss during train time.
1.925837
2
etest_test/fixtures_test/scripts_test/7d982739ef8348d48935d14cb74f160d.py
alunduil/etest
6
6615458
"""Function definition.""" import textwrap from etest_test.fixtures_test.scripts_test import SCRIPTS _ = { "uuid": "7d982739ef8348d48935d14cb74f160d", "description": "function definition", "text": textwrap.dedent( """ python_test() { nosetests || die "Tests failed under ${EPYTHON}" } """, ), "symbols": {}, "correct": None, } SCRIPTS.setdefault("all", []).append(_) SCRIPTS.setdefault("bash", []).append(_)
"""Function definition.""" import textwrap from etest_test.fixtures_test.scripts_test import SCRIPTS _ = { "uuid": "7d982739ef8348d48935d14cb74f160d", "description": "function definition", "text": textwrap.dedent( """ python_test() { nosetests || die "Tests failed under ${EPYTHON}" } """, ), "symbols": {}, "correct": None, } SCRIPTS.setdefault("all", []).append(_) SCRIPTS.setdefault("bash", []).append(_)
en
0.58526
Function definition. python_test() { nosetests || die "Tests failed under ${EPYTHON}" }
1.921487
2
Controllers/rounds_controller.py
HaroldHaldemann/ChessTournament
0
6615459
<gh_stars>0 import Views import Models from .utils import Util from datetime import datetime from copy import deepcopy class RoundController: @staticmethod def check_number_rounds(tournament, number_rounds): """ Check the number of rounds Redirect to first round view """ if number_rounds == "": number_rounds = 4 else: if not number_rounds.isdigit(): print("Nombre de tours invalide") Views.RoundView.def_number_rounds(tournament) if not (0 < int(number_rounds) < 8): print("Nombre de tours invalide") Views.RoundView.def_number_rounds(tournament) tournament.number_rounds = int(number_rounds) Views.RoundView.create_first_round(tournament) @staticmethod def create_first_round(tournament, response): """ Check the response of the corresponding view Redirect to start_round view """ options = { "1": [Models.Round.create_first_round, tournament.players], "2": Views.MenuView.main_menu, } if not Util.check_response(len(options), response): Views.RoundView.create_first_round(tournament) round = Util.call_options(options, response) Views.RoundView.start_round(tournament, round) @staticmethod def create_new_round(tournament, round): """ Assign round.name Calls the method to create a new round Redirect to start_round view """ round.create_new_round() round.name = f"Round {len(tournament.rounds) + 1}" Views.RoundView.start_round(tournament, round) @staticmethod def start_round(tournament, round, response): """ Check the response of the corresponding view Assign round.date_start Redirect to end_round view """ options = { "1": [datetime.now().strftime, "%Y-%m-%d, %H:%M:%S"], } if not Util.check_response(len(options), response): Views.RoundView.start_round(tournament, round) round.date_start = Util.call_options(options, response) Views.RoundView.end_round(tournament, round) @staticmethod def end_round(tournament, round, response): """ Check the response of the corresponding view Assign round.date_end Redirect to results_round view """ options = { "1": [datetime.now().strftime, "%Y-%m-%d, %H:%M:%S"], } if not Util.check_response(len(options), response): Views.RoundView.end_round(tournament, round) round.date_end = Util.call_options(options, response) Views.RoundView.results_round(tournament, round, 0) @staticmethod def results_round(tournament, round, step, response): """ Check the response of the corresponding view Assign the given results to round.matches Redirect to results_round view if unfinished Redirect to confirm_round view if finished """ options = { "1": (1, 0), "2": (0, 1), "3": (0.5, 0.5), } if not Util.check_response(len(options), response): Views.RoundView.results_round(tournament, round, step) round.matches[step].score1 += options[response][0] round.matches[step].score2 += options[response][1] step += 1 if step == 4: Views.RoundView.confirm_round(tournament, round) Views.RoundView.results_round(tournament, round, step) @classmethod def confirm_round(cls, tournament, ROUND, response): """ Check the response of the corresponfding view Add tournament to db Redirect to choson view if unfinished Redirect to end_tournament view if finished """ options = { "1": [tournament.rounds.append, ROUND], "2": [tournament.rounds.append, ROUND], "3": Views.MenuView.main_menu, } if not Util.check_response(len(options), response): Views.RoundView.confirm_round(tournament, ROUND) Util.call_options(options, response) tournament.add_to_db() if response == "2": Views.MenuView.main_menu() if len(tournament.rounds) == tournament.number_rounds: tournament.finished = True tournament.add_to_db() winners = tournament.define_winners() Views.RoundView.end_tournament(tournament, winners) else: round = deepcopy(ROUND) cls.create_new_round(tournament, round) @staticmethod def end_tournament(tournament, winners, response): """ Check the response of the corresponding view Redirect to chosen view """ all_players = Models.Player.get_all_players() options = { "1": [Views.PlayerView.load_player, all_players], "2": Views.MenuView.main_menu, } if not Util.check_response(len(options), response): Views.RoundView.end_tournament(tournament, winners) Util.call_options(options, response)
import Views import Models from .utils import Util from datetime import datetime from copy import deepcopy class RoundController: @staticmethod def check_number_rounds(tournament, number_rounds): """ Check the number of rounds Redirect to first round view """ if number_rounds == "": number_rounds = 4 else: if not number_rounds.isdigit(): print("Nombre de tours invalide") Views.RoundView.def_number_rounds(tournament) if not (0 < int(number_rounds) < 8): print("Nombre de tours invalide") Views.RoundView.def_number_rounds(tournament) tournament.number_rounds = int(number_rounds) Views.RoundView.create_first_round(tournament) @staticmethod def create_first_round(tournament, response): """ Check the response of the corresponding view Redirect to start_round view """ options = { "1": [Models.Round.create_first_round, tournament.players], "2": Views.MenuView.main_menu, } if not Util.check_response(len(options), response): Views.RoundView.create_first_round(tournament) round = Util.call_options(options, response) Views.RoundView.start_round(tournament, round) @staticmethod def create_new_round(tournament, round): """ Assign round.name Calls the method to create a new round Redirect to start_round view """ round.create_new_round() round.name = f"Round {len(tournament.rounds) + 1}" Views.RoundView.start_round(tournament, round) @staticmethod def start_round(tournament, round, response): """ Check the response of the corresponding view Assign round.date_start Redirect to end_round view """ options = { "1": [datetime.now().strftime, "%Y-%m-%d, %H:%M:%S"], } if not Util.check_response(len(options), response): Views.RoundView.start_round(tournament, round) round.date_start = Util.call_options(options, response) Views.RoundView.end_round(tournament, round) @staticmethod def end_round(tournament, round, response): """ Check the response of the corresponding view Assign round.date_end Redirect to results_round view """ options = { "1": [datetime.now().strftime, "%Y-%m-%d, %H:%M:%S"], } if not Util.check_response(len(options), response): Views.RoundView.end_round(tournament, round) round.date_end = Util.call_options(options, response) Views.RoundView.results_round(tournament, round, 0) @staticmethod def results_round(tournament, round, step, response): """ Check the response of the corresponding view Assign the given results to round.matches Redirect to results_round view if unfinished Redirect to confirm_round view if finished """ options = { "1": (1, 0), "2": (0, 1), "3": (0.5, 0.5), } if not Util.check_response(len(options), response): Views.RoundView.results_round(tournament, round, step) round.matches[step].score1 += options[response][0] round.matches[step].score2 += options[response][1] step += 1 if step == 4: Views.RoundView.confirm_round(tournament, round) Views.RoundView.results_round(tournament, round, step) @classmethod def confirm_round(cls, tournament, ROUND, response): """ Check the response of the corresponfding view Add tournament to db Redirect to choson view if unfinished Redirect to end_tournament view if finished """ options = { "1": [tournament.rounds.append, ROUND], "2": [tournament.rounds.append, ROUND], "3": Views.MenuView.main_menu, } if not Util.check_response(len(options), response): Views.RoundView.confirm_round(tournament, ROUND) Util.call_options(options, response) tournament.add_to_db() if response == "2": Views.MenuView.main_menu() if len(tournament.rounds) == tournament.number_rounds: tournament.finished = True tournament.add_to_db() winners = tournament.define_winners() Views.RoundView.end_tournament(tournament, winners) else: round = deepcopy(ROUND) cls.create_new_round(tournament, round) @staticmethod def end_tournament(tournament, winners, response): """ Check the response of the corresponding view Redirect to chosen view """ all_players = Models.Player.get_all_players() options = { "1": [Views.PlayerView.load_player, all_players], "2": Views.MenuView.main_menu, } if not Util.check_response(len(options), response): Views.RoundView.end_tournament(tournament, winners) Util.call_options(options, response)
en
0.868369
Check the number of rounds Redirect to first round view Check the response of the corresponding view Redirect to start_round view Assign round.name Calls the method to create a new round Redirect to start_round view Check the response of the corresponding view Assign round.date_start Redirect to end_round view Check the response of the corresponding view Assign round.date_end Redirect to results_round view Check the response of the corresponding view Assign the given results to round.matches Redirect to results_round view if unfinished Redirect to confirm_round view if finished Check the response of the corresponfding view Add tournament to db Redirect to choson view if unfinished Redirect to end_tournament view if finished Check the response of the corresponding view Redirect to chosen view
2.975222
3
src/catas/dbcan.py
ccdmb/catastrophy
2
6615460
from catas.data import Version DBCAN_URLS = { Version.v4: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-old@UGA/dbCAN-fam-HMMs.txt.v4", # noqa Version.v5: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-old@UGA/dbCAN-fam-HMMs.txt.v5", # noqa Version.v6: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-HMMdb-V6.txt", # noqa Version.v7: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-HMMdb-V7.txt", # noqa Version.v8: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-HMMdb-V8.txt", # noqa Version.v9: "https://bcb.unl.edu/dbCAN2/download/dbCAN-HMMdb-V9.txt", Version.v10: "https://bcb.unl.edu/dbCAN2/download/dbCAN-HMMdb-V10.txt", } def download_file(url: str, destination: str) -> None: import requests response = requests.get(url) response.raise_for_status() with open(destination, "wb") as handle: for chunk in response.iter_content(chunk_size=256): handle.write(chunk) return
from catas.data import Version DBCAN_URLS = { Version.v4: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-old@UGA/dbCAN-fam-HMMs.txt.v4", # noqa Version.v5: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-old@UGA/dbCAN-fam-HMMs.txt.v5", # noqa Version.v6: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-HMMdb-V6.txt", # noqa Version.v7: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-HMMdb-V7.txt", # noqa Version.v8: "http://bcb.unl.edu/dbCAN2/download/Databases/dbCAN-HMMdb-V8.txt", # noqa Version.v9: "https://bcb.unl.edu/dbCAN2/download/dbCAN-HMMdb-V9.txt", Version.v10: "https://bcb.unl.edu/dbCAN2/download/dbCAN-HMMdb-V10.txt", } def download_file(url: str, destination: str) -> None: import requests response = requests.get(url) response.raise_for_status() with open(destination, "wb") as handle: for chunk in response.iter_content(chunk_size=256): handle.write(chunk) return
uz
0.44857
# noqa # noqa # noqa # noqa # noqa
2.446376
2
gregorian.py
martindisch/pytry
0
6615461
# Checks for leap-years while 1: year = input("What's the year? ") if year == 0: break if year % 400 == 0 or year % 4 == 0 and year % 100 != 0: print("You got yourself a leap-year!") else: print("No luck with that...") print "\nPlease come again!\n"
# Checks for leap-years while 1: year = input("What's the year? ") if year == 0: break if year % 400 == 0 or year % 4 == 0 and year % 100 != 0: print("You got yourself a leap-year!") else: print("No luck with that...") print "\nPlease come again!\n"
en
0.944362
# Checks for leap-years
3.972777
4
posts/views.py
dmcrobin/Django-Blog
0
6615462
from django.shortcuts import render, redirect from django.views import generic from .forms import PostsForm from .models import Posts class PostView(generic.ListView): queryset = Posts.objects.filter(status=1).order_by("-post_date") template_name = "index.html" class DetailView(generic.DetailView): model = Posts template_name = "post_detail.html" # def addPost(request): # form = PostsForm() # return render(request, "add.html", {'form' : form}) def index(request): form = PostsForm() if(request.method == "POST"): # print(request.POST) qry = request.POST.copy() print(qry['body']) title = qry['title'] slug = title.lower().replace(" ", "-") qry['slug'] = slug qry['status'] = "1" form = PostsForm(qry) if(form.is_valid()): print("SAVED POST!") form.save() return redirect('/') else: print("ERORR", form.errors) return render(request, "add.html", {"form" : form}) def editPost(request, slug): post = Posts.objects.get(slug=slug) form = PostsForm() # print(form) if(request.method == "POST"): # print(request.POST) qry = request.POST.copy() print(qry['body']) title = qry['title'] slug = title.lower().replace(" ", "-") qry['slug'] = slug qry['status'] = "1" form = PostsForm(instance=post, data=qry) print("SAVED POST!") form.save() return redirect(f'/{slug}') else: form = PostsForm(instance=post) print(form) return render(request, "edit_post.html", {"form" : form, 'post' : post}) def delPost(request, slug): post = Posts.objects.get(slug=slug) if request.method == "POST": post.delete() return redirect('/') else: return render(request, "confirm.html")
from django.shortcuts import render, redirect from django.views import generic from .forms import PostsForm from .models import Posts class PostView(generic.ListView): queryset = Posts.objects.filter(status=1).order_by("-post_date") template_name = "index.html" class DetailView(generic.DetailView): model = Posts template_name = "post_detail.html" # def addPost(request): # form = PostsForm() # return render(request, "add.html", {'form' : form}) def index(request): form = PostsForm() if(request.method == "POST"): # print(request.POST) qry = request.POST.copy() print(qry['body']) title = qry['title'] slug = title.lower().replace(" ", "-") qry['slug'] = slug qry['status'] = "1" form = PostsForm(qry) if(form.is_valid()): print("SAVED POST!") form.save() return redirect('/') else: print("ERORR", form.errors) return render(request, "add.html", {"form" : form}) def editPost(request, slug): post = Posts.objects.get(slug=slug) form = PostsForm() # print(form) if(request.method == "POST"): # print(request.POST) qry = request.POST.copy() print(qry['body']) title = qry['title'] slug = title.lower().replace(" ", "-") qry['slug'] = slug qry['status'] = "1" form = PostsForm(instance=post, data=qry) print("SAVED POST!") form.save() return redirect(f'/{slug}') else: form = PostsForm(instance=post) print(form) return render(request, "edit_post.html", {"form" : form, 'post' : post}) def delPost(request, slug): post = Posts.objects.get(slug=slug) if request.method == "POST": post.delete() return redirect('/') else: return render(request, "confirm.html")
en
0.425009
# def addPost(request): # form = PostsForm() # return render(request, "add.html", {'form' : form}) # print(request.POST) # print(form) # print(request.POST)
2.251804
2
utils.py
cpeng365/ModuleServer
2
6615463
<gh_stars>1-10 import os, time, json, sys, traceback, socket if sys.version_info[0] > 2: import urllib.parse as urllib else: import urllib class timeout(IOError): pass class BadRequest(Exception): pass def modified(path): # Check modification from mtime and hash of contents # First call will return True changed = False mtime = os.path.getmtime(path) try: check_config = modified.last[path] except: check_config = (None,None) if mtime != check_config[0]: time.sleep(0.1) # Allow OS to finish writing with open(path,'rb') as fid: f_hash = hash(fid.read()) if f_hash != check_config[1]: changed = True modified.last[path] = (mtime,f_hash) return changed modified.last = {} # Initialize def recv(connection,delim=b'\n',recv_buffer=4096,time_out=1,validate_exists=[]): buffer = b'' tstart = time.time() while time.time() - tstart < time_out: try: data = connection.recv(recv_buffer) except socket.timeout: raise except IOError as err: if err.errno in [35, 10035]: # Resource temporarily unavailable, Timeout time.sleep(0.01) continue raise if not data: raise IOError('Client disconnected while receiving.') buffer += data if data[-1:] == delim: msg = buffer[0:-len(delim)].decode('utf-8') # Remove delim try: msg = urllib.unquote_plus(msg) msg = json.loads(msg) except Exception as err: raise Exception('Failed to decode msg: "%s"'%(msg,)) for field in validate_exists: if field not in msg: raise BadRequest('"%s" field missing from request.'%field) return msg raise timeout('Did not receive all client data in timeout period (%g seconds). Make sure terminated with "\\n".\nPartial message: "%s"'% \ (time_out,urllib.unquote_plus(buffer.decode('utf-8')))) def send(connection,resp='',delim=b'\n',error=False): # error -> either True/False or an Exception object tb_formatted = '' if error: # Anything but empty, 0, or False if error is True: # Use current exception to print traceback exc = sys.exc_info()[1] # exc_info returns (type,exc,traceback) else: # error is some Exception object, so use that exc = error tb_formatted = ''.join(traceback.format_exception(None,exc,exc.__traceback__)) resp = json.dumps({'response':resp,'error':bool(error),'traceback':tb_formatted}) connection.sendall(bytes(urllib.quote_plus(resp),'utf-8')+delim)
import os, time, json, sys, traceback, socket if sys.version_info[0] > 2: import urllib.parse as urllib else: import urllib class timeout(IOError): pass class BadRequest(Exception): pass def modified(path): # Check modification from mtime and hash of contents # First call will return True changed = False mtime = os.path.getmtime(path) try: check_config = modified.last[path] except: check_config = (None,None) if mtime != check_config[0]: time.sleep(0.1) # Allow OS to finish writing with open(path,'rb') as fid: f_hash = hash(fid.read()) if f_hash != check_config[1]: changed = True modified.last[path] = (mtime,f_hash) return changed modified.last = {} # Initialize def recv(connection,delim=b'\n',recv_buffer=4096,time_out=1,validate_exists=[]): buffer = b'' tstart = time.time() while time.time() - tstart < time_out: try: data = connection.recv(recv_buffer) except socket.timeout: raise except IOError as err: if err.errno in [35, 10035]: # Resource temporarily unavailable, Timeout time.sleep(0.01) continue raise if not data: raise IOError('Client disconnected while receiving.') buffer += data if data[-1:] == delim: msg = buffer[0:-len(delim)].decode('utf-8') # Remove delim try: msg = urllib.unquote_plus(msg) msg = json.loads(msg) except Exception as err: raise Exception('Failed to decode msg: "%s"'%(msg,)) for field in validate_exists: if field not in msg: raise BadRequest('"%s" field missing from request.'%field) return msg raise timeout('Did not receive all client data in timeout period (%g seconds). Make sure terminated with "\\n".\nPartial message: "%s"'% \ (time_out,urllib.unquote_plus(buffer.decode('utf-8')))) def send(connection,resp='',delim=b'\n',error=False): # error -> either True/False or an Exception object tb_formatted = '' if error: # Anything but empty, 0, or False if error is True: # Use current exception to print traceback exc = sys.exc_info()[1] # exc_info returns (type,exc,traceback) else: # error is some Exception object, so use that exc = error tb_formatted = ''.join(traceback.format_exception(None,exc,exc.__traceback__)) resp = json.dumps({'response':resp,'error':bool(error),'traceback':tb_formatted}) connection.sendall(bytes(urllib.quote_plus(resp),'utf-8')+delim)
en
0.68288
# Check modification from mtime and hash of contents # First call will return True # Allow OS to finish writing # Initialize # Resource temporarily unavailable, Timeout # Remove delim # error -> either True/False or an Exception object # Anything but empty, 0, or False # Use current exception to print traceback # exc_info returns (type,exc,traceback) # error is some Exception object, so use that
2.766659
3
modules/ToxNet_21_Prep2D.py
Lenaxiao/ToxNet-Project
4
6615464
# coding: utf-8 # In[1]: import sys sys.path.insert(0, '../chem_scripts') # add path to chem_scripts import pandas as pd import numpy as np import os from rdkit import Chem # In[2]: homedir = os.path.dirname(os.path.realpath('__file__')) homedir = homedir+"/data/" archdir = homedir+"/archive/" # In[3]: from chem_scripts import cs_compute_features, cs_set_resolution, cs_coords_to_grid, cs_check_grid_boundary from chem_scripts import cs_channel_mapping, cs_map_atom_to_grid, cs_map_bond_to_grid, cs_grid_to_image # In[4]: def gen_image(): exclusion_list = [] full_array_list = [] for i in range(0,df.shape[0]): # Extract SMILES string smiles_string = df["smiles"][i] #print(i, smiles_string) # Extract ID of molecule id_string = df["id"][i] # Read SMILES string mol = Chem.MolFromSmiles(smiles_string) # Compute properties mol, df_atom, df_bond, nancheckflag = cs_compute_features(mol) # Intialize grid myarray = cs_set_resolution(gridsize, representation=rep) # Map coordinates to grid df_atom, atomcheckflag = cs_coords_to_grid(df_atom, dim, res) # Check if outside grid sizecheckflag = cs_check_grid_boundary(df_atom, gridsize) if sizecheckflag == True or atomcheckflag == True or nancheckflag == True: exclusion_list.append(id_string) print("EXCLUSION for "+str(id_string)) else: # Initialize channels channel = cs_channel_mapping() # Map atom to grid myarray = cs_map_atom_to_grid(myarray, channel, df_atom, representation=rep) # Map bond to grid myarray = cs_map_bond_to_grid(myarray, channel, df_atom, df_bond, representation=rep) # Visualize status every 1000 steps if (i+1)%nskip==0: print("*** PROCESSING "+str(i+1)+": "+str(id_string)+" "+str(smiles_string)) cs_grid_to_image(myarray, mol) # Generate combined array of raw input curr_array = myarray.flatten() curr_array_list = curr_array.tolist() full_array_list.append(curr_array_list) full_array = np.asarray(full_array_list) print(full_array.shape) print(exclusion_list) return(full_array, exclusion_list) # # Running image preparation # In[5]: dim = 40 # Size of the box in Angstroms, not radius! res = 0.5 # Resolution of each pixel rep = "engA" # Image representation used nskip = 500 # How many steps till next visualization gridsize = int(dim/res) # In[6]: # Specify dataset name jobname = "tox_niehs_int" taskname = ["verytoxic", "nontoxic", "epa", "ghs", "logld50"] for task in taskname: print("PROCESSING TASK: "+str(jobname)+" "+str(task)) # Specify input and output csv filein = homedir+jobname+"_"+task+".csv" fileout = homedir+jobname+"_"+task+"_image.csv" # Specify out npy files fileimage = archdir+jobname+"_"+task+"_img_"+rep+".npy" filelabel = archdir+jobname+"_"+task+"_img_label.npy" # Generate image df = pd.read_csv(filein) full_array, exclusion_list = gen_image() # Dataset statistics before and after image generation print("*** Database Specs:") print(df.shape[0], len(exclusion_list), int(df.shape[0])-int(len(exclusion_list))) # Create csv of final data (after exclusion) print("*** Separating Database:") mod_df = df[~df["id"].isin(exclusion_list)] mod_df.to_csv(fileout, index=False) # Save generated images as npy np.save(fileimage, full_array) print(full_array.shape) # Save labels as npy label_array = mod_df[task].as_matrix().astype("float32") np.save(filelabel, label_array) print(label_array.shape) # In[7]: # Specify dataset name jobname = "tox_niehs_tv" taskname = ["verytoxic", "nontoxic", "epa", "ghs", "logld50"] for task in taskname: print("PROCESSING TASK: "+str(jobname)+" "+str(task)) # Specify input and output csv filein = homedir+jobname+"_"+task+".csv" fileout = homedir+jobname+"_"+task+"_image.csv" # Specify out npy files fileimage = archdir+jobname+"_"+task+"_img_"+rep+".npy" filelabel = archdir+jobname+"_"+task+"_img_label.npy" # Generate image df = pd.read_csv(filein) full_array, exclusion_list = gen_image() # Dataset statistics before and after image generation print("*** Database Specs:") print(df.shape[0], len(exclusion_list), int(df.shape[0])-int(len(exclusion_list))) # Create csv of final data (after exclusion) print("*** Separating Database:") mod_df = df[~df["id"].isin(exclusion_list)] mod_df.to_csv(fileout, index=False) # Save generated images as npy np.save(fileimage, full_array) print(full_array.shape) # Save labels as npy label_array = mod_df[task].as_matrix().astype("float32") np.save(filelabel, label_array) print(label_array.shape)
# coding: utf-8 # In[1]: import sys sys.path.insert(0, '../chem_scripts') # add path to chem_scripts import pandas as pd import numpy as np import os from rdkit import Chem # In[2]: homedir = os.path.dirname(os.path.realpath('__file__')) homedir = homedir+"/data/" archdir = homedir+"/archive/" # In[3]: from chem_scripts import cs_compute_features, cs_set_resolution, cs_coords_to_grid, cs_check_grid_boundary from chem_scripts import cs_channel_mapping, cs_map_atom_to_grid, cs_map_bond_to_grid, cs_grid_to_image # In[4]: def gen_image(): exclusion_list = [] full_array_list = [] for i in range(0,df.shape[0]): # Extract SMILES string smiles_string = df["smiles"][i] #print(i, smiles_string) # Extract ID of molecule id_string = df["id"][i] # Read SMILES string mol = Chem.MolFromSmiles(smiles_string) # Compute properties mol, df_atom, df_bond, nancheckflag = cs_compute_features(mol) # Intialize grid myarray = cs_set_resolution(gridsize, representation=rep) # Map coordinates to grid df_atom, atomcheckflag = cs_coords_to_grid(df_atom, dim, res) # Check if outside grid sizecheckflag = cs_check_grid_boundary(df_atom, gridsize) if sizecheckflag == True or atomcheckflag == True or nancheckflag == True: exclusion_list.append(id_string) print("EXCLUSION for "+str(id_string)) else: # Initialize channels channel = cs_channel_mapping() # Map atom to grid myarray = cs_map_atom_to_grid(myarray, channel, df_atom, representation=rep) # Map bond to grid myarray = cs_map_bond_to_grid(myarray, channel, df_atom, df_bond, representation=rep) # Visualize status every 1000 steps if (i+1)%nskip==0: print("*** PROCESSING "+str(i+1)+": "+str(id_string)+" "+str(smiles_string)) cs_grid_to_image(myarray, mol) # Generate combined array of raw input curr_array = myarray.flatten() curr_array_list = curr_array.tolist() full_array_list.append(curr_array_list) full_array = np.asarray(full_array_list) print(full_array.shape) print(exclusion_list) return(full_array, exclusion_list) # # Running image preparation # In[5]: dim = 40 # Size of the box in Angstroms, not radius! res = 0.5 # Resolution of each pixel rep = "engA" # Image representation used nskip = 500 # How many steps till next visualization gridsize = int(dim/res) # In[6]: # Specify dataset name jobname = "tox_niehs_int" taskname = ["verytoxic", "nontoxic", "epa", "ghs", "logld50"] for task in taskname: print("PROCESSING TASK: "+str(jobname)+" "+str(task)) # Specify input and output csv filein = homedir+jobname+"_"+task+".csv" fileout = homedir+jobname+"_"+task+"_image.csv" # Specify out npy files fileimage = archdir+jobname+"_"+task+"_img_"+rep+".npy" filelabel = archdir+jobname+"_"+task+"_img_label.npy" # Generate image df = pd.read_csv(filein) full_array, exclusion_list = gen_image() # Dataset statistics before and after image generation print("*** Database Specs:") print(df.shape[0], len(exclusion_list), int(df.shape[0])-int(len(exclusion_list))) # Create csv of final data (after exclusion) print("*** Separating Database:") mod_df = df[~df["id"].isin(exclusion_list)] mod_df.to_csv(fileout, index=False) # Save generated images as npy np.save(fileimage, full_array) print(full_array.shape) # Save labels as npy label_array = mod_df[task].as_matrix().astype("float32") np.save(filelabel, label_array) print(label_array.shape) # In[7]: # Specify dataset name jobname = "tox_niehs_tv" taskname = ["verytoxic", "nontoxic", "epa", "ghs", "logld50"] for task in taskname: print("PROCESSING TASK: "+str(jobname)+" "+str(task)) # Specify input and output csv filein = homedir+jobname+"_"+task+".csv" fileout = homedir+jobname+"_"+task+"_image.csv" # Specify out npy files fileimage = archdir+jobname+"_"+task+"_img_"+rep+".npy" filelabel = archdir+jobname+"_"+task+"_img_label.npy" # Generate image df = pd.read_csv(filein) full_array, exclusion_list = gen_image() # Dataset statistics before and after image generation print("*** Database Specs:") print(df.shape[0], len(exclusion_list), int(df.shape[0])-int(len(exclusion_list))) # Create csv of final data (after exclusion) print("*** Separating Database:") mod_df = df[~df["id"].isin(exclusion_list)] mod_df.to_csv(fileout, index=False) # Save generated images as npy np.save(fileimage, full_array) print(full_array.shape) # Save labels as npy label_array = mod_df[task].as_matrix().astype("float32") np.save(filelabel, label_array) print(label_array.shape)
en
0.571354
# coding: utf-8 # In[1]: # add path to chem_scripts # In[2]: # In[3]: # In[4]: # Extract SMILES string #print(i, smiles_string) # Extract ID of molecule # Read SMILES string # Compute properties # Intialize grid # Map coordinates to grid # Check if outside grid # Initialize channels # Map atom to grid # Map bond to grid # Visualize status every 1000 steps # Generate combined array of raw input # # Running image preparation # In[5]: # Size of the box in Angstroms, not radius! # Resolution of each pixel # Image representation used # How many steps till next visualization # In[6]: # Specify dataset name # Specify input and output csv # Specify out npy files # Generate image # Dataset statistics before and after image generation # Create csv of final data (after exclusion) # Save generated images as npy # Save labels as npy # In[7]: # Specify dataset name # Specify input and output csv # Specify out npy files # Generate image # Dataset statistics before and after image generation # Create csv of final data (after exclusion) # Save generated images as npy # Save labels as npy
2.406857
2
scripts/pgindextocsv.py
umairacheema/authorship-attribution
0
6615465
<reponame>umairacheema/authorship-attribution #!/usr/bin/env python #Utility script to convert Gutenberg data index file to CSV #Gutenberg data when downloaded from pgiso.pglaf.org comes with #index file containing metadata about downloaded eBooks #This utility script converts that metadata into CSV format import sys import codecs import re import os import csv from bs4 import BeautifulSoup #Function : print_help #Purpose : Function to display help message def print_help(): print "Usage :"+sys.argv[0]+" <path to index.htm file> + <base url>" print " Where index.htm file is the index file downloaded via pgiso.pglaf.org" print " and base url is the path prefix to be appended to retrieve URL" #Function : get_book_name #Purpose : Retrieves book name from the raw text def get_book_name(raw): if raw is not None: pattern = '[^a-zA-Z0-9_ ]' prog = re.compile(pattern) raw = prog.sub('', raw) return raw else: return "Unknown" #Function : get_author_name #Purpose : Retrieves author's first and last name from the raw text def get_author_name(raw): if raw is not None: raw = raw.replace(';',',') pattern = '[^a-zA-Z, ]' prog = re.compile(pattern) raw = prog.sub('',raw) raw = raw.strip() names = raw.strip(',') names = names.split(',') if len(names)>1: return names[1]+ " " + names[0] elif len(names)==1: return names[0] else: return "Unknown" #Function : get_modified_url #Purpose : If user provides custom base url add that to # file name def get_modified_url(original,custom_base): url_parts = original.split('/') return custom_base + '/' + url_parts[2] + '/' + url_parts[3] #Function : get_book_records #Purpose : Function to retrieve book record def get_book_records(file,base_url): book_records = [] url = "" author_name = "" book_name = "" try: fh_index_file = codecs.open(file,'r','utf-8') index_data = fh_index_file.read() except IOError as e: print "I/O Error".format(e.errno, e.strerror) sys.exit(2) soup = BeautifulSoup(index_data,'html.parser') for link in soup.find_all('a',href=True): #skip useless links if link['href'] == '' or link['href'].startswith('#'): continue url = link.string if base_url is not None: url = get_modified_url(url,base_url) etext = link.find_previous_sibling('font',text='EText-No.').next_sibling book_name = get_book_name(link.find_previous_sibling('font',text='Title:').next_sibling) author_name=get_author_name(link.find_previous_sibling('font',text='Author:').next_sibling) book_records.append({'etext':etext,'author':author_name.strip().strip('of ').lower(),'book':book_name.strip().lower(),'url':url.strip()}) return book_records #Function : write_csv_file #Purpose : Writes book records to csv file def write_csv_file(book_records): if os.path.exists('pgindex.csv'): os.remove('pgindex.csv') with open('pgindex.csv', 'w') as csvfile: fieldnames = ['etext', 'author','book','url'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for record in book_records: writer.writerow(record) #Check input arguments if (len(sys.argv) < 2): print_help() sys.exit(1) base_url = None if (len(sys.argv) == 3): base_url = sys.argv[2] book_records_ = get_book_records(sys.argv[1],base_url) write_csv_file(book_records_)
#!/usr/bin/env python #Utility script to convert Gutenberg data index file to CSV #Gutenberg data when downloaded from pgiso.pglaf.org comes with #index file containing metadata about downloaded eBooks #This utility script converts that metadata into CSV format import sys import codecs import re import os import csv from bs4 import BeautifulSoup #Function : print_help #Purpose : Function to display help message def print_help(): print "Usage :"+sys.argv[0]+" <path to index.htm file> + <base url>" print " Where index.htm file is the index file downloaded via pgiso.pglaf.org" print " and base url is the path prefix to be appended to retrieve URL" #Function : get_book_name #Purpose : Retrieves book name from the raw text def get_book_name(raw): if raw is not None: pattern = '[^a-zA-Z0-9_ ]' prog = re.compile(pattern) raw = prog.sub('', raw) return raw else: return "Unknown" #Function : get_author_name #Purpose : Retrieves author's first and last name from the raw text def get_author_name(raw): if raw is not None: raw = raw.replace(';',',') pattern = '[^a-zA-Z, ]' prog = re.compile(pattern) raw = prog.sub('',raw) raw = raw.strip() names = raw.strip(',') names = names.split(',') if len(names)>1: return names[1]+ " " + names[0] elif len(names)==1: return names[0] else: return "Unknown" #Function : get_modified_url #Purpose : If user provides custom base url add that to # file name def get_modified_url(original,custom_base): url_parts = original.split('/') return custom_base + '/' + url_parts[2] + '/' + url_parts[3] #Function : get_book_records #Purpose : Function to retrieve book record def get_book_records(file,base_url): book_records = [] url = "" author_name = "" book_name = "" try: fh_index_file = codecs.open(file,'r','utf-8') index_data = fh_index_file.read() except IOError as e: print "I/O Error".format(e.errno, e.strerror) sys.exit(2) soup = BeautifulSoup(index_data,'html.parser') for link in soup.find_all('a',href=True): #skip useless links if link['href'] == '' or link['href'].startswith('#'): continue url = link.string if base_url is not None: url = get_modified_url(url,base_url) etext = link.find_previous_sibling('font',text='EText-No.').next_sibling book_name = get_book_name(link.find_previous_sibling('font',text='Title:').next_sibling) author_name=get_author_name(link.find_previous_sibling('font',text='Author:').next_sibling) book_records.append({'etext':etext,'author':author_name.strip().strip('of ').lower(),'book':book_name.strip().lower(),'url':url.strip()}) return book_records #Function : write_csv_file #Purpose : Writes book records to csv file def write_csv_file(book_records): if os.path.exists('pgindex.csv'): os.remove('pgindex.csv') with open('pgindex.csv', 'w') as csvfile: fieldnames = ['etext', 'author','book','url'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for record in book_records: writer.writerow(record) #Check input arguments if (len(sys.argv) < 2): print_help() sys.exit(1) base_url = None if (len(sys.argv) == 3): base_url = sys.argv[2] book_records_ = get_book_records(sys.argv[1],base_url) write_csv_file(book_records_)
en
0.575495
#!/usr/bin/env python #Utility script to convert Gutenberg data index file to CSV #Gutenberg data when downloaded from pgiso.pglaf.org comes with #index file containing metadata about downloaded eBooks #This utility script converts that metadata into CSV format #Function : print_help #Purpose : Function to display help message #Function : get_book_name #Purpose : Retrieves book name from the raw text #Function : get_author_name #Purpose : Retrieves author's first and last name from the raw text #Function : get_modified_url #Purpose : If user provides custom base url add that to # file name #Function : get_book_records #Purpose : Function to retrieve book record #skip useless links #Function : write_csv_file #Purpose : Writes book records to csv file #Check input arguments
3.671247
4
aqmt/plot/colors.py
L4STeam/aqmt
7
6615466
<reponame>L4STeam/aqmt BLUE = "#001E90FF" LILAC = "#007570B3" RED = "#00FF0000" BLACK = "#00333333" GREEN = "#0066A61E" GRAY = "#00666666" CC_DCTCP = BLUE CC_CUBIC = RED CC_RENO = RED CC_CUBIC_ECN = BLACK L4S = BLUE CLASSIC = RED AGGR = GREEN CLASS_NOECT = '#00E7298A' CLASS_ECT0 = '#00333333' CLASS_ECT1 = '#00666666' CLASS_UNKNOWN_UDP = GRAY UNKNOWN = "#00D2691E" DROPS_CLASSIC = RED DROPS_L4S = BLUE MARKS_L4S = GRAY title_map = ( ('cubic-ecn', CC_CUBIC_ECN), ('ecn-cubic', CC_CUBIC_ECN), ('cubic', CC_CUBIC), ('dctcp', CC_DCTCP), ('reno', CC_RENO), ('ect(1)', CLASS_ECT1), ('ect(0)', CLASS_ECT0), ('udp=non ect', CLASS_NOECT), ('udp', CLASS_UNKNOWN_UDP), ('other', UNKNOWN), ) def get_from_tagname(title): title = title.lower() for key, value in title_map: if key in title: return value return UNKNOWN
BLUE = "#001E90FF" LILAC = "#007570B3" RED = "#00FF0000" BLACK = "#00333333" GREEN = "#0066A61E" GRAY = "#00666666" CC_DCTCP = BLUE CC_CUBIC = RED CC_RENO = RED CC_CUBIC_ECN = BLACK L4S = BLUE CLASSIC = RED AGGR = GREEN CLASS_NOECT = '#00E7298A' CLASS_ECT0 = '#00333333' CLASS_ECT1 = '#00666666' CLASS_UNKNOWN_UDP = GRAY UNKNOWN = "#00D2691E" DROPS_CLASSIC = RED DROPS_L4S = BLUE MARKS_L4S = GRAY title_map = ( ('cubic-ecn', CC_CUBIC_ECN), ('ecn-cubic', CC_CUBIC_ECN), ('cubic', CC_CUBIC), ('dctcp', CC_DCTCP), ('reno', CC_RENO), ('ect(1)', CLASS_ECT1), ('ect(0)', CLASS_ECT0), ('udp=non ect', CLASS_NOECT), ('udp', CLASS_UNKNOWN_UDP), ('other', UNKNOWN), ) def get_from_tagname(title): title = title.lower() for key, value in title_map: if key in title: return value return UNKNOWN
none
1
2.293046
2
src/multi_digit/display_image.py
pitsios-s/SVHN-Thesis
6
6615467
<gh_stars>1-10 import h5py from matplotlib import pyplot as plt import numpy as np # Index of image to display index = 0 # Read file h5_plain = h5py.File("../../res/processed/plain_5/train.h5") h5_normalized = h5py.File("../../res/processed/normalized_5/train.h5") h5_gray = h5py.File("../../res/processed/gray_5/train.h5") # Load image image_plain = h5_plain["train_dataset"][index] image_normalized = h5_normalized["train_dataset"][index] image_gray = h5_gray["train_dataset"][index] # Print Label print(h5_plain["train_labels"][index]) # Plot all four images fig, ax = plt.subplots(1, 3) ax[0].imshow(image_plain, interpolation="nearest") ax[1].imshow(image_normalized, interpolation="nearest") ax[2].imshow(np.squeeze(image_gray), cmap="gray", interpolation="nearest") plt.show()
import h5py from matplotlib import pyplot as plt import numpy as np # Index of image to display index = 0 # Read file h5_plain = h5py.File("../../res/processed/plain_5/train.h5") h5_normalized = h5py.File("../../res/processed/normalized_5/train.h5") h5_gray = h5py.File("../../res/processed/gray_5/train.h5") # Load image image_plain = h5_plain["train_dataset"][index] image_normalized = h5_normalized["train_dataset"][index] image_gray = h5_gray["train_dataset"][index] # Print Label print(h5_plain["train_labels"][index]) # Plot all four images fig, ax = plt.subplots(1, 3) ax[0].imshow(image_plain, interpolation="nearest") ax[1].imshow(image_normalized, interpolation="nearest") ax[2].imshow(np.squeeze(image_gray), cmap="gray", interpolation="nearest") plt.show()
en
0.790733
# Index of image to display # Read file # Load image # Print Label # Plot all four images
2.85908
3
lmctl/project/handlers/brent/__init__.py
manojn97/lmctl
3
6615468
from .brent_content import BrentContentHandlerDelegate, BrentPkgContentTree from .brent_src import BrentSourceHandlerDelegate, BrentSourceCreatorDelegate, BrentSourceTree, BrentStagedSourceHandlerDelegate source_creator = BrentSourceCreatorDelegate source_handler = BrentSourceHandlerDelegate content_handler = BrentContentHandlerDelegate source_tree = BrentSourceTree staged_source_handler = BrentStagedSourceHandlerDelegate package_content = BrentPkgContentTree
from .brent_content import BrentContentHandlerDelegate, BrentPkgContentTree from .brent_src import BrentSourceHandlerDelegate, BrentSourceCreatorDelegate, BrentSourceTree, BrentStagedSourceHandlerDelegate source_creator = BrentSourceCreatorDelegate source_handler = BrentSourceHandlerDelegate content_handler = BrentContentHandlerDelegate source_tree = BrentSourceTree staged_source_handler = BrentStagedSourceHandlerDelegate package_content = BrentPkgContentTree
none
1
1.069063
1
plugins/leccion1.py
segoitz-guibert/botBasicoGlitch
0
6615469
<filename>plugins/leccion1.py from config import * # Inicio leccion 1- 19/07/2018 # Variable que se utilizará en el comando /start para enviarlo como el texto del mensaje del bot bot_text = ''' Howdy, how are you doing? Source code on https://glitch.com/~{} '''.format(environ['PROJECT_NAME']) @bot.message_handler(commands=['start', 'help']) # Comando /start o /help . Cuando un usuario escriba cualquiera de los comandos def send_welcome(message): bot.reply_to(message, bot_text) # El bot responde con el contenido de la variable bot_text al mensaje. @bot.message_handler(commands=['ayuda']) # Ejemplo de comando /ayuda que en vez de pasarle una variable, directamente escribimos def ayuda(message): bot.reply_to(message, 'ahora mismo te ayudo') # El bot responde 'ahora mismo te ayudo' al mensaje @bot.message_handler(func=lambda message: True) # Respuestas del bot def echo_message(message): cid = message.chat.id # Guardamos en la variale cid el id de el mensaje recibido idUsu = message.from_user.id if "ban" in message.text.lower().split() : bot.send_message(cid, 'estas ban') if message.text.lower() == "holi": # Comparamos el texto el mensaje si es igual a 'holi' id = message.from_user.id # Guardamos en una variable el id del usuario que envió el mensaje nombre = message.from_user.first_name # Guardamos en una variable el nombre del usuario que envió el mensaje bot.send_message(cid, 'holi ' + nombre ) # El bot responde 'holi' y después el nombre del usuario que guardamos en la variable da arriba if id == 239822769: # Comparamos el id guardado del usuario con un id que le hemos pasado bot.send_message( cid, 'Hola mi creador 😙') # Si es igual responde el mensaje que hemos introducido al chat indicado elif id == 270803389 : # En este caso el id lo comparamos con otra id diferente bot.send_message( cid, '<NAME>') # Aquí envia al chat que le hemos hablado '<NAME>' bot.send_message( 115659666, '<NAME>') # Aquí probamos a pasarle en vez de cid, un id de un usuario y le enviará el mensaje por mensaje #privado else: # Si no se da ninguno de los resultados de arriba hará lo siguiente: bot.send_message( cid, 'No estás registrado') # Enviará por el chat el mensaje 'No estás registrado' elif message.text.lower() == "mensaje": # Aquí probamos un if comparandolo con un String(una cadena de carácteres) bot.send_message( cid, 'mensaje') # Si es así contestará 'mensaje' #Fin charla 1 - 19/07/218
<filename>plugins/leccion1.py from config import * # Inicio leccion 1- 19/07/2018 # Variable que se utilizará en el comando /start para enviarlo como el texto del mensaje del bot bot_text = ''' Howdy, how are you doing? Source code on https://glitch.com/~{} '''.format(environ['PROJECT_NAME']) @bot.message_handler(commands=['start', 'help']) # Comando /start o /help . Cuando un usuario escriba cualquiera de los comandos def send_welcome(message): bot.reply_to(message, bot_text) # El bot responde con el contenido de la variable bot_text al mensaje. @bot.message_handler(commands=['ayuda']) # Ejemplo de comando /ayuda que en vez de pasarle una variable, directamente escribimos def ayuda(message): bot.reply_to(message, 'ahora mismo te ayudo') # El bot responde 'ahora mismo te ayudo' al mensaje @bot.message_handler(func=lambda message: True) # Respuestas del bot def echo_message(message): cid = message.chat.id # Guardamos en la variale cid el id de el mensaje recibido idUsu = message.from_user.id if "ban" in message.text.lower().split() : bot.send_message(cid, 'estas ban') if message.text.lower() == "holi": # Comparamos el texto el mensaje si es igual a 'holi' id = message.from_user.id # Guardamos en una variable el id del usuario que envió el mensaje nombre = message.from_user.first_name # Guardamos en una variable el nombre del usuario que envió el mensaje bot.send_message(cid, 'holi ' + nombre ) # El bot responde 'holi' y después el nombre del usuario que guardamos en la variable da arriba if id == 239822769: # Comparamos el id guardado del usuario con un id que le hemos pasado bot.send_message( cid, 'Hola mi creador 😙') # Si es igual responde el mensaje que hemos introducido al chat indicado elif id == 270803389 : # En este caso el id lo comparamos con otra id diferente bot.send_message( cid, '<NAME>') # Aquí envia al chat que le hemos hablado '<NAME>' bot.send_message( 115659666, '<NAME>') # Aquí probamos a pasarle en vez de cid, un id de un usuario y le enviará el mensaje por mensaje #privado else: # Si no se da ninguno de los resultados de arriba hará lo siguiente: bot.send_message( cid, 'No estás registrado') # Enviará por el chat el mensaje 'No estás registrado' elif message.text.lower() == "mensaje": # Aquí probamos un if comparandolo con un String(una cadena de carácteres) bot.send_message( cid, 'mensaje') # Si es así contestará 'mensaje' #Fin charla 1 - 19/07/218
es
0.976013
# Inicio leccion 1- 19/07/2018 # Variable que se utilizará en el comando /start para enviarlo como el texto del mensaje del bot Howdy, how are you doing? Source code on https://glitch.com/~{} # Comando /start o /help . Cuando un usuario escriba cualquiera de los comandos # El bot responde con el contenido de la variable bot_text al mensaje. # Ejemplo de comando /ayuda que en vez de pasarle una variable, directamente escribimos # El bot responde 'ahora mismo te ayudo' al mensaje # Respuestas del bot # Guardamos en la variale cid el id de el mensaje recibido # Comparamos el texto el mensaje si es igual a 'holi' # Guardamos en una variable el id del usuario que envió el mensaje # Guardamos en una variable el nombre del usuario que envió el mensaje # El bot responde 'holi' y después el nombre del usuario que guardamos en la variable da arriba # Comparamos el id guardado del usuario con un id que le hemos pasado # Si es igual responde el mensaje que hemos introducido al chat indicado # En este caso el id lo comparamos con otra id diferente # Aquí envia al chat que le hemos hablado '<NAME>' # Aquí probamos a pasarle en vez de cid, un id de un usuario y le enviará el mensaje por mensaje #privado # Si no se da ninguno de los resultados de arriba hará lo siguiente: # Enviará por el chat el mensaje 'No estás registrado' # Aquí probamos un if comparandolo con un String(una cadena de carácteres) # Si es así contestará 'mensaje' #Fin charla 1 - 19/07/218
2.750757
3
polaris/polaris/tests/processes/test_create_stellar_deposit.py
brunopedrazza/django-polaris
0
6615470
<reponame>brunopedrazza/django-polaris import pytest import json from unittest.mock import patch, Mock, MagicMock from stellar_sdk import Keypair from stellar_sdk.account import Account, Thresholds from stellar_sdk.client.response import Response from stellar_sdk.exceptions import NotFoundError, BaseHorizonError from polaris.tests.conftest import ( STELLAR_ACCOUNT_1, USD_DISTRIBUTION_SEED, ETH_DISTRIBUTION_SEED, ETH_ISSUER_ACCOUNT, USD_ISSUER_ACCOUNT, ) from polaris.tests.sep24.test_deposit import ( HORIZON_SUCCESS_RESPONSE, HORIZON_SUCCESS_RESPONSE_CLAIM, ) from polaris.utils import create_stellar_deposit from polaris.models import Transaction @pytest.mark.django_db def test_bad_status(acc1_usd_deposit_transaction_factory): deposit = acc1_usd_deposit_transaction_factory() with pytest.raises(ValueError): create_stellar_deposit(deposit) def mock_load_account_no_account(account_id): if isinstance(account_id, Keypair): account_id = account_id.public_key if account_id not in [ Keypair.from_secret(v).public_key for v in [USD_DISTRIBUTION_SEED, ETH_DISTRIBUTION_SEED] ]: raise NotFoundError( response=Response( status_code=404, headers={}, url="", text=json.dumps(dict(status=404)) ) ) account = Account(account_id, 1) account.signers = [] account.thresholds = Thresholds(0, 0, 0) return ( account, [ { "balances": [ {"asset_code": "USD", "asset_issuer": USD_ISSUER_ACCOUNT}, {"asset_code": "ETH", "asset_issuer": ETH_ISSUER_ACCOUNT}, ] } ], ) def mock_get_account_obj(account_id): try: return mock_load_account_no_account(account_id=account_id) except NotFoundError as e: raise RuntimeError(str(e)) mock_server_no_account = Mock( accounts=Mock( return_value=Mock( account_id=Mock(return_value=Mock(call=Mock(return_value={"balances": []}))) ) ), load_account=mock_load_account_no_account, submit_transaction=Mock(return_value=HORIZON_SUCCESS_RESPONSE), fetch_base_fee=Mock(return_value=100), ) channel_account_kp = Keypair.random() channel_account = Account(channel_account_kp.public_key, 1) channel_account.signers = [] channel_account.thresholds = Thresholds(0, 0, 0) mock_account = Account(STELLAR_ACCOUNT_1, 1) mock_account.signers = [ {"key": STELLAR_ACCOUNT_1, "weight": 1, "type": "ed25519_public_key"} ] mock_account.thresholds = Thresholds(low_threshold=0, med_threshold=1, high_threshold=1) @pytest.mark.django_db @patch( "polaris.utils.settings.HORIZON_SERVER", Mock( load_account=Mock(return_value=mock_account), submit_transaction=Mock(return_value=HORIZON_SUCCESS_RESPONSE), fetch_base_fee=Mock(return_value=100), ), ) @patch( "polaris.utils.get_account_obj", Mock( return_value=( mock_account, {"balances": [{"asset_code": "USD", "asset_issuer": USD_ISSUER_ACCOUNT}]}, ) ), ) def test_deposit_stellar_success(acc1_usd_deposit_transaction_factory): """ `create_stellar_deposit` succeeds if the provided transaction's `stellar_account` has a trustline to the issuer for its `asset`, and the Stellar transaction completes successfully. All of these conditions and actions are mocked in this test to avoid network calls. """ deposit = acc1_usd_deposit_transaction_factory() deposit.status = Transaction.STATUS.pending_anchor deposit.save() assert create_stellar_deposit(deposit) assert Transaction.objects.get(id=deposit.id).status == Transaction.STATUS.completed mock_server_no_trust_account_claim = Mock( accounts=Mock( return_value=Mock( account_id=Mock(return_value=Mock(call=Mock(return_value={"balances": []}))) ) ), load_account=mock_account, submit_transaction=Mock(return_value=HORIZON_SUCCESS_RESPONSE_CLAIM), fetch_base_fee=Mock(return_value=100), ) @pytest.mark.django_db @patch( "polaris.utils.get_account_obj", Mock(return_value=(mock_account, {"balances": []})) ) @patch("polaris.utils.settings.HORIZON_SERVER", mock_server_no_trust_account_claim) def test_deposit_stellar_no_trustline_with_claimable_bal( acc1_usd_deposit_transaction_factory, ): """ This is the flow when a wallet/client submits a deposit and the sends "claimable_balance_supported=True" in their POST request body. Such that the deposit transaction is can continue as a claimable balance operation rather than a payment operation `execute_deposits` from `poll_pending_deposits.py` if the provided transaction's Stellar account has no trustline and sees claimable_balance_supported set to True. it will create_stellar_deposit() where it wil complete the deposit flow as a claimable balance """ deposit = acc1_usd_deposit_transaction_factory() deposit.status = Transaction.STATUS.pending_anchor deposit.claimable_balance_supported = True deposit.save() assert create_stellar_deposit(deposit) assert Transaction.objects.get(id=deposit.id).claimable_balance_id assert Transaction.objects.get(id=deposit.id).status == Transaction.STATUS.completed
import pytest import json from unittest.mock import patch, Mock, MagicMock from stellar_sdk import Keypair from stellar_sdk.account import Account, Thresholds from stellar_sdk.client.response import Response from stellar_sdk.exceptions import NotFoundError, BaseHorizonError from polaris.tests.conftest import ( STELLAR_ACCOUNT_1, USD_DISTRIBUTION_SEED, ETH_DISTRIBUTION_SEED, ETH_ISSUER_ACCOUNT, USD_ISSUER_ACCOUNT, ) from polaris.tests.sep24.test_deposit import ( HORIZON_SUCCESS_RESPONSE, HORIZON_SUCCESS_RESPONSE_CLAIM, ) from polaris.utils import create_stellar_deposit from polaris.models import Transaction @pytest.mark.django_db def test_bad_status(acc1_usd_deposit_transaction_factory): deposit = acc1_usd_deposit_transaction_factory() with pytest.raises(ValueError): create_stellar_deposit(deposit) def mock_load_account_no_account(account_id): if isinstance(account_id, Keypair): account_id = account_id.public_key if account_id not in [ Keypair.from_secret(v).public_key for v in [USD_DISTRIBUTION_SEED, ETH_DISTRIBUTION_SEED] ]: raise NotFoundError( response=Response( status_code=404, headers={}, url="", text=json.dumps(dict(status=404)) ) ) account = Account(account_id, 1) account.signers = [] account.thresholds = Thresholds(0, 0, 0) return ( account, [ { "balances": [ {"asset_code": "USD", "asset_issuer": USD_ISSUER_ACCOUNT}, {"asset_code": "ETH", "asset_issuer": ETH_ISSUER_ACCOUNT}, ] } ], ) def mock_get_account_obj(account_id): try: return mock_load_account_no_account(account_id=account_id) except NotFoundError as e: raise RuntimeError(str(e)) mock_server_no_account = Mock( accounts=Mock( return_value=Mock( account_id=Mock(return_value=Mock(call=Mock(return_value={"balances": []}))) ) ), load_account=mock_load_account_no_account, submit_transaction=Mock(return_value=HORIZON_SUCCESS_RESPONSE), fetch_base_fee=Mock(return_value=100), ) channel_account_kp = Keypair.random() channel_account = Account(channel_account_kp.public_key, 1) channel_account.signers = [] channel_account.thresholds = Thresholds(0, 0, 0) mock_account = Account(STELLAR_ACCOUNT_1, 1) mock_account.signers = [ {"key": STELLAR_ACCOUNT_1, "weight": 1, "type": "ed25519_public_key"} ] mock_account.thresholds = Thresholds(low_threshold=0, med_threshold=1, high_threshold=1) @pytest.mark.django_db @patch( "polaris.utils.settings.HORIZON_SERVER", Mock( load_account=Mock(return_value=mock_account), submit_transaction=Mock(return_value=HORIZON_SUCCESS_RESPONSE), fetch_base_fee=Mock(return_value=100), ), ) @patch( "polaris.utils.get_account_obj", Mock( return_value=( mock_account, {"balances": [{"asset_code": "USD", "asset_issuer": USD_ISSUER_ACCOUNT}]}, ) ), ) def test_deposit_stellar_success(acc1_usd_deposit_transaction_factory): """ `create_stellar_deposit` succeeds if the provided transaction's `stellar_account` has a trustline to the issuer for its `asset`, and the Stellar transaction completes successfully. All of these conditions and actions are mocked in this test to avoid network calls. """ deposit = acc1_usd_deposit_transaction_factory() deposit.status = Transaction.STATUS.pending_anchor deposit.save() assert create_stellar_deposit(deposit) assert Transaction.objects.get(id=deposit.id).status == Transaction.STATUS.completed mock_server_no_trust_account_claim = Mock( accounts=Mock( return_value=Mock( account_id=Mock(return_value=Mock(call=Mock(return_value={"balances": []}))) ) ), load_account=mock_account, submit_transaction=Mock(return_value=HORIZON_SUCCESS_RESPONSE_CLAIM), fetch_base_fee=Mock(return_value=100), ) @pytest.mark.django_db @patch( "polaris.utils.get_account_obj", Mock(return_value=(mock_account, {"balances": []})) ) @patch("polaris.utils.settings.HORIZON_SERVER", mock_server_no_trust_account_claim) def test_deposit_stellar_no_trustline_with_claimable_bal( acc1_usd_deposit_transaction_factory, ): """ This is the flow when a wallet/client submits a deposit and the sends "claimable_balance_supported=True" in their POST request body. Such that the deposit transaction is can continue as a claimable balance operation rather than a payment operation `execute_deposits` from `poll_pending_deposits.py` if the provided transaction's Stellar account has no trustline and sees claimable_balance_supported set to True. it will create_stellar_deposit() where it wil complete the deposit flow as a claimable balance """ deposit = acc1_usd_deposit_transaction_factory() deposit.status = Transaction.STATUS.pending_anchor deposit.claimable_balance_supported = True deposit.save() assert create_stellar_deposit(deposit) assert Transaction.objects.get(id=deposit.id).claimable_balance_id assert Transaction.objects.get(id=deposit.id).status == Transaction.STATUS.completed
en
0.859355
`create_stellar_deposit` succeeds if the provided transaction's `stellar_account` has a trustline to the issuer for its `asset`, and the Stellar transaction completes successfully. All of these conditions and actions are mocked in this test to avoid network calls. This is the flow when a wallet/client submits a deposit and the sends "claimable_balance_supported=True" in their POST request body. Such that the deposit transaction is can continue as a claimable balance operation rather than a payment operation `execute_deposits` from `poll_pending_deposits.py` if the provided transaction's Stellar account has no trustline and sees claimable_balance_supported set to True. it will create_stellar_deposit() where it wil complete the deposit flow as a claimable balance
2.0545
2
mzgtfs/transfer.py
andreyz/mapzen-gtfs
29
6615471
<reponame>andreyz/mapzen-gtfs<gh_stars>10-100 """GTFS Transfers.""" import datetime import entity import geom import util import widetime import validation class Transfer(entity.Entity): REQUIRED = [ 'from_stop_id', 'to_stop_id', 'transfer_type' ] OPTIONAL = [ 'min_transfer_time' ] def validate(self, validator=None): validator = super(Transfer, self).validate(validator) # Required with validator(self): assert self.get('from_stop_id'), "Required: from_stop_id" with validator(self): assert self.get('to_stop_id'), "Required: to_stop_id" with validator(self): # field required, blank allowed. assert validation.valid_int(self.get('transfer_type'), vmin=0, vmax=3, empty=True), \ "Invalid transfer_type" with validator(self): if self.get('min_transfer_time'): assert validation.valid_int(self.get('min_transfer_time'), vmin=0), \ "Invalid min_transfer_time" return validator def validate_feed(self, validator=None): validator = super(Transfer, self).validate_feed(validator) with validator(self): assert self._feed.stop(self.get('from_stop_id')), "Unknown from_stop_id" with validator(self): assert self._feed.stop(self.get('to_stop_id')), "Unknown to_stop_id" return validator
"""GTFS Transfers.""" import datetime import entity import geom import util import widetime import validation class Transfer(entity.Entity): REQUIRED = [ 'from_stop_id', 'to_stop_id', 'transfer_type' ] OPTIONAL = [ 'min_transfer_time' ] def validate(self, validator=None): validator = super(Transfer, self).validate(validator) # Required with validator(self): assert self.get('from_stop_id'), "Required: from_stop_id" with validator(self): assert self.get('to_stop_id'), "Required: to_stop_id" with validator(self): # field required, blank allowed. assert validation.valid_int(self.get('transfer_type'), vmin=0, vmax=3, empty=True), \ "Invalid transfer_type" with validator(self): if self.get('min_transfer_time'): assert validation.valid_int(self.get('min_transfer_time'), vmin=0), \ "Invalid min_transfer_time" return validator def validate_feed(self, validator=None): validator = super(Transfer, self).validate_feed(validator) with validator(self): assert self._feed.stop(self.get('from_stop_id')), "Unknown from_stop_id" with validator(self): assert self._feed.stop(self.get('to_stop_id')), "Unknown to_stop_id" return validator
en
0.862909
GTFS Transfers. # Required # field required, blank allowed.
2.466862
2
neighbormodels/neighbors.py
jkglasbrenner/datamaterials-neighbors
4
6615472
# -*- coding: utf-8 -*- from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import pandas as pd from pandas import Categorical, DataFrame, IntervalIndex, Series from pandas.core.groupby import DataFrameGroupBy from pymatgen import PeriodicSite, Structure from neighbormodels.structure import label_subspecies Neighbor = Tuple[PeriodicSite, float, int] SiteNeighbors = List[Optional[Neighbor]] AllNeighborDistances = List[SiteNeighbors] NeighborDistances = Dict[str, Union[List[str], List[float], List[int]]] class NeighborData(NamedTuple): neighbor_count: DataFrame sublattice_pairs: DataFrame structure: Structure def count_neighbors(cell_structure: Structure, r: float) -> NeighborData: """Builds a data frame containing neighbor counts grouped over site-index pairs and separation distances. :param cell_structure: A pymatgen ``Structure`` object. :param r: Radius of sphere. :return: A named tuple with three field names: ``neighbor_count`` A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs and separation distances. ``sublattice_pairs`` A pandas ``DataFrame`` of neighbor distances mapped to unique bin intervals. ``structure`` A copy of the ``Structure`` object defining the crystal structure. """ cell_structure = add_subspecie_labels_if_missing(cell_structure=cell_structure) neighbor_distances_df: DataFrame = get_neighbor_distances_data_frame( cell_structure=cell_structure, r=r ) distance_bins_df: DataFrame = neighbor_distances_df.pipe( define_bins_to_group_and_sort_by_distance ) neighbor_count_df: DataFrame = neighbor_distances_df.pipe( group_site_index_pairs_by_distance, distance_bins_df=distance_bins_df ).pipe(count_neighbors_within_distance_groups).pipe(sort_neighbors_by_site_index_i) sublattice_pairs_df: pd.DataFrame = neighbor_count_df.pipe( sort_and_rank_unique_sublattice_pairs ) return NeighborData( neighbor_count=neighbor_count_df, sublattice_pairs=sublattice_pairs_df, structure=cell_structure, ) def sort_and_rank_unique_sublattice_pairs(data_frame: DataFrame) -> DataFrame: """Group, sort, and rank unique subspecies_ij and distance_bin columns. :param data_frame: A pandas ``DataFrame`` of pairwise neighbor distances. :return: A pandas ``DataFrame`` of unique sublattice pairs. """ subspecies_columns = ["subspecies_i", "subspecies_j"] sublattice_columns = subspecies_columns + ["distance_bin"] return ( data_frame.loc[:, sublattice_columns] .drop_duplicates(subset=sublattice_columns) .sort_values(sublattice_columns) .assign(rank=lambda x: x.groupby(subspecies_columns).cumcount()) .reset_index(drop=True) ) def sort_neighbors_by_site_index_i(neighbor_count_df: DataFrame) -> DataFrame: """Sort by site index i, then neighbor distances, then neighbor index j. :param neighbor_count_df: A data frame of neighbor counts aggregated over site-index pairs and separation distances. :return: A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs and separation distances sorted by site index i, then neighbor distances, then neighbor index j. """ return neighbor_count_df.sort_values(by=["i", "distance_bin", "j"]).reset_index( drop=True ) def count_neighbors_within_distance_groups( grouped_distances: DataFrameGroupBy, ) -> DataFrame: """Count number of neighbors within each group of same-distance site-index pairs. :param grouped_distances: A data frame grouped over site-index pairs, subspecies pairs, and bin intervals. :return: A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs and separation distances. """ return ( grouped_distances.apply( lambda x: pd.to_numeric(arg=x["distance_ij"].count(), downcast="integer") ) .rename("n") .reset_index() ) def group_site_index_pairs_by_distance( neighbor_distances_df: DataFrame, distance_bins_df: DataFrame ) -> DataFrameGroupBy: """Iterate over all sites, grouping by site-index pairs, subspecies pairs, and bin intervals. :param neighbor_distances_df: A pandas ``DataFrame`` containing all pairwise neighbor distances. :param distance_bins_df: A pandas ``DataFrame`` of neighbor distances mapped to unique bin intervals. :return: A data frame grouped over site-index pairs, subspecies pairs, and bin intervals. """ binned_distances: Series = pd.cut( x=neighbor_distances_df["distance_ij"], bins=distance_bins_df.index ).rename("distance_bin") return neighbor_distances_df.groupby( ["i", "j", "subspecies_i", "subspecies_j", binned_distances] ) def define_bins_to_group_and_sort_by_distance( neighbor_distances_df: DataFrame, ) -> DataFrame: """Defines bin intervals to group and sort neighbor pairs by distance. :param neighbor_distances_df: A pandas ``DataFrame`` of pairwise neighbor distances. :return: A pandas ``DataFrame`` of neighbor distances mapped to unique bin intervals. """ unique_distances: np.ndarray = find_unique_distances( distance_ij=neighbor_distances_df["distance_ij"] ) bin_intervals: IntervalIndex = define_bin_intervals( unique_distances=unique_distances ) return DataFrame( data={ "distance_bin": Categorical(values=bin_intervals, ordered=True), "distance_ij": Categorical(values=unique_distances, ordered=True), }, index=bin_intervals, ) def find_unique_distances(distance_ij: Series) -> np.ndarray: """Finds the unique distances that define the neighbor groups. :param distance_ij: A pandas ``Series`` of pairwise neighbor distances. :return: An array of unique neighbor distances. """ unique_floats: np.ndarray = np.sort(distance_ij.unique()) next_distance_not_close: np.ndarray = np.logical_not( np.isclose(unique_floats[1:], unique_floats[:-1]) ) return np.concatenate( (unique_floats[:1], unique_floats[1:][next_distance_not_close]) ) def define_bin_intervals(unique_distances: np.ndarray) -> IntervalIndex: """Constructs bin intervals used to group over neighbor distances. This binning procedure provides a robust method for grouping data based on a variable with a float data type. :param unique_distances: An array of neighbor distances returned by asking pandas to return the unique distances. :return: A pandas ``IntervalIndex`` defining bin intervals can be used to sort and group neighbor distances. """ bin_centers: np.ndarray = np.concatenate(([0], unique_distances)) bin_edges: np.ndarray = np.concatenate( [ bin_centers[:-1] + (bin_centers[1:] - bin_centers[:-1]) / 2, bin_centers[-1:] + (bin_centers[-1:] - bin_centers[-2:-1]) / 2, ] ) return IntervalIndex.from_breaks(breaks=bin_edges) def get_neighbor_distances_data_frame(cell_structure: Structure, r: float) -> DataFrame: """Get data frame of pairwise neighbor distances for each atom in the unit cell, out to a distance ``r``. :param cell_structure: A pymatgen ``Structure`` object. :param r: Radius of sphere. :return: A pandas ``DataFrame`` of pairwise neighbor distances. """ all_neighbors: AllNeighborDistances = cell_structure.get_all_neighbors( r=r, include_index=True ) neighbor_distances: NeighborDistances = extract_neighbor_distance_data( cell_structure=cell_structure, all_neighbors=all_neighbors ) return DataFrame(data=neighbor_distances) def extract_neighbor_distance_data( cell_structure: Structure, all_neighbors: AllNeighborDistances ) -> NeighborDistances: """Extracts the site indices, site species, and neighbor distances for each pair and stores it in a dictionary. :param cell_structure: A pymatgen ``Structure`` object. :param all_neighbors: A list of lists containing the neighbors for each site in the structure. :return: A dictionary of site indices, site species, and neighbor distances for each pair. """ neighbor_distances: NeighborDistances = { "i": [], "j": [], "subspecies_i": [], "subspecies_j": [], "distance_ij": [], } for site_i_index, site_i_neighbors in enumerate(all_neighbors): append_site_i_neighbor_distance_data( site_i_index=site_i_index, site_i_neighbors=site_i_neighbors, cell_structure=cell_structure, neighbor_distances=neighbor_distances, ) return neighbor_distances def append_site_i_neighbor_distance_data( site_i_index: int, site_i_neighbors: SiteNeighbors, cell_structure: Structure, neighbor_distances: NeighborDistances, ) -> None: """Helper function to append indices, species, and distances in the ``neighbor_distances`` dictionary. :param site_i_index: Site index of first site in neighbor pair. :param site_i_neighbors: A list of site i's neighbors. :param cell_structure: The pymatgen ``Structure`` object that defines the crystal structure. :param neighbor_distances: A dictionary of site indices, site species, and neighbor distances for each pair. """ for site_j in site_i_neighbors: subspecies_pair: List[str] = [ cell_structure[site_i_index].properties["subspecie"], cell_structure[site_j[2]].properties["subspecie"], ] index_pair: List[str] = [site_i_index, site_j[2]] neighbor_distances["i"].append(index_pair[0]) neighbor_distances["j"].append(index_pair[1]) neighbor_distances["subspecies_i"].append(subspecies_pair[0]) neighbor_distances["subspecies_j"].append(subspecies_pair[1]) neighbor_distances["distance_ij"].append(site_j[1]) def add_subspecie_labels_if_missing(cell_structure: Structure) -> Structure: """Makes a copy of ``cell_structure`` and then checks if ``cell_structure`` has the subspecie site property. If it does, then return the copy as-is, otherwise label each site of the copy using the site's atomic specie name and then return it. :param cell_structure: A pymatgen ``Structure`` object. :return: An exact copy of the input ``cell_structure`` object with subspecie labels added, if missing. """ cell_structure = cell_structure.copy() if "subspecie" not in cell_structure.site_properties: label_subspecies(cell_structure=cell_structure, site_indices=[]) return cell_structure
# -*- coding: utf-8 -*- from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np import pandas as pd from pandas import Categorical, DataFrame, IntervalIndex, Series from pandas.core.groupby import DataFrameGroupBy from pymatgen import PeriodicSite, Structure from neighbormodels.structure import label_subspecies Neighbor = Tuple[PeriodicSite, float, int] SiteNeighbors = List[Optional[Neighbor]] AllNeighborDistances = List[SiteNeighbors] NeighborDistances = Dict[str, Union[List[str], List[float], List[int]]] class NeighborData(NamedTuple): neighbor_count: DataFrame sublattice_pairs: DataFrame structure: Structure def count_neighbors(cell_structure: Structure, r: float) -> NeighborData: """Builds a data frame containing neighbor counts grouped over site-index pairs and separation distances. :param cell_structure: A pymatgen ``Structure`` object. :param r: Radius of sphere. :return: A named tuple with three field names: ``neighbor_count`` A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs and separation distances. ``sublattice_pairs`` A pandas ``DataFrame`` of neighbor distances mapped to unique bin intervals. ``structure`` A copy of the ``Structure`` object defining the crystal structure. """ cell_structure = add_subspecie_labels_if_missing(cell_structure=cell_structure) neighbor_distances_df: DataFrame = get_neighbor_distances_data_frame( cell_structure=cell_structure, r=r ) distance_bins_df: DataFrame = neighbor_distances_df.pipe( define_bins_to_group_and_sort_by_distance ) neighbor_count_df: DataFrame = neighbor_distances_df.pipe( group_site_index_pairs_by_distance, distance_bins_df=distance_bins_df ).pipe(count_neighbors_within_distance_groups).pipe(sort_neighbors_by_site_index_i) sublattice_pairs_df: pd.DataFrame = neighbor_count_df.pipe( sort_and_rank_unique_sublattice_pairs ) return NeighborData( neighbor_count=neighbor_count_df, sublattice_pairs=sublattice_pairs_df, structure=cell_structure, ) def sort_and_rank_unique_sublattice_pairs(data_frame: DataFrame) -> DataFrame: """Group, sort, and rank unique subspecies_ij and distance_bin columns. :param data_frame: A pandas ``DataFrame`` of pairwise neighbor distances. :return: A pandas ``DataFrame`` of unique sublattice pairs. """ subspecies_columns = ["subspecies_i", "subspecies_j"] sublattice_columns = subspecies_columns + ["distance_bin"] return ( data_frame.loc[:, sublattice_columns] .drop_duplicates(subset=sublattice_columns) .sort_values(sublattice_columns) .assign(rank=lambda x: x.groupby(subspecies_columns).cumcount()) .reset_index(drop=True) ) def sort_neighbors_by_site_index_i(neighbor_count_df: DataFrame) -> DataFrame: """Sort by site index i, then neighbor distances, then neighbor index j. :param neighbor_count_df: A data frame of neighbor counts aggregated over site-index pairs and separation distances. :return: A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs and separation distances sorted by site index i, then neighbor distances, then neighbor index j. """ return neighbor_count_df.sort_values(by=["i", "distance_bin", "j"]).reset_index( drop=True ) def count_neighbors_within_distance_groups( grouped_distances: DataFrameGroupBy, ) -> DataFrame: """Count number of neighbors within each group of same-distance site-index pairs. :param grouped_distances: A data frame grouped over site-index pairs, subspecies pairs, and bin intervals. :return: A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs and separation distances. """ return ( grouped_distances.apply( lambda x: pd.to_numeric(arg=x["distance_ij"].count(), downcast="integer") ) .rename("n") .reset_index() ) def group_site_index_pairs_by_distance( neighbor_distances_df: DataFrame, distance_bins_df: DataFrame ) -> DataFrameGroupBy: """Iterate over all sites, grouping by site-index pairs, subspecies pairs, and bin intervals. :param neighbor_distances_df: A pandas ``DataFrame`` containing all pairwise neighbor distances. :param distance_bins_df: A pandas ``DataFrame`` of neighbor distances mapped to unique bin intervals. :return: A data frame grouped over site-index pairs, subspecies pairs, and bin intervals. """ binned_distances: Series = pd.cut( x=neighbor_distances_df["distance_ij"], bins=distance_bins_df.index ).rename("distance_bin") return neighbor_distances_df.groupby( ["i", "j", "subspecies_i", "subspecies_j", binned_distances] ) def define_bins_to_group_and_sort_by_distance( neighbor_distances_df: DataFrame, ) -> DataFrame: """Defines bin intervals to group and sort neighbor pairs by distance. :param neighbor_distances_df: A pandas ``DataFrame`` of pairwise neighbor distances. :return: A pandas ``DataFrame`` of neighbor distances mapped to unique bin intervals. """ unique_distances: np.ndarray = find_unique_distances( distance_ij=neighbor_distances_df["distance_ij"] ) bin_intervals: IntervalIndex = define_bin_intervals( unique_distances=unique_distances ) return DataFrame( data={ "distance_bin": Categorical(values=bin_intervals, ordered=True), "distance_ij": Categorical(values=unique_distances, ordered=True), }, index=bin_intervals, ) def find_unique_distances(distance_ij: Series) -> np.ndarray: """Finds the unique distances that define the neighbor groups. :param distance_ij: A pandas ``Series`` of pairwise neighbor distances. :return: An array of unique neighbor distances. """ unique_floats: np.ndarray = np.sort(distance_ij.unique()) next_distance_not_close: np.ndarray = np.logical_not( np.isclose(unique_floats[1:], unique_floats[:-1]) ) return np.concatenate( (unique_floats[:1], unique_floats[1:][next_distance_not_close]) ) def define_bin_intervals(unique_distances: np.ndarray) -> IntervalIndex: """Constructs bin intervals used to group over neighbor distances. This binning procedure provides a robust method for grouping data based on a variable with a float data type. :param unique_distances: An array of neighbor distances returned by asking pandas to return the unique distances. :return: A pandas ``IntervalIndex`` defining bin intervals can be used to sort and group neighbor distances. """ bin_centers: np.ndarray = np.concatenate(([0], unique_distances)) bin_edges: np.ndarray = np.concatenate( [ bin_centers[:-1] + (bin_centers[1:] - bin_centers[:-1]) / 2, bin_centers[-1:] + (bin_centers[-1:] - bin_centers[-2:-1]) / 2, ] ) return IntervalIndex.from_breaks(breaks=bin_edges) def get_neighbor_distances_data_frame(cell_structure: Structure, r: float) -> DataFrame: """Get data frame of pairwise neighbor distances for each atom in the unit cell, out to a distance ``r``. :param cell_structure: A pymatgen ``Structure`` object. :param r: Radius of sphere. :return: A pandas ``DataFrame`` of pairwise neighbor distances. """ all_neighbors: AllNeighborDistances = cell_structure.get_all_neighbors( r=r, include_index=True ) neighbor_distances: NeighborDistances = extract_neighbor_distance_data( cell_structure=cell_structure, all_neighbors=all_neighbors ) return DataFrame(data=neighbor_distances) def extract_neighbor_distance_data( cell_structure: Structure, all_neighbors: AllNeighborDistances ) -> NeighborDistances: """Extracts the site indices, site species, and neighbor distances for each pair and stores it in a dictionary. :param cell_structure: A pymatgen ``Structure`` object. :param all_neighbors: A list of lists containing the neighbors for each site in the structure. :return: A dictionary of site indices, site species, and neighbor distances for each pair. """ neighbor_distances: NeighborDistances = { "i": [], "j": [], "subspecies_i": [], "subspecies_j": [], "distance_ij": [], } for site_i_index, site_i_neighbors in enumerate(all_neighbors): append_site_i_neighbor_distance_data( site_i_index=site_i_index, site_i_neighbors=site_i_neighbors, cell_structure=cell_structure, neighbor_distances=neighbor_distances, ) return neighbor_distances def append_site_i_neighbor_distance_data( site_i_index: int, site_i_neighbors: SiteNeighbors, cell_structure: Structure, neighbor_distances: NeighborDistances, ) -> None: """Helper function to append indices, species, and distances in the ``neighbor_distances`` dictionary. :param site_i_index: Site index of first site in neighbor pair. :param site_i_neighbors: A list of site i's neighbors. :param cell_structure: The pymatgen ``Structure`` object that defines the crystal structure. :param neighbor_distances: A dictionary of site indices, site species, and neighbor distances for each pair. """ for site_j in site_i_neighbors: subspecies_pair: List[str] = [ cell_structure[site_i_index].properties["subspecie"], cell_structure[site_j[2]].properties["subspecie"], ] index_pair: List[str] = [site_i_index, site_j[2]] neighbor_distances["i"].append(index_pair[0]) neighbor_distances["j"].append(index_pair[1]) neighbor_distances["subspecies_i"].append(subspecies_pair[0]) neighbor_distances["subspecies_j"].append(subspecies_pair[1]) neighbor_distances["distance_ij"].append(site_j[1]) def add_subspecie_labels_if_missing(cell_structure: Structure) -> Structure: """Makes a copy of ``cell_structure`` and then checks if ``cell_structure`` has the subspecie site property. If it does, then return the copy as-is, otherwise label each site of the copy using the site's atomic specie name and then return it. :param cell_structure: A pymatgen ``Structure`` object. :return: An exact copy of the input ``cell_structure`` object with subspecie labels added, if missing. """ cell_structure = cell_structure.copy() if "subspecie" not in cell_structure.site_properties: label_subspecies(cell_structure=cell_structure, site_indices=[]) return cell_structure
en
0.725492
# -*- coding: utf-8 -*- Builds a data frame containing neighbor counts grouped over site-index pairs and separation distances. :param cell_structure: A pymatgen ``Structure`` object. :param r: Radius of sphere. :return: A named tuple with three field names: ``neighbor_count`` A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs and separation distances. ``sublattice_pairs`` A pandas ``DataFrame`` of neighbor distances mapped to unique bin intervals. ``structure`` A copy of the ``Structure`` object defining the crystal structure. Group, sort, and rank unique subspecies_ij and distance_bin columns. :param data_frame: A pandas ``DataFrame`` of pairwise neighbor distances. :return: A pandas ``DataFrame`` of unique sublattice pairs. Sort by site index i, then neighbor distances, then neighbor index j. :param neighbor_count_df: A data frame of neighbor counts aggregated over site-index pairs and separation distances. :return: A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs and separation distances sorted by site index i, then neighbor distances, then neighbor index j. Count number of neighbors within each group of same-distance site-index pairs. :param grouped_distances: A data frame grouped over site-index pairs, subspecies pairs, and bin intervals. :return: A pandas ``DataFrame`` of neighbor counts aggregated over site-index pairs and separation distances. Iterate over all sites, grouping by site-index pairs, subspecies pairs, and bin intervals. :param neighbor_distances_df: A pandas ``DataFrame`` containing all pairwise neighbor distances. :param distance_bins_df: A pandas ``DataFrame`` of neighbor distances mapped to unique bin intervals. :return: A data frame grouped over site-index pairs, subspecies pairs, and bin intervals. Defines bin intervals to group and sort neighbor pairs by distance. :param neighbor_distances_df: A pandas ``DataFrame`` of pairwise neighbor distances. :return: A pandas ``DataFrame`` of neighbor distances mapped to unique bin intervals. Finds the unique distances that define the neighbor groups. :param distance_ij: A pandas ``Series`` of pairwise neighbor distances. :return: An array of unique neighbor distances. Constructs bin intervals used to group over neighbor distances. This binning procedure provides a robust method for grouping data based on a variable with a float data type. :param unique_distances: An array of neighbor distances returned by asking pandas to return the unique distances. :return: A pandas ``IntervalIndex`` defining bin intervals can be used to sort and group neighbor distances. Get data frame of pairwise neighbor distances for each atom in the unit cell, out to a distance ``r``. :param cell_structure: A pymatgen ``Structure`` object. :param r: Radius of sphere. :return: A pandas ``DataFrame`` of pairwise neighbor distances. Extracts the site indices, site species, and neighbor distances for each pair and stores it in a dictionary. :param cell_structure: A pymatgen ``Structure`` object. :param all_neighbors: A list of lists containing the neighbors for each site in the structure. :return: A dictionary of site indices, site species, and neighbor distances for each pair. Helper function to append indices, species, and distances in the ``neighbor_distances`` dictionary. :param site_i_index: Site index of first site in neighbor pair. :param site_i_neighbors: A list of site i's neighbors. :param cell_structure: The pymatgen ``Structure`` object that defines the crystal structure. :param neighbor_distances: A dictionary of site indices, site species, and neighbor distances for each pair. Makes a copy of ``cell_structure`` and then checks if ``cell_structure`` has the subspecie site property. If it does, then return the copy as-is, otherwise label each site of the copy using the site's atomic specie name and then return it. :param cell_structure: A pymatgen ``Structure`` object. :return: An exact copy of the input ``cell_structure`` object with subspecie labels added, if missing.
2.87746
3
src/viewer/app/views/core.py
mappin/asxtrade
0
6615473
<reponame>mappin/asxtrade """ Responsible for the core view - showing lists (paginated) of stocks handling all required corner conditions for missing data. Other views are derived from this (both FBV and CBV) so be careful to take sub-views needs into account here. """ from django.db.models.query import QuerySet from django.core.paginator import Paginator from django.shortcuts import render from django.http import Http404 from django.contrib.auth.decorators import login_required from app.models import ( Timeframe, user_purchases, latest_quote, user_watchlist, selected_cached_stocks_cip, valid_quotes_only, all_available_dates, validate_date, validate_user, all_etfs, increasing_yield, increasing_eps ) from app.messages import info, warning, add_messages from app.plots import plot_heatmap, plot_breakdown def show_companies( matching_companies, # may be QuerySet or iterable of stock codes (str) request, sentiment_timeframe: Timeframe, extra_context=None, template_name="all_stocks.html", ): """ Support function to public-facing views to eliminate code redundancy """ virtual_purchases_by_user = user_purchases(request.user) if isinstance(matching_companies, QuerySet): stocks_queryset = matching_companies # we assume QuerySet is already sorted by desired criteria elif matching_companies is None or len(matching_companies) > 0: stocks_queryset, _ = latest_quote(matching_companies) # FALLTHRU # sort queryset as this will often be requested by the USER sort_by = tuple(request.GET.get("sort_by", "asx_code").split(",")) info(request, "Sorting by {}".format(sort_by)) stocks_queryset = stocks_queryset.order_by(*sort_by) # keep track of stock codes for template convenience asx_codes = [quote.asx_code for quote in stocks_queryset.all()] n_top_bottom = extra_context['n_top_bottom'] if 'n_top_bottom' in extra_context else 20 print("show_companies: found {} stocks".format(len(asx_codes))) # setup context dict for the render context = { # NB: title and heatmap_title are expected to be supplied by caller via extra_context "timeframe": sentiment_timeframe, "title": "Caller must override", "watched": user_watchlist(request.user), "n_stocks": len(asx_codes), "n_top_bottom": n_top_bottom, "virtual_purchases": virtual_purchases_by_user, } # since we sort above, we must setup the pagination also... assert isinstance(stocks_queryset, QuerySet) paginator = Paginator(stocks_queryset, 50) page_number = request.GET.get("page", 1) page_obj = paginator.page(page_number) context['page_obj'] = page_obj context['object_list'] = paginator if len(asx_codes) <= 0: warning(request, "No matching companies found.") else: df = selected_cached_stocks_cip(asx_codes, sentiment_timeframe) sentiment_heatmap_data, top10, bottom10 = plot_heatmap(df, sentiment_timeframe, n_top_bottom=n_top_bottom) sector_breakdown_plot = plot_breakdown(df) context.update({ "best_ten": top10, "worst_ten": bottom10, "sentiment_heatmap": sentiment_heatmap_data, "sentiment_heatmap_title": "{}: {}".format(context['title'], sentiment_timeframe.description), "sector_breakdown_plot": sector_breakdown_plot, }) if extra_context: context.update(extra_context) add_messages(request, context) #print(context) return render(request, template_name, context=context) @login_required def show_all_stocks(request): all_dates = all_available_dates() if len(all_dates) < 1: raise Http404("No ASX price data available!") ymd = all_dates[-1] validate_date(ymd) qs = valid_quotes_only(ymd) timeframe = Timeframe() return show_companies(qs, request, timeframe, extra_context={ "title": "All stocks", "sentiment_heatmap_title": "All stock sentiment: {}".format(timeframe.description) }) @login_required def show_etfs(request): validate_user(request.user) matching_codes = all_etfs() extra_context = { "title": "Exchange Traded funds over past 300 days", "sentiment_heatmap_title": "Sentiment for ETFs", } return show_companies( matching_codes, request, Timeframe(), extra_context, ) @login_required def show_increasing_eps_stocks(request): validate_user(request.user) matching_companies = increasing_eps(None) extra_context = { "title": "Stocks with increasing EPS over past 300 days", "sentiment_heatmap_title": "Sentiment for selected stocks", } return show_companies( matching_companies, request, Timeframe(), extra_context, ) @login_required def show_increasing_yield_stocks(request): validate_user(request.user) matching_companies = increasing_yield(None) extra_context = { "title": "Stocks with increasing yield over past 300 days", "sentiment_heatmap_title": "Sentiment for selected stocks", } return show_companies( matching_companies, request, Timeframe(), extra_context, )
""" Responsible for the core view - showing lists (paginated) of stocks handling all required corner conditions for missing data. Other views are derived from this (both FBV and CBV) so be careful to take sub-views needs into account here. """ from django.db.models.query import QuerySet from django.core.paginator import Paginator from django.shortcuts import render from django.http import Http404 from django.contrib.auth.decorators import login_required from app.models import ( Timeframe, user_purchases, latest_quote, user_watchlist, selected_cached_stocks_cip, valid_quotes_only, all_available_dates, validate_date, validate_user, all_etfs, increasing_yield, increasing_eps ) from app.messages import info, warning, add_messages from app.plots import plot_heatmap, plot_breakdown def show_companies( matching_companies, # may be QuerySet or iterable of stock codes (str) request, sentiment_timeframe: Timeframe, extra_context=None, template_name="all_stocks.html", ): """ Support function to public-facing views to eliminate code redundancy """ virtual_purchases_by_user = user_purchases(request.user) if isinstance(matching_companies, QuerySet): stocks_queryset = matching_companies # we assume QuerySet is already sorted by desired criteria elif matching_companies is None or len(matching_companies) > 0: stocks_queryset, _ = latest_quote(matching_companies) # FALLTHRU # sort queryset as this will often be requested by the USER sort_by = tuple(request.GET.get("sort_by", "asx_code").split(",")) info(request, "Sorting by {}".format(sort_by)) stocks_queryset = stocks_queryset.order_by(*sort_by) # keep track of stock codes for template convenience asx_codes = [quote.asx_code for quote in stocks_queryset.all()] n_top_bottom = extra_context['n_top_bottom'] if 'n_top_bottom' in extra_context else 20 print("show_companies: found {} stocks".format(len(asx_codes))) # setup context dict for the render context = { # NB: title and heatmap_title are expected to be supplied by caller via extra_context "timeframe": sentiment_timeframe, "title": "Caller must override", "watched": user_watchlist(request.user), "n_stocks": len(asx_codes), "n_top_bottom": n_top_bottom, "virtual_purchases": virtual_purchases_by_user, } # since we sort above, we must setup the pagination also... assert isinstance(stocks_queryset, QuerySet) paginator = Paginator(stocks_queryset, 50) page_number = request.GET.get("page", 1) page_obj = paginator.page(page_number) context['page_obj'] = page_obj context['object_list'] = paginator if len(asx_codes) <= 0: warning(request, "No matching companies found.") else: df = selected_cached_stocks_cip(asx_codes, sentiment_timeframe) sentiment_heatmap_data, top10, bottom10 = plot_heatmap(df, sentiment_timeframe, n_top_bottom=n_top_bottom) sector_breakdown_plot = plot_breakdown(df) context.update({ "best_ten": top10, "worst_ten": bottom10, "sentiment_heatmap": sentiment_heatmap_data, "sentiment_heatmap_title": "{}: {}".format(context['title'], sentiment_timeframe.description), "sector_breakdown_plot": sector_breakdown_plot, }) if extra_context: context.update(extra_context) add_messages(request, context) #print(context) return render(request, template_name, context=context) @login_required def show_all_stocks(request): all_dates = all_available_dates() if len(all_dates) < 1: raise Http404("No ASX price data available!") ymd = all_dates[-1] validate_date(ymd) qs = valid_quotes_only(ymd) timeframe = Timeframe() return show_companies(qs, request, timeframe, extra_context={ "title": "All stocks", "sentiment_heatmap_title": "All stock sentiment: {}".format(timeframe.description) }) @login_required def show_etfs(request): validate_user(request.user) matching_codes = all_etfs() extra_context = { "title": "Exchange Traded funds over past 300 days", "sentiment_heatmap_title": "Sentiment for ETFs", } return show_companies( matching_codes, request, Timeframe(), extra_context, ) @login_required def show_increasing_eps_stocks(request): validate_user(request.user) matching_companies = increasing_eps(None) extra_context = { "title": "Stocks with increasing EPS over past 300 days", "sentiment_heatmap_title": "Sentiment for selected stocks", } return show_companies( matching_companies, request, Timeframe(), extra_context, ) @login_required def show_increasing_yield_stocks(request): validate_user(request.user) matching_companies = increasing_yield(None) extra_context = { "title": "Stocks with increasing yield over past 300 days", "sentiment_heatmap_title": "Sentiment for selected stocks", } return show_companies( matching_companies, request, Timeframe(), extra_context, )
en
0.881484
Responsible for the core view - showing lists (paginated) of stocks handling all required corner conditions for missing data. Other views are derived from this (both FBV and CBV) so be careful to take sub-views needs into account here. # may be QuerySet or iterable of stock codes (str) Support function to public-facing views to eliminate code redundancy # we assume QuerySet is already sorted by desired criteria # FALLTHRU # sort queryset as this will often be requested by the USER # keep track of stock codes for template convenience # setup context dict for the render # NB: title and heatmap_title are expected to be supplied by caller via extra_context # since we sort above, we must setup the pagination also... #print(context)
2.420799
2
0x04-python-more_data_structures/101-square_matrix_map.py
ricardo1470/holbertonschool-higher_level_programming
0
6615474
<reponame>ricardo1470/holbertonschool-higher_level_programming #!/usr/bin/python3 def square_matrix_map(matrix=[]): return list(map(lambda j: list(map(lambda i: i * i, j)), matrix[:]))
#!/usr/bin/python3 def square_matrix_map(matrix=[]): return list(map(lambda j: list(map(lambda i: i * i, j)), matrix[:]))
fr
0.386793
#!/usr/bin/python3
3.343106
3
apps/accounts/views.py
umairqadir97/learning-management-system
7
6615475
import re import datetime from django.conf import settings from django.shortcuts import render, redirect, render_to_response from django.contrib.auth import authenticate, login from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required, permission_required from django.views.decorators.debug import sensitive_post_parameters from django.http import HttpResponse, \ HttpResponseForbidden, \ HttpResponseBadRequest, \ HttpResponseNotFound, \ JsonResponse from .models import PasswordRecovery # from .forms import AuthenticationForm, CaptchaForm # @permission_required('polls.can_vote', login_url='/loginpage/') @login_required(login_url='/accounts/login/') def custom_dashboard(request): context = dict() return render(request, 'home.html', context) @sensitive_post_parameters() @csrf_protect def custom_login(request): context = dict() response = dict(Status="UNKNOWN", Error=[], FieldErrors=[]) if request.method == "POST": username = request.POST.get("username", None) password = request.POST.get("password", None) remember_me = request.POST.get('remember_me', False) # auth_form = AuthenticationForm(request.POST) if auth_form.is_valid(): user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) if not remember_me: request.session.set_expiry(0) response["Status"] = "OK" return JsonResponse(response, **{'status': 200}) else: response["Status"] = "FAILED" response["Error"].append('Sorry! this account is disabled or not active yet') return JsonResponse(response, **{'status': 403}) response["Status"] = "FAILED" response["Error"].append('Invalid credentials, either username/password is incorrect, please try again!') return JsonResponse(response, **{'status': 404}) else: response["Status"] = "FAILED" response["FieldErrors"] = auth_form.errors return JsonResponse(response, **{'status': 400}) else: form = CaptchaForm() # context['form'] = form context['form'] = "" return render(request, 'login.html', context) @sensitive_post_parameters() @csrf_protect def change_password(request, secret_key): context = dict() try: recovery_obj = PasswordRecovery.objects.get(secret_key=secret_key) user = recovery_obj.user context['user'] = user context['secret_key'] = secret_key now = datetime.datetime.now() time_left = recovery_obj.last_modified + datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) time_left = time_left.replace(tzinfo=None) if time_left <= now: context['message'] = 'Forbidden! Your password change request activation link has been expired. ' return render(request, 'error_pages/default.html', context) if request.method == "POST": status = 400 response = dict(Status="UNKNOWN", Error=[], FieldErrors=[]) password1 = request.POST.get("password1", None) password2 = request.POST.get("password2", None) if len(password1) == 0 or password1 == "" or password1 == " " or password1 is None: response["Status"] = "FAILED" response["FieldErrors"] = {"password1": ["This field is required"]} elif len(password2) == 0 or password2 == "" or password2 == " " or password2 is None: response["Status"] = "FAILED" response["FieldErrors"] = {"password2": ["This field is required"]} elif password2 != password1: response["Status"] = "FAILED" response["FieldErrors"] = {"password2": ["Password does not match"]} elif len(password2) < 8: response["Status"] = "FAILED" response["FieldErrors"] = {"password1": ["Please note, your password should have at least 8 characters"]} elif user.check_password(password2): response["Status"] = "FAILED" response["FieldErrors"] = {"password1": ["Password is too similar with old password, please try again"]} elif not re.match(r"^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})$", password2): response["Status"] = "FAILED" response["FieldErrors"] = {"password1": ["Please note, your password must have " "uppercase and lowercase letters, special " "characters and numbers"]} else: status = 200 user.set_password(<PASSWORD>) user.save() response["Status"] = "Success" return JsonResponse(response, **{'status': status}) except PasswordRecovery.DoesNotExist: context['message'] = 'Oops! Invalid password change request. ' return render(request, 'error_pages/default.html', context) return render(request, 'accounts/change_password.html', context) @login_required(login_url='/accounts/login/') def profile_about(request): context = dict() return render(request, 'profile-about.html', context)
import re import datetime from django.conf import settings from django.shortcuts import render, redirect, render_to_response from django.contrib.auth import authenticate, login from django.views.decorators.csrf import csrf_protect from django.contrib.auth.decorators import login_required, permission_required from django.views.decorators.debug import sensitive_post_parameters from django.http import HttpResponse, \ HttpResponseForbidden, \ HttpResponseBadRequest, \ HttpResponseNotFound, \ JsonResponse from .models import PasswordRecovery # from .forms import AuthenticationForm, CaptchaForm # @permission_required('polls.can_vote', login_url='/loginpage/') @login_required(login_url='/accounts/login/') def custom_dashboard(request): context = dict() return render(request, 'home.html', context) @sensitive_post_parameters() @csrf_protect def custom_login(request): context = dict() response = dict(Status="UNKNOWN", Error=[], FieldErrors=[]) if request.method == "POST": username = request.POST.get("username", None) password = request.POST.get("password", None) remember_me = request.POST.get('remember_me', False) # auth_form = AuthenticationForm(request.POST) if auth_form.is_valid(): user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) if not remember_me: request.session.set_expiry(0) response["Status"] = "OK" return JsonResponse(response, **{'status': 200}) else: response["Status"] = "FAILED" response["Error"].append('Sorry! this account is disabled or not active yet') return JsonResponse(response, **{'status': 403}) response["Status"] = "FAILED" response["Error"].append('Invalid credentials, either username/password is incorrect, please try again!') return JsonResponse(response, **{'status': 404}) else: response["Status"] = "FAILED" response["FieldErrors"] = auth_form.errors return JsonResponse(response, **{'status': 400}) else: form = CaptchaForm() # context['form'] = form context['form'] = "" return render(request, 'login.html', context) @sensitive_post_parameters() @csrf_protect def change_password(request, secret_key): context = dict() try: recovery_obj = PasswordRecovery.objects.get(secret_key=secret_key) user = recovery_obj.user context['user'] = user context['secret_key'] = secret_key now = datetime.datetime.now() time_left = recovery_obj.last_modified + datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS) time_left = time_left.replace(tzinfo=None) if time_left <= now: context['message'] = 'Forbidden! Your password change request activation link has been expired. ' return render(request, 'error_pages/default.html', context) if request.method == "POST": status = 400 response = dict(Status="UNKNOWN", Error=[], FieldErrors=[]) password1 = request.POST.get("password1", None) password2 = request.POST.get("password2", None) if len(password1) == 0 or password1 == "" or password1 == " " or password1 is None: response["Status"] = "FAILED" response["FieldErrors"] = {"password1": ["This field is required"]} elif len(password2) == 0 or password2 == "" or password2 == " " or password2 is None: response["Status"] = "FAILED" response["FieldErrors"] = {"password2": ["This field is required"]} elif password2 != password1: response["Status"] = "FAILED" response["FieldErrors"] = {"password2": ["Password does not match"]} elif len(password2) < 8: response["Status"] = "FAILED" response["FieldErrors"] = {"password1": ["Please note, your password should have at least 8 characters"]} elif user.check_password(password2): response["Status"] = "FAILED" response["FieldErrors"] = {"password1": ["Password is too similar with old password, please try again"]} elif not re.match(r"^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})$", password2): response["Status"] = "FAILED" response["FieldErrors"] = {"password1": ["Please note, your password must have " "uppercase and lowercase letters, special " "characters and numbers"]} else: status = 200 user.set_password(<PASSWORD>) user.save() response["Status"] = "Success" return JsonResponse(response, **{'status': status}) except PasswordRecovery.DoesNotExist: context['message'] = 'Oops! Invalid password change request. ' return render(request, 'error_pages/default.html', context) return render(request, 'accounts/change_password.html', context) @login_required(login_url='/accounts/login/') def profile_about(request): context = dict() return render(request, 'profile-about.html', context)
en
0.530577
# from .forms import AuthenticationForm, CaptchaForm # @permission_required('polls.can_vote', login_url='/loginpage/') # auth_form = AuthenticationForm(request.POST) # context['form'] = form #$%]).{8,20})$", password2):
2.057114
2
tests/conftest.py
sudarshanv01/aiida-catmap
0
6615476
"""pytest fixtures for simplified testing.""" from __future__ import absolute_import import pytest # pylint: disable=import-error pytest_plugins = ['aiida.manage.tests.pytest_fixtures'] # pylint: disable=invalid-name @pytest.fixture def fixture_localhost(aiida_localhost): """Return a localhost ``Computer``.""" localhost = aiida_localhost localhost.set_default_mpiprocs_per_machine(1) return localhost @pytest.fixture def generate_parser(): """Fixture to load a parser class for testing parsers.""" def _generate_parser(entry_point_name): """Fixture to load a parser class for testing parsers. :param entry_point_name: entry point name of the parser class :return: the `Parser` sub class """ from aiida.plugins import ParserFactory return ParserFactory(entry_point_name) return _generate_parser @pytest.fixture(scope='function') def fixture_sandbox(): """Return a ``SandboxFolder``.""" from aiida.common.folders import SandboxFolder with SandboxFolder() as folder: yield folder @pytest.fixture def generate_code(fixture_localhost): # pylint: disable=redefined-outer-name """Return a ``Code`` instance configured for testing.""" def _generate_code(entry_point_name): from aiida.common import exceptions from aiida.orm import Code label = f'test.{entry_point_name}' try: return Code.objects.get(label=label) # pylint: disable=no-member except exceptions.NotExistent: return Code( label=label, input_plugin_name=entry_point_name, remote_computer_exec=[fixture_localhost, '/bin/true'], ) return _generate_code @pytest.fixture def generate_calc_job(): """Fixture to construct a new ``CalcJob`` instance and call ``prepare_for_submission``. The fixture will return the ``CalcInfo`` returned by ``prepare_for_submission`` and the temporary folder that was passed to it, into which the raw input files will have been written. """ def _generate_calc_job(folder, entry_point_name, inputs=None): """Fixture to generate a mock ``CalcInfo`` for testing calculation jobs.""" from aiida.engine.utils import instantiate_process from aiida.manage.manager import get_manager from aiida.plugins import CalculationFactory manager = get_manager() runner = manager.get_runner() process_class = CalculationFactory(entry_point_name) process = instantiate_process(runner, process_class, **inputs) calc_info = process.prepare_for_submission(folder) return calc_info return _generate_calc_job @pytest.fixture def generate_calc_job_node(): """Fixture to generate a mock `CalcJobNode` for testing parsers.""" from aiida import orm import collections # pylint: disable=syntax-error def flatten_inputs(inputs, prefix=''): """This function follows roughly the same logic as `aiida.engine.processes.process::Process._flatten_inputs`.""" flat_inputs = [] for key, value in inputs.items(): if isinstance(value, collections.abc.Mapping): flat_inputs.extend( flatten_inputs(value, prefix=prefix + key + '__')) else: flat_inputs.append((prefix + key, value)) return flat_inputs def _generate_calc_job_node(entry_point_name, computer, test_name=None, inputs=None, attributes=None): """Fixture to generate a mock `CalcJobNode` for testing parsers. :param entry_point_name: entry point name of the calculation class :param computer: a `Computer` instance :param test_name: relative path of directory :param inputs: any optional nodes to add as input links to the corrent CalcJobNode :param attributes: any optional attributes to set on the node :return: `CalcJobNode` instance with an attached `FolderData` as the `retrieved` node """ # pylint: disable=too-many-locals import os from aiida.common import LinkType from aiida.plugins.entry_point import format_entry_point_string entry_point = format_entry_point_string('aiida.calculations', entry_point_name) node = orm.CalcJobNode(computer=computer, process_type=entry_point) node.set_option('resources', { 'num_machines': 1, 'num_mpiprocs_per_machine': 1 }) node.set_option('max_wallclock_seconds', 1800) if attributes: node.set_attribute_many(attributes) if inputs: metadata = inputs.pop('metadata', {}) options = metadata.get('options', {}) for name, option in options.items(): node.set_option(name, option) for link_label, input_node in flatten_inputs(inputs): input_node.store() node.add_incoming(input_node, link_type=LinkType.INPUT_CALC, link_label=link_label) node.store() if test_name is not None: basepath = os.path.dirname(os.path.abspath(__file__)) filepath = os.path.join(basepath, 'parsers', 'fixtures', 'catmap', test_name) retrieved = orm.FolderData() retrieved.put_object_from_tree(filepath) retrieved.add_incoming(node, link_type=LinkType.CREATE, link_label='retrieved') retrieved.store() remote_folder = orm.RemoteData(computer=computer, remote_path='/tmp') remote_folder.add_incoming(node, link_type=LinkType.CREATE, link_label='remote_folder') remote_folder.store() return node return _generate_calc_job_node @pytest.fixture def generate_inputs_catmap(generate_code, generate_energy_file): # pylint: disable=redefined-outer-name """Generate inputs for an ``CatMAPCalculation``.""" from aiida.orm import List, Int, Float, Str, Bool, Dict def _generate_inputs_catmap(): species_definitions = {} species_definitions['CO_g'] = { 'pressure': 1. } #define the gas pressures species_definitions['O2_g'] = {'pressure': 1. / 3.} species_definitions['CO2_g'] = {'pressure': 0} species_definitions['s'] = { 'site_names': ['111'], 'total': 1 } #define the site scaling_constraint_dict = { 'O_s': ['+', 0, None], 'CO_s': [0, '+', None], 'O-CO_s': 'initial_state', 'O-O_s': 'final_state', } inputs = { 'electrocatal': Bool(False), 'energies': generate_energy_file(), 'code': generate_code('catmap'), 'rxn_expressions': List(list=[ '*_s + CO_g -> CO*', '2*_s + O2_g <-> O-O* + *_s -> 2O*', 'CO* + O* <-> O-CO* + * -> CO2_g + 2*', ]), 'surface_names': List(list=['Pt', 'Ag', 'Cu', 'Rh', 'Pd', 'Au', 'Ru', 'Ni']), 'descriptor_names': List(list=['O_s', 'CO_s']), 'descriptor_ranges': List(list=[[-1, 3], [-0.5, 4]]), 'resolution': Int(1), 'temperature': Float(500), 'species_definitions': Dict(dict=species_definitions), 'gas_thermo_mode': Str('shomate_gas'), 'adsorbate_thermo_mode': Str('frozen_adsorbate'), 'scaling_constraint_dict': Dict(dict=scaling_constraint_dict), 'decimal_precision': Int(150), 'numerical_solver': Str('coverages'), 'tolerance': Float(1e-20), 'max_rootfinding_iterations': Int(100), 'max_bisections': Int(3), 'metadata': { 'description': "Test job submission with the aiida_catmap plugin", 'options': { 'max_wallclock_seconds': 120 }, }, } return inputs return _generate_inputs_catmap @pytest.fixture def generate_energy_file(): """Return a `SingefileData` node.""" from pathlib import Path from aiida.plugins import DataFactory def _generate_energy_file(): """Return a `KpointsData` with a mesh of npoints in each direction.""" SinglefileData = DataFactory('singlefile') # pylint: disable=invalid-name path_to_file = Path(__file__).parent / 'input_files' / 'energies.txt' single_file = SinglefileData(path_to_file) return single_file return _generate_energy_file
"""pytest fixtures for simplified testing.""" from __future__ import absolute_import import pytest # pylint: disable=import-error pytest_plugins = ['aiida.manage.tests.pytest_fixtures'] # pylint: disable=invalid-name @pytest.fixture def fixture_localhost(aiida_localhost): """Return a localhost ``Computer``.""" localhost = aiida_localhost localhost.set_default_mpiprocs_per_machine(1) return localhost @pytest.fixture def generate_parser(): """Fixture to load a parser class for testing parsers.""" def _generate_parser(entry_point_name): """Fixture to load a parser class for testing parsers. :param entry_point_name: entry point name of the parser class :return: the `Parser` sub class """ from aiida.plugins import ParserFactory return ParserFactory(entry_point_name) return _generate_parser @pytest.fixture(scope='function') def fixture_sandbox(): """Return a ``SandboxFolder``.""" from aiida.common.folders import SandboxFolder with SandboxFolder() as folder: yield folder @pytest.fixture def generate_code(fixture_localhost): # pylint: disable=redefined-outer-name """Return a ``Code`` instance configured for testing.""" def _generate_code(entry_point_name): from aiida.common import exceptions from aiida.orm import Code label = f'test.{entry_point_name}' try: return Code.objects.get(label=label) # pylint: disable=no-member except exceptions.NotExistent: return Code( label=label, input_plugin_name=entry_point_name, remote_computer_exec=[fixture_localhost, '/bin/true'], ) return _generate_code @pytest.fixture def generate_calc_job(): """Fixture to construct a new ``CalcJob`` instance and call ``prepare_for_submission``. The fixture will return the ``CalcInfo`` returned by ``prepare_for_submission`` and the temporary folder that was passed to it, into which the raw input files will have been written. """ def _generate_calc_job(folder, entry_point_name, inputs=None): """Fixture to generate a mock ``CalcInfo`` for testing calculation jobs.""" from aiida.engine.utils import instantiate_process from aiida.manage.manager import get_manager from aiida.plugins import CalculationFactory manager = get_manager() runner = manager.get_runner() process_class = CalculationFactory(entry_point_name) process = instantiate_process(runner, process_class, **inputs) calc_info = process.prepare_for_submission(folder) return calc_info return _generate_calc_job @pytest.fixture def generate_calc_job_node(): """Fixture to generate a mock `CalcJobNode` for testing parsers.""" from aiida import orm import collections # pylint: disable=syntax-error def flatten_inputs(inputs, prefix=''): """This function follows roughly the same logic as `aiida.engine.processes.process::Process._flatten_inputs`.""" flat_inputs = [] for key, value in inputs.items(): if isinstance(value, collections.abc.Mapping): flat_inputs.extend( flatten_inputs(value, prefix=prefix + key + '__')) else: flat_inputs.append((prefix + key, value)) return flat_inputs def _generate_calc_job_node(entry_point_name, computer, test_name=None, inputs=None, attributes=None): """Fixture to generate a mock `CalcJobNode` for testing parsers. :param entry_point_name: entry point name of the calculation class :param computer: a `Computer` instance :param test_name: relative path of directory :param inputs: any optional nodes to add as input links to the corrent CalcJobNode :param attributes: any optional attributes to set on the node :return: `CalcJobNode` instance with an attached `FolderData` as the `retrieved` node """ # pylint: disable=too-many-locals import os from aiida.common import LinkType from aiida.plugins.entry_point import format_entry_point_string entry_point = format_entry_point_string('aiida.calculations', entry_point_name) node = orm.CalcJobNode(computer=computer, process_type=entry_point) node.set_option('resources', { 'num_machines': 1, 'num_mpiprocs_per_machine': 1 }) node.set_option('max_wallclock_seconds', 1800) if attributes: node.set_attribute_many(attributes) if inputs: metadata = inputs.pop('metadata', {}) options = metadata.get('options', {}) for name, option in options.items(): node.set_option(name, option) for link_label, input_node in flatten_inputs(inputs): input_node.store() node.add_incoming(input_node, link_type=LinkType.INPUT_CALC, link_label=link_label) node.store() if test_name is not None: basepath = os.path.dirname(os.path.abspath(__file__)) filepath = os.path.join(basepath, 'parsers', 'fixtures', 'catmap', test_name) retrieved = orm.FolderData() retrieved.put_object_from_tree(filepath) retrieved.add_incoming(node, link_type=LinkType.CREATE, link_label='retrieved') retrieved.store() remote_folder = orm.RemoteData(computer=computer, remote_path='/tmp') remote_folder.add_incoming(node, link_type=LinkType.CREATE, link_label='remote_folder') remote_folder.store() return node return _generate_calc_job_node @pytest.fixture def generate_inputs_catmap(generate_code, generate_energy_file): # pylint: disable=redefined-outer-name """Generate inputs for an ``CatMAPCalculation``.""" from aiida.orm import List, Int, Float, Str, Bool, Dict def _generate_inputs_catmap(): species_definitions = {} species_definitions['CO_g'] = { 'pressure': 1. } #define the gas pressures species_definitions['O2_g'] = {'pressure': 1. / 3.} species_definitions['CO2_g'] = {'pressure': 0} species_definitions['s'] = { 'site_names': ['111'], 'total': 1 } #define the site scaling_constraint_dict = { 'O_s': ['+', 0, None], 'CO_s': [0, '+', None], 'O-CO_s': 'initial_state', 'O-O_s': 'final_state', } inputs = { 'electrocatal': Bool(False), 'energies': generate_energy_file(), 'code': generate_code('catmap'), 'rxn_expressions': List(list=[ '*_s + CO_g -> CO*', '2*_s + O2_g <-> O-O* + *_s -> 2O*', 'CO* + O* <-> O-CO* + * -> CO2_g + 2*', ]), 'surface_names': List(list=['Pt', 'Ag', 'Cu', 'Rh', 'Pd', 'Au', 'Ru', 'Ni']), 'descriptor_names': List(list=['O_s', 'CO_s']), 'descriptor_ranges': List(list=[[-1, 3], [-0.5, 4]]), 'resolution': Int(1), 'temperature': Float(500), 'species_definitions': Dict(dict=species_definitions), 'gas_thermo_mode': Str('shomate_gas'), 'adsorbate_thermo_mode': Str('frozen_adsorbate'), 'scaling_constraint_dict': Dict(dict=scaling_constraint_dict), 'decimal_precision': Int(150), 'numerical_solver': Str('coverages'), 'tolerance': Float(1e-20), 'max_rootfinding_iterations': Int(100), 'max_bisections': Int(3), 'metadata': { 'description': "Test job submission with the aiida_catmap plugin", 'options': { 'max_wallclock_seconds': 120 }, }, } return inputs return _generate_inputs_catmap @pytest.fixture def generate_energy_file(): """Return a `SingefileData` node.""" from pathlib import Path from aiida.plugins import DataFactory def _generate_energy_file(): """Return a `KpointsData` with a mesh of npoints in each direction.""" SinglefileData = DataFactory('singlefile') # pylint: disable=invalid-name path_to_file = Path(__file__).parent / 'input_files' / 'energies.txt' single_file = SinglefileData(path_to_file) return single_file return _generate_energy_file
en
0.676847
pytest fixtures for simplified testing. # pylint: disable=import-error # pylint: disable=invalid-name Return a localhost ``Computer``. Fixture to load a parser class for testing parsers. Fixture to load a parser class for testing parsers. :param entry_point_name: entry point name of the parser class :return: the `Parser` sub class Return a ``SandboxFolder``. # pylint: disable=redefined-outer-name Return a ``Code`` instance configured for testing. # pylint: disable=no-member Fixture to construct a new ``CalcJob`` instance and call ``prepare_for_submission``. The fixture will return the ``CalcInfo`` returned by ``prepare_for_submission`` and the temporary folder that was passed to it, into which the raw input files will have been written. Fixture to generate a mock ``CalcInfo`` for testing calculation jobs. Fixture to generate a mock `CalcJobNode` for testing parsers. # pylint: disable=syntax-error This function follows roughly the same logic as `aiida.engine.processes.process::Process._flatten_inputs`. Fixture to generate a mock `CalcJobNode` for testing parsers. :param entry_point_name: entry point name of the calculation class :param computer: a `Computer` instance :param test_name: relative path of directory :param inputs: any optional nodes to add as input links to the corrent CalcJobNode :param attributes: any optional attributes to set on the node :return: `CalcJobNode` instance with an attached `FolderData` as the `retrieved` node # pylint: disable=too-many-locals # pylint: disable=redefined-outer-name Generate inputs for an ``CatMAPCalculation``. #define the gas pressures #define the site Return a `SingefileData` node. Return a `KpointsData` with a mesh of npoints in each direction. # pylint: disable=invalid-name
2.340539
2
circular_cylinder/verification/t_test.py
J-Massey/postproc
0
6615477
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: <NAME> @description: profiles from DNS @contact: <EMAIL> """ # Imports import numpy as np import postproc.visualise.plotter import postproc.ml_tools.gmm import postproc.frequency_spectra from postproc.boundary_layer import ProfileDataset import torch #%% device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) #%% dtprint = 0.1; t_print = 30; n = t_print/dtprint; t_min=100; t_max=500 colours = ['red', 'green', 'blue', 'purple', 'orange', 'magenta', 'black'] t_comparisons=['t_long'] # t_comparisons=['t_500/'] data_root_t = '/home/masseyjmo/Workspace/Lotus/projects/cf_lotus/ml/real_profiles/DNS/sims/t_test/' #%% xs = []; ys = []; for idx,case in enumerate(t_comparisons): xs.append((ProfileDataset(data_root_t+case).bl_value(single_point=True, length_scale=32))[0]) ys.append((ProfileDataset(data_root_t+case).bl_value(single_point=True, length_scale=32))[1]) angles = ProfileDataset(data_root_t+case).angles print(f"Test angles: {[round(a, 2) for a in angles]}") # %% import importlib importlib.reload(postproc.visualise.plotter) import postproc.visualise.plotter #%% importlib.reload(postproc.frequency_spectra) import postproc.frequency_spectra # %% for idx in range(len(xs[0])): for case, (x, y) in enumerate(zip(xs, ys)): # Plot part of the t_100 case data = torch.tensor([x[idx],y[idx]]).to(device) # Flatten the dat data = torch.transpose(data,0,1) print("Made dat a Tensor"); print("Running GMM") # Next, the Gaussian mixture is instantiated and .. n_components = 2 model = postproc.ml_tools.gmm.GaussianMixture(n_components, np.shape(data)[1]).cuda() model.fit(data, delta=1e-5, n_iter=1e6) print("Gmm fit") # .. used to predict the dat points as they where shifted y = model.predict(data) likelihood = model.score_samples(data).cpu().numpy() # postproc.gmm.plot_gmm(dat.cpu(), Y.cpu(), # y_label=r"$ \theta $", x_label=r"$ r $", label=['3D','2D'], # fn=data_root_t+f"figures/group_{idx}.svg", # tit=f"$ {round(angles[idx], 2)}^r $ from the front", # colours=colours) # plt.close() t=np.linspace(t_min,t_max,len(data)) label = lambda t: f"$ {t_min} \leq t \leq {t} $" labels = [label(int(t)) for t in np.arange(t_min, t_max, t_max / n)] n = max(t) / 50 uks, fs, means, variances = postproc.frequency_spectra.freq_spectra_convergence(t, u, n=n, OL=0.5) # for loop in range(1,8): # window = postproc.frequency_spectra._window(loop * torch / n) # # # pow_spec = postproc.frequency_spectra.freq_spectra_Welch(torch[:int(loop*len(torch)/5)],likelihood[:int(loop*len(torch)/5)]) # # postproc.plotter.simple_plot(*pow_spec, # y_label=r"$ \ln[\mathcal{L}(\mu_k|x_k)] $", x_label=r"$ f/length_scale $", colour=colours[loop-1], # colours=colours[:len(xs)], tit=f"$ {round(angles[idx], 2)}^r $ from the front", # fn=data_root_t+f"figures/pow_spec_welch_{idx}.svg") # # plt.close() #%%
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: <NAME> @description: profiles from DNS @contact: <EMAIL> """ # Imports import numpy as np import postproc.visualise.plotter import postproc.ml_tools.gmm import postproc.frequency_spectra from postproc.boundary_layer import ProfileDataset import torch #%% device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) #%% dtprint = 0.1; t_print = 30; n = t_print/dtprint; t_min=100; t_max=500 colours = ['red', 'green', 'blue', 'purple', 'orange', 'magenta', 'black'] t_comparisons=['t_long'] # t_comparisons=['t_500/'] data_root_t = '/home/masseyjmo/Workspace/Lotus/projects/cf_lotus/ml/real_profiles/DNS/sims/t_test/' #%% xs = []; ys = []; for idx,case in enumerate(t_comparisons): xs.append((ProfileDataset(data_root_t+case).bl_value(single_point=True, length_scale=32))[0]) ys.append((ProfileDataset(data_root_t+case).bl_value(single_point=True, length_scale=32))[1]) angles = ProfileDataset(data_root_t+case).angles print(f"Test angles: {[round(a, 2) for a in angles]}") # %% import importlib importlib.reload(postproc.visualise.plotter) import postproc.visualise.plotter #%% importlib.reload(postproc.frequency_spectra) import postproc.frequency_spectra # %% for idx in range(len(xs[0])): for case, (x, y) in enumerate(zip(xs, ys)): # Plot part of the t_100 case data = torch.tensor([x[idx],y[idx]]).to(device) # Flatten the dat data = torch.transpose(data,0,1) print("Made dat a Tensor"); print("Running GMM") # Next, the Gaussian mixture is instantiated and .. n_components = 2 model = postproc.ml_tools.gmm.GaussianMixture(n_components, np.shape(data)[1]).cuda() model.fit(data, delta=1e-5, n_iter=1e6) print("Gmm fit") # .. used to predict the dat points as they where shifted y = model.predict(data) likelihood = model.score_samples(data).cpu().numpy() # postproc.gmm.plot_gmm(dat.cpu(), Y.cpu(), # y_label=r"$ \theta $", x_label=r"$ r $", label=['3D','2D'], # fn=data_root_t+f"figures/group_{idx}.svg", # tit=f"$ {round(angles[idx], 2)}^r $ from the front", # colours=colours) # plt.close() t=np.linspace(t_min,t_max,len(data)) label = lambda t: f"$ {t_min} \leq t \leq {t} $" labels = [label(int(t)) for t in np.arange(t_min, t_max, t_max / n)] n = max(t) / 50 uks, fs, means, variances = postproc.frequency_spectra.freq_spectra_convergence(t, u, n=n, OL=0.5) # for loop in range(1,8): # window = postproc.frequency_spectra._window(loop * torch / n) # # # pow_spec = postproc.frequency_spectra.freq_spectra_Welch(torch[:int(loop*len(torch)/5)],likelihood[:int(loop*len(torch)/5)]) # # postproc.plotter.simple_plot(*pow_spec, # y_label=r"$ \ln[\mathcal{L}(\mu_k|x_k)] $", x_label=r"$ f/length_scale $", colour=colours[loop-1], # colours=colours[:len(xs)], tit=f"$ {round(angles[idx], 2)}^r $ from the front", # fn=data_root_t+f"figures/pow_spec_welch_{idx}.svg") # # plt.close() #%%
en
0.362676
#!/usr/bin/env python3 # -*- coding: utf-8 -*- @author: <NAME> @description: profiles from DNS @contact: <EMAIL> # Imports #%% #%% # t_comparisons=['t_500/'] #%% # %% #%% # %% # Plot part of the t_100 case # Flatten the dat # Next, the Gaussian mixture is instantiated and .. # .. used to predict the dat points as they where shifted # postproc.gmm.plot_gmm(dat.cpu(), Y.cpu(), # y_label=r"$ \theta $", x_label=r"$ r $", label=['3D','2D'], # fn=data_root_t+f"figures/group_{idx}.svg", # tit=f"$ {round(angles[idx], 2)}^r $ from the front", # colours=colours) # plt.close() # for loop in range(1,8): # window = postproc.frequency_spectra._window(loop * torch / n) # # # pow_spec = postproc.frequency_spectra.freq_spectra_Welch(torch[:int(loop*len(torch)/5)],likelihood[:int(loop*len(torch)/5)]) # # postproc.plotter.simple_plot(*pow_spec, # y_label=r"$ \ln[\mathcal{L}(\mu_k|x_k)] $", x_label=r"$ f/length_scale $", colour=colours[loop-1], # colours=colours[:len(xs)], tit=f"$ {round(angles[idx], 2)}^r $ from the front", # fn=data_root_t+f"figures/pow_spec_welch_{idx}.svg") # # plt.close() #%%
1.999923
2
virtualmother_app/module/tweet.py
guralin/virtual_mother
0
6615478
#!/bin/env python # coding: utf-8 import os import codecs from datetime import datetime from random import randint import json from collections import OrderedDict import pprint from virtualmother_app.module import database,token_check import twitter # python-twitterライブラリ class MothersTwitter(): def __init__(self): self.api = twitter.Api(consumer_key = os.environ.get('CONSUMER_KEY'), consumer_secret = os.environ.get('CONSUMER_SECRET'), access_token_key = os.environ.get('ACCESS_TOKEN'), access_token_secret = os.environ.get('ACCESS_TOKEN_SECRET')) hour = datetime.now().hour minute = datetime.now().minute self.time = f'{ hour }時{ minute }分' try: self.status = self.api.VerifyCredentials() except twitter.error.TwitterError: print('access_token_keyが間違っている可能性があります') oc = token_check.OperationCheck() oc.send_line_message() def morning_dm(self, user_id): # morning.py with open('virtualmother_app/module/json/morning_call.json') as morning_call_words: words = json.load(morning_call_words) word = words[str(randint(0, (len(words) - 1)))] # 環境によってリンクを変える if os.environ.get('environ') == 'master': link_url = 'https://virtualmother.herokuapp.com/wakeup' # 本番環境用 elif os.environ.get('environ') == 'develop': link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # テスト環境用 else: link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # ローカル環境用 morning_call = f'もう{self.time}よ!\n{word}\n{link_url}' print(f'===<Message>===\n{morning_call}\n===============') try: self.api.PostDirectMessage(morning_call, user_id) except KeyError: print("存在しないIDを参照している可能性があります\nヒント:デバック用に変なIDを入れてないですか?") def response(self, user_id, user_name): # /wakeup (DMのリンクがクリックされた時) todo_db = database.TodoData() todos= todo_db.get_todolist_from_single_user(user_id) """ 表示されるtodo_wordsの例 <user_name>おはよう! しっかり起きられて偉いわ! 教えてもらったことを確認するわね <todo> <todo> ... 大丈夫?忘れていることはない? """ todo_words= "" #listのtodosの中身が空である場合はfalseを返すみたいです if todos: for todo in todos: todo ="「" + todo + "」" todo_words += todo todo_words +="って言っていたけど大丈夫?忘れていることはない?" else: todo_words +="・・・\n朝忘れそうなことがあったらお母さんに教えてね\n" todo_words +="明日から伝えるわ\n" todo_words +="つ https://virtualmother.herokuapp.com/todoapp" greeting = f'{ user_name }\nおはよう (^_^)/\nしっかり起きられて偉いわ!\n {todo_words}' self.api.PostDirectMessage(greeting, user_id) def get_screen_name(self, user_id): user = self.api.GetUser(user_id) return user.screen_name def morning_reply(self, user_id): # morning.py (10分以内に起きなかった時) with open('virtualmother_app/module/json/morning_call.json') as morning_call_words: words = json.load(morning_call_words) word = words[str(randint(0, (len(words) - 1)))] # 環境によってリンクを変える if os.environ.get('environ') == 'master': link_url = 'https://virtualmother.herokuapp.com/wakeup' # 本番環境用 elif os.environ.get('environ') == 'develop': link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # テスト環境用 else: link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # ローカル環境用 try: user_name = self.get_screen_name(user_id) morning_call = f'@{user_name}\nもう{self.time}よ! 10分過ぎてるよ!\n{word}\n{link_url}' print(f'===<Message>===\n{morning_call}\n===============') self.api.PostUpdate(morning_call) except KeyError: print("存在しないIDを参照している可能性があります\nヒント:デバック用に変なIDを入れてないですか?") def get_user_name(self, user_id): user = self.api.GetUser(user_id) return user.name def public_post(self,user_id): with open('virtualmother_app/module/json/public_call.json') as morning_call_words: words = json.load(morning_call_words) word = words[str(randint(0, (len(words) - 1)))] # 環境によってリンクを変える if os.environ.get('environ') == 'master': link_url = 'https://virtualmother.herokuapp.com/wakeup' # 本番環境用 elif os.environ.get('environ') == 'develop': link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # テスト環境用 else: link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # ローカル環境用 try: user_name = self.get_user_name(user_id) screen_name = self.get_screen_name(user_id) morning_call = f'もう{self.time}よ! 20分過ぎてるよ!\n{user_name}(@{screen_name}){word}' print(f'===<Message>===\n{morning_call}\n===============') self.api.PostUpdate(morning_call) except KeyError: print("存在しないIDを参照している可能性があります\nヒント:デバック用に変なIDを入れてないですか?") # テスト用 def test_tweet(self, tweet_content): # このクラスに投稿内容を渡すとその内容でツイートしてくれる self.api.PostUpdate(tweet_content) print(tweet_content) def test_dm(self, tweet_content, user_id): self.api.PostDirectMessage(tweet_content, user_id = user_id) print(tweet_content, user_id) def fetch_friend(self): users = self.api.GetFriends() print([u.name for u in users]) def return_user(self): users = self.api.GetUser(screen_name = "virtual_child") print(users.name) def self_profile(self): status = self.api.VerifyCredentials() return status class UsersTwitter(): # api.VerifyCredentials()でインスタンスを作ると、UsersTwitterインスタンスになり、このインスタンスの中にあるid,screen_name,nameなどのキーを指定すると値が返ってくる def __init__(self, access_token, access_token_secret): self.api = twitter.Api(consumer_key = os.environ.get("FOR_USER_CONSUMER_KEY"), consumer_secret = os.environ.get("FOR_USER_CONSUMER_SECRET"), access_token_key = access_token, access_token_secret = access_token_secret) try: self.status = self.api.VerifyCredentials() except twitter.error.TwitterError: print("access_token_keyが間違っている可能性があります") def see_user_id(self): user_id = self.status.id return user_id def see_screen_name(self): screen_name = self.status.screen_name return screen_name def see_user_name(self): user_name = self.status.name return user_name
#!/bin/env python # coding: utf-8 import os import codecs from datetime import datetime from random import randint import json from collections import OrderedDict import pprint from virtualmother_app.module import database,token_check import twitter # python-twitterライブラリ class MothersTwitter(): def __init__(self): self.api = twitter.Api(consumer_key = os.environ.get('CONSUMER_KEY'), consumer_secret = os.environ.get('CONSUMER_SECRET'), access_token_key = os.environ.get('ACCESS_TOKEN'), access_token_secret = os.environ.get('ACCESS_TOKEN_SECRET')) hour = datetime.now().hour minute = datetime.now().minute self.time = f'{ hour }時{ minute }分' try: self.status = self.api.VerifyCredentials() except twitter.error.TwitterError: print('access_token_keyが間違っている可能性があります') oc = token_check.OperationCheck() oc.send_line_message() def morning_dm(self, user_id): # morning.py with open('virtualmother_app/module/json/morning_call.json') as morning_call_words: words = json.load(morning_call_words) word = words[str(randint(0, (len(words) - 1)))] # 環境によってリンクを変える if os.environ.get('environ') == 'master': link_url = 'https://virtualmother.herokuapp.com/wakeup' # 本番環境用 elif os.environ.get('environ') == 'develop': link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # テスト環境用 else: link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # ローカル環境用 morning_call = f'もう{self.time}よ!\n{word}\n{link_url}' print(f'===<Message>===\n{morning_call}\n===============') try: self.api.PostDirectMessage(morning_call, user_id) except KeyError: print("存在しないIDを参照している可能性があります\nヒント:デバック用に変なIDを入れてないですか?") def response(self, user_id, user_name): # /wakeup (DMのリンクがクリックされた時) todo_db = database.TodoData() todos= todo_db.get_todolist_from_single_user(user_id) """ 表示されるtodo_wordsの例 <user_name>おはよう! しっかり起きられて偉いわ! 教えてもらったことを確認するわね <todo> <todo> ... 大丈夫?忘れていることはない? """ todo_words= "" #listのtodosの中身が空である場合はfalseを返すみたいです if todos: for todo in todos: todo ="「" + todo + "」" todo_words += todo todo_words +="って言っていたけど大丈夫?忘れていることはない?" else: todo_words +="・・・\n朝忘れそうなことがあったらお母さんに教えてね\n" todo_words +="明日から伝えるわ\n" todo_words +="つ https://virtualmother.herokuapp.com/todoapp" greeting = f'{ user_name }\nおはよう (^_^)/\nしっかり起きられて偉いわ!\n {todo_words}' self.api.PostDirectMessage(greeting, user_id) def get_screen_name(self, user_id): user = self.api.GetUser(user_id) return user.screen_name def morning_reply(self, user_id): # morning.py (10分以内に起きなかった時) with open('virtualmother_app/module/json/morning_call.json') as morning_call_words: words = json.load(morning_call_words) word = words[str(randint(0, (len(words) - 1)))] # 環境によってリンクを変える if os.environ.get('environ') == 'master': link_url = 'https://virtualmother.herokuapp.com/wakeup' # 本番環境用 elif os.environ.get('environ') == 'develop': link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # テスト環境用 else: link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # ローカル環境用 try: user_name = self.get_screen_name(user_id) morning_call = f'@{user_name}\nもう{self.time}よ! 10分過ぎてるよ!\n{word}\n{link_url}' print(f'===<Message>===\n{morning_call}\n===============') self.api.PostUpdate(morning_call) except KeyError: print("存在しないIDを参照している可能性があります\nヒント:デバック用に変なIDを入れてないですか?") def get_user_name(self, user_id): user = self.api.GetUser(user_id) return user.name def public_post(self,user_id): with open('virtualmother_app/module/json/public_call.json') as morning_call_words: words = json.load(morning_call_words) word = words[str(randint(0, (len(words) - 1)))] # 環境によってリンクを変える if os.environ.get('environ') == 'master': link_url = 'https://virtualmother.herokuapp.com/wakeup' # 本番環境用 elif os.environ.get('environ') == 'develop': link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # テスト環境用 else: link_url = 'https://virtualmother-develop.herokuapp.com/wakeup' # ローカル環境用 try: user_name = self.get_user_name(user_id) screen_name = self.get_screen_name(user_id) morning_call = f'もう{self.time}よ! 20分過ぎてるよ!\n{user_name}(@{screen_name}){word}' print(f'===<Message>===\n{morning_call}\n===============') self.api.PostUpdate(morning_call) except KeyError: print("存在しないIDを参照している可能性があります\nヒント:デバック用に変なIDを入れてないですか?") # テスト用 def test_tweet(self, tweet_content): # このクラスに投稿内容を渡すとその内容でツイートしてくれる self.api.PostUpdate(tweet_content) print(tweet_content) def test_dm(self, tweet_content, user_id): self.api.PostDirectMessage(tweet_content, user_id = user_id) print(tweet_content, user_id) def fetch_friend(self): users = self.api.GetFriends() print([u.name for u in users]) def return_user(self): users = self.api.GetUser(screen_name = "virtual_child") print(users.name) def self_profile(self): status = self.api.VerifyCredentials() return status class UsersTwitter(): # api.VerifyCredentials()でインスタンスを作ると、UsersTwitterインスタンスになり、このインスタンスの中にあるid,screen_name,nameなどのキーを指定すると値が返ってくる def __init__(self, access_token, access_token_secret): self.api = twitter.Api(consumer_key = os.environ.get("FOR_USER_CONSUMER_KEY"), consumer_secret = os.environ.get("FOR_USER_CONSUMER_SECRET"), access_token_key = access_token, access_token_secret = access_token_secret) try: self.status = self.api.VerifyCredentials() except twitter.error.TwitterError: print("access_token_keyが間違っている可能性があります") def see_user_id(self): user_id = self.status.id return user_id def see_screen_name(self): screen_name = self.status.screen_name return screen_name def see_user_name(self): user_name = self.status.name return user_name
ja
0.999823
#!/bin/env python # coding: utf-8 # python-twitterライブラリ # morning.py # 環境によってリンクを変える # 本番環境用 # テスト環境用 # ローカル環境用 # /wakeup (DMのリンクがクリックされた時) 表示されるtodo_wordsの例 <user_name>おはよう! しっかり起きられて偉いわ! 教えてもらったことを確認するわね <todo> <todo> ... 大丈夫?忘れていることはない? #listのtodosの中身が空である場合はfalseを返すみたいです # morning.py (10分以内に起きなかった時) # 環境によってリンクを変える # 本番環境用 # テスト環境用 # ローカル環境用 # 環境によってリンクを変える # 本番環境用 # テスト環境用 # ローカル環境用 # テスト用 # このクラスに投稿内容を渡すとその内容でツイートしてくれる # api.VerifyCredentials()でインスタンスを作ると、UsersTwitterインスタンスになり、このインスタンスの中にあるid,screen_name,nameなどのキーを指定すると値が返ってくる
2.520724
3
debarcer/src/generate_vcf.py
bgfritz1/debarcer
0
6615479
<filename>debarcer/src/generate_vcf.py import sys import pysam import configparser import argparse import operator import functools import csv from src.generate_consensus import ConsDataRow from src.get_ref_seq import get_ref_seq from src.umi_error_correct import UMIGroup from src.get_consensus_seq import get_consensus_seq, get_uncollapsed_seq from src.handle_args import handle_arg from src.get_ref_seq import get_ref_seq from src.generate_consensus import temp_umi_table from src.generate_consensus import generate_uncollapsed from src.generate_consensus import generate_consensus from src.generate_consensus import memoize #from src.generate_merge import check_consfile def parse_raw_table(cons_file, f_sizes): """Parses a .cons file generated by generate_consensus into VCF entries.""" rows = {f_size: [] for f_size in f_sizes} with open(cons_file, "r") as reader: f_size = 0 for line in reader: if line.startswith('#'): f_size = line.split('\t')[11] elif f_size in f_sizes: rows[f_size].append(line) return rows def write_rows(cons_data, f_size, contig, region_start, region_end, output_path, config): with open("{}/{}:{}-{}.{}.vcf".format(output_path, contig, region_start, region_end, f_size), "w") as writer: writer.write("##fileformat=VCFv4.2\n") writer.write("##reference={}\n".format(config['PATHS']['reference_file'])) writer.write("##source=Debarcer2\n") writer.write("##f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata writer.write("##INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") writer.write("##INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") writer.write("##INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") writer.write("##INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") writer.write("##FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") writer.write("##FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth\">\n") writer.write("##FORMAT=<ID=AL,Number=R,Type=Integer,Description=\"Alternate Allele Depth\">\n") writer.write("##FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Alternate Allele Frequency\">\n") writer.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n") for row in cons_data[f_size]: writer.write(row) def vcf_output(cons_file, f_size, contig, region_start, region_end, output_path, config): """Writes a .vcf consensus file.""" with open("{}/{}:{}-{}.fsize{}.vcf".format(output_path, contig, region_start, region_end, f_size), "w") as writer: writer.write("##fileformat=VCFv4.2\n") writer.write("##reference={}\n".format(config['PATHS']['reference_file'])) writer.write("##source=Debarcer2\n") writer.write("##f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata writer.write("##INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") writer.write("##INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") writer.write("##INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") writer.write("##INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") writer.write("##FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") writer.write("##FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth\">\n") writer.write("##FORMAT=<ID=AL,Number=R,Type=Integer,Description=\"Alternate Allele Depth\">\n") writer.write("##FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Alternate Allele Frequency\">\n") ref_threshold = float(config['REPORT']['percent_ref_threshold']) if config else 95.0 all_threshold = float(config['REPORT']['percent_allele_threshold']) if config else 2.0 writer.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n") for base_pos in range(region_start, region_end): if base_pos in cons_data[f_size]: row = cons_data[f_size][base_pos] ref = row.get_ref_info() cons = row.get_cons_info() stats = row.get_stats() if stats['ref_freq'] <= ref_threshold: alleles = row.get_alleles(all_threshold) ref_bases = set([allele[0] for allele in alleles]) ref_allele = (ref_seq[base_pos - region_start], ref_seq[base_pos - region_start]) depths = row.impute_allele_depths() ref_depth = depths[ref_allele] if ref_allele in depths else 0 alt_freqs = row.impute_allele_freqs(all_threshold) info = "RDP={};CDP={};MIF={};MNF={:.1f}".format( stats['rawdp'], stats['consdp'], stats['min_fam'], stats['mean_fam']) fmt_string = "AD:AL:AF" # Allele depth, alt allele depth, reference frequency for ref_base in ref_bases: snips = [] for allele in alleles: if allele[0] == ref_base: snips.append(allele) alt_string = ','.join( [allele[1] for allele in snips] ) depth_string = ','.join( [str(depths[allele]) for allele in snips] ) freq_string = ','.join( ["{:.2f}".format(alt_freqs[allele]) for allele in snips] ) smp_string = "{}:{}:{}".format(ref_depth, depth_string, freq_string) filt = "PASS" if any( [depths[alt] > 10 for alt in snips] ) else "a10" writer.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( contig, base_pos, ".", ref_base, alt_string, "0", filt, info, fmt_string, smp_string)) def create_vcf_output(cons_file, f_size, cons_data, ref_seq, contig, region_start, region_end, output_path, config): #base_positions, ref_bases = {}, {} ref_threshold = float(config['REPORT']['percent_ref_threshold']) if config else 95.0 all_threshold = float(config['REPORT']['percent_allele_threshold']) if config else 2.0 #Read cons file with open(cons_file, "r") as reader: print("Reading cons file") #f_size = 0 i = region_start for line in reader: ref_freq = line.split('\t')[13] if i <= region_end: #contig[i] = line.split('\t')[1] #### CHANGE: Added the following lines base_positions[i] = line.split('\t')[2] ref_bases[i] = line.split('\t')[3] #rawdps[i] = line.split('\t')[10] #consdps[i] = line.split('\t')[11] #f_size[i] = line.split('\t')[12] ##### CHANGE: from [11] to [12] i=+1 with open("{}/{}:{}-{}.{}.vcf".format(output_path, contig, region_start, region_end, f_size), "w") as writer: writer.write("##fileformat=VCFv4.2\n") writer.write("##reference={}\n".format(config['PATHS']['reference_file'])) writer.write("##source=Debarcer2\n") writer.write("##f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata writer.write("##INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") writer.write("##INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") writer.write("##INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") writer.write("##INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") writer.write("##FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") writer.write("##FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth\">\n") writer.write("##FORMAT=<ID=AL,Number=R,Type=Integer,Description=\"Alternate Allele Depth\">\n") writer.write("##FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Alternate Allele Frequency\">\n") writer.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n") for base_pos in range(region_start, region_end): #if any( [base_pos in cons_data[f_size] for f_size in cons_data]): #for f_size in cons_data: if base_pos in cons_data[f_size]: row = cons_data[f_size][base_pos] ref = row.get_ref_info() cons = row.get_cons_info() stats = row.get_stats() if stats['ref_freq'] <= ref_threshold: alleles = row.get_alleles(all_threshold) depths = row.impute_allele_depths() ref_bases = set([allele[0] for allele in alleles]) ref_allele = (ref_seq[base_pos - region_start], ref_seq[base_pos - region_start]) depths = row.impute_allele_depths() ref_depth = depths[ref_allele] if ref_allele in depths else 0 alt_freqs = row.impute_allele_freqs(all_threshold) info = "RDP={};CDP={};MIF={};MNF={:.1f}".format( stats['rawdp'], stats['consdp'], stats['min_fam'], stats['mean_fam']) fmt_string = "AD:AL:AF" # Allele depth, alt allele depth, reference frequency for ref_base in ref_bases: snips = [] for allele in alleles: if allele[0] == ref_base: snips.append(allele) alt_string = ','.join( [allele[1] for allele in snips] ) depth_string = ','.join( [str(depths[allele]) for allele in snips] ) freq_string = ','.join( ["{:.2f}".format(alt_freqs[allele]) for allele in snips] ) smp_string = "{}:{}:{}".format(ref_depth, depth_string, freq_string) filt = "PASS" if any( [depths[alt] > 10 for alt in snips] ) else "a10" writer.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( contig, base_pos, ".", ref_base, alt_string, "0", filt, info, fmt_string, smp_string)) def create_consensus_output(cons_file, f_sizes, contig, region_start, region_end, bam_file, output_path, config): print("Building temporary UMI table...") umi_table = temp_umi_table(contig, region_start, region_end, bam_file, config) ## Lists of umi families with count >= f_size f_sizes = [int(n) for n in config['SETTINGS']['min_family_sizes'].split(',')] if config else [1, 2, 5] ## Get reference sequence for the region print("Getting reference sequence...") ref_seq = get_ref_seq(contig, region_start, region_end, config) ## Get consensus data for each f_size + uncollapsed data print("Building consensus data...") cons_data = {} cons_data[0] = generate_uncollapsed(ref_seq, contig, region_start, region_end, bam_file, config) for f_size in f_sizes: cons_data[f_size] = generate_consensus(umi_table, f_size, ref_seq, contig, region_start, region_end, bam_file, config) if f_size in cons_data: ## Output print("Writing output...") create_vcf_output(cons_file, f_size, cons_data, ref_seq, contig, region_start, region_end, output_path, config) def generate_vcf_output(cons_file, f_sizes, contig, region_start, region_end, output_path, config): """(Main) generates VCF output file(s).""" ## Get reference sequence for the region ref_seq = get_ref_seq(contig, region_start, region_end, config) ## Parse table to extract VCF events cons_data = parse_raw_table(cons_file, f_sizes) ## Generate vcf files for f_size in f_sizes: if f_size in cons_data: write_rows(cons_data, f_size, contig, region_start, region_end, output_path, config) def check_consfile(cons_file): f = open(cons_file, "r") #reader = csv.reader(f, delimiter='\t') line = f.readline() if 'INTVL' in line: return True else: return False def write_vcf(id, config, contigs, f_sizes, base_positions, region_start, region_end, ref_base, alt_string, filt, info, fmt_string, smp_string, output_path, cons_is_merged): ref_threshold = 100.0 #fam_idx = 0 if not cons_is_merged: for i in range(len(contigs)): for size in f_sizes: if contigs[i][size] != None: contig = contigs[i][size] break #Create vcf file for a given base position for specified min fam size for f_size in f_sizes: if cons_is_merged: writer = open("{}/RUNID_{}.{}.vcf".format(output_path, id, str(f_size)), "w") else: writer = open("{}/{}:{}-{}.{}.vcf".format(output_path, contig, region_start, region_end, str(f_size)), "w") writer.write("##fileformat=VCFv4.2\n") writer.write("##reference={}\n".format(config['PATHS']['reference_file'])) writer.write("##source=Debarcer2\n") writer.write("##f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata writer.write("##INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") writer.write("##INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") writer.write("##INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") writer.write("##INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") writer.write("##FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") writer.write("##FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth (ref allele depth, alt allele depth(s))\">\n") writer.write("##FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Allele Frequency (ref allele frequency, alt allele freq(s))\">\n") writer.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n") for index in range(len(contigs)): if contigs[index][f_size] != None: writer.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( contigs[index][f_size], base_positions[index][f_size], ".", ref_base[index][f_size], alt_string[index][f_size], "0", filt[index][f_size], info[index][f_size], fmt_string, smp_string[index][f_size])) #fam_idx += 1 def get_data(f_sizes, ref_base, base_A, base_C, base_G, base_T, filt, consdps, alt_string_info, allele_data, sample_data, rawdps, mean_fams, min_fam, intvls): for index in range(len(ref_base)): for f_size in f_sizes: if ref_base[index][f_size] != None: AD_string = "" alt_string = "" freq_string = "" alleles = {} ref_allele = ref_base[index][f_size] #Temporarily assigning keys (base) to value (allele depth) alleles['A'] = int(base_A[index][f_size]) alleles['C'] = int(base_C[index][f_size]) alleles['G'] = int(base_G[index][f_size]) alleles['T'] = int(base_T[index][f_size]) #Sort dict 'alleles' from most-frequent allele to least-frequent allele temp_tuple = sorted(alleles.items(), key=operator.itemgetter(1)) sorted_alleles = [temp_tuple[3][0], temp_tuple[2][0], temp_tuple[1][0], temp_tuple[0][0]] sorted_alleles_depth = [int(temp_tuple[3][1]), int(temp_tuple[2][1]), int(temp_tuple[1][1]), int(temp_tuple[0][1])] #getting index of the reference allele, and ref depth ref_index = int(sorted_alleles.index(ref_allele)) ref_allele_depth = sorted_alleles_depth[ref_index] AD_string = str(ref_allele_depth) #Sample string: ref allele depth, alt allele depth(s) ref_AF = ((ref_allele_depth)/(int(consdps[index][f_size])))*100 freq_string = "{:.2f}".format(ref_AF) filt[index][f_size] = "a10" for count in range(4): if sorted_alleles_depth[count] >= 10: filt[index][f_size] = "PASS" #Check that the allele is not the ref allele and that it has a depth greater than 0, and append to the appropriate string if count != ref_index and sorted_alleles_depth[count] != 0: #AD_string consists of allele depths as: ref_allele_depth, alt_alleles_depth(s) #alt_string consists of all alternate alleles at each base position, ordered from most-frequenct to least-frequent #freq_string consists of the frequency that each alternate allele occurs at a given base position AD_string = AD_string+","+str(sorted_alleles_depth[count]) if alt_string != "": alt_string = alt_string+","+sorted_alleles[count] else: alt_string = sorted_alleles[count] AF_value = ((sorted_alleles_depth[count])/(int(consdps[index][f_size])))*100 freq_string = freq_string+","+"{:.2f}".format(AF_value) if alt_string != "": alt_string_info[index][f_size] = alt_string else: alt_string_info[index][f_size] = "N/A" allele_data[index][f_size] = "AD="+AD_string+":AF="+freq_string sample_data[index][f_size] = "RDP="+rawdps[index][f_size]+":CDP="+consdps[index][f_size]+":MNF="+mean_fams[index][f_size]+":"+allele_data[index][f_size] if (f_size != None) and (intvls == None): min_fam[index][f_size] = "MIF="+str(min(i for i in f_sizes if int(i) > 0)) elif (f_size != None) and (intvls != None): intvl_str = "INTVL="+intvls[index][f_size] min_fam_str = "MIF="+str(min(i for i in f_sizes if int(i) > 0)) min_fam[index][f_size] = min_fam_str+":"+intvl_str def get_vcf_output(cons_file, region_start, region_end, output_path, config, id): cons_is_merged = check_consfile(cons_file) #f_sizes = [int(n) for n in config['SETTINGS']['min_family_sizes'].split(',')] if config else [1, 2, 5] f_sizes=[1,2,5] max_size = max(f_sizes)+1 fams, contigs, ref_base, base_positions, base_A, base_C, base_G, base_T, rawdps, consdps, mean_fams = ([] for i in range(11)) temp_fams, temp_cont, temp_ref, temp_pos, temp_baseA, temp_baseC, temp_baseG, temp_baseT, temp_rawdps, temp_consdps, temp_mf = ([None]*max_size for i in range(11)) if cons_is_merged: intvls = [] temp_intvls = [None]*max_size else: intvls = None fmt_string = "RDP:CDP:MNF:AD:AF" #ref_threshold = float(config['REPORT']['percent_ref_threshold']) if config else 95.0 ref_threshold = 100.0 #Read data from each line of the cons file into the appropriate 2-D list, and ignore/skip cons file if it does not exist try: with open(cons_file, "r") as file: first_line = file.readline().strip() #Get the first line in the cons file headers = first_line.split('\t') reader = csv.DictReader(file, delimiter='\t', fieldnames=headers) next(reader) for line in reader: #Create vcf record for base position only if ref_freq <= ref_threshold when reads are uncollapsed fam_size = int(line['FAM']) ref_freq = float(line['REF_FREQ']) if ref_freq <= ref_threshold: if fam_size in f_sizes: mfam = float(line['MEAN_FAM']) mfam = "{:.2f}".format(mfam) temp_fams[fam_size]=line['FAM']; temp_cont[fam_size]=line['CHROM']; temp_ref[fam_size]=line['REF']; temp_pos[fam_size]=line['POS']; temp_baseA[fam_size]=line['A']; temp_baseC[fam_size]=line['C']; temp_baseG[fam_size]=line['G']; temp_baseT[fam_size]=line['T']; temp_rawdps[fam_size]=line['RAWDP']; temp_consdps[fam_size]=line['CONSDP']; temp_mf[fam_size]=str(mfam) if cons_is_merged: temp_intvls[fam_size]=line['INTVL'] if fam_size == max(f_sizes): if cons_is_merged == False: contigs.append(temp_cont); base_positions.append(temp_pos); ref_base.append(temp_ref); base_A.append(temp_baseA); base_C.append(temp_baseC); base_G.append(temp_baseG); base_T.append(temp_baseT); rawdps.append(temp_rawdps); consdps.append(temp_consdps); fams.append(temp_fams); mean_fams.append(temp_mf) temp_fams, temp_cont, temp_ref, temp_pos, temp_baseA, temp_baseC, temp_baseG, temp_baseT, temp_rawdps, temp_consdps, temp_mf = ([None for x in range(max_size)] for i in range(11)) elif cons_is_merged == True: contigs.append(temp_cont); base_positions.append(temp_pos); ref_base.append(temp_ref); base_A.append(temp_baseA); base_C.append(temp_baseC); base_G.append(temp_baseG); base_T.append(temp_baseT); rawdps.append(temp_rawdps); consdps.append(temp_consdps); fams.append(temp_fams); mean_fams.append(temp_mf); intvls.append(temp_intvls) temp_fams, temp_cont, temp_ref, temp_pos, temp_baseA, temp_baseC, temp_baseG, temp_baseT, temp_rawdps, temp_consdps, temp_mf, temp_intvls = ([None for x in range(max_size)] for i in range(12)) except FileNotFoundError: pass filt, alt_string_info, allele_data, sample_data, min_fam = ([[0 for x in range(max_size)] for y in range(len(contigs))] for i in range(5)) get_data(f_sizes, ref_base, base_A, base_C, base_G, base_T, filt, consdps, alt_string_info, allele_data, sample_data, rawdps, mean_fams, min_fam, intvls) #Write vcf files write_vcf(id, config, contigs, f_sizes, base_positions, region_start, region_end, ref_base, alt_string_info, filt, min_fam, fmt_string, sample_data, output_path, cons_is_merged)
<filename>debarcer/src/generate_vcf.py import sys import pysam import configparser import argparse import operator import functools import csv from src.generate_consensus import ConsDataRow from src.get_ref_seq import get_ref_seq from src.umi_error_correct import UMIGroup from src.get_consensus_seq import get_consensus_seq, get_uncollapsed_seq from src.handle_args import handle_arg from src.get_ref_seq import get_ref_seq from src.generate_consensus import temp_umi_table from src.generate_consensus import generate_uncollapsed from src.generate_consensus import generate_consensus from src.generate_consensus import memoize #from src.generate_merge import check_consfile def parse_raw_table(cons_file, f_sizes): """Parses a .cons file generated by generate_consensus into VCF entries.""" rows = {f_size: [] for f_size in f_sizes} with open(cons_file, "r") as reader: f_size = 0 for line in reader: if line.startswith('#'): f_size = line.split('\t')[11] elif f_size in f_sizes: rows[f_size].append(line) return rows def write_rows(cons_data, f_size, contig, region_start, region_end, output_path, config): with open("{}/{}:{}-{}.{}.vcf".format(output_path, contig, region_start, region_end, f_size), "w") as writer: writer.write("##fileformat=VCFv4.2\n") writer.write("##reference={}\n".format(config['PATHS']['reference_file'])) writer.write("##source=Debarcer2\n") writer.write("##f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata writer.write("##INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") writer.write("##INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") writer.write("##INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") writer.write("##INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") writer.write("##FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") writer.write("##FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth\">\n") writer.write("##FORMAT=<ID=AL,Number=R,Type=Integer,Description=\"Alternate Allele Depth\">\n") writer.write("##FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Alternate Allele Frequency\">\n") writer.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n") for row in cons_data[f_size]: writer.write(row) def vcf_output(cons_file, f_size, contig, region_start, region_end, output_path, config): """Writes a .vcf consensus file.""" with open("{}/{}:{}-{}.fsize{}.vcf".format(output_path, contig, region_start, region_end, f_size), "w") as writer: writer.write("##fileformat=VCFv4.2\n") writer.write("##reference={}\n".format(config['PATHS']['reference_file'])) writer.write("##source=Debarcer2\n") writer.write("##f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata writer.write("##INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") writer.write("##INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") writer.write("##INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") writer.write("##INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") writer.write("##FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") writer.write("##FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth\">\n") writer.write("##FORMAT=<ID=AL,Number=R,Type=Integer,Description=\"Alternate Allele Depth\">\n") writer.write("##FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Alternate Allele Frequency\">\n") ref_threshold = float(config['REPORT']['percent_ref_threshold']) if config else 95.0 all_threshold = float(config['REPORT']['percent_allele_threshold']) if config else 2.0 writer.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n") for base_pos in range(region_start, region_end): if base_pos in cons_data[f_size]: row = cons_data[f_size][base_pos] ref = row.get_ref_info() cons = row.get_cons_info() stats = row.get_stats() if stats['ref_freq'] <= ref_threshold: alleles = row.get_alleles(all_threshold) ref_bases = set([allele[0] for allele in alleles]) ref_allele = (ref_seq[base_pos - region_start], ref_seq[base_pos - region_start]) depths = row.impute_allele_depths() ref_depth = depths[ref_allele] if ref_allele in depths else 0 alt_freqs = row.impute_allele_freqs(all_threshold) info = "RDP={};CDP={};MIF={};MNF={:.1f}".format( stats['rawdp'], stats['consdp'], stats['min_fam'], stats['mean_fam']) fmt_string = "AD:AL:AF" # Allele depth, alt allele depth, reference frequency for ref_base in ref_bases: snips = [] for allele in alleles: if allele[0] == ref_base: snips.append(allele) alt_string = ','.join( [allele[1] for allele in snips] ) depth_string = ','.join( [str(depths[allele]) for allele in snips] ) freq_string = ','.join( ["{:.2f}".format(alt_freqs[allele]) for allele in snips] ) smp_string = "{}:{}:{}".format(ref_depth, depth_string, freq_string) filt = "PASS" if any( [depths[alt] > 10 for alt in snips] ) else "a10" writer.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( contig, base_pos, ".", ref_base, alt_string, "0", filt, info, fmt_string, smp_string)) def create_vcf_output(cons_file, f_size, cons_data, ref_seq, contig, region_start, region_end, output_path, config): #base_positions, ref_bases = {}, {} ref_threshold = float(config['REPORT']['percent_ref_threshold']) if config else 95.0 all_threshold = float(config['REPORT']['percent_allele_threshold']) if config else 2.0 #Read cons file with open(cons_file, "r") as reader: print("Reading cons file") #f_size = 0 i = region_start for line in reader: ref_freq = line.split('\t')[13] if i <= region_end: #contig[i] = line.split('\t')[1] #### CHANGE: Added the following lines base_positions[i] = line.split('\t')[2] ref_bases[i] = line.split('\t')[3] #rawdps[i] = line.split('\t')[10] #consdps[i] = line.split('\t')[11] #f_size[i] = line.split('\t')[12] ##### CHANGE: from [11] to [12] i=+1 with open("{}/{}:{}-{}.{}.vcf".format(output_path, contig, region_start, region_end, f_size), "w") as writer: writer.write("##fileformat=VCFv4.2\n") writer.write("##reference={}\n".format(config['PATHS']['reference_file'])) writer.write("##source=Debarcer2\n") writer.write("##f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata writer.write("##INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") writer.write("##INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") writer.write("##INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") writer.write("##INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") writer.write("##FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") writer.write("##FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth\">\n") writer.write("##FORMAT=<ID=AL,Number=R,Type=Integer,Description=\"Alternate Allele Depth\">\n") writer.write("##FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Alternate Allele Frequency\">\n") writer.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n") for base_pos in range(region_start, region_end): #if any( [base_pos in cons_data[f_size] for f_size in cons_data]): #for f_size in cons_data: if base_pos in cons_data[f_size]: row = cons_data[f_size][base_pos] ref = row.get_ref_info() cons = row.get_cons_info() stats = row.get_stats() if stats['ref_freq'] <= ref_threshold: alleles = row.get_alleles(all_threshold) depths = row.impute_allele_depths() ref_bases = set([allele[0] for allele in alleles]) ref_allele = (ref_seq[base_pos - region_start], ref_seq[base_pos - region_start]) depths = row.impute_allele_depths() ref_depth = depths[ref_allele] if ref_allele in depths else 0 alt_freqs = row.impute_allele_freqs(all_threshold) info = "RDP={};CDP={};MIF={};MNF={:.1f}".format( stats['rawdp'], stats['consdp'], stats['min_fam'], stats['mean_fam']) fmt_string = "AD:AL:AF" # Allele depth, alt allele depth, reference frequency for ref_base in ref_bases: snips = [] for allele in alleles: if allele[0] == ref_base: snips.append(allele) alt_string = ','.join( [allele[1] for allele in snips] ) depth_string = ','.join( [str(depths[allele]) for allele in snips] ) freq_string = ','.join( ["{:.2f}".format(alt_freqs[allele]) for allele in snips] ) smp_string = "{}:{}:{}".format(ref_depth, depth_string, freq_string) filt = "PASS" if any( [depths[alt] > 10 for alt in snips] ) else "a10" writer.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( contig, base_pos, ".", ref_base, alt_string, "0", filt, info, fmt_string, smp_string)) def create_consensus_output(cons_file, f_sizes, contig, region_start, region_end, bam_file, output_path, config): print("Building temporary UMI table...") umi_table = temp_umi_table(contig, region_start, region_end, bam_file, config) ## Lists of umi families with count >= f_size f_sizes = [int(n) for n in config['SETTINGS']['min_family_sizes'].split(',')] if config else [1, 2, 5] ## Get reference sequence for the region print("Getting reference sequence...") ref_seq = get_ref_seq(contig, region_start, region_end, config) ## Get consensus data for each f_size + uncollapsed data print("Building consensus data...") cons_data = {} cons_data[0] = generate_uncollapsed(ref_seq, contig, region_start, region_end, bam_file, config) for f_size in f_sizes: cons_data[f_size] = generate_consensus(umi_table, f_size, ref_seq, contig, region_start, region_end, bam_file, config) if f_size in cons_data: ## Output print("Writing output...") create_vcf_output(cons_file, f_size, cons_data, ref_seq, contig, region_start, region_end, output_path, config) def generate_vcf_output(cons_file, f_sizes, contig, region_start, region_end, output_path, config): """(Main) generates VCF output file(s).""" ## Get reference sequence for the region ref_seq = get_ref_seq(contig, region_start, region_end, config) ## Parse table to extract VCF events cons_data = parse_raw_table(cons_file, f_sizes) ## Generate vcf files for f_size in f_sizes: if f_size in cons_data: write_rows(cons_data, f_size, contig, region_start, region_end, output_path, config) def check_consfile(cons_file): f = open(cons_file, "r") #reader = csv.reader(f, delimiter='\t') line = f.readline() if 'INTVL' in line: return True else: return False def write_vcf(id, config, contigs, f_sizes, base_positions, region_start, region_end, ref_base, alt_string, filt, info, fmt_string, smp_string, output_path, cons_is_merged): ref_threshold = 100.0 #fam_idx = 0 if not cons_is_merged: for i in range(len(contigs)): for size in f_sizes: if contigs[i][size] != None: contig = contigs[i][size] break #Create vcf file for a given base position for specified min fam size for f_size in f_sizes: if cons_is_merged: writer = open("{}/RUNID_{}.{}.vcf".format(output_path, id, str(f_size)), "w") else: writer = open("{}/{}:{}-{}.{}.vcf".format(output_path, contig, region_start, region_end, str(f_size)), "w") writer.write("##fileformat=VCFv4.2\n") writer.write("##reference={}\n".format(config['PATHS']['reference_file'])) writer.write("##source=Debarcer2\n") writer.write("##f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata writer.write("##INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") writer.write("##INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") writer.write("##INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") writer.write("##INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") writer.write("##FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") writer.write("##FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth (ref allele depth, alt allele depth(s))\">\n") writer.write("##FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Allele Frequency (ref allele frequency, alt allele freq(s))\">\n") writer.write("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSAMPLE\n") for index in range(len(contigs)): if contigs[index][f_size] != None: writer.write("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n".format( contigs[index][f_size], base_positions[index][f_size], ".", ref_base[index][f_size], alt_string[index][f_size], "0", filt[index][f_size], info[index][f_size], fmt_string, smp_string[index][f_size])) #fam_idx += 1 def get_data(f_sizes, ref_base, base_A, base_C, base_G, base_T, filt, consdps, alt_string_info, allele_data, sample_data, rawdps, mean_fams, min_fam, intvls): for index in range(len(ref_base)): for f_size in f_sizes: if ref_base[index][f_size] != None: AD_string = "" alt_string = "" freq_string = "" alleles = {} ref_allele = ref_base[index][f_size] #Temporarily assigning keys (base) to value (allele depth) alleles['A'] = int(base_A[index][f_size]) alleles['C'] = int(base_C[index][f_size]) alleles['G'] = int(base_G[index][f_size]) alleles['T'] = int(base_T[index][f_size]) #Sort dict 'alleles' from most-frequent allele to least-frequent allele temp_tuple = sorted(alleles.items(), key=operator.itemgetter(1)) sorted_alleles = [temp_tuple[3][0], temp_tuple[2][0], temp_tuple[1][0], temp_tuple[0][0]] sorted_alleles_depth = [int(temp_tuple[3][1]), int(temp_tuple[2][1]), int(temp_tuple[1][1]), int(temp_tuple[0][1])] #getting index of the reference allele, and ref depth ref_index = int(sorted_alleles.index(ref_allele)) ref_allele_depth = sorted_alleles_depth[ref_index] AD_string = str(ref_allele_depth) #Sample string: ref allele depth, alt allele depth(s) ref_AF = ((ref_allele_depth)/(int(consdps[index][f_size])))*100 freq_string = "{:.2f}".format(ref_AF) filt[index][f_size] = "a10" for count in range(4): if sorted_alleles_depth[count] >= 10: filt[index][f_size] = "PASS" #Check that the allele is not the ref allele and that it has a depth greater than 0, and append to the appropriate string if count != ref_index and sorted_alleles_depth[count] != 0: #AD_string consists of allele depths as: ref_allele_depth, alt_alleles_depth(s) #alt_string consists of all alternate alleles at each base position, ordered from most-frequenct to least-frequent #freq_string consists of the frequency that each alternate allele occurs at a given base position AD_string = AD_string+","+str(sorted_alleles_depth[count]) if alt_string != "": alt_string = alt_string+","+sorted_alleles[count] else: alt_string = sorted_alleles[count] AF_value = ((sorted_alleles_depth[count])/(int(consdps[index][f_size])))*100 freq_string = freq_string+","+"{:.2f}".format(AF_value) if alt_string != "": alt_string_info[index][f_size] = alt_string else: alt_string_info[index][f_size] = "N/A" allele_data[index][f_size] = "AD="+AD_string+":AF="+freq_string sample_data[index][f_size] = "RDP="+rawdps[index][f_size]+":CDP="+consdps[index][f_size]+":MNF="+mean_fams[index][f_size]+":"+allele_data[index][f_size] if (f_size != None) and (intvls == None): min_fam[index][f_size] = "MIF="+str(min(i for i in f_sizes if int(i) > 0)) elif (f_size != None) and (intvls != None): intvl_str = "INTVL="+intvls[index][f_size] min_fam_str = "MIF="+str(min(i for i in f_sizes if int(i) > 0)) min_fam[index][f_size] = min_fam_str+":"+intvl_str def get_vcf_output(cons_file, region_start, region_end, output_path, config, id): cons_is_merged = check_consfile(cons_file) #f_sizes = [int(n) for n in config['SETTINGS']['min_family_sizes'].split(',')] if config else [1, 2, 5] f_sizes=[1,2,5] max_size = max(f_sizes)+1 fams, contigs, ref_base, base_positions, base_A, base_C, base_G, base_T, rawdps, consdps, mean_fams = ([] for i in range(11)) temp_fams, temp_cont, temp_ref, temp_pos, temp_baseA, temp_baseC, temp_baseG, temp_baseT, temp_rawdps, temp_consdps, temp_mf = ([None]*max_size for i in range(11)) if cons_is_merged: intvls = [] temp_intvls = [None]*max_size else: intvls = None fmt_string = "RDP:CDP:MNF:AD:AF" #ref_threshold = float(config['REPORT']['percent_ref_threshold']) if config else 95.0 ref_threshold = 100.0 #Read data from each line of the cons file into the appropriate 2-D list, and ignore/skip cons file if it does not exist try: with open(cons_file, "r") as file: first_line = file.readline().strip() #Get the first line in the cons file headers = first_line.split('\t') reader = csv.DictReader(file, delimiter='\t', fieldnames=headers) next(reader) for line in reader: #Create vcf record for base position only if ref_freq <= ref_threshold when reads are uncollapsed fam_size = int(line['FAM']) ref_freq = float(line['REF_FREQ']) if ref_freq <= ref_threshold: if fam_size in f_sizes: mfam = float(line['MEAN_FAM']) mfam = "{:.2f}".format(mfam) temp_fams[fam_size]=line['FAM']; temp_cont[fam_size]=line['CHROM']; temp_ref[fam_size]=line['REF']; temp_pos[fam_size]=line['POS']; temp_baseA[fam_size]=line['A']; temp_baseC[fam_size]=line['C']; temp_baseG[fam_size]=line['G']; temp_baseT[fam_size]=line['T']; temp_rawdps[fam_size]=line['RAWDP']; temp_consdps[fam_size]=line['CONSDP']; temp_mf[fam_size]=str(mfam) if cons_is_merged: temp_intvls[fam_size]=line['INTVL'] if fam_size == max(f_sizes): if cons_is_merged == False: contigs.append(temp_cont); base_positions.append(temp_pos); ref_base.append(temp_ref); base_A.append(temp_baseA); base_C.append(temp_baseC); base_G.append(temp_baseG); base_T.append(temp_baseT); rawdps.append(temp_rawdps); consdps.append(temp_consdps); fams.append(temp_fams); mean_fams.append(temp_mf) temp_fams, temp_cont, temp_ref, temp_pos, temp_baseA, temp_baseC, temp_baseG, temp_baseT, temp_rawdps, temp_consdps, temp_mf = ([None for x in range(max_size)] for i in range(11)) elif cons_is_merged == True: contigs.append(temp_cont); base_positions.append(temp_pos); ref_base.append(temp_ref); base_A.append(temp_baseA); base_C.append(temp_baseC); base_G.append(temp_baseG); base_T.append(temp_baseT); rawdps.append(temp_rawdps); consdps.append(temp_consdps); fams.append(temp_fams); mean_fams.append(temp_mf); intvls.append(temp_intvls) temp_fams, temp_cont, temp_ref, temp_pos, temp_baseA, temp_baseC, temp_baseG, temp_baseT, temp_rawdps, temp_consdps, temp_mf, temp_intvls = ([None for x in range(max_size)] for i in range(12)) except FileNotFoundError: pass filt, alt_string_info, allele_data, sample_data, min_fam = ([[0 for x in range(max_size)] for y in range(len(contigs))] for i in range(5)) get_data(f_sizes, ref_base, base_A, base_C, base_G, base_T, filt, consdps, alt_string_info, allele_data, sample_data, rawdps, mean_fams, min_fam, intvls) #Write vcf files write_vcf(id, config, contigs, f_sizes, base_positions, region_start, region_end, ref_base, alt_string_info, filt, min_fam, fmt_string, sample_data, output_path, cons_is_merged)
en
0.454644
#from src.generate_merge import check_consfile Parses a .cons file generated by generate_consensus into VCF entries. #fileformat=VCFv4.2\n") #reference={}\n".format(config['PATHS']['reference_file'])) #source=Debarcer2\n") #f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata #INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") #INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") #INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") #INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") #FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") #FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth\">\n") #FORMAT=<ID=AL,Number=R,Type=Integer,Description=\"Alternate Allele Depth\">\n") #FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Alternate Allele Frequency\">\n") Writes a .vcf consensus file. #fileformat=VCFv4.2\n") #reference={}\n".format(config['PATHS']['reference_file'])) #source=Debarcer2\n") #f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata #INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") #INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") #INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") #INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") #FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") #FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth\">\n") #FORMAT=<ID=AL,Number=R,Type=Integer,Description=\"Alternate Allele Depth\">\n") #FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Alternate Allele Frequency\">\n") # Allele depth, alt allele depth, reference frequency #base_positions, ref_bases = {}, {} #Read cons file #f_size = 0 #contig[i] = line.split('\t')[1] #### CHANGE: Added the following lines #rawdps[i] = line.split('\t')[10] #consdps[i] = line.split('\t')[11] #f_size[i] = line.split('\t')[12] ##### CHANGE: from [11] to [12] #fileformat=VCFv4.2\n") #reference={}\n".format(config['PATHS']['reference_file'])) #source=Debarcer2\n") #f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata #INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") #INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") #INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") #INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") #FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") #FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth\">\n") #FORMAT=<ID=AL,Number=R,Type=Integer,Description=\"Alternate Allele Depth\">\n") #FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Alternate Allele Frequency\">\n") #if any( [base_pos in cons_data[f_size] for f_size in cons_data]): #for f_size in cons_data: # Allele depth, alt allele depth, reference frequency ## Lists of umi families with count >= f_size ## Get reference sequence for the region ## Get consensus data for each f_size + uncollapsed data ## Output (Main) generates VCF output file(s). ## Get reference sequence for the region ## Parse table to extract VCF events ## Generate vcf files #reader = csv.reader(f, delimiter='\t') #fam_idx = 0 #Create vcf file for a given base position for specified min fam size #fileformat=VCFv4.2\n") #reference={}\n".format(config['PATHS']['reference_file'])) #source=Debarcer2\n") #f_size={}\n".format(f_size)) ## INFO/FILTER/FORMAT metadata #INFO=<ID=RDP,Number=1,Type=Integer,Description=\"Raw Depth\">\n") #INFO=<ID=CDP,Number=1,Type=Integer,Description=\"Consensus Depth\">\n") #INFO=<ID=MIF,Number=1,Type=Integer,Description=\"Minimum Family Size\">\n") #INFO=<ID=MNF,Number=1,Type=Float,Description=\"Mean Family Size\">\n") #FILTER=<ID=a10,Description=\"Alt allele depth below 10\">\n") #FORMAT=<ID=AD,Number=1,Type=Integer,Description=\"Allele Depth (ref allele depth, alt allele depth(s))\">\n") #FORMAT=<ID=AF,Number=R,Type=Float,Description=\"Allele Frequency (ref allele frequency, alt allele freq(s))\">\n") #fam_idx += 1 #Temporarily assigning keys (base) to value (allele depth) #Sort dict 'alleles' from most-frequent allele to least-frequent allele #getting index of the reference allele, and ref depth #Sample string: ref allele depth, alt allele depth(s) #Check that the allele is not the ref allele and that it has a depth greater than 0, and append to the appropriate string #AD_string consists of allele depths as: ref_allele_depth, alt_alleles_depth(s) #alt_string consists of all alternate alleles at each base position, ordered from most-frequenct to least-frequent #freq_string consists of the frequency that each alternate allele occurs at a given base position #f_sizes = [int(n) for n in config['SETTINGS']['min_family_sizes'].split(',')] if config else [1, 2, 5] #ref_threshold = float(config['REPORT']['percent_ref_threshold']) if config else 95.0 #Read data from each line of the cons file into the appropriate 2-D list, and ignore/skip cons file if it does not exist #Get the first line in the cons file #Create vcf record for base position only if ref_freq <= ref_threshold when reads are uncollapsed #Write vcf files
2.53169
3
analyze/__init__.py
sssssssuzuki/autd3-paper
0
6615480
<gh_stars>0 ''' File: __init__.py Project: analyze Created Date: 16/02/2021 Author: <NAME> ----- Last Modified: 16/02/2021 Modified By: <NAME> (<EMAIL>) ----- Copyright (c) 2021 Hapis Lab. All rights reserved. '''
''' File: __init__.py Project: analyze Created Date: 16/02/2021 Author: <NAME> ----- Last Modified: 16/02/2021 Modified By: <NAME> (<EMAIL>) ----- Copyright (c) 2021 Hapis Lab. All rights reserved. '''
en
0.632574
File: __init__.py Project: analyze Created Date: 16/02/2021 Author: <NAME> ----- Last Modified: 16/02/2021 Modified By: <NAME> (<EMAIL>) ----- Copyright (c) 2021 Hapis Lab. All rights reserved.
0.972146
1
utils/functionnal.py
Zadigo/zineb
3
6615481
<filename>utils/functionnal.py import operator import copy def create_proxy_function(func): def inner(self, *args, **kwargs): if self.cached_object is None: self._init_object() return func(self.cached_object, *args, **kwargs) return inner class LazyObject: cached_object = None def __init__(self): self.cached_object = None def __getattr__(self, name): if self.cached_object is None: self._init_object() return getattr(self.cached_object, name) def __setattr__(self, name, value): if name == 'cached_object': self.__dict__['cached_object'] = value if self.cached_object is None: self._init_object() setattr(self.cached_object, name, value) def __delattr__(self, name): if self.cached_object is None: self._init_object() delattr(self.cached_object, name) def __copy__(self): if self.cached_object is None: return type(self)() return copy.copy(self.cached_object) def __call__(self, **kwargs): if self.cached_object is None: self._init_object() self.cached_object(**kwargs) __dir__ = create_proxy_function(dir) __str__ = create_proxy_function(str) __repr__ = create_proxy_function(repr) __getitem__ = create_proxy_function(operator.getitem) __setitem__ = create_proxy_function(operator.setitem) def _init_object(self): """ Use this class to implement the element that should stored in the cached_object attribute """ pass
<filename>utils/functionnal.py import operator import copy def create_proxy_function(func): def inner(self, *args, **kwargs): if self.cached_object is None: self._init_object() return func(self.cached_object, *args, **kwargs) return inner class LazyObject: cached_object = None def __init__(self): self.cached_object = None def __getattr__(self, name): if self.cached_object is None: self._init_object() return getattr(self.cached_object, name) def __setattr__(self, name, value): if name == 'cached_object': self.__dict__['cached_object'] = value if self.cached_object is None: self._init_object() setattr(self.cached_object, name, value) def __delattr__(self, name): if self.cached_object is None: self._init_object() delattr(self.cached_object, name) def __copy__(self): if self.cached_object is None: return type(self)() return copy.copy(self.cached_object) def __call__(self, **kwargs): if self.cached_object is None: self._init_object() self.cached_object(**kwargs) __dir__ = create_proxy_function(dir) __str__ = create_proxy_function(str) __repr__ = create_proxy_function(repr) __getitem__ = create_proxy_function(operator.getitem) __setitem__ = create_proxy_function(operator.setitem) def _init_object(self): """ Use this class to implement the element that should stored in the cached_object attribute """ pass
en
0.745552
Use this class to implement the element that should stored in the cached_object attribute
3.035753
3
setup.py
dillon-cullinan/asvdb
0
6615482
from setuptools import setup import asvdb setup(name="asvdb", version=asvdb.__version__, packages=["asvdb"], description='ASV "database" interface', entry_points={ "console_scripts": [ "asvdb = asvdb.__main__:main" ] }, )
from setuptools import setup import asvdb setup(name="asvdb", version=asvdb.__version__, packages=["asvdb"], description='ASV "database" interface', entry_points={ "console_scripts": [ "asvdb = asvdb.__main__:main" ] }, )
none
1
1.138155
1
applications/LinearSolversApplication/tests/test_eigen_dense_decompositions.py
lkusch/Kratos
0
6615483
<filename>applications/LinearSolversApplication/tests/test_eigen_dense_decompositions.py<gh_stars>0 from __future__ import print_function, absolute_import, division import random import KratosMultiphysics import KratosMultiphysics.KratosUnittest as KratosUnittest import KratosMultiphysics.LinearSolversApplication as LinearSolversApplication class TestEigenDenseDecompositions(KratosUnittest.TestCase): def _square_matrix_3x3(self): A = KratosMultiphysics.Matrix(3,3) A[0,0] = 0.57690 A[0,1] = 0.28760 A[0,2] = 0.63942 A[1,0] = 0.72886 A[1,1] = 0.40541 A[1,2] = 0.13415 A[2,0] = 0.81972 A[2,1] = 0.54501 A[2,2] = 0.28974 return A def _random_matrix_mxn(self, m, n): A = KratosMultiphysics.Matrix(m,n) for i in range(m): for j in range(n): A[i,j] = random.random() return A def _execute_eigen_dense_decomposition_test(self, decomposition, generate_matrix_function, thin_u_v = False): # Generate the sampling matrix A = generate_matrix_function() # Compute the SVD decomposition S = KratosMultiphysics.Vector() U = KratosMultiphysics.Matrix() V = KratosMultiphysics.Matrix() settings = KratosMultiphysics.Parameters('''{}''') if thin_u_v: settings.AddBool("compute_thin_u", True) settings.AddBool("compute_thin_v", True) decomposition.Compute(A, S, U, V, settings) # Reconstruct the sampling matrix with the SVD arrays aux_S_mat = KratosMultiphysics.Matrix(S.Size(), V.Size2(), 0.0) for i in range(S.Size()): aux_S_mat[i,i] = S[i] m = A.Size1() n = A.Size2() A_svd = KratosMultiphysics.Matrix(m, n, 0.0) for i in range(m): for j in range(n): for k in range(U.Size2()): for m in range(aux_S_mat.Size2()): A_svd[i,j] += U[i,k] * aux_S_mat[k,m] * V[j,m] # Check that input matrix equals the decomposition reconstructed one for i in range(A.Size1()): for j in range(A.Size2()): self.assertAlmostEqual(A[i,j], A_svd[i,j], 7) def test_eigen_dense_BDC_SVD_3x3(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, self._square_matrix_3x3) def test_eigen_dense_BDC_SVD_5x4_random(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(5,4)) def test_eigen_dense_BDC_SVD_3x10_random(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(3,10)) def test_eigen_dense_BDC_SVD_5x4_random_thin(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(5,4), True) def test_eigen_dense_BDC_SVD_3x10_random_thin(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(3,10), True) def test_eigen_dense_Jacobi_SVD_3x3(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, self._square_matrix_3x3) def test_eigen_dense_Jacobi_SVD_5x4_random(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(5,4)) def test_eigen_dense_Jacobi_SVD_3x10_random(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(3,10)) def test_eigen_dense_Jacobi_SVD_5x4_random_thin(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(5,4), True) def test_eigen_dense_Jacobi_SVD_3x10_random_thin(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(3,10), True) if __name__ == '__main__': KratosUnittest.main()
<filename>applications/LinearSolversApplication/tests/test_eigen_dense_decompositions.py<gh_stars>0 from __future__ import print_function, absolute_import, division import random import KratosMultiphysics import KratosMultiphysics.KratosUnittest as KratosUnittest import KratosMultiphysics.LinearSolversApplication as LinearSolversApplication class TestEigenDenseDecompositions(KratosUnittest.TestCase): def _square_matrix_3x3(self): A = KratosMultiphysics.Matrix(3,3) A[0,0] = 0.57690 A[0,1] = 0.28760 A[0,2] = 0.63942 A[1,0] = 0.72886 A[1,1] = 0.40541 A[1,2] = 0.13415 A[2,0] = 0.81972 A[2,1] = 0.54501 A[2,2] = 0.28974 return A def _random_matrix_mxn(self, m, n): A = KratosMultiphysics.Matrix(m,n) for i in range(m): for j in range(n): A[i,j] = random.random() return A def _execute_eigen_dense_decomposition_test(self, decomposition, generate_matrix_function, thin_u_v = False): # Generate the sampling matrix A = generate_matrix_function() # Compute the SVD decomposition S = KratosMultiphysics.Vector() U = KratosMultiphysics.Matrix() V = KratosMultiphysics.Matrix() settings = KratosMultiphysics.Parameters('''{}''') if thin_u_v: settings.AddBool("compute_thin_u", True) settings.AddBool("compute_thin_v", True) decomposition.Compute(A, S, U, V, settings) # Reconstruct the sampling matrix with the SVD arrays aux_S_mat = KratosMultiphysics.Matrix(S.Size(), V.Size2(), 0.0) for i in range(S.Size()): aux_S_mat[i,i] = S[i] m = A.Size1() n = A.Size2() A_svd = KratosMultiphysics.Matrix(m, n, 0.0) for i in range(m): for j in range(n): for k in range(U.Size2()): for m in range(aux_S_mat.Size2()): A_svd[i,j] += U[i,k] * aux_S_mat[k,m] * V[j,m] # Check that input matrix equals the decomposition reconstructed one for i in range(A.Size1()): for j in range(A.Size2()): self.assertAlmostEqual(A[i,j], A_svd[i,j], 7) def test_eigen_dense_BDC_SVD_3x3(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, self._square_matrix_3x3) def test_eigen_dense_BDC_SVD_5x4_random(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(5,4)) def test_eigen_dense_BDC_SVD_3x10_random(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(3,10)) def test_eigen_dense_BDC_SVD_5x4_random_thin(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(5,4), True) def test_eigen_dense_BDC_SVD_3x10_random_thin(self): decomposition = LinearSolversApplication.EigenDenseBDCSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(3,10), True) def test_eigen_dense_Jacobi_SVD_3x3(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, self._square_matrix_3x3) def test_eigen_dense_Jacobi_SVD_5x4_random(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(5,4)) def test_eigen_dense_Jacobi_SVD_3x10_random(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(3,10)) def test_eigen_dense_Jacobi_SVD_5x4_random_thin(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(5,4), True) def test_eigen_dense_Jacobi_SVD_3x10_random_thin(self): decomposition = LinearSolversApplication.EigenDenseJacobiSVD() self._execute_eigen_dense_decomposition_test(decomposition, lambda : self._random_matrix_mxn(3,10), True) if __name__ == '__main__': KratosUnittest.main()
en
0.752937
# Generate the sampling matrix # Compute the SVD decomposition {} # Reconstruct the sampling matrix with the SVD arrays # Check that input matrix equals the decomposition reconstructed one
2.20753
2
RDF/test_script.py
NJManganelli/FourTopNAOD
1
6615484
<reponame>NJManganelli/FourTopNAOD import ROOT import numpy import ctypes import array ROOT.gROOT.ProcessLine(".L FTFunctions.cpp") print("Testing HLT SF for tight-tight ID leptons in emu channel") xvec = array.array('d', [20, 40, 60, 80, 100, 150, 200]) yvec = array.array('d', [15, 30, 45, 60, 80, 100, 150, 200]) HLTSF = ROOT.TH2D("HLTSF", "HLT SF test; lep1 pt(); lep2 pt()", 6, xvec, 7, yvec) for xin in [30, 50, 70, 90, 125, 175]: for yin in [22.5, 37.5, 52.5, 70, 90, 125, 175]: z = ROOT.FTA.ElMu2017HLTSF(xin, yin) if z > 0: HLTSF.Fill(xin, yin, z) hltcan = ROOT.TCanvas("HLTCAN", "", 800, 600) HLTSF.SetMinimum(0.88) HLTSF.SetMaximum(0.998) HLTSF.Draw("COLZ TEXT") hltcan.Draw() f_mc = "/eos/user/n/nmangane/data/20200403/mc_test_file.root" f_data = "/eos/user/n/nmangane/data/20200403/data_test_file.root" print("Test files for...\nMC:{}\nData:{}".format(f_mc, f_data)) print("Testing TH2Lookup class") aa = ROOT.TH2Lookup("/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/select_20200403/ElMu_selection/BtaggingYields/BTaggingYields.root") ROOT.gInterpreter.Declare("TH2Lookup* yielder;") ROOT.yielder = aa valnJet = ctypes.c_int(6) valHT = ctypes.c_double(823) valYield = ROOT.yielder.getEventYieldRatio("Aggregate", "_deepcsv", valnJet.value, valHT.value) print("Yield value: {}".format(valYield)) v=ROOT.std.vector(str)(3) v[0]="Inclusive_bjets_DeepCSV_M" v[1]="Inclusive_cjets_DeepCSV_M" v[2]="Inclusive_udsgjets_DeepCSV_M" for vv in v: print(vv) a = ROOT.TH2Lookup("/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/select_20200323/ElMu_selection/BtaggingEfficiency/tt_DL-GF_BTagEff.root", v) ROOT.gInterpreter.Declare("TH2Lookup* alook;") ROOT.alook = a r = ROOT.ROOT.RDataFrame("Events", f_mc)#.Range(1000) rd = r.Define("Jet_eff", 'alook->getJetEfficiency("Inclusive", "DeepCSV_M", &Jet_hadronFlavour, &Jet_pt, &Jet_eta)') print("Testing FTA::generateIndices function") jidx = r.Range(10).Define("Jet_idx", "FTA::generateIndices(Jet_pt);").AsNumpy(["Jet_idx", "nJet"]) print(jidx["Jet_idx"]) print(jidx["nJet"]) print("Testing FTA::METXYCorr function") rd = rd.Define("MET_xycorr_doublet", "FTA::METXYCorr(METFixEE2017_pt, METFixEE2017_phi, run, 2017, false, PV_npvs)") rd = rd.Define("MET_xycorr_pt", "MET_xycorr_doublet.first") rd = rd.Define("MET_xycorr_phi", "MET_xycorr_doublet.second") rd = rd.Define("MET_xycorr_pt_shift", "MET_xycorr_pt - METFixEE2017_pt") rd = rd.Define("MET_xycorr_phi_shift", "abs(MET_xycorr_phi - METFixEE2017_phi)") print("Testing FTA::btagEventWeight_shape function") rd =rd.Define("jet_mask", "Jet_pt > 20 && abs(Jet_eta) < 2.5") rd = rd.Define("btagPreEventWeight", "genWeight * FTA::btagEventWeight_shape(Jet_btagSF_deepcsv_shape, jet_mask)") rd = rd.Define("btagEventWeight", "btagPreEventWeight * yielder->getEventYieldRatio(\"Aggregate\", \"_deepcsv\", Jet_pt[jet_mask].size(), Sum(Jet_pt[jet_mask]));") rd = rd.Define("btagPreShift", "(1 - btagPreEventWeight/genWeight)") rd = rd.Define("btagFinalShift", "(1 - btagEventWeight/genWeight)") s1 = rd.Mean("MET_xycorr_pt_shift") s11 = rd.Mean("MET_xycorr_phi_shift") r2 = ROOT.ROOT.RDataFrame("Events", f_data)#.Range(1000) rd2 = r2.Define("genWeight", "double y = 1.0; return y;") #fake the genweight for simplicity of test rd2 = rd2.Define("MET_xycorr_doublet", "FTA::METXYCorr(METFixEE2017_pt, METFixEE2017_phi, run, 2017, true, PV_npvs)") rd2 = rd2.Define("MET_xycorr_pt", "MET_xycorr_doublet.first") rd2 = rd2.Define("MET_xycorr_phi", "MET_xycorr_doublet.second") rd2 = rd2.Define("MET_xycorr_pt_shift", "MET_xycorr_pt - METFixEE2017_pt") rd2 = rd2.Define("MET_xycorr_phi_shift", "(MET_xycorr_phi - METFixEE2017_phi)") s2 = rd2.Mean("MET_xycorr_pt_shift") s22 = rd2.Mean("MET_xycorr_phi_shift") # n = rd.AsNumpy("Jet_eff") # print(n) print("{} {} {} {}".format(s1.GetValue(), s11.GetValue(), s2.GetValue(), s22.GetValue())) hists = {} canv = {} #MC #hists["MC_jet_eff"] = rd.Histo1D(("hr", "", 100, 0, 1), "Jet_eff", "genWeight") #hists["MC_pt"] = rd.Histo2D(("hpt", "", 120, 0, 1200, 120, 0, 1200), "METFixEE2017_pt", "MET_xycorr_pt", "genWeight") #hists["MC_phi"] = rd.Histo2D(("hphi", "", 72, -3.14, 3.14, 72, -3.14, 3.14), "METFixEE2017_phi", "MET_xycorr_phi", "genWeight") hists["MC_phi_uncorr"] = rd.Histo1D(("hphi_uncorr", "", 36, -3.14, 3.14), "METFixEE2017_phi", "genWeight") hists["MC_phi_corr"] = rd.Histo1D(("hphi_corr", "", 36, -3.14, 3.14), "MET_xycorr_phi", "genWeight") hists["MC_pt_shift"] = rd.Histo1D(("hpt_shift", "", 100, -10, 10), "MET_xycorr_pt_shift", "genWeight") hists["MC_phi_shift"] = rd.Histo1D(("hphi_shift", "", 72, -3.14, 3.14), "MET_xycorr_phi_shift", "genWeight") hists["MC_btagPreShift"] = rd.Histo1D(("hbtagPreShift", "", 100, -1, 1), "btagPreShift") hists["MC_btagFinalShift"] = rd.Histo1D(("hbtagFinalShift", "", 100, -1, 1), "btagFinalShift") #Data #hists["Data_pt"] = rd2.Histo2D(("hdpt", "", 120, 0, 1200, 120, 0, 1200), "METFixEE2017_pt", "MET_xycorr_pt", "genWeight") #hists["Data_phi"] = rd2.Histo2D(("hdphi", "", 72, -3.14, 3.14, 72, -3.14, 3.14), "METFixEE2017_phi", "MET_xycorr_phi", "genWeight") hists["Data_phi_uncorr"] = rd2.Histo1D(("hdphi_uncorr", "", 36, -3.14, 3.14), "METFixEE2017_phi", "genWeight") hists["Data_phi_corr"] = rd2.Histo1D(("hdphi_corr", "", 36, -3.14, 3.14), "MET_xycorr_phi", "genWeight") hists["Data_pt_shift"] = rd.Histo1D(("hdpt_shift", "", 100, -10, 10), "MET_xycorr_pt_shift", "genWeight") hists["Data_phi_shift"] = rd.Histo1D(("hdphi_shift", "", 72, -3.14, 3.14), "MET_xycorr_phi_shift", "genWeight") for hname, hist in hists.items(): t = type(hist.GetValue()) if "TH2" in str(t): canv[hname] = ROOT.TCanvas("c_{}".format(hname), "", 800, 600) hist.Draw("COLZ TEXT") else: if "Data_" in hname: continue canv[hname] = ROOT.TCanvas("c_{}".format(hname), "", 800, 600) hist.DrawNormalized("HIST") if hname.replace("MC_", "Data_") in hists: hists["{}".format(hname.replace("MC_","Data_"))].SetLineColor(ROOT.kRed) hists["{}".format(hname.replace("MC_","Data_"))].DrawNormalized("HIST SAME") if "eff" in hname: canv[hname].SetLogx() canv[hname].Draw()
import ROOT import numpy import ctypes import array ROOT.gROOT.ProcessLine(".L FTFunctions.cpp") print("Testing HLT SF for tight-tight ID leptons in emu channel") xvec = array.array('d', [20, 40, 60, 80, 100, 150, 200]) yvec = array.array('d', [15, 30, 45, 60, 80, 100, 150, 200]) HLTSF = ROOT.TH2D("HLTSF", "HLT SF test; lep1 pt(); lep2 pt()", 6, xvec, 7, yvec) for xin in [30, 50, 70, 90, 125, 175]: for yin in [22.5, 37.5, 52.5, 70, 90, 125, 175]: z = ROOT.FTA.ElMu2017HLTSF(xin, yin) if z > 0: HLTSF.Fill(xin, yin, z) hltcan = ROOT.TCanvas("HLTCAN", "", 800, 600) HLTSF.SetMinimum(0.88) HLTSF.SetMaximum(0.998) HLTSF.Draw("COLZ TEXT") hltcan.Draw() f_mc = "/eos/user/n/nmangane/data/20200403/mc_test_file.root" f_data = "/eos/user/n/nmangane/data/20200403/data_test_file.root" print("Test files for...\nMC:{}\nData:{}".format(f_mc, f_data)) print("Testing TH2Lookup class") aa = ROOT.TH2Lookup("/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/select_20200403/ElMu_selection/BtaggingYields/BTaggingYields.root") ROOT.gInterpreter.Declare("TH2Lookup* yielder;") ROOT.yielder = aa valnJet = ctypes.c_int(6) valHT = ctypes.c_double(823) valYield = ROOT.yielder.getEventYieldRatio("Aggregate", "_deepcsv", valnJet.value, valHT.value) print("Yield value: {}".format(valYield)) v=ROOT.std.vector(str)(3) v[0]="Inclusive_bjets_DeepCSV_M" v[1]="Inclusive_cjets_DeepCSV_M" v[2]="Inclusive_udsgjets_DeepCSV_M" for vv in v: print(vv) a = ROOT.TH2Lookup("/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/select_20200323/ElMu_selection/BtaggingEfficiency/tt_DL-GF_BTagEff.root", v) ROOT.gInterpreter.Declare("TH2Lookup* alook;") ROOT.alook = a r = ROOT.ROOT.RDataFrame("Events", f_mc)#.Range(1000) rd = r.Define("Jet_eff", 'alook->getJetEfficiency("Inclusive", "DeepCSV_M", &Jet_hadronFlavour, &Jet_pt, &Jet_eta)') print("Testing FTA::generateIndices function") jidx = r.Range(10).Define("Jet_idx", "FTA::generateIndices(Jet_pt);").AsNumpy(["Jet_idx", "nJet"]) print(jidx["Jet_idx"]) print(jidx["nJet"]) print("Testing FTA::METXYCorr function") rd = rd.Define("MET_xycorr_doublet", "FTA::METXYCorr(METFixEE2017_pt, METFixEE2017_phi, run, 2017, false, PV_npvs)") rd = rd.Define("MET_xycorr_pt", "MET_xycorr_doublet.first") rd = rd.Define("MET_xycorr_phi", "MET_xycorr_doublet.second") rd = rd.Define("MET_xycorr_pt_shift", "MET_xycorr_pt - METFixEE2017_pt") rd = rd.Define("MET_xycorr_phi_shift", "abs(MET_xycorr_phi - METFixEE2017_phi)") print("Testing FTA::btagEventWeight_shape function") rd =rd.Define("jet_mask", "Jet_pt > 20 && abs(Jet_eta) < 2.5") rd = rd.Define("btagPreEventWeight", "genWeight * FTA::btagEventWeight_shape(Jet_btagSF_deepcsv_shape, jet_mask)") rd = rd.Define("btagEventWeight", "btagPreEventWeight * yielder->getEventYieldRatio(\"Aggregate\", \"_deepcsv\", Jet_pt[jet_mask].size(), Sum(Jet_pt[jet_mask]));") rd = rd.Define("btagPreShift", "(1 - btagPreEventWeight/genWeight)") rd = rd.Define("btagFinalShift", "(1 - btagEventWeight/genWeight)") s1 = rd.Mean("MET_xycorr_pt_shift") s11 = rd.Mean("MET_xycorr_phi_shift") r2 = ROOT.ROOT.RDataFrame("Events", f_data)#.Range(1000) rd2 = r2.Define("genWeight", "double y = 1.0; return y;") #fake the genweight for simplicity of test rd2 = rd2.Define("MET_xycorr_doublet", "FTA::METXYCorr(METFixEE2017_pt, METFixEE2017_phi, run, 2017, true, PV_npvs)") rd2 = rd2.Define("MET_xycorr_pt", "MET_xycorr_doublet.first") rd2 = rd2.Define("MET_xycorr_phi", "MET_xycorr_doublet.second") rd2 = rd2.Define("MET_xycorr_pt_shift", "MET_xycorr_pt - METFixEE2017_pt") rd2 = rd2.Define("MET_xycorr_phi_shift", "(MET_xycorr_phi - METFixEE2017_phi)") s2 = rd2.Mean("MET_xycorr_pt_shift") s22 = rd2.Mean("MET_xycorr_phi_shift") # n = rd.AsNumpy("Jet_eff") # print(n) print("{} {} {} {}".format(s1.GetValue(), s11.GetValue(), s2.GetValue(), s22.GetValue())) hists = {} canv = {} #MC #hists["MC_jet_eff"] = rd.Histo1D(("hr", "", 100, 0, 1), "Jet_eff", "genWeight") #hists["MC_pt"] = rd.Histo2D(("hpt", "", 120, 0, 1200, 120, 0, 1200), "METFixEE2017_pt", "MET_xycorr_pt", "genWeight") #hists["MC_phi"] = rd.Histo2D(("hphi", "", 72, -3.14, 3.14, 72, -3.14, 3.14), "METFixEE2017_phi", "MET_xycorr_phi", "genWeight") hists["MC_phi_uncorr"] = rd.Histo1D(("hphi_uncorr", "", 36, -3.14, 3.14), "METFixEE2017_phi", "genWeight") hists["MC_phi_corr"] = rd.Histo1D(("hphi_corr", "", 36, -3.14, 3.14), "MET_xycorr_phi", "genWeight") hists["MC_pt_shift"] = rd.Histo1D(("hpt_shift", "", 100, -10, 10), "MET_xycorr_pt_shift", "genWeight") hists["MC_phi_shift"] = rd.Histo1D(("hphi_shift", "", 72, -3.14, 3.14), "MET_xycorr_phi_shift", "genWeight") hists["MC_btagPreShift"] = rd.Histo1D(("hbtagPreShift", "", 100, -1, 1), "btagPreShift") hists["MC_btagFinalShift"] = rd.Histo1D(("hbtagFinalShift", "", 100, -1, 1), "btagFinalShift") #Data #hists["Data_pt"] = rd2.Histo2D(("hdpt", "", 120, 0, 1200, 120, 0, 1200), "METFixEE2017_pt", "MET_xycorr_pt", "genWeight") #hists["Data_phi"] = rd2.Histo2D(("hdphi", "", 72, -3.14, 3.14, 72, -3.14, 3.14), "METFixEE2017_phi", "MET_xycorr_phi", "genWeight") hists["Data_phi_uncorr"] = rd2.Histo1D(("hdphi_uncorr", "", 36, -3.14, 3.14), "METFixEE2017_phi", "genWeight") hists["Data_phi_corr"] = rd2.Histo1D(("hdphi_corr", "", 36, -3.14, 3.14), "MET_xycorr_phi", "genWeight") hists["Data_pt_shift"] = rd.Histo1D(("hdpt_shift", "", 100, -10, 10), "MET_xycorr_pt_shift", "genWeight") hists["Data_phi_shift"] = rd.Histo1D(("hdphi_shift", "", 72, -3.14, 3.14), "MET_xycorr_phi_shift", "genWeight") for hname, hist in hists.items(): t = type(hist.GetValue()) if "TH2" in str(t): canv[hname] = ROOT.TCanvas("c_{}".format(hname), "", 800, 600) hist.Draw("COLZ TEXT") else: if "Data_" in hname: continue canv[hname] = ROOT.TCanvas("c_{}".format(hname), "", 800, 600) hist.DrawNormalized("HIST") if hname.replace("MC_", "Data_") in hists: hists["{}".format(hname.replace("MC_","Data_"))].SetLineColor(ROOT.kRed) hists["{}".format(hname.replace("MC_","Data_"))].DrawNormalized("HIST SAME") if "eff" in hname: canv[hname].SetLogx() canv[hname].Draw()
en
0.295605
#.Range(1000) #.Range(1000) #fake the genweight for simplicity of test # n = rd.AsNumpy("Jet_eff") # print(n) #MC #hists["MC_jet_eff"] = rd.Histo1D(("hr", "", 100, 0, 1), "Jet_eff", "genWeight") #hists["MC_pt"] = rd.Histo2D(("hpt", "", 120, 0, 1200, 120, 0, 1200), "METFixEE2017_pt", "MET_xycorr_pt", "genWeight") #hists["MC_phi"] = rd.Histo2D(("hphi", "", 72, -3.14, 3.14, 72, -3.14, 3.14), "METFixEE2017_phi", "MET_xycorr_phi", "genWeight") #Data #hists["Data_pt"] = rd2.Histo2D(("hdpt", "", 120, 0, 1200, 120, 0, 1200), "METFixEE2017_pt", "MET_xycorr_pt", "genWeight") #hists["Data_phi"] = rd2.Histo2D(("hdphi", "", 72, -3.14, 3.14, 72, -3.14, 3.14), "METFixEE2017_phi", "MET_xycorr_phi", "genWeight")
2.089443
2
tp4/entrega/preproceso.py
mvpossum/deep-learning
1
6615485
import os import re import os.path import argparse import paths import numpy as np from PIL import Image, ImageFont, ImageOps, ImageEnhance from PIL.ImageDraw import Draw contrast_ratio = 3 def resize(img,hMax): (wIm,hIm) = img.size ratio = hMax/float(hIm) (wNewIm,hNewIm) = (int(wIm*ratio),hMax) newIm = img.resize((wNewIm,hNewIm),Image.ANTIALIAS) return newIm def fill_border(img,left,right,hMax): arr = np.asarray(img) col = 255 l=np.full((hMax,left), col, dtype=np.uint8) r=np.full((hMax,right), col, dtype=np.uint8) arr=np.c_[l,arr,r] img=Image.fromarray(arr) return img def crop_and_save_line(image,ymin,ymax,name): xmin = 0 xmax = image.size[0] line_image = image.crop((xmin,ymin,xmax,ymax)) line_image=resize(line_image,32) line_image=fill_border(line_image,16,16,32) contrast=ImageEnhance.Contrast(line_image) line_image=contrast.enhance(contrast_ratio) if paths.previewPath(): line_image.save(os.path.join(paths.previewPath() , name)) return line_image def refine_line_bounds(image): ymin = 0 ymax = image.size[1] contrast = ImageEnhance.Contrast(image) line_np = 255 - np.array(contrast.enhance(2)) histo = np.square(np.mean(line_np,axis=(1))) prob = histo / np.sum(histo) y = np.asarray(range(ymin,ymax)) y_mean = np.dot(prob,y) s = (y - y_mean)**2 s = np.sqrt(np.dot(prob,s)) ymax = min(ymax,int(round(y_mean+2*s))) ymin = max(ymin,int(round(y_mean-1.2*s))) return ymin, ymax def preprocessOne(f): img = Image.open(f) img = ImageOps.grayscale(img) ymin, ymax = 0, img.size[1] baseName=os.path.basename(f) img = crop_and_save_line(img,ymin,ymax, baseName) return baseName,img
import os import re import os.path import argparse import paths import numpy as np from PIL import Image, ImageFont, ImageOps, ImageEnhance from PIL.ImageDraw import Draw contrast_ratio = 3 def resize(img,hMax): (wIm,hIm) = img.size ratio = hMax/float(hIm) (wNewIm,hNewIm) = (int(wIm*ratio),hMax) newIm = img.resize((wNewIm,hNewIm),Image.ANTIALIAS) return newIm def fill_border(img,left,right,hMax): arr = np.asarray(img) col = 255 l=np.full((hMax,left), col, dtype=np.uint8) r=np.full((hMax,right), col, dtype=np.uint8) arr=np.c_[l,arr,r] img=Image.fromarray(arr) return img def crop_and_save_line(image,ymin,ymax,name): xmin = 0 xmax = image.size[0] line_image = image.crop((xmin,ymin,xmax,ymax)) line_image=resize(line_image,32) line_image=fill_border(line_image,16,16,32) contrast=ImageEnhance.Contrast(line_image) line_image=contrast.enhance(contrast_ratio) if paths.previewPath(): line_image.save(os.path.join(paths.previewPath() , name)) return line_image def refine_line_bounds(image): ymin = 0 ymax = image.size[1] contrast = ImageEnhance.Contrast(image) line_np = 255 - np.array(contrast.enhance(2)) histo = np.square(np.mean(line_np,axis=(1))) prob = histo / np.sum(histo) y = np.asarray(range(ymin,ymax)) y_mean = np.dot(prob,y) s = (y - y_mean)**2 s = np.sqrt(np.dot(prob,s)) ymax = min(ymax,int(round(y_mean+2*s))) ymin = max(ymin,int(round(y_mean-1.2*s))) return ymin, ymax def preprocessOne(f): img = Image.open(f) img = ImageOps.grayscale(img) ymin, ymax = 0, img.size[1] baseName=os.path.basename(f) img = crop_and_save_line(img,ymin,ymax, baseName) return baseName,img
none
1
2.766356
3
upload_site.py
caltechlibrary/caltechdata_migrate
1
6615486
<gh_stars>1-10 from caltechdata_api import caltechdata_edit from caltechdata_api import caltechdata_write from update_doi import update_doi from create_doi import create_doi import requests import os,glob,json,csv,subprocess,datetime,copy,argparse path = '/data/tccon/temp' #Switch for test or production production = True os.chdir(path) token = os.environ['TINDTOK'] parser = argparse.ArgumentParser(description=\ "Creates a new TCCON site") parser.add_argument('sid', metavar='ID', type=str,nargs='+',\ help='The TCCON two letter Site ID (e.g. pa for park falls)') args = parser.parse_args() #For each new site release for skey in args.sid: #Gather information about release #sname = T_FULL[skey] sname =\ subprocess.check_output(['get_site_name',skey]).decode("utf-8").rstrip() new_version = 'R0' #Get new file sitef = glob.glob(skey+'*.nc') if len(sitef) != 1: print("Cannot find public site file in /data/tccon/temp") exit() else: sitef = sitef[0] #Re-read metadata mfname =\ '/data/tccon/metadata/tccon.ggg2014.'+sname+'.'+new_version+".json" metaf = open(mfname,'r') metadata = json.load(metaf) #Generate new readme email =\ subprocess.check_output(['get_site_email',skey]).decode("utf-8").rstrip() contact =\ subprocess.check_output(['get_site_contact',skey]).decode("utf-8").rstrip() # Run scrit tp generate README outf = open('README.txt','w') subprocess.run(['create_readme_contents_tccon-data',sitef],check=True,stdout=outf) #Generate new license lic_f = open("/data/tccon/license.txt","r") lic_t = open("/data/tccon/license_tag.txt","r") lic = lic_f.read() cite =\ subprocess.check_output(['get_site_reference',skey]).decode("utf-8").rstrip() lic = lic + cite lic = lic + '\n\n' + lic_t.read() outf = open('LICENSE.txt','w') outf.write(lic) outf.close() files = ['README.txt','LICENSE.txt',sitef] cred = sitef[2:6]+'-'+sitef[6:8]+'-'+sitef[8:10]+\ '/'+sitef[11:15]+'-'+sitef[15:17]+'-'+sitef[17:19] metadata['publicationDate'] = datetime.date.today().isoformat() metadata['publisher'] = "CaltechDATA" today = datetime.date.today().isoformat() metadata['dates'] = [{'dateType':'Collected','date':cred},\ {'dateType':'Updated','date':today},\ {'dateType':'Created','date':today}] contributors = metadata['contributors'] contributors.append({'contributorType':'ContactPerson',\ 'contributorEmail':email,'contributorName':contact}) contributors.append({'contributorType':'HostingInstitution',\ 'contributorName':'California Institute of Techonolgy, Pasadena, CA (US)'}) print(metadata['identifier']) response = caltechdata_write(copy.deepcopy(metadata),token,files,production) print(response) new_id = response.split('/')[4].split('.')[0] print(new_id) doi = metadata['identifier']['identifier'] #Get file url if production == False: api_url = 'https://cd-sandbox.tind.io/api/record/' else: api_url = 'https://data.caltech.edu/api/record/' response = requests.get(api_url+new_id) ex_metadata = response.json()['metadata'] for f in ex_metadata['electronic_location_and_access']: if f['electronic_name'][0]=='LICENSE.txt': url = f['uniform_resource_identifier'] metadata['rightsList'] = [{'rightsURI':url,'rights':'TCCON Data License'}] response = caltechdata_edit(token,new_id,copy.deepcopy(metadata),{},{},production) print(response) for t in metadata['titles']: if 'titleType' not in t: title = t['title'].split('from')[1].split(',')[0].strip() split = cred.split('/') first = split[0] second = split[1] outsites = title+' ['+sname+'],https://doi.org/'+doi+','+first+','+second+'\n' #print( metadata['identifier']['identifier'].encode("utf-8")) #Dummy doi for testing if production == False: doi='10.5072/FK2NV9HP7P' #Strip contributor emails for c in metadata['contributors']: if 'contributorEmail' in c: c.pop('contributorEmail') if 'publicationDate' in metadata: metadata.pop('publicationDate') #Stripping because of bad schema validator for t in metadata['titles']: if 'titleType' in t: t.pop('titleType') create_doi(doi,metadata,'https://data.caltech.edu/records/'+new_id) # Update sites file infile = open("/data/tccon/site_ids.csv") site_ids = csv.reader(infile) outstr = sname+','+new_id+','+new_version+'\n' for row in site_ids: outstr = outstr+','.join(row)+'\n' infile.close() if production == True: os.rename('/data/tccon/site_ids.csv','/data/tccon/old/site_ids.csv') out_id = open("/data/tccon/site_ids.csv",'w') out_id.write(outstr) out_id.close() #Update site list - fails with multiple sites existing = open('/data/tccon/sites.csv','r') sites = csv.reader(existing) outstr = '' included = False for row in sites: if row[0][0] > outsites[0] and included == False: outstr = outstr + outsites outstr = outstr + ','.join(row)+'\n' included = True else: outstr = outstr + ','.join(row)+'\n' outsites = open('/data/tccon/temp/sites.csv','w') outsites.write(outstr) outsites.close() #Update .tgz file #First set the CaltechDATA Identifier for the .tgz record tgz_id = 293 #Need to update date and file mfname ='/data/tccon/metadata/tccon.ggg2014.json' metaf = open(mfname,'r') metadata = json.load(metaf) for d in metadata['dates']: if d['dateType'] == 'Updated': d['date'] = datetime.date.today().isoformat() files = ['tccon.latest.public.tgz'] caltechdata_edit(token,tgz_id,copy.deepcopy(metadata),files,[],production) doi = metadata['identifier']['identifier'] #Strip contributor emails if 'contributors' in metadata: for c in metadata['contributors']: if 'contributorEmail' in c: c.pop('contributorEmail') if 'publicationDate' in metadata: metadata.pop('publicationDate') #Stripping because of bad schema validator for t in metadata['titles']: if 'titleType' in t: t.pop('titleType') #Dummy doi for testing if production == False: doi='10.5072/FK2NV9HP6P' update_doi(doi,metadata,'https://data.caltech.edu/records/'+str(tgz_id)) #Move temp files if production == True: os.rename('/data/tccon/sites.csv','/data/tccon/old/sites.csv') os.rename('/data/tccon/temp/sites.csv','/data/tccon/sites.csv') for mfile in glob.glob("metadata/*"): os.rename(mfile,"/data/tccon/"+mfile) # Update big DOI infile = open('/data/tccon/sites.csv','r') site_ids = csv.reader(infile) dois = [] for row in site_ids: doi = row[1].split('doi.org')[1][1:] dois.append(doi) related = [{"relatedIdentifier":"10.14291/tccon.ggg2014.documentation.R0/1221662", "relatedIdentifierType": "DOI", "relationType": "IsDocumentedBy"}] for d in dois: related.append({"relatedIdentifier":d, "relatedIdentifierType": "DOI", "relationType": "HasPart"}) idv = "10.14291/tccon.archive/1348407" infile = open('/data/tccon/metadata/tccon.archive','r') metadata = json.load(infile) metadata['relatedIdentifiers']= related update_doi(idv,metadata,'http://tccondata.org')
from caltechdata_api import caltechdata_edit from caltechdata_api import caltechdata_write from update_doi import update_doi from create_doi import create_doi import requests import os,glob,json,csv,subprocess,datetime,copy,argparse path = '/data/tccon/temp' #Switch for test or production production = True os.chdir(path) token = os.environ['TINDTOK'] parser = argparse.ArgumentParser(description=\ "Creates a new TCCON site") parser.add_argument('sid', metavar='ID', type=str,nargs='+',\ help='The TCCON two letter Site ID (e.g. pa for park falls)') args = parser.parse_args() #For each new site release for skey in args.sid: #Gather information about release #sname = T_FULL[skey] sname =\ subprocess.check_output(['get_site_name',skey]).decode("utf-8").rstrip() new_version = 'R0' #Get new file sitef = glob.glob(skey+'*.nc') if len(sitef) != 1: print("Cannot find public site file in /data/tccon/temp") exit() else: sitef = sitef[0] #Re-read metadata mfname =\ '/data/tccon/metadata/tccon.ggg2014.'+sname+'.'+new_version+".json" metaf = open(mfname,'r') metadata = json.load(metaf) #Generate new readme email =\ subprocess.check_output(['get_site_email',skey]).decode("utf-8").rstrip() contact =\ subprocess.check_output(['get_site_contact',skey]).decode("utf-8").rstrip() # Run scrit tp generate README outf = open('README.txt','w') subprocess.run(['create_readme_contents_tccon-data',sitef],check=True,stdout=outf) #Generate new license lic_f = open("/data/tccon/license.txt","r") lic_t = open("/data/tccon/license_tag.txt","r") lic = lic_f.read() cite =\ subprocess.check_output(['get_site_reference',skey]).decode("utf-8").rstrip() lic = lic + cite lic = lic + '\n\n' + lic_t.read() outf = open('LICENSE.txt','w') outf.write(lic) outf.close() files = ['README.txt','LICENSE.txt',sitef] cred = sitef[2:6]+'-'+sitef[6:8]+'-'+sitef[8:10]+\ '/'+sitef[11:15]+'-'+sitef[15:17]+'-'+sitef[17:19] metadata['publicationDate'] = datetime.date.today().isoformat() metadata['publisher'] = "CaltechDATA" today = datetime.date.today().isoformat() metadata['dates'] = [{'dateType':'Collected','date':cred},\ {'dateType':'Updated','date':today},\ {'dateType':'Created','date':today}] contributors = metadata['contributors'] contributors.append({'contributorType':'ContactPerson',\ 'contributorEmail':email,'contributorName':contact}) contributors.append({'contributorType':'HostingInstitution',\ 'contributorName':'California Institute of Techonolgy, Pasadena, CA (US)'}) print(metadata['identifier']) response = caltechdata_write(copy.deepcopy(metadata),token,files,production) print(response) new_id = response.split('/')[4].split('.')[0] print(new_id) doi = metadata['identifier']['identifier'] #Get file url if production == False: api_url = 'https://cd-sandbox.tind.io/api/record/' else: api_url = 'https://data.caltech.edu/api/record/' response = requests.get(api_url+new_id) ex_metadata = response.json()['metadata'] for f in ex_metadata['electronic_location_and_access']: if f['electronic_name'][0]=='LICENSE.txt': url = f['uniform_resource_identifier'] metadata['rightsList'] = [{'rightsURI':url,'rights':'TCCON Data License'}] response = caltechdata_edit(token,new_id,copy.deepcopy(metadata),{},{},production) print(response) for t in metadata['titles']: if 'titleType' not in t: title = t['title'].split('from')[1].split(',')[0].strip() split = cred.split('/') first = split[0] second = split[1] outsites = title+' ['+sname+'],https://doi.org/'+doi+','+first+','+second+'\n' #print( metadata['identifier']['identifier'].encode("utf-8")) #Dummy doi for testing if production == False: doi='10.5072/FK2NV9HP7P' #Strip contributor emails for c in metadata['contributors']: if 'contributorEmail' in c: c.pop('contributorEmail') if 'publicationDate' in metadata: metadata.pop('publicationDate') #Stripping because of bad schema validator for t in metadata['titles']: if 'titleType' in t: t.pop('titleType') create_doi(doi,metadata,'https://data.caltech.edu/records/'+new_id) # Update sites file infile = open("/data/tccon/site_ids.csv") site_ids = csv.reader(infile) outstr = sname+','+new_id+','+new_version+'\n' for row in site_ids: outstr = outstr+','.join(row)+'\n' infile.close() if production == True: os.rename('/data/tccon/site_ids.csv','/data/tccon/old/site_ids.csv') out_id = open("/data/tccon/site_ids.csv",'w') out_id.write(outstr) out_id.close() #Update site list - fails with multiple sites existing = open('/data/tccon/sites.csv','r') sites = csv.reader(existing) outstr = '' included = False for row in sites: if row[0][0] > outsites[0] and included == False: outstr = outstr + outsites outstr = outstr + ','.join(row)+'\n' included = True else: outstr = outstr + ','.join(row)+'\n' outsites = open('/data/tccon/temp/sites.csv','w') outsites.write(outstr) outsites.close() #Update .tgz file #First set the CaltechDATA Identifier for the .tgz record tgz_id = 293 #Need to update date and file mfname ='/data/tccon/metadata/tccon.ggg2014.json' metaf = open(mfname,'r') metadata = json.load(metaf) for d in metadata['dates']: if d['dateType'] == 'Updated': d['date'] = datetime.date.today().isoformat() files = ['tccon.latest.public.tgz'] caltechdata_edit(token,tgz_id,copy.deepcopy(metadata),files,[],production) doi = metadata['identifier']['identifier'] #Strip contributor emails if 'contributors' in metadata: for c in metadata['contributors']: if 'contributorEmail' in c: c.pop('contributorEmail') if 'publicationDate' in metadata: metadata.pop('publicationDate') #Stripping because of bad schema validator for t in metadata['titles']: if 'titleType' in t: t.pop('titleType') #Dummy doi for testing if production == False: doi='10.5072/FK2NV9HP6P' update_doi(doi,metadata,'https://data.caltech.edu/records/'+str(tgz_id)) #Move temp files if production == True: os.rename('/data/tccon/sites.csv','/data/tccon/old/sites.csv') os.rename('/data/tccon/temp/sites.csv','/data/tccon/sites.csv') for mfile in glob.glob("metadata/*"): os.rename(mfile,"/data/tccon/"+mfile) # Update big DOI infile = open('/data/tccon/sites.csv','r') site_ids = csv.reader(infile) dois = [] for row in site_ids: doi = row[1].split('doi.org')[1][1:] dois.append(doi) related = [{"relatedIdentifier":"10.14291/tccon.ggg2014.documentation.R0/1221662", "relatedIdentifierType": "DOI", "relationType": "IsDocumentedBy"}] for d in dois: related.append({"relatedIdentifier":d, "relatedIdentifierType": "DOI", "relationType": "HasPart"}) idv = "10.14291/tccon.archive/1348407" infile = open('/data/tccon/metadata/tccon.archive','r') metadata = json.load(infile) metadata['relatedIdentifiers']= related update_doi(idv,metadata,'http://tccondata.org')
en
0.666995
#Switch for test or production #For each new site release #Gather information about release #sname = T_FULL[skey] #Get new file #Re-read metadata #Generate new readme # Run scrit tp generate README #Generate new license #Get file url #print( metadata['identifier']['identifier'].encode("utf-8")) #Dummy doi for testing #Strip contributor emails #Stripping because of bad schema validator # Update sites file #Update site list - fails with multiple sites #Update .tgz file #First set the CaltechDATA Identifier for the .tgz record #Need to update date and file #Strip contributor emails #Stripping because of bad schema validator #Dummy doi for testing #Move temp files # Update big DOI
2.219762
2
cms/cms/page/cms_page_builder/cms_page_builder.py
praveenbaghale/repo-cms
0
6615487
from __future__ import unicode_literals import frappe import json @frappe.whitelist() def get_page_details(page): cms_page = frappe.db.get_all("CMS Page", filters={"name": page}, fields=["name"]) if cms_page: for item in cms_page: sections = frappe.db.sql( """ select sec.name, sec.layout, sec.title, sec.layout_html, sec.custom_style, sec.custom_script, csec.idx from `tabPage Section` sec inner join `tabCMS Page Sections` csec on sec.name=csec.section where csec.parent=%(parent)s order by csec.idx """, {"parent": item.name}, as_dict=1, ) if sections: for sec in sections: sec.component_values = frappe.db.sql( """ select name, parent_id, class, value, attribute, component from `tabSection Components` where parent=%(parent)s """, {"parent": sec.name}, as_dict=1, ) section_components = frappe.db.sql( """ select name, class_name, value, parent_id, component, attribute from `tabSection Components` where parent=%(parent)s """, {"parent": sec.name}, as_dict=1, ) sec.section_components = section_components item.sections = sections return cms_page[0] @frappe.whitelist() def get_all_components(): components = frappe.db.sql( """select name, title, html from `tabLayout Components`""", as_dict=1 ) if components: for item in components: item.fields_list = frappe.db.sql( """ select title, field_description, class_name, value_type, attribute_name, field_type, dropdown_options, line_item, name from `tabComponent Fields` where parent=%(parent)s """, {"parent": item.name}, as_dict=1, ) layouts = frappe.db.sql( """select column_width, name, layout_html, layout_image from `tabLayout`""", as_dict=1, ) return {"components": components, "layout": layouts} @frappe.whitelist() def add_sections(sections): ref = json.loads(sections) if ref: for item in ref: if not item.get("page_section_name"): page_section = frappe.new_doc("Page Section") page_section.page_id = item.get("page") if item.get("components"): for c in item.get("components"): page_section.append("components", c) else: page_section = frappe.get_doc( "Page Section", item.get("page_section_name") ) if item.get("components"): for c in item.get("components"): if not c.get("name"): page_section.append("components", c) else: if frappe.db.get_value("Section Components", c.get("name")): code = frappe.get_doc( "Section Components", c.get("name") ) code.parent_id = c.get("parent_id") code.class_name = c.get("class_name") code.component = c.get("component") code.value = c.get("value") code.attribute = c.get("attribute") code.save() else: page_section.append("components", c) page_section.title = item.get("title") page_section.description = item.get("html") page_section.data_idx = item.get("idx") page_section.layout_html = item.get("layout_html") page_section.custom_style = item.get("custom_css") page_section.custom_script = item.get("custom_script") page_section.save() @frappe.whitelist() def delete_components(components): res = json.loads(components) for item in res: data = frappe.db.get_all("Section Components", filters={"name": item}) if data: frappe.db.sql( """delete from `tabSection Components` where name=%(name)s""", {"name": item}, ) @frappe.whitelist() def delete_section(section, component, page): try: res = json.loads(component) for item in res: frappe.db.sql( """delete from `tabSection Components` where name=%(name)s""", {"name": item}, ) frappe.db.sql( """delete from `tabCMS Page Sections` where parent=%(page)s and section=%(section)s""", {"page": page, "section": section}, ) frappe.db.sql( """delete from `tabPage Section` where name=%(section)s""", {"section": section}, ) except Exception as e: print(e)
from __future__ import unicode_literals import frappe import json @frappe.whitelist() def get_page_details(page): cms_page = frappe.db.get_all("CMS Page", filters={"name": page}, fields=["name"]) if cms_page: for item in cms_page: sections = frappe.db.sql( """ select sec.name, sec.layout, sec.title, sec.layout_html, sec.custom_style, sec.custom_script, csec.idx from `tabPage Section` sec inner join `tabCMS Page Sections` csec on sec.name=csec.section where csec.parent=%(parent)s order by csec.idx """, {"parent": item.name}, as_dict=1, ) if sections: for sec in sections: sec.component_values = frappe.db.sql( """ select name, parent_id, class, value, attribute, component from `tabSection Components` where parent=%(parent)s """, {"parent": sec.name}, as_dict=1, ) section_components = frappe.db.sql( """ select name, class_name, value, parent_id, component, attribute from `tabSection Components` where parent=%(parent)s """, {"parent": sec.name}, as_dict=1, ) sec.section_components = section_components item.sections = sections return cms_page[0] @frappe.whitelist() def get_all_components(): components = frappe.db.sql( """select name, title, html from `tabLayout Components`""", as_dict=1 ) if components: for item in components: item.fields_list = frappe.db.sql( """ select title, field_description, class_name, value_type, attribute_name, field_type, dropdown_options, line_item, name from `tabComponent Fields` where parent=%(parent)s """, {"parent": item.name}, as_dict=1, ) layouts = frappe.db.sql( """select column_width, name, layout_html, layout_image from `tabLayout`""", as_dict=1, ) return {"components": components, "layout": layouts} @frappe.whitelist() def add_sections(sections): ref = json.loads(sections) if ref: for item in ref: if not item.get("page_section_name"): page_section = frappe.new_doc("Page Section") page_section.page_id = item.get("page") if item.get("components"): for c in item.get("components"): page_section.append("components", c) else: page_section = frappe.get_doc( "Page Section", item.get("page_section_name") ) if item.get("components"): for c in item.get("components"): if not c.get("name"): page_section.append("components", c) else: if frappe.db.get_value("Section Components", c.get("name")): code = frappe.get_doc( "Section Components", c.get("name") ) code.parent_id = c.get("parent_id") code.class_name = c.get("class_name") code.component = c.get("component") code.value = c.get("value") code.attribute = c.get("attribute") code.save() else: page_section.append("components", c) page_section.title = item.get("title") page_section.description = item.get("html") page_section.data_idx = item.get("idx") page_section.layout_html = item.get("layout_html") page_section.custom_style = item.get("custom_css") page_section.custom_script = item.get("custom_script") page_section.save() @frappe.whitelist() def delete_components(components): res = json.loads(components) for item in res: data = frappe.db.get_all("Section Components", filters={"name": item}) if data: frappe.db.sql( """delete from `tabSection Components` where name=%(name)s""", {"name": item}, ) @frappe.whitelist() def delete_section(section, component, page): try: res = json.loads(component) for item in res: frappe.db.sql( """delete from `tabSection Components` where name=%(name)s""", {"name": item}, ) frappe.db.sql( """delete from `tabCMS Page Sections` where parent=%(page)s and section=%(section)s""", {"page": page, "section": section}, ) frappe.db.sql( """delete from `tabPage Section` where name=%(section)s""", {"section": section}, ) except Exception as e: print(e)
en
0.592509
select sec.name, sec.layout, sec.title, sec.layout_html, sec.custom_style, sec.custom_script, csec.idx from `tabPage Section` sec inner join `tabCMS Page Sections` csec on sec.name=csec.section where csec.parent=%(parent)s order by csec.idx select name, parent_id, class, value, attribute, component from `tabSection Components` where parent=%(parent)s select name, class_name, value, parent_id, component, attribute from `tabSection Components` where parent=%(parent)s select name, title, html from `tabLayout Components` select title, field_description, class_name, value_type, attribute_name, field_type, dropdown_options, line_item, name from `tabComponent Fields` where parent=%(parent)s select column_width, name, layout_html, layout_image from `tabLayout` delete from `tabSection Components` where name=%(name)s delete from `tabSection Components` where name=%(name)s delete from `tabCMS Page Sections` where parent=%(page)s and section=%(section)s delete from `tabPage Section` where name=%(section)s
2.134454
2
sorting/soa.py
willi-z/TrashSorting
0
6615488
""" State of the Art Tree-Based Classification with scikit-learn """ """ from sklearn import tree import graphviz X = [[0,0],[1,1]] Y = [0, 1] clf = tree.DecisionTreeClassifier() # clf for Classifier clf = clf.fit(X, Y) tree.plot_tree(clf) # should plot but does not dot_data = tree.export_graphviz(clf, out_file=None) graph = graphviz.Source(dot_data) graph.render("iris") graph """ from sklearn.datasets import load_iris from sklearn import tree import graphviz iris = load_iris() X, y = iris.data, iris.target clf = tree.DecisionTreeClassifier() clf = clf.fit(X, y) tree.plot_tree(clf) dot_data = tree.export_graphviz(clf, out_file=None) graph = graphviz.Source(dot_data) graph.render("iris")
""" State of the Art Tree-Based Classification with scikit-learn """ """ from sklearn import tree import graphviz X = [[0,0],[1,1]] Y = [0, 1] clf = tree.DecisionTreeClassifier() # clf for Classifier clf = clf.fit(X, Y) tree.plot_tree(clf) # should plot but does not dot_data = tree.export_graphviz(clf, out_file=None) graph = graphviz.Source(dot_data) graph.render("iris") graph """ from sklearn.datasets import load_iris from sklearn import tree import graphviz iris = load_iris() X, y = iris.data, iris.target clf = tree.DecisionTreeClassifier() clf = clf.fit(X, y) tree.plot_tree(clf) dot_data = tree.export_graphviz(clf, out_file=None) graph = graphviz.Source(dot_data) graph.render("iris")
en
0.653603
State of the Art Tree-Based Classification with scikit-learn from sklearn import tree import graphviz X = [[0,0],[1,1]] Y = [0, 1] clf = tree.DecisionTreeClassifier() # clf for Classifier clf = clf.fit(X, Y) tree.plot_tree(clf) # should plot but does not dot_data = tree.export_graphviz(clf, out_file=None) graph = graphviz.Source(dot_data) graph.render("iris") graph
3.170026
3
Vision/ICamera.py
EdwardAlchikha/Capstone
0
6615489
<reponame>EdwardAlchikha/Capstone<filename>Vision/ICamera.py from abc import ABC, abstractmethod class ICamera(ABC): @abstractmethod def placeholder(self): pass
from abc import ABC, abstractmethod class ICamera(ABC): @abstractmethod def placeholder(self): pass
none
1
2.725559
3
utils/redis_util.py
r3fR4in/AutoTest_platform
0
6615490
<filename>utils/redis_util.py<gh_stars>0 import pickle import redis from flask import current_app as app class Redis(object): @staticmethod def _get_r(): host = app.config['REDIS_HOST'] port = app.config['REDIS_PORT'] db = app.config['REDIS_DB'] passwd = app.config['REDIS_PWD'] r = redis.StrictRedis(host=host, port=port, db=db, password=<PASSWORD>) return r @classmethod def write(self, key, value, expire=None): """ 写入键值对 """ # 判断是否有过期时间,没有就设置默认值 if expire: expire_in_seconds = expire else: expire_in_seconds = app.config['REDIS_EXPIRE'] r = self._get_r() r.set(key, value, ex=expire_in_seconds) @classmethod def write_dict(self, key, value, expire=None): """将内存数据二进制通过序列号转为文本流,再存入redis""" if expire: expire_in_seconds = expire else: expire_in_seconds = app.config['REDIS_EXPIRE'] r = self._get_r() r.set(pickle.dumps(key), pickle.dumps(value), ex=expire_in_seconds) @classmethod def read_dict(self, key): """将文本流从redis中读取并反序列化,返回""" r = self._get_r() data = r.get(pickle.dumps(key)) if data is None: return None return pickle.loads(data) @classmethod def read(self, key): """ 读取键值对内容 """ r = self._get_r() value = r.get(key) return value.decode('utf-8') if value else value @classmethod def hset(self, name, key, value): """ 写入hash表 """ r = self._get_r() r.hset(name, key, value) @classmethod def hmset(self, key, *value): """ 读取指定hash表的所有给定字段的值 """ r = self._get_r() value = r.hmset(key, *value) return value @classmethod def hget(self, name, key): """ 读取指定hash表的键值 """ r = self._get_r() value = r.hget(name, key) return value.decode('utf-8') if value else value @classmethod def hgetall(self, name): """ 获取指定hash表所有的值 """ r = self._get_r() return r.hgetall(name) @classmethod def delete(self, *names): """ 删除一个或者多个 """ r = self._get_r() r.delete(*names) @classmethod def hdel(self, name, key): """ 删除指定hash表的键值 """ r = self._get_r() r.hdel(name, key) @classmethod def expire(self, name, expire=None): """ 设置过期时间 """ if expire: expire_in_seconds = expire else: expire_in_seconds = app.config['REDIS_EXPIRE'] r = self._get_r() r.expire(name, expire_in_seconds)
<filename>utils/redis_util.py<gh_stars>0 import pickle import redis from flask import current_app as app class Redis(object): @staticmethod def _get_r(): host = app.config['REDIS_HOST'] port = app.config['REDIS_PORT'] db = app.config['REDIS_DB'] passwd = app.config['REDIS_PWD'] r = redis.StrictRedis(host=host, port=port, db=db, password=<PASSWORD>) return r @classmethod def write(self, key, value, expire=None): """ 写入键值对 """ # 判断是否有过期时间,没有就设置默认值 if expire: expire_in_seconds = expire else: expire_in_seconds = app.config['REDIS_EXPIRE'] r = self._get_r() r.set(key, value, ex=expire_in_seconds) @classmethod def write_dict(self, key, value, expire=None): """将内存数据二进制通过序列号转为文本流,再存入redis""" if expire: expire_in_seconds = expire else: expire_in_seconds = app.config['REDIS_EXPIRE'] r = self._get_r() r.set(pickle.dumps(key), pickle.dumps(value), ex=expire_in_seconds) @classmethod def read_dict(self, key): """将文本流从redis中读取并反序列化,返回""" r = self._get_r() data = r.get(pickle.dumps(key)) if data is None: return None return pickle.loads(data) @classmethod def read(self, key): """ 读取键值对内容 """ r = self._get_r() value = r.get(key) return value.decode('utf-8') if value else value @classmethod def hset(self, name, key, value): """ 写入hash表 """ r = self._get_r() r.hset(name, key, value) @classmethod def hmset(self, key, *value): """ 读取指定hash表的所有给定字段的值 """ r = self._get_r() value = r.hmset(key, *value) return value @classmethod def hget(self, name, key): """ 读取指定hash表的键值 """ r = self._get_r() value = r.hget(name, key) return value.decode('utf-8') if value else value @classmethod def hgetall(self, name): """ 获取指定hash表所有的值 """ r = self._get_r() return r.hgetall(name) @classmethod def delete(self, *names): """ 删除一个或者多个 """ r = self._get_r() r.delete(*names) @classmethod def hdel(self, name, key): """ 删除指定hash表的键值 """ r = self._get_r() r.hdel(name, key) @classmethod def expire(self, name, expire=None): """ 设置过期时间 """ if expire: expire_in_seconds = expire else: expire_in_seconds = app.config['REDIS_EXPIRE'] r = self._get_r() r.expire(name, expire_in_seconds)
zh
0.96026
写入键值对 # 判断是否有过期时间,没有就设置默认值 将内存数据二进制通过序列号转为文本流,再存入redis 将文本流从redis中读取并反序列化,返回 读取键值对内容 写入hash表 读取指定hash表的所有给定字段的值 读取指定hash表的键值 获取指定hash表所有的值 删除一个或者多个 删除指定hash表的键值 设置过期时间
2.843031
3
generative_models/lstm_hc/train_directed_generator.py
MorganCThomas/MolScore
28
6615491
""" Adapted from guacamol_baselines https://github.com/BenevolentAI/guacamol_baselines """ import argparse import os # from guacamol.assess_goal_directed_generation import assess_goal_directed_generation # from guacamol.utils.helpers import setup_default_logger from directed_generator import SmilesRnnDirectedGenerator from molscore.manager import MolScore def get_args(): parser = argparse.ArgumentParser(description='Goal-directed generation benchmark for SMILES RNN', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--molscore_config', '-m', type=str, help='Path to molscore config (.json)') parser.add_argument('--model_path', default=None, help='Full path to the pre-trained SMILES RNN model') parser.add_argument('--max_len', default=100, type=int, help='Max length of a SMILES string') parser.add_argument('--seed', default=42, type=int, help='Random seed') parser.add_argument('--number_repetitions', default=1, type=int, help='Number of re-training runs to average') parser.add_argument('--keep_top', default=512, type=int, help='Molecules kept each step') parser.add_argument('--n_epochs', default=20, type=int, help='Epochs to sample') parser.add_argument('--mols_to_sample', default=1024, type=int, help='Molecules sampled at each step') parser.add_argument('--optimize_batch_size', default=256, type=int, help='Batch size for the optimization') parser.add_argument('--optimize_n_epochs', default=2, type=int, help='Number of epochs for the optimization') parser.add_argument('--smiles_file', default='data/guacamol_v1_all.smiles') parser.add_argument('--random_start', action='store_true') parser.add_argument('--n_jobs', type=int, default=-1) args = parser.parse_args() return args def main(args): ms = MolScore(model_name='lstm_hc', task_config=args.molscore_config) if args.model_path is None: dir_path = os.path.dirname(os.path.realpath(__file__)) args.model_path = os.path.join(dir_path, 'pretrained_model', 'model_final_0.473.pt') optimizer = SmilesRnnDirectedGenerator(pretrained_model_path=args.model_path, n_epochs=args.n_epochs, mols_to_sample=args.mols_to_sample, keep_top=args.keep_top, optimize_n_epochs=args.optimize_n_epochs, max_len=args.max_len, optimize_batch_size=args.optimize_batch_size, random_start=args.random_start, smi_file=args.smiles_file, n_jobs=args.n_jobs) ms.log_parameters({'n_epochs': args.n_epochs, 'sample_size': args.mols_to_sample, 'keep_top': args.keep_top, 'optimize_n_epochs': args.optimize_n_epochs, 'batch_size': args.optimize_batch_size, 'pretrained_model': args.model_path, 'smi_file': args.smiles_file}) final_population_smiles = optimizer.generate_optimized_molecules(scoring_function=ms, number_molecules=0) ms.write_scores() ms.kill_dash_monitor() with open(os.path.join(ms.save_dir, 'final_sample.smi'), 'w') as f: [f.write(smi + '\n') for smi in final_population_smiles] return if __name__ == '__main__': # setup_default_logger() args = get_args() main(args)
""" Adapted from guacamol_baselines https://github.com/BenevolentAI/guacamol_baselines """ import argparse import os # from guacamol.assess_goal_directed_generation import assess_goal_directed_generation # from guacamol.utils.helpers import setup_default_logger from directed_generator import SmilesRnnDirectedGenerator from molscore.manager import MolScore def get_args(): parser = argparse.ArgumentParser(description='Goal-directed generation benchmark for SMILES RNN', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--molscore_config', '-m', type=str, help='Path to molscore config (.json)') parser.add_argument('--model_path', default=None, help='Full path to the pre-trained SMILES RNN model') parser.add_argument('--max_len', default=100, type=int, help='Max length of a SMILES string') parser.add_argument('--seed', default=42, type=int, help='Random seed') parser.add_argument('--number_repetitions', default=1, type=int, help='Number of re-training runs to average') parser.add_argument('--keep_top', default=512, type=int, help='Molecules kept each step') parser.add_argument('--n_epochs', default=20, type=int, help='Epochs to sample') parser.add_argument('--mols_to_sample', default=1024, type=int, help='Molecules sampled at each step') parser.add_argument('--optimize_batch_size', default=256, type=int, help='Batch size for the optimization') parser.add_argument('--optimize_n_epochs', default=2, type=int, help='Number of epochs for the optimization') parser.add_argument('--smiles_file', default='data/guacamol_v1_all.smiles') parser.add_argument('--random_start', action='store_true') parser.add_argument('--n_jobs', type=int, default=-1) args = parser.parse_args() return args def main(args): ms = MolScore(model_name='lstm_hc', task_config=args.molscore_config) if args.model_path is None: dir_path = os.path.dirname(os.path.realpath(__file__)) args.model_path = os.path.join(dir_path, 'pretrained_model', 'model_final_0.473.pt') optimizer = SmilesRnnDirectedGenerator(pretrained_model_path=args.model_path, n_epochs=args.n_epochs, mols_to_sample=args.mols_to_sample, keep_top=args.keep_top, optimize_n_epochs=args.optimize_n_epochs, max_len=args.max_len, optimize_batch_size=args.optimize_batch_size, random_start=args.random_start, smi_file=args.smiles_file, n_jobs=args.n_jobs) ms.log_parameters({'n_epochs': args.n_epochs, 'sample_size': args.mols_to_sample, 'keep_top': args.keep_top, 'optimize_n_epochs': args.optimize_n_epochs, 'batch_size': args.optimize_batch_size, 'pretrained_model': args.model_path, 'smi_file': args.smiles_file}) final_population_smiles = optimizer.generate_optimized_molecules(scoring_function=ms, number_molecules=0) ms.write_scores() ms.kill_dash_monitor() with open(os.path.join(ms.save_dir, 'final_sample.smi'), 'w') as f: [f.write(smi + '\n') for smi in final_population_smiles] return if __name__ == '__main__': # setup_default_logger() args = get_args() main(args)
en
0.602758
Adapted from guacamol_baselines https://github.com/BenevolentAI/guacamol_baselines # from guacamol.assess_goal_directed_generation import assess_goal_directed_generation # from guacamol.utils.helpers import setup_default_logger # setup_default_logger()
2.751848
3
attention_embedder/src/preprocessing.py
elalamik/NLP_Capgemini_Data_Camp
0
6615492
<gh_stars>0 import tensorflow as tf import logzero import logging from logzero import logger def review_preprocessing(review, tokenizer, words_maxlen=50, sentences_maxlen=10): """Preprocessing function to build appropriate padded sequences for HAN. Parameters ---------- review: list. List of sentences (strings) of the review. words_maxlen: int. Maximal length/number of words for a sentence. sentences_maxlen: int. Maximal length/number of sentences for a review. Returns ------- padded_sequences: tf.Tensor. Tensor of shape (sentences_maxlen, words_maxlen) """ # tokenizer = tf.keras.preprocessing.text.Tokenizer(filters=' ', char_level=False) sequences = tokenizer.texts_to_sequences(review) padded_sequences = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=words_maxlen, padding="post") if padded_sequences.shape[0] < sentences_maxlen: padded_sequences = tf.pad( padded_sequences, paddings=tf.constant([[0, sentences_maxlen-padded_sequences.shape[0]], [0, 0]]) ) elif padded_sequences.shape[0] > sentences_maxlen: padded_sequences = padded_sequences[:sentences_maxlen] assert padded_sequences.shape == (sentences_maxlen, words_maxlen) return padded_sequences
import tensorflow as tf import logzero import logging from logzero import logger def review_preprocessing(review, tokenizer, words_maxlen=50, sentences_maxlen=10): """Preprocessing function to build appropriate padded sequences for HAN. Parameters ---------- review: list. List of sentences (strings) of the review. words_maxlen: int. Maximal length/number of words for a sentence. sentences_maxlen: int. Maximal length/number of sentences for a review. Returns ------- padded_sequences: tf.Tensor. Tensor of shape (sentences_maxlen, words_maxlen) """ # tokenizer = tf.keras.preprocessing.text.Tokenizer(filters=' ', char_level=False) sequences = tokenizer.texts_to_sequences(review) padded_sequences = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=words_maxlen, padding="post") if padded_sequences.shape[0] < sentences_maxlen: padded_sequences = tf.pad( padded_sequences, paddings=tf.constant([[0, sentences_maxlen-padded_sequences.shape[0]], [0, 0]]) ) elif padded_sequences.shape[0] > sentences_maxlen: padded_sequences = padded_sequences[:sentences_maxlen] assert padded_sequences.shape == (sentences_maxlen, words_maxlen) return padded_sequences
en
0.602397
Preprocessing function to build appropriate padded sequences for HAN. Parameters ---------- review: list. List of sentences (strings) of the review. words_maxlen: int. Maximal length/number of words for a sentence. sentences_maxlen: int. Maximal length/number of sentences for a review. Returns ------- padded_sequences: tf.Tensor. Tensor of shape (sentences_maxlen, words_maxlen) # tokenizer = tf.keras.preprocessing.text.Tokenizer(filters=' ', char_level=False)
2.905343
3
compliance_exceptions/aws-kms-mrk-aware-multi-keyrings.py
farleyb-amazon/aws-encryption-sdk-python
95
6615493
# The AWS Encryption SDK - Python does not implement Keyrings # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# The caller MUST provide: # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# If an empty set of Region is provided this function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# If # //# any element of the set of regions is null or an empty string this # //# function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# If a regional client supplier is not passed, # //# then a default MUST be created that takes a region string and # //# generates a default AWS SDK client for the given region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# A set of AWS KMS clients MUST be created by calling regional client # //# supplier for each region in the input set of regions. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# Then a set of AWS KMS MRK Aware Symmetric Region Discovery Keyring # //# (aws-kms-mrk-aware-symmetric-region-discovery-keyring.md) MUST be # //# created for each AWS KMS client by initializing each keyring with # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize # //# by using this set of discovery keyrings as the child keyrings # //# (../multi-keyring.md#child-keyrings). # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# This Multi-Keyring MUST be # //# this functions output. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# The caller MUST provide: # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If any of the AWS KMS key identifiers is null or an empty string this # //# function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# At least one non-null or non-empty string AWS # //# KMS key identifiers exists in the input this function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If # //# a regional client supplier is not passed, then a default MUST be # //# created that takes a region string and generates a default AWS SDK # //# client for the given region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If there is a generator input then the generator keyring MUST be a # //# AWS KMS MRK Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric- # //# keyring.md) initialized with # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# * The AWS KMS client that MUST be created by the regional client # //# supplier when called with the region part of the generator ARN or # //# a signal for the AWS SDK to select the default region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If there is a set of child identifiers then a set of AWS KMS MRK # //# Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric-keyring.md) MUST # //# be created for each AWS KMS key identifier by initialized each # //# keyring with # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# * The AWS KMS client that MUST be created by the regional client # //# supplier when called with the region part of the AWS KMS key # //# identifier or a signal for the AWS SDK to select the default # //# region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# NOTE: The AWS Encryption SDK SHOULD NOT attempt to evaluate its own # //# default region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize # //# by using this generator keyring as the generator keyring (../multi- # //# keyring.md#generator-keyring) and this set of child keyrings as the # //# child keyrings (../multi-keyring.md#child-keyrings). # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# This Multi- # //# Keyring MUST be this functions output. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# All # //# AWS KMS identifiers are passed to Assert AWS KMS MRK are unique (aws- # //# kms-mrk-are-unique.md#Implementation) and the function MUST return # //# success otherwise this MUST fail.
# The AWS Encryption SDK - Python does not implement Keyrings # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# The caller MUST provide: # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# If an empty set of Region is provided this function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# If # //# any element of the set of regions is null or an empty string this # //# function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# If a regional client supplier is not passed, # //# then a default MUST be created that takes a region string and # //# generates a default AWS SDK client for the given region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# A set of AWS KMS clients MUST be created by calling regional client # //# supplier for each region in the input set of regions. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# Then a set of AWS KMS MRK Aware Symmetric Region Discovery Keyring # //# (aws-kms-mrk-aware-symmetric-region-discovery-keyring.md) MUST be # //# created for each AWS KMS client by initializing each keyring with # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize # //# by using this set of discovery keyrings as the child keyrings # //# (../multi-keyring.md#child-keyrings). # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# This Multi-Keyring MUST be # //# this functions output. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# The caller MUST provide: # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If any of the AWS KMS key identifiers is null or an empty string this # //# function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# At least one non-null or non-empty string AWS # //# KMS key identifiers exists in the input this function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If # //# a regional client supplier is not passed, then a default MUST be # //# created that takes a region string and generates a default AWS SDK # //# client for the given region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If there is a generator input then the generator keyring MUST be a # //# AWS KMS MRK Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric- # //# keyring.md) initialized with # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# * The AWS KMS client that MUST be created by the regional client # //# supplier when called with the region part of the generator ARN or # //# a signal for the AWS SDK to select the default region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If there is a set of child identifiers then a set of AWS KMS MRK # //# Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric-keyring.md) MUST # //# be created for each AWS KMS key identifier by initialized each # //# keyring with # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# * The AWS KMS client that MUST be created by the regional client # //# supplier when called with the region part of the AWS KMS key # //# identifier or a signal for the AWS SDK to select the default # //# region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# NOTE: The AWS Encryption SDK SHOULD NOT attempt to evaluate its own # //# default region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize # //# by using this generator keyring as the generator keyring (../multi- # //# keyring.md#generator-keyring) and this set of child keyrings as the # //# child keyrings (../multi-keyring.md#child-keyrings). # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# This Multi- # //# Keyring MUST be this functions output. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# All # //# AWS KMS identifiers are passed to Assert AWS KMS MRK are unique (aws- # //# kms-mrk-are-unique.md#Implementation) and the function MUST return # //# success otherwise this MUST fail.
en
0.745929
# The AWS Encryption SDK - Python does not implement Keyrings # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# The caller MUST provide: # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# If an empty set of Region is provided this function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# If # //# any element of the set of regions is null or an empty string this # //# function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# If a regional client supplier is not passed, # //# then a default MUST be created that takes a region string and # //# generates a default AWS SDK client for the given region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# A set of AWS KMS clients MUST be created by calling regional client # //# supplier for each region in the input set of regions. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# Then a set of AWS KMS MRK Aware Symmetric Region Discovery Keyring # //# (aws-kms-mrk-aware-symmetric-region-discovery-keyring.md) MUST be # //# created for each AWS KMS client by initializing each keyring with # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize # //# by using this set of discovery keyrings as the child keyrings # //# (../multi-keyring.md#child-keyrings). # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.5 # //= type=exception # //# This Multi-Keyring MUST be # //# this functions output. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# The caller MUST provide: # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If any of the AWS KMS key identifiers is null or an empty string this # //# function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# At least one non-null or non-empty string AWS # //# KMS key identifiers exists in the input this function MUST fail. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If # //# a regional client supplier is not passed, then a default MUST be # //# created that takes a region string and generates a default AWS SDK # //# client for the given region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If there is a generator input then the generator keyring MUST be a # //# AWS KMS MRK Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric- # //# keyring.md) initialized with # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# * The AWS KMS client that MUST be created by the regional client # //# supplier when called with the region part of the generator ARN or # //# a signal for the AWS SDK to select the default region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# If there is a set of child identifiers then a set of AWS KMS MRK # //# Aware Symmetric Keyring (aws-kms-mrk-aware-symmetric-keyring.md) MUST # //# be created for each AWS KMS key identifier by initialized each # //# keyring with # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# * The AWS KMS client that MUST be created by the regional client # //# supplier when called with the region part of the AWS KMS key # //# identifier or a signal for the AWS SDK to select the default # //# region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# NOTE: The AWS Encryption SDK SHOULD NOT attempt to evaluate its own # //# default region. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# Then a Multi-Keyring (../multi-keyring.md#inputs) MUST be initialize # //# by using this generator keyring as the generator keyring (../multi- # //# keyring.md#generator-keyring) and this set of child keyrings as the # //# child keyrings (../multi-keyring.md#child-keyrings). # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# This Multi- # //# Keyring MUST be this functions output. # //= compliance/framework/aws-kms/aws-kms-mrk-aware-multi-keyrings.txt#2.6 # //= type=exception # //# All # //# AWS KMS identifiers are passed to Assert AWS KMS MRK are unique (aws- # //# kms-mrk-are-unique.md#Implementation) and the function MUST return # //# success otherwise this MUST fail.
2.309161
2
344_reverse_string.py
Sanster/LeetCode
2
6615494
<filename>344_reverse_string.py<gh_stars>1-10 class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ return s[::-1] def reverseString2(self, s): r = list(s) k = len(s) - 1 i = 0 while i < k: r[i], r[k] = r[k], r[i] i += 1 k -= 1 return ''.join(r) if __name__ == "__main__": s = Solution() print(s.reverseString2("Hello")) print(s.reverseString2("H")) print(s.reverseString2(""))
<filename>344_reverse_string.py<gh_stars>1-10 class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ return s[::-1] def reverseString2(self, s): r = list(s) k = len(s) - 1 i = 0 while i < k: r[i], r[k] = r[k], r[i] i += 1 k -= 1 return ''.join(r) if __name__ == "__main__": s = Solution() print(s.reverseString2("Hello")) print(s.reverseString2("H")) print(s.reverseString2(""))
en
0.287785
:type s: str :rtype: str
3.522274
4
vgio/quake/protocol.py
joshuaskelly/game-tools
22
6615495
"""This module provides file I/O for the Quake network protocol. References: Quake Source - id Software - https://github.com/id-Software/Quake The Unofficial DEM Format Description - <NAME>, et al. - https://www.quakewiki.net/archives/demospecs/dem/dem.html """ import io import struct __all__ = ['Bad', 'Nop', 'Disconnect', 'UpdateStat', 'Version', 'SetView', 'Sound', 'Time', 'Print', 'StuffText', 'SetAngle', 'ServerInfo', 'LightStyle', 'UpdateName', 'UpdateFrags', 'ClientData', 'StopSound', 'UpdateColors', 'Particle', 'Damage', 'SpawnStatic', 'SpawnBinary', 'SpawnBaseline', 'TempEntity', 'SetPause', 'SignOnNum', 'CenterPrint', 'KilledMonster', 'FoundSecret', 'SpawnStaticSound', 'Intermission', 'Finale', 'CdTrack', 'SellScreen', 'CutScene', 'UpdateEntity', 'MessageBlock'] class _IO: """Simple namespace for protocol IO""" @staticmethod def _read(fmt, file): return struct.unpack(fmt, file.read(struct.calcsize(fmt)))[0] class read: """Read IO namespace""" @staticmethod def char(file): return int(_IO._read('<b', file)) @staticmethod def byte(file): return int(_IO._read('<B', file)) @staticmethod def short(file): return int(_IO._read('<h', file)) @staticmethod def long(file): return int(_IO._read('<l', file)) @staticmethod def float(file): return float(_IO._read('<f', file)) @staticmethod def coord(file): return _IO.read.short(file) * 0.125 @staticmethod def position(file): return _IO.read.coord(file), _IO.read.coord(file), _IO.read.coord(file) @staticmethod def angle(file): return _IO.read.char(file) * 360 / 256 @staticmethod def angles(file): return _IO.read.angle(file), _IO.read.angle(file), _IO.read.angle(file) @staticmethod def string(file, terminal_byte=b'\x00'): string = b'' char = _IO._read('<s', file) while char != terminal_byte: string += char char = _IO._read('<s', file) return string.decode('ascii') @staticmethod def _write(fmt, file, value): data = struct.pack(fmt, value) file.write(data) class write: """Write IO namespace""" @staticmethod def char(file, value): _IO._write('<b', file, int(value)) @staticmethod def byte(file, value): _IO._write('<B', file, int(value)) @staticmethod def short(file, value): _IO._write('<h', file, int(value)) @staticmethod def long(file, value): _IO._write('<l', file, int(value)) @staticmethod def float(file, value): _IO._write('<f', file, float(value)) @staticmethod def coord(file, value): _IO.write.short(file, value / 0.125) @staticmethod def position(file, values): _IO.write.coord(file, values[0]), _IO.write.coord(file, values[1]), _IO.write.coord(file, values[2]) @staticmethod def angle(file, value): _IO.write.char(file, int(value * 256 / 360)) @staticmethod def angles(file, values): _IO.write.angle(file, values[0]), _IO.write.angle(file, values[1]), _IO.write.angle(file, values[2]) @staticmethod def string(file, value, terminal_byte=b'\x00'): value = value[:2048] size = len(value) format = '<%is' % (size + 1) v = value.encode('ascii') + terminal_byte data = struct.pack(format, v) file.write(data) class BadMessage(Exception): pass SVC_BAD = 0 SVC_NOP = 1 SVC_DISCONNECT = 2 SVC_UPDATESTAT = 3 SVC_VERSION = 4 SVC_SETVIEW = 5 SVC_SOUND = 6 SVC_TIME = 7 SVC_PRINT = 8 SVC_STUFFTEXT = 9 SVC_SETANGLE = 10 SVC_SERVERINFO = 11 SVC_LIGHTSTYLE = 12 SVC_UPDATENAME = 13 SVC_UPDATEFRAGS = 14 SVC_CLIENTDATA = 15 SVC_STOPSOUND = 16 SVC_UPDATECOLORS = 17 SVC_PARTICLE = 18 SVC_DAMAGE = 19 SVC_SPAWNSTATIC = 20 SVC_SPAWNBINARY = 21 SVC_SPAWNBASELINE = 22 SVC_TEMP_ENTITY = 23 SVC_SETPAUSE = 24 SVC_SIGNONNUM = 25 SVC_CENTERPRINT = 26 SVC_KILLEDMONSTER = 27 SVC_FOUNDSECRET = 28 SVC_SPAWNSTATICSOUND = 29 SVC_INTERMISSION = 30 SVC_FINALE = 31 SVC_CDTRACK = 32 SVC_SELLSCREEN = 33 SVC_CUTSCENE = 34 class Bad: """Class for representing a Bad message This is an error message and should not appear. """ __slots__ = () @staticmethod def write(file, bad=None): _IO.write.byte(file, SVC_BAD) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_BAD return Bad() class Nop: """Class for representing a Nop message""" __slots__ = () @staticmethod def write(file, nop=None): _IO.write.byte(file, SVC_NOP) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_NOP return Nop() class Disconnect: """Class for representing a Disconnect message Disconnect from the server and end the game. Typically this the last message of a demo. """ __slots__ = () @staticmethod def write(file, disconnect=None): _IO.write.byte(file, SVC_DISCONNECT) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_DISCONNECT return Disconnect() class UpdateStat: """Class for representing UpdateStat messages Updates a player state value. Attributes: index: The index to update in the player state array. value: The new value to set. """ __slots__ = ( 'index', 'value' ) def __init__(self): self.index = None self.value = None @staticmethod def write(file, update_stat): _IO.write.byte(file, SVC_UPDATESTAT) _IO.write.byte(file, update_stat.index) _IO.write.long(file, update_stat.value) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_UPDATESTAT update_stat = UpdateStat() update_stat.index = _IO.read.byte(file) update_stat.value = _IO.read.long(file) return update_stat class Version: """Class for representing Version messages Attributes: protocol_version: Protocol version of the server. Quake uses 15. """ __slots__ = ( 'protocol_version' ) def __init__(self): self.protocol_version = None @staticmethod def write(file, version): _IO.write.byte(file, SVC_VERSION) _IO.write.long(file, version.protocol_version) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_VERSION version = Version() version.protocol_version = _IO.read.long(file) return version class SetView: """Class for representing SetView messages Sets the camera position to the given entity. Attributes: entity: The entity number """ __slots__ = ( 'entity' ) def __init__(self): self.entity = None @staticmethod def write(file, set_view): _IO.write.byte(file, SVC_SETVIEW) _IO.write.short(file, set_view.entity) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SETVIEW set_view = SetView() set_view.entity = _IO.read.short(file) return set_view SND_VOLUME = 0b0001 SND_ATTENUATION = 0b0010 SND_LOOPING = 0b0100 class Sound: """Class for representing Sound messages Plays a sound on a channel at a position. Attributes: entity: The entity that caused the sound. bit_mask: A bit field indicating what data is sent. volume: Optional. The sound volume or None. attenuation: Optional. The sound attenuation or None. channel: The sound channel, maximum of eight. sound_number: The number of the sound in the sound table. origin: The position of the sound. """ __slots__ = ( 'entity', 'bit_mask', 'volume', 'attenuation', 'channel', 'sound_number', 'origin' ) def __init__(self): self.entity = None self.bit_mask = 0b0000 self.volume = 255 self.attenuation = 1.0 self.channel = None self.sound_number = None self.origin = None, None, None @staticmethod def write(file, sound): _IO.write.byte(file, SVC_SOUND) _IO.write.byte(file, sound.bit_mask) if sound.bit_mask & SND_VOLUME: _IO.write.byte(file, sound.volume) if sound.bit_mask & SND_ATTENUATION: _IO.write.byte(file, sound.attenuation * 64) channel = sound.entity << 3 channel |= sound.channel _IO.write.short(file, channel) _IO.write.byte(file, sound.sound_number) _IO.write.position(file, sound.origin) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SOUND sound = Sound() sound.bit_mask = _IO.read.byte(file) if sound.bit_mask & SND_VOLUME: sound.volume = _IO.read.byte(file) if sound.bit_mask & SND_ATTENUATION: sound.attenuation = _IO.read.byte(file) / 64 sound.channel = _IO.read.short(file) sound.entity = sound.channel >> 3 sound.channel &= 7 sound.sound_number = _IO.read.byte(file) sound.origin = _IO.read.position(file) return sound class Time: """Class for representing Time messages A time stamp that should appear in each block of messages. Attributes: time: The amount of elapsed time(in seconds) since the start of the game. """ __slots__ = ( 'time' ) def __init__(self): self.time = None @staticmethod def write(file, time): _IO.write.byte(file, SVC_TIME) _IO.write.float(file, time.time) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_TIME time = Time() time.time = _IO.read.float(file) return time class Print: """Class for representing Print messages Prints text in the top left corner of the screen and console. Attributes: text: The text to be shown. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, _print): _IO.write.byte(file, SVC_PRINT) _IO.write.string(file, _print.text) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_PRINT _print = Print() _print.text = _IO.read.string(file) return _print class StuffText: """Class for representing StuffText messages Text sent to the client console and ran. Attributes: text: The text to send to the client console. Note: This string is terminated with the newline character. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, stuff_text): _IO.write.byte(file, SVC_STUFFTEXT) _IO.write.string(file, stuff_text.text, b'\n') @staticmethod def read(file): assert _IO.read.byte(file) == SVC_STUFFTEXT stuff_text = StuffText() stuff_text.text = _IO.read.string(file, b'\n') return stuff_text class SetAngle: """Class for representing SetAngle messages Sets the camera's orientation. Attributes: angles: The new angles for the camera. """ __slots__ = ( 'angles' ) def __init__(self): self.angles = None @staticmethod def write(file, set_angle): _IO.write.byte(file, SVC_SETANGLE) _IO.write.angles(file, set_angle.angles) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SETANGLE set_angle = SetAngle() set_angle.angles = _IO.read.angles(file) return set_angle class ServerInfo: """Class for representing ServerInfo messages Handles the loading of assets. Usually first message sent after a level change. Attributes: protocol_version: Protocol version of the server. Quake uses 15. max_clients: Number of clients. multi: Multiplayer flag. Set to 0 for single-player and 1 for multiplayer. map_name: The name of the level. models: The model table as as sequence of strings. sounds: The sound table as a sequence of strings. """ __slots__ = ( 'protocol_version', 'max_clients', 'multi', 'map_name', 'models', 'sounds' ) def __init__(self): self.protocol_version = 15 self.max_clients = 0 self.multi = 0 self.map_name = '' self.models = [] self.sounds = [] @staticmethod def write(file, server_data): _IO.write.byte(file, SVC_SERVERINFO) _IO.write.long(file, server_data.protocol_version) _IO.write.byte(file, server_data.max_clients) _IO.write.byte(file, server_data.multi) _IO.write.string(file, server_data.map_name) for model in server_data.models: _IO.write.string(file, model) _IO.write.byte(file, 0) for sound in server_data.sounds: _IO.write.string(file, sound) _IO.write.byte(file, 0) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SERVERINFO server_data = ServerInfo() server_data.protocol_version = _IO.read.long(file) server_data.max_clients = _IO.read.byte(file) server_data.multi = _IO.read.byte(file) server_data.map_name = _IO.read.string(file) model = _IO.read.string(file) while model: server_data.models.append(model) model = _IO.read.string(file) server_data.models = tuple(server_data.models) sound = _IO.read.string(file) while sound: server_data.sounds.append(sound) sound = _IO.read.string(file) server_data.sounds = tuple(server_data.sounds) return server_data class LightStyle: """Class for representing a LightStyle message Defines the style of a light. Usually happens shortly after level change. Attributes: style: The light style number. string: A string of arbitrary length representing the brightness of the light. The brightness is mapped to the characters 'a' to 'z', with 'a' being black and 'z' being pure white. Example: # Flickering light light_style_message = LightStyle() light_style.style = 0 light_style.string = 'aaazaazaaaaaz' """ __slots__ = ( 'style', 'string' ) def __init__(self): self.style = None self.string = None @staticmethod def write(file, light_style): _IO.write.byte(file, SVC_LIGHTSTYLE) _IO.write.byte(file, light_style.style) _IO.write.string(file, light_style.string) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_LIGHTSTYLE light_style = LightStyle() light_style.style = _IO.read.byte(file) light_style.string = _IO.read.string(file) return light_style class UpdateName: """Class for representing UpdateName messages Sets the player's name. Attributes: player: The player number to update. name: The new name as a string. """ __slots__ = ( 'player', 'name' ) def __init__(self): self.player = None self.name = None @staticmethod def write(file, update_name): _IO.write.byte(file, SVC_UPDATENAME) _IO.write.byte(file, update_name.player) _IO.write.string(file, update_name.name) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_UPDATENAME update_name = UpdateName() update_name.player = _IO.read.byte(file) update_name.name = _IO.read.string(file) return update_name class UpdateFrags: """Class for representing UpdateFrags messages Sets the player's frag count. Attributes: player: The player to update. frags: The new frag count. """ __slots__ = ( 'player', 'frags' ) def __init__(self): self.player = None self.frags = None @staticmethod def write(file, update_frags): _IO.write.byte(file, SVC_UPDATEFRAGS) _IO.write.byte(file, update_frags.player) _IO.write.short(file, update_frags.frags) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_UPDATEFRAGS update_frags = UpdateFrags() update_frags.player = _IO.read.byte(file) update_frags.frags = _IO.read.short(file) return update_frags # Client Data bit mask SU_VIEWHEIGHT = 0b0000000000000001 SU_IDEALPITCH = 0b0000000000000010 SU_PUNCH1 = 0b0000000000000100 SU_PUNCH2 = 0b0000000000001000 SU_PUNCH3 = 0b0000000000010000 SU_VELOCITY1 = 0b0000000000100000 SU_VELOCITY2 = 0b0000000001000000 SU_VELOCITY3 = 0b0000000010000000 SU_ITEMS = 0b0000001000000000 SU_ONGROUND = 0b0000010000000000 SU_INWATER = 0b0000100000000000 SU_WEAPONFRAME = 0b0001000000000000 SU_ARMOR = 0b0010000000000000 SU_WEAPON = 0b0100000000000000 class ClientData: """Class for representing ClientData messages Server information about this client. Attributes: bit_mask: A bit field indicating what data is sent. view_height: Optional. The view offset from the origin along the z-axis. ideal_pitch: Optional. The calculated angle for looking up/down slopes. punch_angle: Optional. A triple representing camera shake. velocity: Optional. Player velocity. item_bit_mask: A bit field for player inventory. on_ground: Flag indicating if player is on the ground. in_water: Flag indicating if player is in a water volume. weapon_frame: Optional. The animation frame of the weapon. armor: Optional. The current armor value. weapon: Optional. The model number in the model table. health: The current health value. active_ammo: The amount count for the active weapon. ammo: The current ammo counts as a quadruple. active_weapon: The actively held weapon. """ __slots__ = ( 'bit_mask', 'view_height', 'ideal_pitch', 'punch_angle', 'velocity', 'item_bit_mask', 'on_ground', 'in_water', 'weapon_frame', 'armor', 'weapon', 'health', 'active_ammo', 'ammo', 'active_weapon' ) def __init__(self): self.bit_mask = 0b0000000000000000 self.view_height = 22 self.ideal_pitch = 0 self.punch_angle = 0, 0, 0 self.velocity = 0, 0, 0 self.item_bit_mask = 0b0000 self.on_ground = False self.in_water = False self.weapon_frame = 0 self.armor = 0 self.weapon = None self.health = None self.active_ammo = None self.ammo = None self.active_weapon = None @staticmethod def write(file, client_data): _IO.write.byte(file, SVC_CLIENTDATA) if client_data.on_ground: client_data.bit_mask |= SU_ONGROUND if client_data.in_water: client_data.bit_mask |= SU_INWATER _IO.write.short(file, client_data.bit_mask) if client_data.bit_mask & SU_VIEWHEIGHT: _IO.write.char(file, client_data.view_height) if client_data.bit_mask & SU_IDEALPITCH: _IO.write.char(file, client_data.ideal_pitch) if client_data.bit_mask & SU_PUNCH1: pa = client_data.punch_angle _IO.write.angle(file, pa[0]) if client_data.bit_mask & SU_VELOCITY1: ve = client_data.velocity _IO.write.char(file, ve[0] // 16) if client_data.bit_mask & SU_PUNCH2: pa = client_data.punch_angle _IO.write.angle(file, pa[1]) if client_data.bit_mask & SU_VELOCITY2: ve = client_data.velocity _IO.write.char(file, ve[1] // 16) if client_data.bit_mask & SU_PUNCH3: pa = client_data.punch_angle _IO.write.angle(file, pa[2]) if client_data.bit_mask & SU_VELOCITY3: ve = client_data.velocity _IO.write.char(file, ve[2] // 16) _IO.write.long(file, client_data.item_bit_mask) if client_data.bit_mask & SU_WEAPONFRAME: _IO.write.byte(file, client_data.weapon_frame) if client_data.bit_mask & SU_ARMOR: _IO.write.byte(file, client_data.armor) if client_data.bit_mask & SU_WEAPON: _IO.write.byte(file, client_data.weapon) _IO.write.short(file, client_data.health) _IO.write.byte(file, client_data.active_ammo) _IO.write.byte(file, client_data.ammo[0]) _IO.write.byte(file, client_data.ammo[1]) _IO.write.byte(file, client_data.ammo[2]) _IO.write.byte(file, client_data.ammo[3]) _IO.write.byte(file, client_data.active_weapon) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_CLIENTDATA client_data = ClientData() client_data.bit_mask = _IO.read.short(file) client_data.on_ground = client_data.bit_mask & SU_ONGROUND != 0 client_data.in_water = client_data.bit_mask & SU_INWATER != 0 if client_data.bit_mask & SU_VIEWHEIGHT: client_data.view_height = _IO.read.char(file) if client_data.bit_mask & SU_IDEALPITCH: client_data.ideal_pitch = _IO.read.char(file) if client_data.bit_mask & SU_PUNCH1: pa = client_data.punch_angle client_data.punch_angle = _IO.read.angle(file), pa[1], pa[2] if client_data.bit_mask & SU_VELOCITY1: ve = client_data.velocity client_data.velocity = _IO.read.char(file) * 16, ve[1], ve[2] if client_data.bit_mask & SU_PUNCH2: pa = client_data.punch_angle client_data.punch_angle = pa[0], _IO.read.angle(file), pa[2] if client_data.bit_mask & SU_VELOCITY2: ve = client_data.velocity client_data.velocity = ve[0], _IO.read.char(file) * 16, ve[2] if client_data.bit_mask & SU_PUNCH3: pa = client_data.punch_angle client_data.punch_angle = pa[0], pa[1], _IO.read.angle(file) if client_data.bit_mask & SU_VELOCITY3: ve = client_data.velocity client_data.velocity = ve[0], ve[1], _IO.read.char(file) * 16 client_data.item_bit_mask = _IO.read.long(file) if client_data.bit_mask & SU_WEAPONFRAME: client_data.weapon_frame = _IO.read.byte(file) if client_data.bit_mask & SU_ARMOR: client_data.armor = _IO.read.byte(file) if client_data.bit_mask & SU_WEAPON: client_data.weapon = _IO.read.byte(file) client_data.health = _IO.read.short(file) client_data.active_ammo = _IO.read.byte(file) client_data.ammo = _IO.read.byte(file), _IO.read.byte(file), _IO.read.byte(file), _IO.read.byte(file) client_data.active_weapon = _IO.read.byte(file) return client_data class StopSound: """Class for representing StopSound messages Stops a playing sound. Attributes: channel: The channel on which the sound is playing. entity: The entity that caused the sound. """ __slots__ = ( 'channel', 'entity' ) def __init__(self): self.channel = None @staticmethod def write(file, stop_sound): _IO.write.byte(file, SVC_STOPSOUND) data = stop_sound.entity << 3 | (stop_sound.channel & 0x07) _IO.write.short(file, data) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_STOPSOUND stop_sound = StopSound() data = _IO.read.short(file) stop_sound.channel = data & 0x07 stop_sound.entity = data >> 3 return stop_sound class UpdateColors: """Class for representing UpdateColors messages Sets the player's colors. Attributes: player: The player to update. colors: The combined shirt/pant color. """ __slots__ = ( 'player', 'colors' ) def __init__(self): self.player = None self.colors = None @staticmethod def write(file, update_colors): _IO.write.byte(file, SVC_UPDATECOLORS) _IO.write.byte(file, update_colors.player) _IO.write.byte(file, update_colors.colors) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_UPDATECOLORS update_colors = UpdateColors() update_colors.player = _IO.read.byte(file) update_colors.colors = _IO.read.byte(file) return update_colors class Particle: """Class for representing Particle messages Creates particle effects Attributes: origin: The origin position of the particles. direction: The velocity of the particles represented as a triple. count: The number of particles. color: The color index of the particle. """ __slots__ = ( 'origin', 'direction', 'count', 'color' ) def __init__(self): self.origin = None self.direction = None self.count = None self.color = None @staticmethod def write(file, particle): _IO.write.byte(file, SVC_PARTICLE) _IO.write.position(file, particle.origin) _IO.write.char(file, particle.direction[0] * 16) _IO.write.char(file, particle.direction[1] * 16) _IO.write.char(file, particle.direction[2] * 16) _IO.write.byte(file, particle.count) _IO.write.byte(file, particle.color) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_PARTICLE particle = Particle() particle.origin = _IO.read.position(file) particle.direction = _IO.read.char(file) / 16, _IO.read.char(file) / 16, _IO.read.char(file) / 16, particle.count = _IO.read.byte(file) particle.color = _IO.read.byte(file) return particle class Damage: """Class for representing Damage messages Damage information Attributes: armor: The damage amount to be deducted from player armor. blood: The damage amount to be deducted from player health. origin: The position of the entity that inflicted the damage. """ __slots__ = ( 'armor', 'blood', 'origin' ) def __init__(self): self.armor = None self.blood = None self.origin = None @staticmethod def write(file, damage): _IO.write.byte(file, SVC_DAMAGE) _IO.write.byte(file, damage.armor) _IO.write.byte(file, damage.blood) _IO.write.position(file, damage.origin) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_DAMAGE damage = Damage() damage.armor = _IO.read.byte(file) damage.blood = _IO.read.byte(file) damage.origin = _IO.read.position(file) return damage class SpawnStatic: """Class for representing SpawnStatic messages Creates a static entity Attributes: model_index: The model number in the model table. frame: The frame number of the model. color_map: The color map used to display the model. skin: The skin number of the model. origin: The position of the entity. angles: The orientation of the entity. """ __slots__ = ( 'model_index', 'frame', 'color_map', 'skin', 'origin', 'angles' ) def __init__(self): self.model_index = None self.frame = None self.color_map = None self.skin = None self.origin = None self.angles = None @staticmethod def write(file, spawn_static): _IO.write.byte(file, SVC_SPAWNSTATIC) _IO.write.byte(file, spawn_static.model_index) _IO.write.byte(file, spawn_static.frame) _IO.write.byte(file, spawn_static.color_map) _IO.write.byte(file, spawn_static.skin) _IO.write.position(file, spawn_static.origin) _IO.write.angles(file, spawn_static.angles) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SPAWNSTATIC spawn_static = SpawnStatic() spawn_static.model_index = _IO.read.byte(file) spawn_static.frame = _IO.read.byte(file) spawn_static.color_map = _IO.read.byte(file) spawn_static.skin = _IO.read.byte(file) spawn_static.origin = _IO.read.position(file) spawn_static.angles = _IO.read.angles(file) return spawn_static class SpawnBinary: """Class for representing SpawnBinary messages This is a deprecated message. """ __slots__ = () @staticmethod def write(file): raise BadMessage('SpawnBinary message obsolete') @staticmethod def read(file): raise BadMessage('SpawnBinary message obsolete') class SpawnBaseline: """Class for representing SpawnBaseline messages Creates a dynamic entity Attributes: entity: The number of the entity. model_index: The number of the model in the model table. frame: The frame number of the model. color_map: The color map used to display the model. skin: The skin number of the model. origin: The position of the entity. angles: The orientation of the entity. """ __slots__ = ( 'entity', 'model_index', 'frame', 'color_map', 'skin', 'origin', 'angles' ) def __init__(self): self.entity = None self.model_index = None self.frame = None self.color_map = None self.skin = None self.origin = None self.angles = None @staticmethod def write(file, spawn_baseline): _IO.write.byte(file, SVC_SPAWNBASELINE) _IO.write.short(file, spawn_baseline.entity) _IO.write.byte(file, spawn_baseline.model_index) _IO.write.byte(file, spawn_baseline.frame) _IO.write.byte(file, spawn_baseline.color_map) _IO.write.byte(file, spawn_baseline.skin) _IO.write.position(file, spawn_baseline.origin) _IO.write.angles(file, spawn_baseline.angles) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SPAWNBASELINE spawn_baseline = SpawnBaseline() spawn_baseline.entity = _IO.read.short(file) spawn_baseline.model_index = _IO.read.byte(file) spawn_baseline.frame = _IO.read.byte(file) spawn_baseline.color_map = _IO.read.byte(file) spawn_baseline.skin = _IO.read.byte(file) spawn_baseline.origin = _IO.read.position(file) spawn_baseline.angles = _IO.read.angles(file) return spawn_baseline TE_SPIKE = 0 TE_SUPERSPIKE = 1 TE_GUNSHOT = 2 TE_EXPLOSION = 3 TE_TAREXPLOSION = 4 TE_LIGHTNING1 = 5 TE_LIGHTNING2 = 6 TE_WIZSPIKE = 7 TE_KNIGHTSPIKE = 8 TE_LIGHTNING3 = 9 TE_LAVASPLASH = 10 TE_TELEPORT = 11 TE_EXPLOSION2 = 12 TE_BEAM = 13 class TempEntity: """Class for representing TempEntity messages Creates a temporary entity. The attributes of the message depend on the type of entity being created. Attributes: type: The type of the temporary entity. """ def __init__(self): self.type = None @staticmethod def write(file, temp_entity): _IO.write.byte(file, SVC_TEMP_ENTITY) _IO.write.byte(file, temp_entity.type) if temp_entity.type == TE_WIZSPIKE or \ temp_entity.type == TE_KNIGHTSPIKE or \ temp_entity.type == TE_SPIKE or \ temp_entity.type == TE_SUPERSPIKE or \ temp_entity.type == TE_GUNSHOT or \ temp_entity.type == TE_EXPLOSION or \ temp_entity.type == TE_TAREXPLOSION or \ temp_entity.type == TE_LAVASPLASH or \ temp_entity.type == TE_TELEPORT: _IO.write.position(file, temp_entity.origin) elif temp_entity.type == TE_LIGHTNING1 or \ temp_entity.type == TE_LIGHTNING2 or \ temp_entity.type == TE_LIGHTNING3 or \ temp_entity.type == TE_BEAM: _IO.write.short(file, temp_entity.entity) _IO.write.position(file, temp_entity.start) _IO.write.position(file, temp_entity.end) elif temp_entity.type == TE_EXPLOSION2: _IO.write.position(file, temp_entity.origin) _IO.write.byte(file, temp_entity.color_start) _IO.write.byte(file, temp_entity.color_length) else: raise BadMessage('Invalid Temporary Entity type: %r' % temp_entity.type) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_TEMP_ENTITY temp_entity = TempEntity() temp_entity.type = _IO.read.byte(file) if temp_entity.type == TE_WIZSPIKE or \ temp_entity.type == TE_KNIGHTSPIKE or \ temp_entity.type == TE_SPIKE or \ temp_entity.type == TE_SUPERSPIKE or \ temp_entity.type == TE_GUNSHOT or \ temp_entity.type == TE_EXPLOSION or \ temp_entity.type == TE_TAREXPLOSION or \ temp_entity.type == TE_LAVASPLASH or \ temp_entity.type == TE_TELEPORT: temp_entity.origin = _IO.read.position(file) elif temp_entity.type == TE_LIGHTNING1 or \ temp_entity.type == TE_LIGHTNING2 or \ temp_entity.type == TE_LIGHTNING3 or \ temp_entity.type == TE_BEAM: temp_entity.entity = _IO.read.short(file) temp_entity.start = _IO.read.position(file) temp_entity.end = _IO.read.position(file) elif temp_entity.type == TE_EXPLOSION2: temp_entity.origin = _IO.read.position(file) temp_entity.color_start = _IO.read.byte(file) temp_entity.color_length = _IO.read.byte(file) else: raise BadMessage(f'Invalid Temporary Entity type: {temp_entity.type}') return temp_entity class SetPause: """Class for representing SetPause messages Sets the pause state Attributes: paused: The pause state. 1 for paused, 0 otherwise. """ __slots__ = ( 'paused' ) def __init__(self): self.paused = None @staticmethod def write(file, set_pause): _IO.write.byte(file, SVC_SETPAUSE) _IO.write.byte(file, set_pause.paused) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SETPAUSE set_pause = SetPause() set_pause.paused = _IO.read.byte(file) return set_pause class SignOnNum: """Class for representing SignOnNum messages This message represents the client state. Attributes: sign_on: The client state. """ __slots__ = ( 'sign_on' ) def __init__(self): self.sign_on = None @staticmethod def write(file, sign_on_num): _IO.write.byte(file, SVC_SIGNONNUM) _IO.write.byte(file, sign_on_num.sign_on) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SIGNONNUM sign_on_num = SignOnNum() sign_on_num.sign_on = _IO.read.byte(file) return sign_on_num class CenterPrint: """Class for representing CenterPrint messages Prints text in the center of the screen. Attributes: text: The text to be shown. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, center_print): _IO.write.byte(file, SVC_CENTERPRINT) _IO.write.string(file, center_print.text) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_CENTERPRINT center_print = CenterPrint() center_print.text = _IO.read.string(file) return center_print class KilledMonster: """Class for representing KilledMonster messages Indicates the death of a monster. """ __slots__ = () @staticmethod def write(file, killed_monster=None): _IO.write.byte(file, SVC_KILLEDMONSTER) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_KILLEDMONSTER return KilledMonster() class FoundSecret: """Class for representing FoundSecret messages Indicates a secret has been found. """ __slots__ = () @staticmethod def write(file, found_secret=None): _IO.write.byte(file, SVC_FOUNDSECRET) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_FOUNDSECRET return FoundSecret() class SpawnStaticSound: """Class for representing SpawnStaticSound messages Creates a static sound Attributes: origin: The position of the sound. sound_number: The sound number in the sound table. volume: The sound volume. attenuation: The sound attenuation. """ __slots__ = ( 'origin', 'sound_number', 'volume', 'attenuation' ) def __init__(self): self.origin = None self.sound_number = None self.volume = None self.attenuation = None @staticmethod def write(file, spawn_static_sound): _IO.write.byte(file, SVC_SPAWNSTATICSOUND) _IO.write.position(file, spawn_static_sound.origin) _IO.write.byte(file, spawn_static_sound.sound_number) _IO.write.byte(file, spawn_static_sound.volume * 256) _IO.write.byte(file, spawn_static_sound.attenuation * 64) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SPAWNSTATICSOUND spawn_static_sound = SpawnStaticSound() spawn_static_sound.origin = _IO.read.position(file) spawn_static_sound.sound_number = _IO.read.byte(file) spawn_static_sound.volume = _IO.read.byte(file) / 256 spawn_static_sound.attenuation = _IO.read.byte(file) / 64 return spawn_static_sound class Intermission: """Class for representing Intermission messages Displays the level end screen. """ __slots__ = () @staticmethod def write(file, intermission=None): _IO.write.byte(file, SVC_INTERMISSION) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_INTERMISSION return Intermission() class Finale: """Class for representing Finale messages Displays the episode end screen. Attributes: text: The text to show. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, finale): _IO.write.byte(file, SVC_FINALE) _IO.write.string(file, finale.text) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_FINALE finale = Finale() finale.text = _IO.read.string(file) return finale class CdTrack: """Class for representing CdTrack messages Selects the cd track Attributes: from_track: The start track. to_track: The end track. """ __slots__ = ( 'from_track', 'to_track' ) def __init__(self): self.from_track = None self.to_track = None @staticmethod def write(file, cd_track): _IO.write.byte(file, SVC_CDTRACK) _IO.write.byte(file, cd_track.from_track) _IO.write.byte(file, cd_track.to_track) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_CDTRACK cd_track = CdTrack() cd_track.from_track = _IO.read.byte(file) cd_track.to_track = _IO.read.byte(file) return cd_track class SellScreen: """Class for representing SellScreen messages Displays the help and sell screen. """ __slots__ = () @staticmethod def write(file, sell_screen=None): _IO.write.byte(file, SVC_SELLSCREEN) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SELLSCREEN return SellScreen() class CutScene: """Class for representing CutScene messages Displays end screen and text. Attributes: text: The text to be shown. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, cut_scene): _IO.write.byte(file, SVC_CUTSCENE) _IO.write.string(file, cut_scene.text) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_CUTSCENE cut_scene = CutScene() cut_scene.text = _IO.read.string(file) return cut_scene _messages = [Bad, Nop, Disconnect, UpdateStat, Version, SetView, Sound, Time, Print, StuffText, SetAngle, ServerInfo, LightStyle, UpdateName, UpdateFrags, ClientData, StopSound, UpdateColors, Particle, Damage, SpawnStatic, SpawnBinary, SpawnBaseline, TempEntity, SetPause, SignOnNum, CenterPrint, KilledMonster, FoundSecret, SpawnStaticSound, Intermission, Finale, CdTrack, SellScreen, CutScene] U_MOREBITS = 0b0000000000000001 U_ORIGIN1 = 0b0000000000000010 U_ORIGIN2 = 0b0000000000000100 U_ORIGIN3 = 0b0000000000001000 U_ANGLE2 = 0b0000000000010000 U_NOLERP = 0b0000000000100000 U_FRAME = 0b0000000001000000 U_SIGNAL = 0b0000000010000000 U_ANGLE1 = 0b0000000100000000 U_ANGLE3 = 0b0000001000000000 U_MODEL = 0b0000010000000000 U_COLORMAP = 0b0000100000000000 U_SKIN = 0b0001000000000000 U_EFFECTS = 0b0010000000000000 U_LONGENTITY = 0b0100000000000000 class UpdateEntity: """Class for representing UpdateEntity messages Updates an entity. Attributes: bit_mask: A bit field indicating what data is sent. entity: The number of the entity. model_index: The number of the model in the model table. frame: The frame number of the model. color_map: The color map used to display the model. skin: The skin number of the model. effects: A bit field indicating special effects. origin: The position of the entity. angles: The orientation of the entity. """ __slots__ = ( 'bit_mask', 'entity', 'model_index', 'frame', 'colormap', 'skin', 'effects', 'origin', 'angles' ) def __init__(self): self.bit_mask = 0b0000000000000000 self.entity = None self.model_index = None self.frame = None self.colormap = None self.skin = None self.effects = None self.origin = None, None, None self.angles = None, None, None @staticmethod def write(file, update_entity): _IO.write.byte(file, update_entity.bit_mask & 0xFF | 0x80) if update_entity.bit_mask & U_MOREBITS: _IO.write.byte(file, update_entity.bit_mask >> 8 & 0xFF) if update_entity.bit_mask & U_LONGENTITY: _IO.write.short(file, update_entity.entity) else: _IO.write.byte(file, update_entity.entity) if update_entity.bit_mask & U_MODEL: _IO.write.byte(file, update_entity.model_index) if update_entity.bit_mask & U_FRAME: _IO.write.byte(file, update_entity.frame) if update_entity.bit_mask & U_COLORMAP: _IO.write.byte(file, update_entity.colormap) if update_entity.bit_mask & U_SKIN: _IO.write.byte(file, update_entity.skin) if update_entity.bit_mask & U_EFFECTS: _IO.write.byte(file, update_entity.effects) if update_entity.bit_mask & U_ORIGIN1: _IO.write.coord(file, update_entity.origin[0]) if update_entity.bit_mask & U_ANGLE1: _IO.write.angle(file, update_entity.angles[0]) if update_entity.bit_mask & U_ORIGIN2: _IO.write.coord(file, update_entity.origin[1]) if update_entity.bit_mask & U_ANGLE2: _IO.write.angle(file, update_entity.angles[1]) if update_entity.bit_mask & U_ORIGIN3: _IO.write.coord(file, update_entity.origin[2]) if update_entity.bit_mask & U_ANGLE3: _IO.write.angle(file, update_entity.angles[2]) @staticmethod def read(file): update_entity = UpdateEntity() b = _IO.read.byte(file) update_entity.bit_mask = b & 0x7F if update_entity.bit_mask & U_MOREBITS: update_entity.bit_mask |= _IO.read.byte(file) << 8 if update_entity.bit_mask & U_LONGENTITY: update_entity.entity = _IO.read.short(file) else: update_entity.entity = _IO.read.byte(file) if update_entity.bit_mask & U_MODEL: update_entity.model_index = _IO.read.byte(file) if update_entity.bit_mask & U_FRAME: update_entity.frame = _IO.read.byte(file) if update_entity.bit_mask & U_COLORMAP: update_entity.colormap = _IO.read.byte(file) if update_entity.bit_mask & U_SKIN: update_entity.skin = _IO.read.byte(file) if update_entity.bit_mask & U_EFFECTS: update_entity.effects = _IO.read.byte(file) if update_entity.bit_mask & U_ORIGIN1: update_entity.origin = _IO.read.coord(file), update_entity.origin[1], update_entity.origin[2] if update_entity.bit_mask & U_ANGLE1: update_entity.angles = _IO.read.angle(file), update_entity.angles[1], update_entity.angles[2] if update_entity.bit_mask & U_ORIGIN2: update_entity.origin = update_entity.origin[0], _IO.read.coord(file), update_entity.origin[2] if update_entity.bit_mask & U_ANGLE2: update_entity.angles = update_entity.angles[0], _IO.read.angle(file), update_entity.angles[2] if update_entity.bit_mask & U_ORIGIN3: update_entity.origin = update_entity.origin[0], update_entity.origin[1], _IO.read.coord(file) if update_entity.bit_mask & U_ANGLE3: update_entity.angles = update_entity.angles[0], update_entity.angles[1], _IO.read.angle(file) return update_entity class MessageBlock: """Class for representing a message block Attributes: view_angles: The client view angles. messages: A sequence of messages. """ __slots__ = ( 'view_angles', 'messages' ) def __init__(self): self.view_angles = None self.messages = [] @staticmethod def write(file, message_block): start_of_block = file.tell() _IO.write.long(file, 0) _IO.write.float(file, message_block.view_angles[0]) _IO.write.float(file, message_block.view_angles[1]) _IO.write.float(file, message_block.view_angles[2]) start_of_messages = file.tell() for message in message_block.messages: message.__class__.write(file, message) end_of_messages = file.tell() block_size = end_of_messages - start_of_messages file.seek(start_of_block) _IO.write.long(file, block_size) file.seek(end_of_messages ) @staticmethod def read(file): message_block = MessageBlock() blocksize = _IO.read.long(file) message_block.view_angles = _IO.read.float(file), _IO.read.float(file), _IO.read.float(file) message_block_data = file.read(blocksize) buff = io.BufferedReader(io.BytesIO(message_block_data)) message_id = buff.peek(1)[:1] while message_id != b'': message_id = struct.unpack('<B', message_id)[0] if message_id < 128: message = _messages[message_id].read(buff) else: message = UpdateEntity.read(buff) if message: message_block.messages.append(message) message_id = buff.peek(1)[:1] buff.close() return message_block
"""This module provides file I/O for the Quake network protocol. References: Quake Source - id Software - https://github.com/id-Software/Quake The Unofficial DEM Format Description - <NAME>, et al. - https://www.quakewiki.net/archives/demospecs/dem/dem.html """ import io import struct __all__ = ['Bad', 'Nop', 'Disconnect', 'UpdateStat', 'Version', 'SetView', 'Sound', 'Time', 'Print', 'StuffText', 'SetAngle', 'ServerInfo', 'LightStyle', 'UpdateName', 'UpdateFrags', 'ClientData', 'StopSound', 'UpdateColors', 'Particle', 'Damage', 'SpawnStatic', 'SpawnBinary', 'SpawnBaseline', 'TempEntity', 'SetPause', 'SignOnNum', 'CenterPrint', 'KilledMonster', 'FoundSecret', 'SpawnStaticSound', 'Intermission', 'Finale', 'CdTrack', 'SellScreen', 'CutScene', 'UpdateEntity', 'MessageBlock'] class _IO: """Simple namespace for protocol IO""" @staticmethod def _read(fmt, file): return struct.unpack(fmt, file.read(struct.calcsize(fmt)))[0] class read: """Read IO namespace""" @staticmethod def char(file): return int(_IO._read('<b', file)) @staticmethod def byte(file): return int(_IO._read('<B', file)) @staticmethod def short(file): return int(_IO._read('<h', file)) @staticmethod def long(file): return int(_IO._read('<l', file)) @staticmethod def float(file): return float(_IO._read('<f', file)) @staticmethod def coord(file): return _IO.read.short(file) * 0.125 @staticmethod def position(file): return _IO.read.coord(file), _IO.read.coord(file), _IO.read.coord(file) @staticmethod def angle(file): return _IO.read.char(file) * 360 / 256 @staticmethod def angles(file): return _IO.read.angle(file), _IO.read.angle(file), _IO.read.angle(file) @staticmethod def string(file, terminal_byte=b'\x00'): string = b'' char = _IO._read('<s', file) while char != terminal_byte: string += char char = _IO._read('<s', file) return string.decode('ascii') @staticmethod def _write(fmt, file, value): data = struct.pack(fmt, value) file.write(data) class write: """Write IO namespace""" @staticmethod def char(file, value): _IO._write('<b', file, int(value)) @staticmethod def byte(file, value): _IO._write('<B', file, int(value)) @staticmethod def short(file, value): _IO._write('<h', file, int(value)) @staticmethod def long(file, value): _IO._write('<l', file, int(value)) @staticmethod def float(file, value): _IO._write('<f', file, float(value)) @staticmethod def coord(file, value): _IO.write.short(file, value / 0.125) @staticmethod def position(file, values): _IO.write.coord(file, values[0]), _IO.write.coord(file, values[1]), _IO.write.coord(file, values[2]) @staticmethod def angle(file, value): _IO.write.char(file, int(value * 256 / 360)) @staticmethod def angles(file, values): _IO.write.angle(file, values[0]), _IO.write.angle(file, values[1]), _IO.write.angle(file, values[2]) @staticmethod def string(file, value, terminal_byte=b'\x00'): value = value[:2048] size = len(value) format = '<%is' % (size + 1) v = value.encode('ascii') + terminal_byte data = struct.pack(format, v) file.write(data) class BadMessage(Exception): pass SVC_BAD = 0 SVC_NOP = 1 SVC_DISCONNECT = 2 SVC_UPDATESTAT = 3 SVC_VERSION = 4 SVC_SETVIEW = 5 SVC_SOUND = 6 SVC_TIME = 7 SVC_PRINT = 8 SVC_STUFFTEXT = 9 SVC_SETANGLE = 10 SVC_SERVERINFO = 11 SVC_LIGHTSTYLE = 12 SVC_UPDATENAME = 13 SVC_UPDATEFRAGS = 14 SVC_CLIENTDATA = 15 SVC_STOPSOUND = 16 SVC_UPDATECOLORS = 17 SVC_PARTICLE = 18 SVC_DAMAGE = 19 SVC_SPAWNSTATIC = 20 SVC_SPAWNBINARY = 21 SVC_SPAWNBASELINE = 22 SVC_TEMP_ENTITY = 23 SVC_SETPAUSE = 24 SVC_SIGNONNUM = 25 SVC_CENTERPRINT = 26 SVC_KILLEDMONSTER = 27 SVC_FOUNDSECRET = 28 SVC_SPAWNSTATICSOUND = 29 SVC_INTERMISSION = 30 SVC_FINALE = 31 SVC_CDTRACK = 32 SVC_SELLSCREEN = 33 SVC_CUTSCENE = 34 class Bad: """Class for representing a Bad message This is an error message and should not appear. """ __slots__ = () @staticmethod def write(file, bad=None): _IO.write.byte(file, SVC_BAD) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_BAD return Bad() class Nop: """Class for representing a Nop message""" __slots__ = () @staticmethod def write(file, nop=None): _IO.write.byte(file, SVC_NOP) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_NOP return Nop() class Disconnect: """Class for representing a Disconnect message Disconnect from the server and end the game. Typically this the last message of a demo. """ __slots__ = () @staticmethod def write(file, disconnect=None): _IO.write.byte(file, SVC_DISCONNECT) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_DISCONNECT return Disconnect() class UpdateStat: """Class for representing UpdateStat messages Updates a player state value. Attributes: index: The index to update in the player state array. value: The new value to set. """ __slots__ = ( 'index', 'value' ) def __init__(self): self.index = None self.value = None @staticmethod def write(file, update_stat): _IO.write.byte(file, SVC_UPDATESTAT) _IO.write.byte(file, update_stat.index) _IO.write.long(file, update_stat.value) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_UPDATESTAT update_stat = UpdateStat() update_stat.index = _IO.read.byte(file) update_stat.value = _IO.read.long(file) return update_stat class Version: """Class for representing Version messages Attributes: protocol_version: Protocol version of the server. Quake uses 15. """ __slots__ = ( 'protocol_version' ) def __init__(self): self.protocol_version = None @staticmethod def write(file, version): _IO.write.byte(file, SVC_VERSION) _IO.write.long(file, version.protocol_version) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_VERSION version = Version() version.protocol_version = _IO.read.long(file) return version class SetView: """Class for representing SetView messages Sets the camera position to the given entity. Attributes: entity: The entity number """ __slots__ = ( 'entity' ) def __init__(self): self.entity = None @staticmethod def write(file, set_view): _IO.write.byte(file, SVC_SETVIEW) _IO.write.short(file, set_view.entity) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SETVIEW set_view = SetView() set_view.entity = _IO.read.short(file) return set_view SND_VOLUME = 0b0001 SND_ATTENUATION = 0b0010 SND_LOOPING = 0b0100 class Sound: """Class for representing Sound messages Plays a sound on a channel at a position. Attributes: entity: The entity that caused the sound. bit_mask: A bit field indicating what data is sent. volume: Optional. The sound volume or None. attenuation: Optional. The sound attenuation or None. channel: The sound channel, maximum of eight. sound_number: The number of the sound in the sound table. origin: The position of the sound. """ __slots__ = ( 'entity', 'bit_mask', 'volume', 'attenuation', 'channel', 'sound_number', 'origin' ) def __init__(self): self.entity = None self.bit_mask = 0b0000 self.volume = 255 self.attenuation = 1.0 self.channel = None self.sound_number = None self.origin = None, None, None @staticmethod def write(file, sound): _IO.write.byte(file, SVC_SOUND) _IO.write.byte(file, sound.bit_mask) if sound.bit_mask & SND_VOLUME: _IO.write.byte(file, sound.volume) if sound.bit_mask & SND_ATTENUATION: _IO.write.byte(file, sound.attenuation * 64) channel = sound.entity << 3 channel |= sound.channel _IO.write.short(file, channel) _IO.write.byte(file, sound.sound_number) _IO.write.position(file, sound.origin) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SOUND sound = Sound() sound.bit_mask = _IO.read.byte(file) if sound.bit_mask & SND_VOLUME: sound.volume = _IO.read.byte(file) if sound.bit_mask & SND_ATTENUATION: sound.attenuation = _IO.read.byte(file) / 64 sound.channel = _IO.read.short(file) sound.entity = sound.channel >> 3 sound.channel &= 7 sound.sound_number = _IO.read.byte(file) sound.origin = _IO.read.position(file) return sound class Time: """Class for representing Time messages A time stamp that should appear in each block of messages. Attributes: time: The amount of elapsed time(in seconds) since the start of the game. """ __slots__ = ( 'time' ) def __init__(self): self.time = None @staticmethod def write(file, time): _IO.write.byte(file, SVC_TIME) _IO.write.float(file, time.time) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_TIME time = Time() time.time = _IO.read.float(file) return time class Print: """Class for representing Print messages Prints text in the top left corner of the screen and console. Attributes: text: The text to be shown. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, _print): _IO.write.byte(file, SVC_PRINT) _IO.write.string(file, _print.text) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_PRINT _print = Print() _print.text = _IO.read.string(file) return _print class StuffText: """Class for representing StuffText messages Text sent to the client console and ran. Attributes: text: The text to send to the client console. Note: This string is terminated with the newline character. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, stuff_text): _IO.write.byte(file, SVC_STUFFTEXT) _IO.write.string(file, stuff_text.text, b'\n') @staticmethod def read(file): assert _IO.read.byte(file) == SVC_STUFFTEXT stuff_text = StuffText() stuff_text.text = _IO.read.string(file, b'\n') return stuff_text class SetAngle: """Class for representing SetAngle messages Sets the camera's orientation. Attributes: angles: The new angles for the camera. """ __slots__ = ( 'angles' ) def __init__(self): self.angles = None @staticmethod def write(file, set_angle): _IO.write.byte(file, SVC_SETANGLE) _IO.write.angles(file, set_angle.angles) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SETANGLE set_angle = SetAngle() set_angle.angles = _IO.read.angles(file) return set_angle class ServerInfo: """Class for representing ServerInfo messages Handles the loading of assets. Usually first message sent after a level change. Attributes: protocol_version: Protocol version of the server. Quake uses 15. max_clients: Number of clients. multi: Multiplayer flag. Set to 0 for single-player and 1 for multiplayer. map_name: The name of the level. models: The model table as as sequence of strings. sounds: The sound table as a sequence of strings. """ __slots__ = ( 'protocol_version', 'max_clients', 'multi', 'map_name', 'models', 'sounds' ) def __init__(self): self.protocol_version = 15 self.max_clients = 0 self.multi = 0 self.map_name = '' self.models = [] self.sounds = [] @staticmethod def write(file, server_data): _IO.write.byte(file, SVC_SERVERINFO) _IO.write.long(file, server_data.protocol_version) _IO.write.byte(file, server_data.max_clients) _IO.write.byte(file, server_data.multi) _IO.write.string(file, server_data.map_name) for model in server_data.models: _IO.write.string(file, model) _IO.write.byte(file, 0) for sound in server_data.sounds: _IO.write.string(file, sound) _IO.write.byte(file, 0) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SERVERINFO server_data = ServerInfo() server_data.protocol_version = _IO.read.long(file) server_data.max_clients = _IO.read.byte(file) server_data.multi = _IO.read.byte(file) server_data.map_name = _IO.read.string(file) model = _IO.read.string(file) while model: server_data.models.append(model) model = _IO.read.string(file) server_data.models = tuple(server_data.models) sound = _IO.read.string(file) while sound: server_data.sounds.append(sound) sound = _IO.read.string(file) server_data.sounds = tuple(server_data.sounds) return server_data class LightStyle: """Class for representing a LightStyle message Defines the style of a light. Usually happens shortly after level change. Attributes: style: The light style number. string: A string of arbitrary length representing the brightness of the light. The brightness is mapped to the characters 'a' to 'z', with 'a' being black and 'z' being pure white. Example: # Flickering light light_style_message = LightStyle() light_style.style = 0 light_style.string = 'aaazaazaaaaaz' """ __slots__ = ( 'style', 'string' ) def __init__(self): self.style = None self.string = None @staticmethod def write(file, light_style): _IO.write.byte(file, SVC_LIGHTSTYLE) _IO.write.byte(file, light_style.style) _IO.write.string(file, light_style.string) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_LIGHTSTYLE light_style = LightStyle() light_style.style = _IO.read.byte(file) light_style.string = _IO.read.string(file) return light_style class UpdateName: """Class for representing UpdateName messages Sets the player's name. Attributes: player: The player number to update. name: The new name as a string. """ __slots__ = ( 'player', 'name' ) def __init__(self): self.player = None self.name = None @staticmethod def write(file, update_name): _IO.write.byte(file, SVC_UPDATENAME) _IO.write.byte(file, update_name.player) _IO.write.string(file, update_name.name) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_UPDATENAME update_name = UpdateName() update_name.player = _IO.read.byte(file) update_name.name = _IO.read.string(file) return update_name class UpdateFrags: """Class for representing UpdateFrags messages Sets the player's frag count. Attributes: player: The player to update. frags: The new frag count. """ __slots__ = ( 'player', 'frags' ) def __init__(self): self.player = None self.frags = None @staticmethod def write(file, update_frags): _IO.write.byte(file, SVC_UPDATEFRAGS) _IO.write.byte(file, update_frags.player) _IO.write.short(file, update_frags.frags) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_UPDATEFRAGS update_frags = UpdateFrags() update_frags.player = _IO.read.byte(file) update_frags.frags = _IO.read.short(file) return update_frags # Client Data bit mask SU_VIEWHEIGHT = 0b0000000000000001 SU_IDEALPITCH = 0b0000000000000010 SU_PUNCH1 = 0b0000000000000100 SU_PUNCH2 = 0b0000000000001000 SU_PUNCH3 = 0b0000000000010000 SU_VELOCITY1 = 0b0000000000100000 SU_VELOCITY2 = 0b0000000001000000 SU_VELOCITY3 = 0b0000000010000000 SU_ITEMS = 0b0000001000000000 SU_ONGROUND = 0b0000010000000000 SU_INWATER = 0b0000100000000000 SU_WEAPONFRAME = 0b0001000000000000 SU_ARMOR = 0b0010000000000000 SU_WEAPON = 0b0100000000000000 class ClientData: """Class for representing ClientData messages Server information about this client. Attributes: bit_mask: A bit field indicating what data is sent. view_height: Optional. The view offset from the origin along the z-axis. ideal_pitch: Optional. The calculated angle for looking up/down slopes. punch_angle: Optional. A triple representing camera shake. velocity: Optional. Player velocity. item_bit_mask: A bit field for player inventory. on_ground: Flag indicating if player is on the ground. in_water: Flag indicating if player is in a water volume. weapon_frame: Optional. The animation frame of the weapon. armor: Optional. The current armor value. weapon: Optional. The model number in the model table. health: The current health value. active_ammo: The amount count for the active weapon. ammo: The current ammo counts as a quadruple. active_weapon: The actively held weapon. """ __slots__ = ( 'bit_mask', 'view_height', 'ideal_pitch', 'punch_angle', 'velocity', 'item_bit_mask', 'on_ground', 'in_water', 'weapon_frame', 'armor', 'weapon', 'health', 'active_ammo', 'ammo', 'active_weapon' ) def __init__(self): self.bit_mask = 0b0000000000000000 self.view_height = 22 self.ideal_pitch = 0 self.punch_angle = 0, 0, 0 self.velocity = 0, 0, 0 self.item_bit_mask = 0b0000 self.on_ground = False self.in_water = False self.weapon_frame = 0 self.armor = 0 self.weapon = None self.health = None self.active_ammo = None self.ammo = None self.active_weapon = None @staticmethod def write(file, client_data): _IO.write.byte(file, SVC_CLIENTDATA) if client_data.on_ground: client_data.bit_mask |= SU_ONGROUND if client_data.in_water: client_data.bit_mask |= SU_INWATER _IO.write.short(file, client_data.bit_mask) if client_data.bit_mask & SU_VIEWHEIGHT: _IO.write.char(file, client_data.view_height) if client_data.bit_mask & SU_IDEALPITCH: _IO.write.char(file, client_data.ideal_pitch) if client_data.bit_mask & SU_PUNCH1: pa = client_data.punch_angle _IO.write.angle(file, pa[0]) if client_data.bit_mask & SU_VELOCITY1: ve = client_data.velocity _IO.write.char(file, ve[0] // 16) if client_data.bit_mask & SU_PUNCH2: pa = client_data.punch_angle _IO.write.angle(file, pa[1]) if client_data.bit_mask & SU_VELOCITY2: ve = client_data.velocity _IO.write.char(file, ve[1] // 16) if client_data.bit_mask & SU_PUNCH3: pa = client_data.punch_angle _IO.write.angle(file, pa[2]) if client_data.bit_mask & SU_VELOCITY3: ve = client_data.velocity _IO.write.char(file, ve[2] // 16) _IO.write.long(file, client_data.item_bit_mask) if client_data.bit_mask & SU_WEAPONFRAME: _IO.write.byte(file, client_data.weapon_frame) if client_data.bit_mask & SU_ARMOR: _IO.write.byte(file, client_data.armor) if client_data.bit_mask & SU_WEAPON: _IO.write.byte(file, client_data.weapon) _IO.write.short(file, client_data.health) _IO.write.byte(file, client_data.active_ammo) _IO.write.byte(file, client_data.ammo[0]) _IO.write.byte(file, client_data.ammo[1]) _IO.write.byte(file, client_data.ammo[2]) _IO.write.byte(file, client_data.ammo[3]) _IO.write.byte(file, client_data.active_weapon) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_CLIENTDATA client_data = ClientData() client_data.bit_mask = _IO.read.short(file) client_data.on_ground = client_data.bit_mask & SU_ONGROUND != 0 client_data.in_water = client_data.bit_mask & SU_INWATER != 0 if client_data.bit_mask & SU_VIEWHEIGHT: client_data.view_height = _IO.read.char(file) if client_data.bit_mask & SU_IDEALPITCH: client_data.ideal_pitch = _IO.read.char(file) if client_data.bit_mask & SU_PUNCH1: pa = client_data.punch_angle client_data.punch_angle = _IO.read.angle(file), pa[1], pa[2] if client_data.bit_mask & SU_VELOCITY1: ve = client_data.velocity client_data.velocity = _IO.read.char(file) * 16, ve[1], ve[2] if client_data.bit_mask & SU_PUNCH2: pa = client_data.punch_angle client_data.punch_angle = pa[0], _IO.read.angle(file), pa[2] if client_data.bit_mask & SU_VELOCITY2: ve = client_data.velocity client_data.velocity = ve[0], _IO.read.char(file) * 16, ve[2] if client_data.bit_mask & SU_PUNCH3: pa = client_data.punch_angle client_data.punch_angle = pa[0], pa[1], _IO.read.angle(file) if client_data.bit_mask & SU_VELOCITY3: ve = client_data.velocity client_data.velocity = ve[0], ve[1], _IO.read.char(file) * 16 client_data.item_bit_mask = _IO.read.long(file) if client_data.bit_mask & SU_WEAPONFRAME: client_data.weapon_frame = _IO.read.byte(file) if client_data.bit_mask & SU_ARMOR: client_data.armor = _IO.read.byte(file) if client_data.bit_mask & SU_WEAPON: client_data.weapon = _IO.read.byte(file) client_data.health = _IO.read.short(file) client_data.active_ammo = _IO.read.byte(file) client_data.ammo = _IO.read.byte(file), _IO.read.byte(file), _IO.read.byte(file), _IO.read.byte(file) client_data.active_weapon = _IO.read.byte(file) return client_data class StopSound: """Class for representing StopSound messages Stops a playing sound. Attributes: channel: The channel on which the sound is playing. entity: The entity that caused the sound. """ __slots__ = ( 'channel', 'entity' ) def __init__(self): self.channel = None @staticmethod def write(file, stop_sound): _IO.write.byte(file, SVC_STOPSOUND) data = stop_sound.entity << 3 | (stop_sound.channel & 0x07) _IO.write.short(file, data) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_STOPSOUND stop_sound = StopSound() data = _IO.read.short(file) stop_sound.channel = data & 0x07 stop_sound.entity = data >> 3 return stop_sound class UpdateColors: """Class for representing UpdateColors messages Sets the player's colors. Attributes: player: The player to update. colors: The combined shirt/pant color. """ __slots__ = ( 'player', 'colors' ) def __init__(self): self.player = None self.colors = None @staticmethod def write(file, update_colors): _IO.write.byte(file, SVC_UPDATECOLORS) _IO.write.byte(file, update_colors.player) _IO.write.byte(file, update_colors.colors) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_UPDATECOLORS update_colors = UpdateColors() update_colors.player = _IO.read.byte(file) update_colors.colors = _IO.read.byte(file) return update_colors class Particle: """Class for representing Particle messages Creates particle effects Attributes: origin: The origin position of the particles. direction: The velocity of the particles represented as a triple. count: The number of particles. color: The color index of the particle. """ __slots__ = ( 'origin', 'direction', 'count', 'color' ) def __init__(self): self.origin = None self.direction = None self.count = None self.color = None @staticmethod def write(file, particle): _IO.write.byte(file, SVC_PARTICLE) _IO.write.position(file, particle.origin) _IO.write.char(file, particle.direction[0] * 16) _IO.write.char(file, particle.direction[1] * 16) _IO.write.char(file, particle.direction[2] * 16) _IO.write.byte(file, particle.count) _IO.write.byte(file, particle.color) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_PARTICLE particle = Particle() particle.origin = _IO.read.position(file) particle.direction = _IO.read.char(file) / 16, _IO.read.char(file) / 16, _IO.read.char(file) / 16, particle.count = _IO.read.byte(file) particle.color = _IO.read.byte(file) return particle class Damage: """Class for representing Damage messages Damage information Attributes: armor: The damage amount to be deducted from player armor. blood: The damage amount to be deducted from player health. origin: The position of the entity that inflicted the damage. """ __slots__ = ( 'armor', 'blood', 'origin' ) def __init__(self): self.armor = None self.blood = None self.origin = None @staticmethod def write(file, damage): _IO.write.byte(file, SVC_DAMAGE) _IO.write.byte(file, damage.armor) _IO.write.byte(file, damage.blood) _IO.write.position(file, damage.origin) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_DAMAGE damage = Damage() damage.armor = _IO.read.byte(file) damage.blood = _IO.read.byte(file) damage.origin = _IO.read.position(file) return damage class SpawnStatic: """Class for representing SpawnStatic messages Creates a static entity Attributes: model_index: The model number in the model table. frame: The frame number of the model. color_map: The color map used to display the model. skin: The skin number of the model. origin: The position of the entity. angles: The orientation of the entity. """ __slots__ = ( 'model_index', 'frame', 'color_map', 'skin', 'origin', 'angles' ) def __init__(self): self.model_index = None self.frame = None self.color_map = None self.skin = None self.origin = None self.angles = None @staticmethod def write(file, spawn_static): _IO.write.byte(file, SVC_SPAWNSTATIC) _IO.write.byte(file, spawn_static.model_index) _IO.write.byte(file, spawn_static.frame) _IO.write.byte(file, spawn_static.color_map) _IO.write.byte(file, spawn_static.skin) _IO.write.position(file, spawn_static.origin) _IO.write.angles(file, spawn_static.angles) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SPAWNSTATIC spawn_static = SpawnStatic() spawn_static.model_index = _IO.read.byte(file) spawn_static.frame = _IO.read.byte(file) spawn_static.color_map = _IO.read.byte(file) spawn_static.skin = _IO.read.byte(file) spawn_static.origin = _IO.read.position(file) spawn_static.angles = _IO.read.angles(file) return spawn_static class SpawnBinary: """Class for representing SpawnBinary messages This is a deprecated message. """ __slots__ = () @staticmethod def write(file): raise BadMessage('SpawnBinary message obsolete') @staticmethod def read(file): raise BadMessage('SpawnBinary message obsolete') class SpawnBaseline: """Class for representing SpawnBaseline messages Creates a dynamic entity Attributes: entity: The number of the entity. model_index: The number of the model in the model table. frame: The frame number of the model. color_map: The color map used to display the model. skin: The skin number of the model. origin: The position of the entity. angles: The orientation of the entity. """ __slots__ = ( 'entity', 'model_index', 'frame', 'color_map', 'skin', 'origin', 'angles' ) def __init__(self): self.entity = None self.model_index = None self.frame = None self.color_map = None self.skin = None self.origin = None self.angles = None @staticmethod def write(file, spawn_baseline): _IO.write.byte(file, SVC_SPAWNBASELINE) _IO.write.short(file, spawn_baseline.entity) _IO.write.byte(file, spawn_baseline.model_index) _IO.write.byte(file, spawn_baseline.frame) _IO.write.byte(file, spawn_baseline.color_map) _IO.write.byte(file, spawn_baseline.skin) _IO.write.position(file, spawn_baseline.origin) _IO.write.angles(file, spawn_baseline.angles) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SPAWNBASELINE spawn_baseline = SpawnBaseline() spawn_baseline.entity = _IO.read.short(file) spawn_baseline.model_index = _IO.read.byte(file) spawn_baseline.frame = _IO.read.byte(file) spawn_baseline.color_map = _IO.read.byte(file) spawn_baseline.skin = _IO.read.byte(file) spawn_baseline.origin = _IO.read.position(file) spawn_baseline.angles = _IO.read.angles(file) return spawn_baseline TE_SPIKE = 0 TE_SUPERSPIKE = 1 TE_GUNSHOT = 2 TE_EXPLOSION = 3 TE_TAREXPLOSION = 4 TE_LIGHTNING1 = 5 TE_LIGHTNING2 = 6 TE_WIZSPIKE = 7 TE_KNIGHTSPIKE = 8 TE_LIGHTNING3 = 9 TE_LAVASPLASH = 10 TE_TELEPORT = 11 TE_EXPLOSION2 = 12 TE_BEAM = 13 class TempEntity: """Class for representing TempEntity messages Creates a temporary entity. The attributes of the message depend on the type of entity being created. Attributes: type: The type of the temporary entity. """ def __init__(self): self.type = None @staticmethod def write(file, temp_entity): _IO.write.byte(file, SVC_TEMP_ENTITY) _IO.write.byte(file, temp_entity.type) if temp_entity.type == TE_WIZSPIKE or \ temp_entity.type == TE_KNIGHTSPIKE or \ temp_entity.type == TE_SPIKE or \ temp_entity.type == TE_SUPERSPIKE or \ temp_entity.type == TE_GUNSHOT or \ temp_entity.type == TE_EXPLOSION or \ temp_entity.type == TE_TAREXPLOSION or \ temp_entity.type == TE_LAVASPLASH or \ temp_entity.type == TE_TELEPORT: _IO.write.position(file, temp_entity.origin) elif temp_entity.type == TE_LIGHTNING1 or \ temp_entity.type == TE_LIGHTNING2 or \ temp_entity.type == TE_LIGHTNING3 or \ temp_entity.type == TE_BEAM: _IO.write.short(file, temp_entity.entity) _IO.write.position(file, temp_entity.start) _IO.write.position(file, temp_entity.end) elif temp_entity.type == TE_EXPLOSION2: _IO.write.position(file, temp_entity.origin) _IO.write.byte(file, temp_entity.color_start) _IO.write.byte(file, temp_entity.color_length) else: raise BadMessage('Invalid Temporary Entity type: %r' % temp_entity.type) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_TEMP_ENTITY temp_entity = TempEntity() temp_entity.type = _IO.read.byte(file) if temp_entity.type == TE_WIZSPIKE or \ temp_entity.type == TE_KNIGHTSPIKE or \ temp_entity.type == TE_SPIKE or \ temp_entity.type == TE_SUPERSPIKE or \ temp_entity.type == TE_GUNSHOT or \ temp_entity.type == TE_EXPLOSION or \ temp_entity.type == TE_TAREXPLOSION or \ temp_entity.type == TE_LAVASPLASH or \ temp_entity.type == TE_TELEPORT: temp_entity.origin = _IO.read.position(file) elif temp_entity.type == TE_LIGHTNING1 or \ temp_entity.type == TE_LIGHTNING2 or \ temp_entity.type == TE_LIGHTNING3 or \ temp_entity.type == TE_BEAM: temp_entity.entity = _IO.read.short(file) temp_entity.start = _IO.read.position(file) temp_entity.end = _IO.read.position(file) elif temp_entity.type == TE_EXPLOSION2: temp_entity.origin = _IO.read.position(file) temp_entity.color_start = _IO.read.byte(file) temp_entity.color_length = _IO.read.byte(file) else: raise BadMessage(f'Invalid Temporary Entity type: {temp_entity.type}') return temp_entity class SetPause: """Class for representing SetPause messages Sets the pause state Attributes: paused: The pause state. 1 for paused, 0 otherwise. """ __slots__ = ( 'paused' ) def __init__(self): self.paused = None @staticmethod def write(file, set_pause): _IO.write.byte(file, SVC_SETPAUSE) _IO.write.byte(file, set_pause.paused) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SETPAUSE set_pause = SetPause() set_pause.paused = _IO.read.byte(file) return set_pause class SignOnNum: """Class for representing SignOnNum messages This message represents the client state. Attributes: sign_on: The client state. """ __slots__ = ( 'sign_on' ) def __init__(self): self.sign_on = None @staticmethod def write(file, sign_on_num): _IO.write.byte(file, SVC_SIGNONNUM) _IO.write.byte(file, sign_on_num.sign_on) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SIGNONNUM sign_on_num = SignOnNum() sign_on_num.sign_on = _IO.read.byte(file) return sign_on_num class CenterPrint: """Class for representing CenterPrint messages Prints text in the center of the screen. Attributes: text: The text to be shown. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, center_print): _IO.write.byte(file, SVC_CENTERPRINT) _IO.write.string(file, center_print.text) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_CENTERPRINT center_print = CenterPrint() center_print.text = _IO.read.string(file) return center_print class KilledMonster: """Class for representing KilledMonster messages Indicates the death of a monster. """ __slots__ = () @staticmethod def write(file, killed_monster=None): _IO.write.byte(file, SVC_KILLEDMONSTER) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_KILLEDMONSTER return KilledMonster() class FoundSecret: """Class for representing FoundSecret messages Indicates a secret has been found. """ __slots__ = () @staticmethod def write(file, found_secret=None): _IO.write.byte(file, SVC_FOUNDSECRET) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_FOUNDSECRET return FoundSecret() class SpawnStaticSound: """Class for representing SpawnStaticSound messages Creates a static sound Attributes: origin: The position of the sound. sound_number: The sound number in the sound table. volume: The sound volume. attenuation: The sound attenuation. """ __slots__ = ( 'origin', 'sound_number', 'volume', 'attenuation' ) def __init__(self): self.origin = None self.sound_number = None self.volume = None self.attenuation = None @staticmethod def write(file, spawn_static_sound): _IO.write.byte(file, SVC_SPAWNSTATICSOUND) _IO.write.position(file, spawn_static_sound.origin) _IO.write.byte(file, spawn_static_sound.sound_number) _IO.write.byte(file, spawn_static_sound.volume * 256) _IO.write.byte(file, spawn_static_sound.attenuation * 64) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SPAWNSTATICSOUND spawn_static_sound = SpawnStaticSound() spawn_static_sound.origin = _IO.read.position(file) spawn_static_sound.sound_number = _IO.read.byte(file) spawn_static_sound.volume = _IO.read.byte(file) / 256 spawn_static_sound.attenuation = _IO.read.byte(file) / 64 return spawn_static_sound class Intermission: """Class for representing Intermission messages Displays the level end screen. """ __slots__ = () @staticmethod def write(file, intermission=None): _IO.write.byte(file, SVC_INTERMISSION) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_INTERMISSION return Intermission() class Finale: """Class for representing Finale messages Displays the episode end screen. Attributes: text: The text to show. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, finale): _IO.write.byte(file, SVC_FINALE) _IO.write.string(file, finale.text) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_FINALE finale = Finale() finale.text = _IO.read.string(file) return finale class CdTrack: """Class for representing CdTrack messages Selects the cd track Attributes: from_track: The start track. to_track: The end track. """ __slots__ = ( 'from_track', 'to_track' ) def __init__(self): self.from_track = None self.to_track = None @staticmethod def write(file, cd_track): _IO.write.byte(file, SVC_CDTRACK) _IO.write.byte(file, cd_track.from_track) _IO.write.byte(file, cd_track.to_track) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_CDTRACK cd_track = CdTrack() cd_track.from_track = _IO.read.byte(file) cd_track.to_track = _IO.read.byte(file) return cd_track class SellScreen: """Class for representing SellScreen messages Displays the help and sell screen. """ __slots__ = () @staticmethod def write(file, sell_screen=None): _IO.write.byte(file, SVC_SELLSCREEN) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_SELLSCREEN return SellScreen() class CutScene: """Class for representing CutScene messages Displays end screen and text. Attributes: text: The text to be shown. """ __slots__ = ( 'text' ) def __init__(self): self.text = None @staticmethod def write(file, cut_scene): _IO.write.byte(file, SVC_CUTSCENE) _IO.write.string(file, cut_scene.text) @staticmethod def read(file): assert _IO.read.byte(file) == SVC_CUTSCENE cut_scene = CutScene() cut_scene.text = _IO.read.string(file) return cut_scene _messages = [Bad, Nop, Disconnect, UpdateStat, Version, SetView, Sound, Time, Print, StuffText, SetAngle, ServerInfo, LightStyle, UpdateName, UpdateFrags, ClientData, StopSound, UpdateColors, Particle, Damage, SpawnStatic, SpawnBinary, SpawnBaseline, TempEntity, SetPause, SignOnNum, CenterPrint, KilledMonster, FoundSecret, SpawnStaticSound, Intermission, Finale, CdTrack, SellScreen, CutScene] U_MOREBITS = 0b0000000000000001 U_ORIGIN1 = 0b0000000000000010 U_ORIGIN2 = 0b0000000000000100 U_ORIGIN3 = 0b0000000000001000 U_ANGLE2 = 0b0000000000010000 U_NOLERP = 0b0000000000100000 U_FRAME = 0b0000000001000000 U_SIGNAL = 0b0000000010000000 U_ANGLE1 = 0b0000000100000000 U_ANGLE3 = 0b0000001000000000 U_MODEL = 0b0000010000000000 U_COLORMAP = 0b0000100000000000 U_SKIN = 0b0001000000000000 U_EFFECTS = 0b0010000000000000 U_LONGENTITY = 0b0100000000000000 class UpdateEntity: """Class for representing UpdateEntity messages Updates an entity. Attributes: bit_mask: A bit field indicating what data is sent. entity: The number of the entity. model_index: The number of the model in the model table. frame: The frame number of the model. color_map: The color map used to display the model. skin: The skin number of the model. effects: A bit field indicating special effects. origin: The position of the entity. angles: The orientation of the entity. """ __slots__ = ( 'bit_mask', 'entity', 'model_index', 'frame', 'colormap', 'skin', 'effects', 'origin', 'angles' ) def __init__(self): self.bit_mask = 0b0000000000000000 self.entity = None self.model_index = None self.frame = None self.colormap = None self.skin = None self.effects = None self.origin = None, None, None self.angles = None, None, None @staticmethod def write(file, update_entity): _IO.write.byte(file, update_entity.bit_mask & 0xFF | 0x80) if update_entity.bit_mask & U_MOREBITS: _IO.write.byte(file, update_entity.bit_mask >> 8 & 0xFF) if update_entity.bit_mask & U_LONGENTITY: _IO.write.short(file, update_entity.entity) else: _IO.write.byte(file, update_entity.entity) if update_entity.bit_mask & U_MODEL: _IO.write.byte(file, update_entity.model_index) if update_entity.bit_mask & U_FRAME: _IO.write.byte(file, update_entity.frame) if update_entity.bit_mask & U_COLORMAP: _IO.write.byte(file, update_entity.colormap) if update_entity.bit_mask & U_SKIN: _IO.write.byte(file, update_entity.skin) if update_entity.bit_mask & U_EFFECTS: _IO.write.byte(file, update_entity.effects) if update_entity.bit_mask & U_ORIGIN1: _IO.write.coord(file, update_entity.origin[0]) if update_entity.bit_mask & U_ANGLE1: _IO.write.angle(file, update_entity.angles[0]) if update_entity.bit_mask & U_ORIGIN2: _IO.write.coord(file, update_entity.origin[1]) if update_entity.bit_mask & U_ANGLE2: _IO.write.angle(file, update_entity.angles[1]) if update_entity.bit_mask & U_ORIGIN3: _IO.write.coord(file, update_entity.origin[2]) if update_entity.bit_mask & U_ANGLE3: _IO.write.angle(file, update_entity.angles[2]) @staticmethod def read(file): update_entity = UpdateEntity() b = _IO.read.byte(file) update_entity.bit_mask = b & 0x7F if update_entity.bit_mask & U_MOREBITS: update_entity.bit_mask |= _IO.read.byte(file) << 8 if update_entity.bit_mask & U_LONGENTITY: update_entity.entity = _IO.read.short(file) else: update_entity.entity = _IO.read.byte(file) if update_entity.bit_mask & U_MODEL: update_entity.model_index = _IO.read.byte(file) if update_entity.bit_mask & U_FRAME: update_entity.frame = _IO.read.byte(file) if update_entity.bit_mask & U_COLORMAP: update_entity.colormap = _IO.read.byte(file) if update_entity.bit_mask & U_SKIN: update_entity.skin = _IO.read.byte(file) if update_entity.bit_mask & U_EFFECTS: update_entity.effects = _IO.read.byte(file) if update_entity.bit_mask & U_ORIGIN1: update_entity.origin = _IO.read.coord(file), update_entity.origin[1], update_entity.origin[2] if update_entity.bit_mask & U_ANGLE1: update_entity.angles = _IO.read.angle(file), update_entity.angles[1], update_entity.angles[2] if update_entity.bit_mask & U_ORIGIN2: update_entity.origin = update_entity.origin[0], _IO.read.coord(file), update_entity.origin[2] if update_entity.bit_mask & U_ANGLE2: update_entity.angles = update_entity.angles[0], _IO.read.angle(file), update_entity.angles[2] if update_entity.bit_mask & U_ORIGIN3: update_entity.origin = update_entity.origin[0], update_entity.origin[1], _IO.read.coord(file) if update_entity.bit_mask & U_ANGLE3: update_entity.angles = update_entity.angles[0], update_entity.angles[1], _IO.read.angle(file) return update_entity class MessageBlock: """Class for representing a message block Attributes: view_angles: The client view angles. messages: A sequence of messages. """ __slots__ = ( 'view_angles', 'messages' ) def __init__(self): self.view_angles = None self.messages = [] @staticmethod def write(file, message_block): start_of_block = file.tell() _IO.write.long(file, 0) _IO.write.float(file, message_block.view_angles[0]) _IO.write.float(file, message_block.view_angles[1]) _IO.write.float(file, message_block.view_angles[2]) start_of_messages = file.tell() for message in message_block.messages: message.__class__.write(file, message) end_of_messages = file.tell() block_size = end_of_messages - start_of_messages file.seek(start_of_block) _IO.write.long(file, block_size) file.seek(end_of_messages ) @staticmethod def read(file): message_block = MessageBlock() blocksize = _IO.read.long(file) message_block.view_angles = _IO.read.float(file), _IO.read.float(file), _IO.read.float(file) message_block_data = file.read(blocksize) buff = io.BufferedReader(io.BytesIO(message_block_data)) message_id = buff.peek(1)[:1] while message_id != b'': message_id = struct.unpack('<B', message_id)[0] if message_id < 128: message = _messages[message_id].read(buff) else: message = UpdateEntity.read(buff) if message: message_block.messages.append(message) message_id = buff.peek(1)[:1] buff.close() return message_block
en
0.79079
This module provides file I/O for the Quake network protocol. References: Quake Source - id Software - https://github.com/id-Software/Quake The Unofficial DEM Format Description - <NAME>, et al. - https://www.quakewiki.net/archives/demospecs/dem/dem.html Simple namespace for protocol IO Read IO namespace Write IO namespace Class for representing a Bad message This is an error message and should not appear. Class for representing a Nop message Class for representing a Disconnect message Disconnect from the server and end the game. Typically this the last message of a demo. Class for representing UpdateStat messages Updates a player state value. Attributes: index: The index to update in the player state array. value: The new value to set. Class for representing Version messages Attributes: protocol_version: Protocol version of the server. Quake uses 15. Class for representing SetView messages Sets the camera position to the given entity. Attributes: entity: The entity number Class for representing Sound messages Plays a sound on a channel at a position. Attributes: entity: The entity that caused the sound. bit_mask: A bit field indicating what data is sent. volume: Optional. The sound volume or None. attenuation: Optional. The sound attenuation or None. channel: The sound channel, maximum of eight. sound_number: The number of the sound in the sound table. origin: The position of the sound. Class for representing Time messages A time stamp that should appear in each block of messages. Attributes: time: The amount of elapsed time(in seconds) since the start of the game. Class for representing Print messages Prints text in the top left corner of the screen and console. Attributes: text: The text to be shown. Class for representing StuffText messages Text sent to the client console and ran. Attributes: text: The text to send to the client console. Note: This string is terminated with the newline character. Class for representing SetAngle messages Sets the camera's orientation. Attributes: angles: The new angles for the camera. Class for representing ServerInfo messages Handles the loading of assets. Usually first message sent after a level change. Attributes: protocol_version: Protocol version of the server. Quake uses 15. max_clients: Number of clients. multi: Multiplayer flag. Set to 0 for single-player and 1 for multiplayer. map_name: The name of the level. models: The model table as as sequence of strings. sounds: The sound table as a sequence of strings. Class for representing a LightStyle message Defines the style of a light. Usually happens shortly after level change. Attributes: style: The light style number. string: A string of arbitrary length representing the brightness of the light. The brightness is mapped to the characters 'a' to 'z', with 'a' being black and 'z' being pure white. Example: # Flickering light light_style_message = LightStyle() light_style.style = 0 light_style.string = 'aaazaazaaaaaz' Class for representing UpdateName messages Sets the player's name. Attributes: player: The player number to update. name: The new name as a string. Class for representing UpdateFrags messages Sets the player's frag count. Attributes: player: The player to update. frags: The new frag count. # Client Data bit mask Class for representing ClientData messages Server information about this client. Attributes: bit_mask: A bit field indicating what data is sent. view_height: Optional. The view offset from the origin along the z-axis. ideal_pitch: Optional. The calculated angle for looking up/down slopes. punch_angle: Optional. A triple representing camera shake. velocity: Optional. Player velocity. item_bit_mask: A bit field for player inventory. on_ground: Flag indicating if player is on the ground. in_water: Flag indicating if player is in a water volume. weapon_frame: Optional. The animation frame of the weapon. armor: Optional. The current armor value. weapon: Optional. The model number in the model table. health: The current health value. active_ammo: The amount count for the active weapon. ammo: The current ammo counts as a quadruple. active_weapon: The actively held weapon. Class for representing StopSound messages Stops a playing sound. Attributes: channel: The channel on which the sound is playing. entity: The entity that caused the sound. Class for representing UpdateColors messages Sets the player's colors. Attributes: player: The player to update. colors: The combined shirt/pant color. Class for representing Particle messages Creates particle effects Attributes: origin: The origin position of the particles. direction: The velocity of the particles represented as a triple. count: The number of particles. color: The color index of the particle. Class for representing Damage messages Damage information Attributes: armor: The damage amount to be deducted from player armor. blood: The damage amount to be deducted from player health. origin: The position of the entity that inflicted the damage. Class for representing SpawnStatic messages Creates a static entity Attributes: model_index: The model number in the model table. frame: The frame number of the model. color_map: The color map used to display the model. skin: The skin number of the model. origin: The position of the entity. angles: The orientation of the entity. Class for representing SpawnBinary messages This is a deprecated message. Class for representing SpawnBaseline messages Creates a dynamic entity Attributes: entity: The number of the entity. model_index: The number of the model in the model table. frame: The frame number of the model. color_map: The color map used to display the model. skin: The skin number of the model. origin: The position of the entity. angles: The orientation of the entity. Class for representing TempEntity messages Creates a temporary entity. The attributes of the message depend on the type of entity being created. Attributes: type: The type of the temporary entity. Class for representing SetPause messages Sets the pause state Attributes: paused: The pause state. 1 for paused, 0 otherwise. Class for representing SignOnNum messages This message represents the client state. Attributes: sign_on: The client state. Class for representing CenterPrint messages Prints text in the center of the screen. Attributes: text: The text to be shown. Class for representing KilledMonster messages Indicates the death of a monster. Class for representing FoundSecret messages Indicates a secret has been found. Class for representing SpawnStaticSound messages Creates a static sound Attributes: origin: The position of the sound. sound_number: The sound number in the sound table. volume: The sound volume. attenuation: The sound attenuation. Class for representing Intermission messages Displays the level end screen. Class for representing Finale messages Displays the episode end screen. Attributes: text: The text to show. Class for representing CdTrack messages Selects the cd track Attributes: from_track: The start track. to_track: The end track. Class for representing SellScreen messages Displays the help and sell screen. Class for representing CutScene messages Displays end screen and text. Attributes: text: The text to be shown. Class for representing UpdateEntity messages Updates an entity. Attributes: bit_mask: A bit field indicating what data is sent. entity: The number of the entity. model_index: The number of the model in the model table. frame: The frame number of the model. color_map: The color map used to display the model. skin: The skin number of the model. effects: A bit field indicating special effects. origin: The position of the entity. angles: The orientation of the entity. Class for representing a message block Attributes: view_angles: The client view angles. messages: A sequence of messages.
2.602014
3
src/parsers/cppCheck.py
MitchelPaulin/StaticSummary
0
6615496
"""A implementation of a parser for the cppcheck utility""" from parsers.aParser import Parser from common.error import Error from subprocess import run, PIPE import re class CppCheckParser(Parser): def __init__(self, targetDir: str): super().__init__(targetDir) def parse(self): # execute cpp check result = run(['cppcheck', self.targetDir], stdout=PIPE, stderr=PIPE) errors = str(result.stderr).split('\\n') # get relevant information ret = [] pattern = re.compile(".*\[(.*):(\d*)\]: *(.*)$") for err in errors: res = pattern.match(err) if res: result = Error(int(res.group(2)), res.group(1), res.group(3), 'cppcheck') ret.append(result) return ret
"""A implementation of a parser for the cppcheck utility""" from parsers.aParser import Parser from common.error import Error from subprocess import run, PIPE import re class CppCheckParser(Parser): def __init__(self, targetDir: str): super().__init__(targetDir) def parse(self): # execute cpp check result = run(['cppcheck', self.targetDir], stdout=PIPE, stderr=PIPE) errors = str(result.stderr).split('\\n') # get relevant information ret = [] pattern = re.compile(".*\[(.*):(\d*)\]: *(.*)$") for err in errors: res = pattern.match(err) if res: result = Error(int(res.group(2)), res.group(1), res.group(3), 'cppcheck') ret.append(result) return ret
en
0.622433
A implementation of a parser for the cppcheck utility # execute cpp check # get relevant information
2.863857
3
whynot/algorithms/__init__.py
yoshavit/whynot
376
6615497
<filename>whynot/algorithms/__init__.py """Algorithms initialization.""" from .causal_suite import causal_suite from . import ols from . import propensity_score_matching from . import propensity_weighted_ols
<filename>whynot/algorithms/__init__.py """Algorithms initialization.""" from .causal_suite import causal_suite from . import ols from . import propensity_score_matching from . import propensity_weighted_ols
en
0.725833
Algorithms initialization.
1.205301
1
fsfs/lockfile.py
danbradham/fsfs
18
6615498
<reponame>danbradham/fsfs<gh_stars>10-100 # -*- coding: utf-8 -*- from __future__ import absolute_import __all__ = [ 'LockFileError', 'LockFileTimeOutError', 'LockFilePump', 'LockFile', 'lockfile' ] import atexit import os import time import errno import threading from warnings import warn from datetime import datetime from timeit import default_timer from contextlib import contextmanager class LockFileError(Exception): pass class LockFileTimeOutError(Exception): pass class LockFilePump(threading.Thread): '''A daemon thread that updates all acquired LockFiles held by this process. This keeps the locks from expiring while the process has them. ''' def __init__(self): super(LockFilePump, self).__init__() self.daemon = True self._shutdown = threading.Event() self._stopped = threading.Event() self._started = threading.Event() atexit.register(self.stop) @property def started(self): return self._started.is_set() @property def stopped(self): return self._stopped.is_set() @property def shutdown(self): return self._shutdown.is_set() def stop(self): if not self.started and not self.shutdown: return self._shutdown.set() self._stopped.wait() if self.isAlive(): self.join() def run(self): try: self._started.set() while True: for lock in list(LockFile._acquired_locks): if lock.locked: try: lock._touch() except OSError as e: msg = ( 'PumpThread failed to update mtime of lock: \n' '{errno}: {massge}' ).format(e.errno, e.message) warn(msg) if self._shutdown.wait(LockFile._pump_interval_): break finally: self._stopped.set() class LockFile(object): '''Uses a file as a lock. When a LockFile is acquired a file is created at its associated path. While this file exists no other process can acquire the lock. When a LockFile is released, the file is removed, allowing other processes to acquire the lock. To make sure we don't leave hanging locks, locks expire after LockFile._expiration (defaults to 2 seconds). This works because we have a background thread constantly updating the mtime of all locks the current process holds. Once this process exits, any hanging locks will finally have a static mtime, and they can expire. Examples: Acquire a lock. >>> lock = LockFile('.lock') >>> lock.acquire() >>> assert lock.acquired >>> assert lock.locked Acquire a lock using a timeout. >>> lock2 = LockFile('.lock') >>> assert not lock2.acquired >>> assert lock2.locked >>> lock2.acquire(0.1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockFileTimeOutError: Timed out while trying to acquire lock... Release a lock and acquire a new one using another LockFile instance. >>> lock.release() >>> assert not lock.acquired >>> lock2.acquire() >>> assert lock2.acquired >>> lock2.release() >>> assert not lock2.acquired Use LockFile as a contextmanager. >>> with lock: ... assert lock.acquired ... Call a LockFile to use it as a contextmanager with a timeout. >>> lock2.acquire() >>> with lock(0.1): ... pass # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockFileTimeOutError: Timed out while trying to acquire lock... >>> lock2.release() ''' _pump_ = LockFilePump() _pump_interval_ = 1 _expiration = 2 # Expiration must be greater than pump interval _acquired_locks = [] def __init__(self, path): self.path = os.path.abspath(path) self.acquired = False self._depth = 0 self._start_pump() def __enter__(self): if self._depth == 0: self.acquire() self._depth += 1 return self def __exit__(self, exc_type, exc_val, exc_tb): if self._depth == 1: self.release() self._depth -= 1 @contextmanager def __call__(self, timeout=0): try: if self._depth == 0: self.acquire(timeout) self._depth += 1 yield self finally: if self._depth == 1: self.release() self._depth -= 1 @property def locked(self): '''Check if this lock is currently locked...''' return os.path.exists(self.path) @property def expired(self): '''Check if this lock has expired...''' return self._time_since_modified() > self._expiration def _start_pump(self): '''Start the pump thread''' if self._pump_.started: return self._pump_.start() # Wait for pump thread to start while not self._pump_.started: time.sleep(0.01) def _touch(self): '''Touch the lock file, updates the files mtime''' with open(self.path, 'a'): os.utime(self.path, None) def _time_since_modified(self): '''Return the total seconds since the specified file was modified''' return ( datetime.now() - datetime.fromtimestamp(os.path.getmtime(self.path)) ).total_seconds() def _acquire_expired_lock(self): '''Attempt to acquire an expired lock''' self._release_lockfile() self._try_to_acquire() if not self.acquired: raise LockFileError('Failed to acquire expired lock...') def _try_to_acquire(self): '''Creates the lockfile on the filesystem. Returns True if the lockfile is successfully created. ''' if self.acquired: self.acquired = True return if self.locked: self.acquired = False return self._touch() self._acquired_locks.append(self) self.acquired = True def acquire(self, timeout=0): '''Acquire the lock. Raises an exception when timeout is reached. Arguments: timeout (int or float): Amount of time to wait for lock ''' self._try_to_acquire() if self.acquired: return if self.locked and self.expired: self._acquire_expired_lock() return s = default_timer() while not self.acquired: if timeout > 0 and default_timer() - s > timeout: raise LockFileTimeOutError( 'Timed out while trying to acquire lock...' ) if self.locked and self.expired: self._acquire_expired_lock() return self._try_to_acquire() time.sleep(0.05) def _release_lockfile(self): '''Removes the lockfile on the filesystem. Returns True if the lockfile is successfully removed. ''' try: os.remove(self.path) except OSError as e: if e.errno != errno.ENOENT: raise e finally: if self in self._acquired_locks: self._acquired_locks.remove(self) self.acquired = False def release(self): '''Release the lock''' if not self.acquired: raise LockFileError('Can not release an unacquired lock...') self._release_lockfile() @classmethod def _release_locks(cls): '''Releases all locks that are unreleased. This function is registered as an atexit function, making sure we do not leave any lock files floating around on program termination. ''' for lock in list(cls._acquired_locks): lock.release() @contextmanager def lockfile(path, timeout=0): '''LockFile contextmanager, for when you only need to acquire a lock once. Arguments: path (str): path to the lockfile timeout (int or float): time to wait for the lock Returns: Acquired LockFile Raises: LockFileTimeOutError: when timeout reached Examples: >>> with lockfile('.lock') as l: ... assert l.acquired >>> l = LockFile('.lock') >>> l.acquire() >>> with lockfile('.lock', 0.1): ... pass # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockFileTimeOutError: Timed out while trying to acquire lock... ''' lock = LockFile(path) lock.acquire(timeout) try: yield lock finally: lock.release() # Make sure that all locks are released on program exit atexit.register(LockFile._release_locks)
# -*- coding: utf-8 -*- from __future__ import absolute_import __all__ = [ 'LockFileError', 'LockFileTimeOutError', 'LockFilePump', 'LockFile', 'lockfile' ] import atexit import os import time import errno import threading from warnings import warn from datetime import datetime from timeit import default_timer from contextlib import contextmanager class LockFileError(Exception): pass class LockFileTimeOutError(Exception): pass class LockFilePump(threading.Thread): '''A daemon thread that updates all acquired LockFiles held by this process. This keeps the locks from expiring while the process has them. ''' def __init__(self): super(LockFilePump, self).__init__() self.daemon = True self._shutdown = threading.Event() self._stopped = threading.Event() self._started = threading.Event() atexit.register(self.stop) @property def started(self): return self._started.is_set() @property def stopped(self): return self._stopped.is_set() @property def shutdown(self): return self._shutdown.is_set() def stop(self): if not self.started and not self.shutdown: return self._shutdown.set() self._stopped.wait() if self.isAlive(): self.join() def run(self): try: self._started.set() while True: for lock in list(LockFile._acquired_locks): if lock.locked: try: lock._touch() except OSError as e: msg = ( 'PumpThread failed to update mtime of lock: \n' '{errno}: {massge}' ).format(e.errno, e.message) warn(msg) if self._shutdown.wait(LockFile._pump_interval_): break finally: self._stopped.set() class LockFile(object): '''Uses a file as a lock. When a LockFile is acquired a file is created at its associated path. While this file exists no other process can acquire the lock. When a LockFile is released, the file is removed, allowing other processes to acquire the lock. To make sure we don't leave hanging locks, locks expire after LockFile._expiration (defaults to 2 seconds). This works because we have a background thread constantly updating the mtime of all locks the current process holds. Once this process exits, any hanging locks will finally have a static mtime, and they can expire. Examples: Acquire a lock. >>> lock = LockFile('.lock') >>> lock.acquire() >>> assert lock.acquired >>> assert lock.locked Acquire a lock using a timeout. >>> lock2 = LockFile('.lock') >>> assert not lock2.acquired >>> assert lock2.locked >>> lock2.acquire(0.1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockFileTimeOutError: Timed out while trying to acquire lock... Release a lock and acquire a new one using another LockFile instance. >>> lock.release() >>> assert not lock.acquired >>> lock2.acquire() >>> assert lock2.acquired >>> lock2.release() >>> assert not lock2.acquired Use LockFile as a contextmanager. >>> with lock: ... assert lock.acquired ... Call a LockFile to use it as a contextmanager with a timeout. >>> lock2.acquire() >>> with lock(0.1): ... pass # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockFileTimeOutError: Timed out while trying to acquire lock... >>> lock2.release() ''' _pump_ = LockFilePump() _pump_interval_ = 1 _expiration = 2 # Expiration must be greater than pump interval _acquired_locks = [] def __init__(self, path): self.path = os.path.abspath(path) self.acquired = False self._depth = 0 self._start_pump() def __enter__(self): if self._depth == 0: self.acquire() self._depth += 1 return self def __exit__(self, exc_type, exc_val, exc_tb): if self._depth == 1: self.release() self._depth -= 1 @contextmanager def __call__(self, timeout=0): try: if self._depth == 0: self.acquire(timeout) self._depth += 1 yield self finally: if self._depth == 1: self.release() self._depth -= 1 @property def locked(self): '''Check if this lock is currently locked...''' return os.path.exists(self.path) @property def expired(self): '''Check if this lock has expired...''' return self._time_since_modified() > self._expiration def _start_pump(self): '''Start the pump thread''' if self._pump_.started: return self._pump_.start() # Wait for pump thread to start while not self._pump_.started: time.sleep(0.01) def _touch(self): '''Touch the lock file, updates the files mtime''' with open(self.path, 'a'): os.utime(self.path, None) def _time_since_modified(self): '''Return the total seconds since the specified file was modified''' return ( datetime.now() - datetime.fromtimestamp(os.path.getmtime(self.path)) ).total_seconds() def _acquire_expired_lock(self): '''Attempt to acquire an expired lock''' self._release_lockfile() self._try_to_acquire() if not self.acquired: raise LockFileError('Failed to acquire expired lock...') def _try_to_acquire(self): '''Creates the lockfile on the filesystem. Returns True if the lockfile is successfully created. ''' if self.acquired: self.acquired = True return if self.locked: self.acquired = False return self._touch() self._acquired_locks.append(self) self.acquired = True def acquire(self, timeout=0): '''Acquire the lock. Raises an exception when timeout is reached. Arguments: timeout (int or float): Amount of time to wait for lock ''' self._try_to_acquire() if self.acquired: return if self.locked and self.expired: self._acquire_expired_lock() return s = default_timer() while not self.acquired: if timeout > 0 and default_timer() - s > timeout: raise LockFileTimeOutError( 'Timed out while trying to acquire lock...' ) if self.locked and self.expired: self._acquire_expired_lock() return self._try_to_acquire() time.sleep(0.05) def _release_lockfile(self): '''Removes the lockfile on the filesystem. Returns True if the lockfile is successfully removed. ''' try: os.remove(self.path) except OSError as e: if e.errno != errno.ENOENT: raise e finally: if self in self._acquired_locks: self._acquired_locks.remove(self) self.acquired = False def release(self): '''Release the lock''' if not self.acquired: raise LockFileError('Can not release an unacquired lock...') self._release_lockfile() @classmethod def _release_locks(cls): '''Releases all locks that are unreleased. This function is registered as an atexit function, making sure we do not leave any lock files floating around on program termination. ''' for lock in list(cls._acquired_locks): lock.release() @contextmanager def lockfile(path, timeout=0): '''LockFile contextmanager, for when you only need to acquire a lock once. Arguments: path (str): path to the lockfile timeout (int or float): time to wait for the lock Returns: Acquired LockFile Raises: LockFileTimeOutError: when timeout reached Examples: >>> with lockfile('.lock') as l: ... assert l.acquired >>> l = LockFile('.lock') >>> l.acquire() >>> with lockfile('.lock', 0.1): ... pass # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockFileTimeOutError: Timed out while trying to acquire lock... ''' lock = LockFile(path) lock.acquire(timeout) try: yield lock finally: lock.release() # Make sure that all locks are released on program exit atexit.register(LockFile._release_locks)
en
0.891625
# -*- coding: utf-8 -*- A daemon thread that updates all acquired LockFiles held by this process. This keeps the locks from expiring while the process has them. Uses a file as a lock. When a LockFile is acquired a file is created at its associated path. While this file exists no other process can acquire the lock. When a LockFile is released, the file is removed, allowing other processes to acquire the lock. To make sure we don't leave hanging locks, locks expire after LockFile._expiration (defaults to 2 seconds). This works because we have a background thread constantly updating the mtime of all locks the current process holds. Once this process exits, any hanging locks will finally have a static mtime, and they can expire. Examples: Acquire a lock. >>> lock = LockFile('.lock') >>> lock.acquire() >>> assert lock.acquired >>> assert lock.locked Acquire a lock using a timeout. >>> lock2 = LockFile('.lock') >>> assert not lock2.acquired >>> assert lock2.locked >>> lock2.acquire(0.1) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockFileTimeOutError: Timed out while trying to acquire lock... Release a lock and acquire a new one using another LockFile instance. >>> lock.release() >>> assert not lock.acquired >>> lock2.acquire() >>> assert lock2.acquired >>> lock2.release() >>> assert not lock2.acquired Use LockFile as a contextmanager. >>> with lock: ... assert lock.acquired ... Call a LockFile to use it as a contextmanager with a timeout. >>> lock2.acquire() >>> with lock(0.1): ... pass # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockFileTimeOutError: Timed out while trying to acquire lock... >>> lock2.release() # Expiration must be greater than pump interval Check if this lock is currently locked... Check if this lock has expired... Start the pump thread # Wait for pump thread to start Touch the lock file, updates the files mtime Return the total seconds since the specified file was modified Attempt to acquire an expired lock Creates the lockfile on the filesystem. Returns True if the lockfile is successfully created. Acquire the lock. Raises an exception when timeout is reached. Arguments: timeout (int or float): Amount of time to wait for lock Removes the lockfile on the filesystem. Returns True if the lockfile is successfully removed. Release the lock Releases all locks that are unreleased. This function is registered as an atexit function, making sure we do not leave any lock files floating around on program termination. LockFile contextmanager, for when you only need to acquire a lock once. Arguments: path (str): path to the lockfile timeout (int or float): time to wait for the lock Returns: Acquired LockFile Raises: LockFileTimeOutError: when timeout reached Examples: >>> with lockfile('.lock') as l: ... assert l.acquired >>> l = LockFile('.lock') >>> l.acquire() >>> with lockfile('.lock', 0.1): ... pass # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockFileTimeOutError: Timed out while trying to acquire lock... # Make sure that all locks are released on program exit
2.632381
3
heldags/heldags/asgi.py
AndersFelde/IT-heldags
0
6615499
""" ASGI config for heldags heldags. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoheldags.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'heldags.settings') application = get_asgi_application()
""" ASGI config for heldags heldags. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoheldags.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'heldags.settings') application = get_asgi_application()
en
0.656591
ASGI config for heldags heldags. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoheldags.com/en/3.1/howto/deployment/asgi/
1.652006
2
bonus/cicd/test_ex4/test_netmiko_fixture.py
anejolazaro70/python_july19
0
6615500
#!/usr/bin/env python import pytest from netmiko import ConnectHandler from getpass import getpass password = getpass() arista1 = { "host": "arista1.lasthop.io", "device_type": "arista_eos", "username": "pyclass", "password": password, } @pytest.fixture(scope="module") def netmiko_conn(): conn = ConnectHandler(**arista1) return conn def test_netmiko_con(netmiko_conn): assert "arista1" in netmiko_conn.find_prompt() def test_show_version(netmiko_conn): assert "4.20.10M" in netmiko_conn.send_command("show version")
#!/usr/bin/env python import pytest from netmiko import ConnectHandler from getpass import getpass password = getpass() arista1 = { "host": "arista1.lasthop.io", "device_type": "arista_eos", "username": "pyclass", "password": password, } @pytest.fixture(scope="module") def netmiko_conn(): conn = ConnectHandler(**arista1) return conn def test_netmiko_con(netmiko_conn): assert "arista1" in netmiko_conn.find_prompt() def test_show_version(netmiko_conn): assert "4.20.10M" in netmiko_conn.send_command("show version")
ru
0.26433
#!/usr/bin/env python
1.875334
2
py/112. Path Sum.py
longwangjhu/LeetCode
3
6615501
# https://leetcode.com/problems/path-sum/ # Given the root of a binary tree and an integer targetSum, return true if the # tree has a root-to-leaf path such that adding up all the values along the path # equals targetSum. # A leaf is a node with no children. ################################################################################ # divide and conquer # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: if not root: return False if not root.left and not root.right: return targetSum == root.val has_left = self.hasPathSum(root.left, targetSum - root.val) has_right = self.hasPathSum(root.right, targetSum - root.val) return has_left or has_right
# https://leetcode.com/problems/path-sum/ # Given the root of a binary tree and an integer targetSum, return true if the # tree has a root-to-leaf path such that adding up all the values along the path # equals targetSum. # A leaf is a node with no children. ################################################################################ # divide and conquer # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: if not root: return False if not root.left and not root.right: return targetSum == root.val has_left = self.hasPathSum(root.left, targetSum - root.val) has_right = self.hasPathSum(root.right, targetSum - root.val) return has_left or has_right
en
0.651813
# https://leetcode.com/problems/path-sum/ # Given the root of a binary tree and an integer targetSum, return true if the # tree has a root-to-leaf path such that adding up all the values along the path # equals targetSum. # A leaf is a node with no children. ################################################################################ # divide and conquer # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right
3.939167
4
LibMTL/weighting/UW.py
median-research-group/LibMTL
83
6615502
<gh_stars>10-100 import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from LibMTL.weighting.abstract_weighting import AbsWeighting class UW(AbsWeighting): r"""Uncertainty Weights (UW). This method is proposed in `Multi-Task Learning Using Uncertainty to Weigh Losses for Scene Geometry and Semantics (CVPR 2018) <https://openaccess.thecvf.com/content_cvpr_2018/papers/Kendall_Multi-Task_Learning_Using_CVPR_2018_paper.pdf>`_ \ and implemented by us. """ def __init__(self): super(UW, self).__init__() def init_param(self): self.loss_scale = nn.Parameter(torch.tensor([-0.5]*self.task_num, device=self.device)) def backward(self, losses, **kwargs): loss = (losses/(2*self.loss_scale.exp())+self.loss_scale/2).sum() loss.backward() return (1/(2*torch.exp(self.loss_scale))).detach().cpu().numpy()
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from LibMTL.weighting.abstract_weighting import AbsWeighting class UW(AbsWeighting): r"""Uncertainty Weights (UW). This method is proposed in `Multi-Task Learning Using Uncertainty to Weigh Losses for Scene Geometry and Semantics (CVPR 2018) <https://openaccess.thecvf.com/content_cvpr_2018/papers/Kendall_Multi-Task_Learning_Using_CVPR_2018_paper.pdf>`_ \ and implemented by us. """ def __init__(self): super(UW, self).__init__() def init_param(self): self.loss_scale = nn.Parameter(torch.tensor([-0.5]*self.task_num, device=self.device)) def backward(self, losses, **kwargs): loss = (losses/(2*self.loss_scale.exp())+self.loss_scale/2).sum() loss.backward() return (1/(2*torch.exp(self.loss_scale))).detach().cpu().numpy()
en
0.76842
Uncertainty Weights (UW). This method is proposed in `Multi-Task Learning Using Uncertainty to Weigh Losses for Scene Geometry and Semantics (CVPR 2018) <https://openaccess.thecvf.com/content_cvpr_2018/papers/Kendall_Multi-Task_Learning_Using_CVPR_2018_paper.pdf>`_ \ and implemented by us.
2.888478
3
scripts/generate_image_layout.py
seendsouza/2381-Robotics
1
6615503
<reponame>seendsouza/2381-Robotics """ Automates the HTML (Jekyll form) creation for media.html, so that the images do not have to be manually inserted into it. """ import os def generate_list(relative_path): """ Generates a list of image names """ current_path = os.path.dirname(__file__) file_path = os.path.relpath(relative_path, current_path) filenames = os.listdir(file_path) image_names = list() for _, filename in enumerate(filenames): image_names.append(filename) return image_names def format_names(image_names, relative_path): """ Formats the image names into the Jekyll format wanted """ top_text = "---\nlayout: media\ntitle: Media\nimages:\n" bottom_text = "---" output = top_text for _, image in enumerate(image_names): image_name = extract_title(image) output += " - image_path: {}\n title: {}\n".format(relative_path + image, image_name) output += bottom_text return output def extract_title(image): """ Makes titles from filenames """ name = str() for _, char in enumerate(image): if char == "-": break elif char == "_": char = " " name += char name = name.title() return name def main(input_path, output_path): """ The input path is where Python can find the folder. The output path is where the generated html can find the folder. """ image_names = generate_list(input_path) output = format_names(image_names, output_path) with open("media.html", "w") as text_file: text_file.write(output) if __name__ == "__main__": main("../img/media/", "./img/media/")
""" Automates the HTML (Jekyll form) creation for media.html, so that the images do not have to be manually inserted into it. """ import os def generate_list(relative_path): """ Generates a list of image names """ current_path = os.path.dirname(__file__) file_path = os.path.relpath(relative_path, current_path) filenames = os.listdir(file_path) image_names = list() for _, filename in enumerate(filenames): image_names.append(filename) return image_names def format_names(image_names, relative_path): """ Formats the image names into the Jekyll format wanted """ top_text = "---\nlayout: media\ntitle: Media\nimages:\n" bottom_text = "---" output = top_text for _, image in enumerate(image_names): image_name = extract_title(image) output += " - image_path: {}\n title: {}\n".format(relative_path + image, image_name) output += bottom_text return output def extract_title(image): """ Makes titles from filenames """ name = str() for _, char in enumerate(image): if char == "-": break elif char == "_": char = " " name += char name = name.title() return name def main(input_path, output_path): """ The input path is where Python can find the folder. The output path is where the generated html can find the folder. """ image_names = generate_list(input_path) output = format_names(image_names, output_path) with open("media.html", "w") as text_file: text_file.write(output) if __name__ == "__main__": main("../img/media/", "./img/media/")
en
0.830319
Automates the HTML (Jekyll form) creation for media.html, so that the images do not have to be manually inserted into it. Generates a list of image names Formats the image names into the Jekyll format wanted Makes titles from filenames The input path is where Python can find the folder. The output path is where the generated html can find the folder.
3.568545
4
model/test_handler.py
liveonnet/p3_server
0
6615504
<filename>model/test_handler.py #-#from aiohttp import web #-#from asyncio import CancelledError from random import randrange #-#from random import choice from aiohttp import web #-#from asyncio import sleep from lib.tools_lib import pcformat from aiohttp.web import View #-#from lib.tools_lib import check_wx_auth #-#from lib.tools_lib import get_wx_auth from lib.handler_lib import BaseHandler from lib.handler_lib import route from lib.cache_lib import K from lib.applog import app_log info, debug, error, warn = app_log.info, app_log.debug, app_log.error, app_log.warning pcformat @route('/user/{uid}') class UserHandler(BaseHandler): #-# def __init__(self): # uc -ACNqse "select uid from z_user" > /tmp/1.csv #-# self.l_uid = [int(x) for x in open('/tmp/1.csv').read().split('\n') if x] #-# self.l_uid = self.l_uid[:400] #-# info('l_uid %s', len(self.l_uid)) async def get(self): #-# uid = request.match_info.get('uid', '0') uid = randrange(10000000, 99999999) #-# uid = choice(self.l_uid) c_k = K._UINFO_ + str(uid) r = await self.getCache('ad') data = await r.getObj(c_k) if data is None: conn = await self.getDB('uc_read') data = await conn.getOne('select * from z_user where uid=%s', (uid, ), 'dict') await r.setObj(c_k, data, 60) else: info('cache hit %s', c_k) #-# await sleep(3) #-# data = {'uid': uid} return self.writeJson(data) #-# return web.Response(text="this is aio project.") @route('/empty') class EmptyHandler(View): async def get(self): #-# info('hehe %s', id(self)) #-# info('self %s', pcformat(dir(self.request))) #-# info(pcformat(list(x for x in dir(self) if not x.startswith('_')))) return web.Response(text='ok') @route('/test') class TestHandler(BaseHandler): async def get(self): return web.Response(text='test ok')
<filename>model/test_handler.py #-#from aiohttp import web #-#from asyncio import CancelledError from random import randrange #-#from random import choice from aiohttp import web #-#from asyncio import sleep from lib.tools_lib import pcformat from aiohttp.web import View #-#from lib.tools_lib import check_wx_auth #-#from lib.tools_lib import get_wx_auth from lib.handler_lib import BaseHandler from lib.handler_lib import route from lib.cache_lib import K from lib.applog import app_log info, debug, error, warn = app_log.info, app_log.debug, app_log.error, app_log.warning pcformat @route('/user/{uid}') class UserHandler(BaseHandler): #-# def __init__(self): # uc -ACNqse "select uid from z_user" > /tmp/1.csv #-# self.l_uid = [int(x) for x in open('/tmp/1.csv').read().split('\n') if x] #-# self.l_uid = self.l_uid[:400] #-# info('l_uid %s', len(self.l_uid)) async def get(self): #-# uid = request.match_info.get('uid', '0') uid = randrange(10000000, 99999999) #-# uid = choice(self.l_uid) c_k = K._UINFO_ + str(uid) r = await self.getCache('ad') data = await r.getObj(c_k) if data is None: conn = await self.getDB('uc_read') data = await conn.getOne('select * from z_user where uid=%s', (uid, ), 'dict') await r.setObj(c_k, data, 60) else: info('cache hit %s', c_k) #-# await sleep(3) #-# data = {'uid': uid} return self.writeJson(data) #-# return web.Response(text="this is aio project.") @route('/empty') class EmptyHandler(View): async def get(self): #-# info('hehe %s', id(self)) #-# info('self %s', pcformat(dir(self.request))) #-# info(pcformat(list(x for x in dir(self) if not x.startswith('_')))) return web.Response(text='ok') @route('/test') class TestHandler(BaseHandler): async def get(self): return web.Response(text='test ok')
en
0.211008
#-#from aiohttp import web #-#from asyncio import CancelledError #-#from random import choice #-#from asyncio import sleep #-#from lib.tools_lib import check_wx_auth #-#from lib.tools_lib import get_wx_auth #-# def __init__(self): # uc -ACNqse "select uid from z_user" > /tmp/1.csv #-# self.l_uid = [int(x) for x in open('/tmp/1.csv').read().split('\n') if x] #-# self.l_uid = self.l_uid[:400] #-# info('l_uid %s', len(self.l_uid)) #-# uid = request.match_info.get('uid', '0') #-# uid = choice(self.l_uid) #-# await sleep(3) #-# data = {'uid': uid} #-# return web.Response(text="this is aio project.") #-# info('hehe %s', id(self)) #-# info('self %s', pcformat(dir(self.request))) #-# info(pcformat(list(x for x in dir(self) if not x.startswith('_'))))
2.051236
2
main.py
Devoxin/WindowsRPC
2
6615505
import psutil import re from pypresence import Presence from time import time, sleep from win32gui import GetForegroundWindow, GetWindowText from win32process import GetWindowThreadProcessId client = Presence(659889732939022366) client.connect() last_activity = '' def get_current_process(): fw = GetForegroundWindow() pid = GetWindowThreadProcessId(fw) window_title = GetWindowText(fw) proc_name = psutil.Process(pid[-1]).name() return window_title, proc_name while True: w_t, p_n = get_current_process() activity = w_t or 'desktop' # cleaned_pn = p_n.split('.')[0] # if re.match(r'^[a-z]', cleaned_pn): # cleaned_pn = cleaned_pn.title() if activity != last_activity: last_activity = activity client.update(details=activity[:128], state=p_n, start=time(), instance=False) sleep(15) else: sleep(2)
import psutil import re from pypresence import Presence from time import time, sleep from win32gui import GetForegroundWindow, GetWindowText from win32process import GetWindowThreadProcessId client = Presence(659889732939022366) client.connect() last_activity = '' def get_current_process(): fw = GetForegroundWindow() pid = GetWindowThreadProcessId(fw) window_title = GetWindowText(fw) proc_name = psutil.Process(pid[-1]).name() return window_title, proc_name while True: w_t, p_n = get_current_process() activity = w_t or 'desktop' # cleaned_pn = p_n.split('.')[0] # if re.match(r'^[a-z]', cleaned_pn): # cleaned_pn = cleaned_pn.title() if activity != last_activity: last_activity = activity client.update(details=activity[:128], state=p_n, start=time(), instance=False) sleep(15) else: sleep(2)
en
0.316502
# cleaned_pn = p_n.split('.')[0] # if re.match(r'^[a-z]', cleaned_pn): # cleaned_pn = cleaned_pn.title()
2.124113
2
ros2_oled/launch/emulator.launch.py
gbr1/ros2_luma
3
6615506
# # The MIT License # # Copyright (c) 2022 <NAME> https://gbr1.github.io # # 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 use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node def generate_launch_description(): filename=LaunchConfiguration('filename') publish_rate=LaunchConfiguration('publish_rate') declare_filename_cmd = DeclareLaunchArgument('filename', description='Filename used for video') declare_publish_rate_cmd = DeclareLaunchArgument('publish_rate', default_value='25.0', description='Publish rate') oled_node = Node( package='ros2_oled', executable='oled_node', namespace="display_1", parameters=[ {'display.emulation':True}, {'display.type':'pygame'}, ] ) video_node = Node( package='image_publisher', executable='image_publisher_node', parameters=[ {'filename':filename}, {'publish_rate':publish_rate}, ] ) ld = LaunchDescription() ld.add_action(declare_filename_cmd) ld.add_action(declare_publish_rate_cmd) ld.add_action(oled_node) ld.add_action(video_node) return ld
# # The MIT License # # Copyright (c) 2022 <NAME> https://gbr1.github.io # # 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 use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node def generate_launch_description(): filename=LaunchConfiguration('filename') publish_rate=LaunchConfiguration('publish_rate') declare_filename_cmd = DeclareLaunchArgument('filename', description='Filename used for video') declare_publish_rate_cmd = DeclareLaunchArgument('publish_rate', default_value='25.0', description='Publish rate') oled_node = Node( package='ros2_oled', executable='oled_node', namespace="display_1", parameters=[ {'display.emulation':True}, {'display.type':'pygame'}, ] ) video_node = Node( package='image_publisher', executable='image_publisher_node', parameters=[ {'filename':filename}, {'publish_rate':publish_rate}, ] ) ld = LaunchDescription() ld.add_action(declare_filename_cmd) ld.add_action(declare_publish_rate_cmd) ld.add_action(oled_node) ld.add_action(video_node) return ld
en
0.761615
# # The MIT License # # Copyright (c) 2022 <NAME> https://gbr1.github.io # # 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 use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #
2.150716
2
src/new_event.py
org97/incredible-citizen-bot
2
6615507
<reponame>org97/incredible-citizen-bot from telegram.ext import ( ConversationHandler, MessageHandler, Filters, CallbackQueryHandler, CallbackContext) from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode from menu import default_markup from models import User, Event, City, Region import strings as s from datetime import datetime, timedelta from configuration import conf from utils import cities_keyboard, regions_keyboard, region_cities_keyboard, user_allowed # New event stages START, SELECTING_CITY, TYPING_NAME, TYPING_DATES, \ TYPING_DESCRIPTION, REVIEW = range(6) @user_allowed def start_new_event(update: Update, context: CallbackContext): keyboard = [ [InlineKeyboardButton(s.start_new_event_process_button, callback_data='select_event_city')], ] update.message.reply_text( s.how_to_create_description, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard) ) return START def select_event_city(update: Update, context: CallbackContext): query = update.callback_query query.answer() user = User.by(query.from_user.id) if not user.can_create_new_events: query.from_user.send_message(s.events_limit_reached_error, reply_markup=default_markup) return ConversationHandler.END event_cities_keyboard = [ [InlineKeyboardButton( user.city.name, callback_data='select_city:%s' % user.city.name)], [InlineKeyboardButton( "Города Беларуси >>", callback_data='select_city_2')], [InlineKeyboardButton( s.geo_independent_event, callback_data='select_city:None')], ] reply_markup = InlineKeyboardMarkup(event_cities_keyboard) if query.message.text == s.how_to_create_description: # on starting query.from_user.send_message(s.step1_select_event_city, parse_mode=ParseMode.HTML, reply_markup=reply_markup) else: # on navigating back query.edit_message_text(s.step1_select_event_city, parse_mode=ParseMode.HTML, reply_markup=reply_markup) return SELECTING_CITY def select_event_city_2(update: Update, context: CallbackContext): query = update.callback_query user = query.from_user query.answer() reply_markup = InlineKeyboardMarkup(regions_keyboard()) query.edit_message_text( s.step1_select_event_city, parse_mode=ParseMode.HTML, reply_markup=reply_markup) return SELECTING_CITY def select_event_city_3(update: Update, context: CallbackContext): query = update.callback_query user = query.from_user query.answer() region_name = query.data.split(':')[1] region = Region.by(name=region_name) reply_markup = InlineKeyboardMarkup(region_cities_keyboard(region=region)) query.edit_message_text( s.step1_select_event_city, parse_mode=ParseMode.HTML, reply_markup=reply_markup) return SELECTING_CITY def enter_event_name(update: Update, context: CallbackContext): query = update.callback_query query.answer() # on stepping back there is no city name in query data if 'select_city' in query.data: city_name = query.data.split(':')[1] context.user_data['city_name'] = city_name keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='select_event_city')], ] context.bot.send_message(chat_id=update.effective_chat.id, text=s.step2_event_name_description, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) context.bot.send_message(chat_id=update.effective_chat.id, text=s.typing_hint) return TYPING_NAME def select_start_date(update: Update, context: CallbackContext): if update.message: # on specifying valid event name event_name = update.message.text elif update.edited_message: # on editing event name event_name = update.edited_message.text else: # on stepping back if update.callback_query: update.callback_query.answer() event_name = context.user_data['event_name'] context.user_data['event_name'] = event_name if len(event_name) > conf.event_name_max_length: context.bot.send_message(chat_id=update.effective_chat.id, text=s.event_name_too_long_error) return TYPING_NAME keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='enter_event_name')], ] example_date = (datetime.now() + timedelta(1)).replace(hour=17, minute=0) text = s.step31_select_event_start_date.format( example_date.strftime(conf.date_format)) context.bot.send_message(chat_id=update.effective_chat.id, text=text, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) return TYPING_DATES def select_start_time(update: Update, context: CallbackContext): if update.message: # on specifying correct start date start_date_str = update.message.text elif update.edited_message: # on editing start date start_date_str = update.edited_message.text else: # on stepping back # TODO: on edit message there is an error update.callback_query.answer() start_date_str = context.user_data['start_date_str'] context.user_data['start_date_str'] = start_date_str try: start_date = datetime.strptime(start_date_str, conf.date_format) except ValueError: # if user enters some invalid date like '30.02.2021 17:00' conf.logger.info('User entered invalid date: %s' % start_date_str) typing_dates_error(update, context) return TYPING_DATES # Check that start_date is within boundaries. # Note that we will not perform this check at the final step when # the event is actually submitted. It is in the interest of the user to satisfy # the lower boundary. diff_in_sec = (start_date - datetime.now()).total_seconds() diff_in_hours = divmod(diff_in_sec, 3600)[0] if diff_in_hours < conf.earliest_event_start_time_from_now: typing_dates_error( update, context, message=s.start_date_is_too_early_error) return TYPING_DATES elif diff_in_hours > conf.latest_event_start_time_from_now: typing_dates_error( update, context, message=s.start_date_is_too_late_error) return TYPING_DATES keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='select_start_date')], [InlineKeyboardButton(s.skip, callback_data='skip_start_time')], ] time_example = '01:30' text = s.step32_select_event_end_date.format(time_example) context.bot.send_message(chat_id=update.effective_chat.id, text=text, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) return TYPING_DATES def typing_dates_error(update: Update, context, message=s.typing_dates_error): context.bot.send_message(chat_id=update.effective_chat.id, text=message, parse_mode=ParseMode.HTML) update.message = None select_start_date(update, context) return TYPING_DATES def enter_event_description(update: Update, context: CallbackContext): if update.message: # on typing valid duration duration_str = update.message.text elif 'skip_start_time' in update.callback_query.data: # on skip duration time duration_str = None update.callback_query.answer() elif 'duration_str' in context.user_data: # on step back duration_str = context.user_data['duration_str'] update.callback_query.answer() else: # fallback duration_str = None context.user_data['duration_str'] = duration_str keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='select_start_date')], ] context.bot.send_message(chat_id=update.effective_chat.id, text=s.step4_event_description, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) return TYPING_DESCRIPTION def review_event(update: Update, context: CallbackContext): # only two cases should be possible here: handling message or edited message if update.message: context.user_data['event_description'] = update.message.text elif update.edited_message: context.user_data['event_description'] = update.message.text if len(context.user_data['event_description']) > conf.event_description_max_length: context.bot.send_message(chat_id=update.effective_chat.id, text=s.event_description_too_long_error) return TYPING_DESCRIPTION keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='enter_event_description')], [InlineKeyboardButton(s.send_for_review, callback_data='finish_event')], ] city = s.geo_independent_event if context.user_data[ 'city_name'] == 'None' else context.user_data['city_name'] time = context.user_data['start_date_str'] start_date = datetime.strptime(time, conf.date_format) end_date = start_date if context.user_data['duration_str']: hours, minutes = [int(x) for x in context.user_data['duration_str'].split(':')] end_date += timedelta(hours=hours, minutes=minutes) time += ' - %s' % end_date.strftime(conf.date_format) review_message = s.step5_event_review_description.format( city, context.user_data['event_name'], time, context.user_data['event_description']) context.bot.send_message(chat_id=update.effective_chat.id, text=review_message, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) return REVIEW def finish(update: Update, context: CallbackContext): query = update.callback_query query.answer() user = User.by(query.from_user.id) city = City.by(context.user_data['city_name']) start_date = datetime.strptime( context.user_data['start_date_str'], conf.date_format) end_date = start_date if context.user_data['duration_str']: hours, minutes = [int(x) for x in context.user_data['duration_str'].split(':')] end_date += timedelta(hours=hours, minutes=minutes) event = Event.create(creator=user, city=city, name=context.user_data['event_name'], description=context.user_data['event_description'], start_date=start_date, end_date=end_date) query.from_user.send_message( s.thanks_for_event_creation_message, parse_mode=ParseMode.HTML, reply_markup=default_markup) return ConversationHandler.END def unknown(update: Update, context: CallbackContext): context.bot.send_message(chat_id=update.effective_chat.id, text=s.event_creation_process_interrupted_message) return ConversationHandler.END conv_handler = ConversationHandler( entry_points=[MessageHandler( Filters.regex('^%s$' % s.propose_new_event), start_new_event)], states={ START: [ CallbackQueryHandler( select_event_city, pattern='^select_event_city$'), ], SELECTING_CITY: [ # going back from the list of regional cities CallbackQueryHandler(select_event_city, pattern='^select_city_1$'), # selecting a region CallbackQueryHandler(select_event_city_2, pattern='^select_city_2$'), # selecting a city by region CallbackQueryHandler(select_event_city_3, pattern='^select_city_3'), # concrete city is selected CallbackQueryHandler(enter_event_name, pattern='^select_city'), ], TYPING_NAME: [ # on going back from setting event name CallbackQueryHandler(select_event_city, pattern='^select_event_city$'), # on receiving event name MessageHandler( Filters.text & ~Filters.command, select_start_date ) ], TYPING_DATES: [ # on typing event start date MessageHandler(Filters.regex( r'^([0-2][0-9]|(3)[0-1])(\.)(((0)[0-9])|((1)[0-2]))(\.)20[0-9][0-9] ([0-1][0-9]|(2)[0-3]):([0-5][0-9])$'), select_start_time), # on going back from selecting date CallbackQueryHandler(enter_event_name, pattern='^enter_event_name$'), # on going back from selecting duration CallbackQueryHandler(select_start_date, pattern='^select_start_date$'), # on skippin selecting start time CallbackQueryHandler(enter_event_description, pattern='^skip_start_time$'), # on typing event duration MessageHandler(Filters.regex( r'^\d{1,2}:\d{2}$'), enter_event_description), # on invalid date/time format MessageHandler(Filters.text & ~Filters.command, typing_dates_error) ], TYPING_DESCRIPTION: [ # on going back from typing description we restart TYPING_DATES process CallbackQueryHandler(select_start_date, pattern='^select_start_date$'), # on getting description MessageHandler( Filters.text & ~Filters.command, review_event ) ], REVIEW: [ CallbackQueryHandler(enter_event_description, pattern='^enter_event_description$'), CallbackQueryHandler(finish, pattern='^finish_event$'), ] }, fallbacks=[ MessageHandler(Filters.text, unknown), ] )
from telegram.ext import ( ConversationHandler, MessageHandler, Filters, CallbackQueryHandler, CallbackContext) from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode from menu import default_markup from models import User, Event, City, Region import strings as s from datetime import datetime, timedelta from configuration import conf from utils import cities_keyboard, regions_keyboard, region_cities_keyboard, user_allowed # New event stages START, SELECTING_CITY, TYPING_NAME, TYPING_DATES, \ TYPING_DESCRIPTION, REVIEW = range(6) @user_allowed def start_new_event(update: Update, context: CallbackContext): keyboard = [ [InlineKeyboardButton(s.start_new_event_process_button, callback_data='select_event_city')], ] update.message.reply_text( s.how_to_create_description, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard) ) return START def select_event_city(update: Update, context: CallbackContext): query = update.callback_query query.answer() user = User.by(query.from_user.id) if not user.can_create_new_events: query.from_user.send_message(s.events_limit_reached_error, reply_markup=default_markup) return ConversationHandler.END event_cities_keyboard = [ [InlineKeyboardButton( user.city.name, callback_data='select_city:%s' % user.city.name)], [InlineKeyboardButton( "Города Беларуси >>", callback_data='select_city_2')], [InlineKeyboardButton( s.geo_independent_event, callback_data='select_city:None')], ] reply_markup = InlineKeyboardMarkup(event_cities_keyboard) if query.message.text == s.how_to_create_description: # on starting query.from_user.send_message(s.step1_select_event_city, parse_mode=ParseMode.HTML, reply_markup=reply_markup) else: # on navigating back query.edit_message_text(s.step1_select_event_city, parse_mode=ParseMode.HTML, reply_markup=reply_markup) return SELECTING_CITY def select_event_city_2(update: Update, context: CallbackContext): query = update.callback_query user = query.from_user query.answer() reply_markup = InlineKeyboardMarkup(regions_keyboard()) query.edit_message_text( s.step1_select_event_city, parse_mode=ParseMode.HTML, reply_markup=reply_markup) return SELECTING_CITY def select_event_city_3(update: Update, context: CallbackContext): query = update.callback_query user = query.from_user query.answer() region_name = query.data.split(':')[1] region = Region.by(name=region_name) reply_markup = InlineKeyboardMarkup(region_cities_keyboard(region=region)) query.edit_message_text( s.step1_select_event_city, parse_mode=ParseMode.HTML, reply_markup=reply_markup) return SELECTING_CITY def enter_event_name(update: Update, context: CallbackContext): query = update.callback_query query.answer() # on stepping back there is no city name in query data if 'select_city' in query.data: city_name = query.data.split(':')[1] context.user_data['city_name'] = city_name keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='select_event_city')], ] context.bot.send_message(chat_id=update.effective_chat.id, text=s.step2_event_name_description, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) context.bot.send_message(chat_id=update.effective_chat.id, text=s.typing_hint) return TYPING_NAME def select_start_date(update: Update, context: CallbackContext): if update.message: # on specifying valid event name event_name = update.message.text elif update.edited_message: # on editing event name event_name = update.edited_message.text else: # on stepping back if update.callback_query: update.callback_query.answer() event_name = context.user_data['event_name'] context.user_data['event_name'] = event_name if len(event_name) > conf.event_name_max_length: context.bot.send_message(chat_id=update.effective_chat.id, text=s.event_name_too_long_error) return TYPING_NAME keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='enter_event_name')], ] example_date = (datetime.now() + timedelta(1)).replace(hour=17, minute=0) text = s.step31_select_event_start_date.format( example_date.strftime(conf.date_format)) context.bot.send_message(chat_id=update.effective_chat.id, text=text, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) return TYPING_DATES def select_start_time(update: Update, context: CallbackContext): if update.message: # on specifying correct start date start_date_str = update.message.text elif update.edited_message: # on editing start date start_date_str = update.edited_message.text else: # on stepping back # TODO: on edit message there is an error update.callback_query.answer() start_date_str = context.user_data['start_date_str'] context.user_data['start_date_str'] = start_date_str try: start_date = datetime.strptime(start_date_str, conf.date_format) except ValueError: # if user enters some invalid date like '30.02.2021 17:00' conf.logger.info('User entered invalid date: %s' % start_date_str) typing_dates_error(update, context) return TYPING_DATES # Check that start_date is within boundaries. # Note that we will not perform this check at the final step when # the event is actually submitted. It is in the interest of the user to satisfy # the lower boundary. diff_in_sec = (start_date - datetime.now()).total_seconds() diff_in_hours = divmod(diff_in_sec, 3600)[0] if diff_in_hours < conf.earliest_event_start_time_from_now: typing_dates_error( update, context, message=s.start_date_is_too_early_error) return TYPING_DATES elif diff_in_hours > conf.latest_event_start_time_from_now: typing_dates_error( update, context, message=s.start_date_is_too_late_error) return TYPING_DATES keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='select_start_date')], [InlineKeyboardButton(s.skip, callback_data='skip_start_time')], ] time_example = '01:30' text = s.step32_select_event_end_date.format(time_example) context.bot.send_message(chat_id=update.effective_chat.id, text=text, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) return TYPING_DATES def typing_dates_error(update: Update, context, message=s.typing_dates_error): context.bot.send_message(chat_id=update.effective_chat.id, text=message, parse_mode=ParseMode.HTML) update.message = None select_start_date(update, context) return TYPING_DATES def enter_event_description(update: Update, context: CallbackContext): if update.message: # on typing valid duration duration_str = update.message.text elif 'skip_start_time' in update.callback_query.data: # on skip duration time duration_str = None update.callback_query.answer() elif 'duration_str' in context.user_data: # on step back duration_str = context.user_data['duration_str'] update.callback_query.answer() else: # fallback duration_str = None context.user_data['duration_str'] = duration_str keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='select_start_date')], ] context.bot.send_message(chat_id=update.effective_chat.id, text=s.step4_event_description, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) return TYPING_DESCRIPTION def review_event(update: Update, context: CallbackContext): # only two cases should be possible here: handling message or edited message if update.message: context.user_data['event_description'] = update.message.text elif update.edited_message: context.user_data['event_description'] = update.message.text if len(context.user_data['event_description']) > conf.event_description_max_length: context.bot.send_message(chat_id=update.effective_chat.id, text=s.event_description_too_long_error) return TYPING_DESCRIPTION keyboard = [ [InlineKeyboardButton(s.step_back_button, callback_data='enter_event_description')], [InlineKeyboardButton(s.send_for_review, callback_data='finish_event')], ] city = s.geo_independent_event if context.user_data[ 'city_name'] == 'None' else context.user_data['city_name'] time = context.user_data['start_date_str'] start_date = datetime.strptime(time, conf.date_format) end_date = start_date if context.user_data['duration_str']: hours, minutes = [int(x) for x in context.user_data['duration_str'].split(':')] end_date += timedelta(hours=hours, minutes=minutes) time += ' - %s' % end_date.strftime(conf.date_format) review_message = s.step5_event_review_description.format( city, context.user_data['event_name'], time, context.user_data['event_description']) context.bot.send_message(chat_id=update.effective_chat.id, text=review_message, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup(keyboard)) return REVIEW def finish(update: Update, context: CallbackContext): query = update.callback_query query.answer() user = User.by(query.from_user.id) city = City.by(context.user_data['city_name']) start_date = datetime.strptime( context.user_data['start_date_str'], conf.date_format) end_date = start_date if context.user_data['duration_str']: hours, minutes = [int(x) for x in context.user_data['duration_str'].split(':')] end_date += timedelta(hours=hours, minutes=minutes) event = Event.create(creator=user, city=city, name=context.user_data['event_name'], description=context.user_data['event_description'], start_date=start_date, end_date=end_date) query.from_user.send_message( s.thanks_for_event_creation_message, parse_mode=ParseMode.HTML, reply_markup=default_markup) return ConversationHandler.END def unknown(update: Update, context: CallbackContext): context.bot.send_message(chat_id=update.effective_chat.id, text=s.event_creation_process_interrupted_message) return ConversationHandler.END conv_handler = ConversationHandler( entry_points=[MessageHandler( Filters.regex('^%s$' % s.propose_new_event), start_new_event)], states={ START: [ CallbackQueryHandler( select_event_city, pattern='^select_event_city$'), ], SELECTING_CITY: [ # going back from the list of regional cities CallbackQueryHandler(select_event_city, pattern='^select_city_1$'), # selecting a region CallbackQueryHandler(select_event_city_2, pattern='^select_city_2$'), # selecting a city by region CallbackQueryHandler(select_event_city_3, pattern='^select_city_3'), # concrete city is selected CallbackQueryHandler(enter_event_name, pattern='^select_city'), ], TYPING_NAME: [ # on going back from setting event name CallbackQueryHandler(select_event_city, pattern='^select_event_city$'), # on receiving event name MessageHandler( Filters.text & ~Filters.command, select_start_date ) ], TYPING_DATES: [ # on typing event start date MessageHandler(Filters.regex( r'^([0-2][0-9]|(3)[0-1])(\.)(((0)[0-9])|((1)[0-2]))(\.)20[0-9][0-9] ([0-1][0-9]|(2)[0-3]):([0-5][0-9])$'), select_start_time), # on going back from selecting date CallbackQueryHandler(enter_event_name, pattern='^enter_event_name$'), # on going back from selecting duration CallbackQueryHandler(select_start_date, pattern='^select_start_date$'), # on skippin selecting start time CallbackQueryHandler(enter_event_description, pattern='^skip_start_time$'), # on typing event duration MessageHandler(Filters.regex( r'^\d{1,2}:\d{2}$'), enter_event_description), # on invalid date/time format MessageHandler(Filters.text & ~Filters.command, typing_dates_error) ], TYPING_DESCRIPTION: [ # on going back from typing description we restart TYPING_DATES process CallbackQueryHandler(select_start_date, pattern='^select_start_date$'), # on getting description MessageHandler( Filters.text & ~Filters.command, review_event ) ], REVIEW: [ CallbackQueryHandler(enter_event_description, pattern='^enter_event_description$'), CallbackQueryHandler(finish, pattern='^finish_event$'), ] }, fallbacks=[ MessageHandler(Filters.text, unknown), ] )
en
0.845824
# New event stages # on starting # on navigating back # on stepping back there is no city name in query data # on specifying valid event name # on editing event name # on stepping back # on specifying correct start date # on editing start date # on stepping back # TODO: on edit message there is an error # if user enters some invalid date like '30.02.2021 17:00' # Check that start_date is within boundaries. # Note that we will not perform this check at the final step when # the event is actually submitted. It is in the interest of the user to satisfy # the lower boundary. # on typing valid duration # on skip duration time # on step back # fallback # only two cases should be possible here: handling message or edited message # going back from the list of regional cities # selecting a region # selecting a city by region # concrete city is selected # on going back from setting event name # on receiving event name # on typing event start date # on going back from selecting date # on going back from selecting duration # on skippin selecting start time # on typing event duration # on invalid date/time format # on going back from typing description we restart TYPING_DATES process # on getting description
2.210157
2
regression_tests/parsers/c_parser/module.py
mehrdad-shokri/retdec-regression-tests-framework
21
6615508
<filename>regression_tests/parsers/c_parser/module.py """ A module (translation unit). """ import io import re import sys from clang import cindex from regression_tests.parsers.c_parser.comment import Comment from regression_tests.parsers.c_parser.include import Include from regression_tests.parsers.c_parser.types.enum_type import EnumType from regression_tests.parsers.c_parser.types.struct_type import StructType from regression_tests.parsers.c_parser.types.union_type import UnionType from regression_tests.parsers.c_parser.utils import get_name from regression_tests.parsers.c_parser.utils import get_parse_errors from regression_tests.parsers.c_parser.utils import get_set_of_names from regression_tests.parsers.c_parser.utils import has_tokens from regression_tests.parsers.c_parser.utils import underline from regression_tests.parsers.c_parser.utils import visit_node from regression_tests.parsers.text_parser import Text from regression_tests.utils import memoize from regression_tests.utils.list import NamedObjectList from regression_tests.utils.list import names_of class Module(Text): """A module (translation unit). The instances of this class behave like strings with additional properties and methods. """ def __new__(cls, code, tu): """Constructs a new parsed C code. :param str code: The original C code. :param clang.TranslationUnit tu: The underlying translation unit. """ c_code = Text.__new__(cls, code) return c_code def __init__(self, code, tu): """ :param str code: The original C code. :param clang.TranslationUnit tu: The underlying translation unit. """ self._code = code self._tu = tu @property def code(self): """The original C code (`str`).""" return self._code @property def file_name(self): """Name of the original source file (`str`).""" return self._tu.spelling def has_parse_errors(self): """Does the module contain some parsing errors?""" parse_errors = get_parse_errors(self._tu.diagnostics) return bool(parse_errors) @property @memoize def global_vars(self): """Global variables (list of :class:`.Variable`). The returned list can be indexed by either positions (0, 1, ...) or names. Example: .. code-block:: python module.global_vars[0] # Returns the first global variable. module.global_vars['g'] # Returns the global variable named 'g'. When there is no such global variable, it raises ``IndexError``. """ var_nodes = filter(self._is_global_var, self._tu.cursor.get_children()) return NamedObjectList(map(Variable, var_nodes)) @property @memoize def global_var_names(self): """Names of the global variables (list of `str`).""" return names_of(self.global_vars) @property def global_var_count(self): """Number of global variables.""" return len(self.global_vars) def has_any_global_vars(self): """Are there any global variables (at least one)?""" return self.global_var_count > 0 def has_global_vars(self, *vars): """Are there given global variables? :param vars: Variable names or instances of :class:`.Variable`. Example: .. code-block:: python module.has_global_vars('g1', 'g2') module.has_global_vars('g1', var1) The order is irrelevant. If you want to check that only the given global variables appear in the module and no other other global variables are present, use :func:`has_global_vars()` instead. If you call this method without any arguments, it checks whether there is at least one global variable in the module: .. code-block:: python module.has_global_vars() """ names = get_set_of_names(vars) if not names: return self.global_var_count > 0 return names.issubset(set(self.global_var_names)) def has_no_global_vars(self): """Are there no global variables?""" return self.global_var_count == 0 def has_just_global_vars(self, *vars): """Are there only specified global variables? :param vars: Variable names or instances of :class:`.Variable`. Example: .. code-block:: python module.has_just_global_vars('g1', 'g2') module.has_just_global_vars('g', var) The order is irrelevant. """ return set(self.global_var_names) == get_set_of_names(vars) def has_global_var(self, var): """Is there specified global variable? :param var: Variable name or instance of :class:`.Variable`. """ return get_name(var) in self.global_var_names @property @memoize def funcs(self): """Functions (list of :class:`.Function`). The returned list can be indexed by either positions (0, 1, ...) or function names. Example: .. code-block:: python module.funcs[0] # Returns the first function. module.funcs['main'] # Returns the function named 'main'. When there is no such function, it raises ``IndexError``. """ func_nodes = filter(self._is_func, self._tu.cursor.get_children()) return NamedObjectList(map(Function, func_nodes)) @property @memoize def func_names(self): """Names of the functions (list of `str`).""" return names_of(self.funcs) @property def func_count(self): """Number of functions.""" return len(self.funcs) def func(self, *functions): """Returns the first function corresponding to an item in `functions`. Names as strings or objects of :class:`.Function` can be used as parameters. This is useful because on x86 + PE, functions may be prefixed with ``_``. Instead of using an if/else (ELF vs PE), you can simply obtain the function in the following way: .. code-block:: python my_func = module.func('my_func', '_my_func') my_func = module.func(foo, '_foo') When there is no such function, it raises ``AssertionError``. """ if not functions: raise AssertionError('at least one function name has to be given') for name in map(get_name, functions): for func in self.funcs: if func.name == name: return func raise AssertionError('no such function') def has_funcs(self, *functions): """Are there given functions? :param functions: Function names or instances of :class:`.Function`. Example: .. code-block:: python module.has_funcs('func1', 'func2') module.has_funcs('func1', foo) The order is irrelevant. If you want to check that only the given functions appear in the module and no other functions, use :func:`has_just_funcs()` instead. If you call this method without any arguments, it checks whether there is at least one function in the module: .. code-block:: python module.has_funcs() """ names = get_set_of_names(functions) if not names: return self.func_count > 0 return names.issubset(set(self.func_names)) def has_no_funcs(self): """Are there no functions?""" return self.func_count == 0 def has_just_funcs(self, *functions): """Are there only given functions? Names as strings or objects of :class:`.Function` can be used as parameters. Example: .. code-block:: python module.has_just_funcs('func1', 'func2') module.has_just_funcs('func1', foo) The order is irrelevant. """ return set(self.func_names) == get_set_of_names(functions) def has_func(self, name): """Is there a function with the given name (`str`)?""" return name in self.func_names def has_func_matching(self, regexp): """Is there a function with a name matching the given regular expression? `regexp` can be either a string or a compiled regular expression. The standard function ``re.fullmatch()`` is used to perform the matching. """ for name in self.func_names: if re.fullmatch(regexp, name) is not None: return True return False @property @memoize def comments(self): """Comments in the code (list of :class:`.Comment`).""" comments = [] for token in self._tu.cursor.get_tokens(): if token.kind == cindex.TokenKind.COMMENT: comments.append(Comment(token.spelling)) return comments def has_comment_matching(self, regexp): """Is there a comment matching the given regular expression? See the description of :func:`~regression_tests.parsers.c_parser.comment.Comment.matches()` for more info. """ for comment in self.comments: if comment.matches(regexp): return True return False @property @memoize def includes(self): """Includes in the code (list of :class:`.Include`). Only direct includes are considered (i.e. nested includes are discarded). """ # We have to iterate through the tokens because # # (1) includes are not available through self._tu.cursor.get_children(), # # (2) file inclusions from self._tu.get_includes() have just # absolute paths to the included files. includes = [] tokens = list(self._tu.cursor.get_tokens()) i = 0 while i < len(tokens): include, i = self._try_read_next_include(tokens, i) if include is not None: includes.append(include) return includes def has_include_of_file(self, file): """Is there an include of the given file (`str`)?""" for include in self.includes: if include.file == file: return True return False @property @memoize def string_literal_values(self): """Returns a set of values of all string literals (a set of `str`).""" values = set() def add_to_values_if_string_literal(node): if node.kind != cindex.CursorKind.STRING_LITERAL: return # There seems to be a bug in clang (cindex) that causes NAN, # which expands to __builtin_nanf, to be considered a string # literal with no tokens. As a workaround, do not consider # nodes without tokens to be valid string literals. if not has_tokens(node): return values.add(StringLiteral(node).value) # We have to visit all the global variables and functions. for node in self._tu.cursor.get_children(): if self._is_func(node) or self._is_global_var(node): visit_node(node, add_to_values_if_string_literal) return values def has_string_literal(self, value): """Is there a string literal of the given value? It searches through the whole module (global variables and function bodies). Example: .. code-block:: python module.has_string_literal('Result is: %d') When the literal is not found in :attr:`string_literal_values`, :func:`~regression_tests.parsers.text_parser.Text.contains()` is called to check whether the literal exists in the module. This behavior is needed because there may be a syntax error near the string literal. In such cases, the literal is not present in the module because the code that contains it is skipped during parsing. """ if value in self.string_literal_values: return True return self.contains('"{}"'.format(re.escape(value))) def has_string_literal_matching(self, regexp): """Is there a string literal matching the given regular expression? `regexp` can be either a string or a compiled regular expression. The standard function ``re.fullmatch()`` is used to perform the matching. When the literal is not found in :attr:`string_literal_values`, :func:`~regression_tests.parsers.text_parser.Text.contains()` is called to check whether a matching literal exists in the module. See the description of :func:`has_string_literal()` for the reason. """ if self._has_string_literal_value_matching(regexp): return True return self._contains_string_literal_matching(regexp) @property @memoize def structs(self): """Structures (list of :class:`.StructType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ struct_nodes = filter(self._is_struct, self._tu.cursor.get_children()) return [StructType(node.type) for node in struct_nodes] @property @memoize def unnamed_structs(self): """Unnamed structures (list of :class:`.StructType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ return [struct for struct in self.structs if not struct.has_name()] @property @memoize def named_structs(self): """Named structures (list of :class:`.StructType`). The returned list can be indexed by either positions (0, 1, ...) or structure names. Example: .. code-block:: python module.named_structs[0] # Returns the first structure. module.named_structs['node'] # Returns the structure named 'node'. When there is no such structure, it raises ``IndexError``. """ return NamedObjectList([x for x in self.structs if x.has_name()]) @property @memoize def struct_names(self): """Names of the structures (list of `str`).""" return names_of(self.named_structs) @property def struct_count(self): """Number of structures.""" return len(self.structs) @property def unnamed_struct_count(self): """Number of unnamed structures.""" return len(self.unnamed_structs) @property def named_struct_count(self): """Number of named structures.""" return len(self.named_structs) def has_any_structs(self): """Are there any structures (at least one)?""" return self.struct_count > 0 def has_any_unnamed_structs(self): """Are there any unnamed structures (at least one)?""" return self.unnamed_struct_count > 0 def has_any_named_structs(self): """Are there any named structures (at least one)?""" return self.named_struct_count > 0 def has_named_structs(self, *structs): """Are there given named structures? :param structs: Structure names or instances of :class:`.StructType`. Example: .. code-block:: python module.has_named_structs('s1', 's2') module.has_named_structs('s1', struct) The order is irrelevant. If you want to check that only the given named structures appear in the module and no other named structures are present, use :func:`has_just_named_structs()` instead. If you call this method without any arguments, it checks whether there is at least one struct in the module: .. code-block:: python module.has_named_structs() """ names = get_set_of_names(structs) if not names: return self.has_any_named_structs() return names.issubset(set(self.struct_names)) def has_no_structs(self): """Are there no structures?""" return self.struct_count == 0 def has_no_unnamed_structs(self): """Are there no unnamed structures?""" return self.unnamed_struct_count == 0 def has_no_named_structs(self): """Are there no named structures?""" return self.named_struct_count == 0 def has_just_named_structs(self, *structs): """Are there only given named structures? :param structs: Structure names or instances of :class:`.StructType`. Example: .. code-block:: python module.has_just_named_structs('s1', 's2') module.has_just_named_structs('s1', struct) The order is irrelevant. """ return set(self.struct_names) == get_set_of_names(structs) def has_named_struct(self, struct): """Is there specified named structure? :param struct: Structure name or instance of :class:`.StructType`. """ return get_name(struct) in self.struct_names @property @memoize def unions(self): """Unions (list of :class:`.UnionType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ union_nodes = filter(self._is_union, self._tu.cursor.get_children()) return [UnionType(node.type) for node in union_nodes] @property @memoize def unnamed_unions(self): """Unnamed unions (list of :class:`.UnionType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ return [union for union in self.unions if not union.has_name()] @property @memoize def named_unions(self): """Named unions (list of :class:`.UnionType`). The returned list can be indexed by either positions (0, 1, ...) or union names. Example: .. code-block:: python module.named_unions[0] # Returns the first union. module.named_unions['node'] # Returns the union named 'node'. When there is no such union, it raises ``IndexError``. """ return NamedObjectList([x for x in self.unions if x.has_name()]) @property @memoize def union_names(self): """Names of the unions (list of `str`).""" return names_of(self.named_unions) @property def union_count(self): """Number of unions.""" return len(self.unions) @property def unnamed_union_count(self): """Number of unnamed unions.""" return len(self.unnamed_unions) @property def named_union_count(self): """Number of named unions.""" return len(self.named_unions) def has_any_unions(self): """Are there any unions (at least one)?""" return self.union_count > 0 def has_any_unnamed_unions(self): """Are there any unnamed unions (at least one)?""" return self.unnamed_union_count > 0 def has_any_named_unions(self): """Are there any named unions (at least one)?""" return self.named_union_count > 0 def has_named_unions(self, *unions): """Are there given named unions? :param unions: Union names or instances of :class:`.UnionType`. Example: .. code-block:: python module.has_named_unions('u1', 'u2') module.has_named_unions('u1', union) The order is irrelevant. If you want to check that only the given named unions appear in the module and no other named unions are present, use :func:`has_just_named_unions()` instead. If you call this method without any arguments, it checks whether there is at least one union in the module: .. code-block:: python module.has_named_unions() """ names = get_set_of_names(unions) if not names: return self.has_any_named_unions() return names.issubset(set(self.union_names)) def has_no_unions(self): """Are there no unions?""" return self.union_count == 0 def has_no_unnamed_unions(self): """Are there no unnamed unions?""" return self.unnamed_union_count == 0 def has_no_named_unions(self): """Are there no named unions?""" return self.named_union_count == 0 def has_just_named_unions(self, *unions): """Are there only given named unions? :param unions: Union names or instances of :class:`.UnionType`. Example: .. code-block:: python module.has_just_named_unions('u1', 'u2') module.has_just_named_unions('u1', union) The order is irrelevant. """ return set(self.union_names) == get_set_of_names(unions) def has_named_union(self, union): """Is there specified named union? :param union: Union name or instance of :class:`.UnionType`. """ return get_name(union) in self.union_names @property @memoize def enums(self): """Enums (list of :class:`.EnumType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ enum_nodes = filter(self._is_enum, self._tu.cursor.get_children()) return [EnumType(node.type, node) for node in enum_nodes] @property @memoize def unnamed_enums(self): """Unnamed enums (list of :class:`.EnumType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ return [enum for enum in self.enums if not enum.has_name()] @property @memoize def named_enums(self): """Named enums (list of :class:`.EnumType`). The returned list can be indexed by either positions (0, 1, ...) or enum names. Example: .. code-block:: python module.named_enums[0] # Returns the first enum. module.named_enums['node'] # Returns the enum named 'node'. When there is no such enum, it raises ``IndexError``. """ return NamedObjectList([x for x in self.enums if x.has_name()]) @property @memoize def enum_names(self): """Names of the enums (list of `str`).""" return names_of(self.named_enums) @property def enum_count(self): """Number of enums.""" return len(self.enums) @property def unnamed_enum_count(self): """Number of unnamed enums.""" return len(self.unnamed_enums) @property def named_enum_count(self): """Number of named enums.""" return len(self.named_enums) def has_any_enums(self): """Are there any enums (at least one)?""" return self.enum_count > 0 def has_any_unnamed_enums(self): """Are there any unnamed enums (at least one)?""" return self.unnamed_enum_count > 0 def has_any_named_enums(self): """Are there any named enums (at least one)?""" return self.named_enum_count > 0 def has_named_enums(self, *enums): """Are there given named enums? :param enums: Enum names or instances of :class:`.EnumType`. Example: .. code-block:: python module.has_named_enums('e1', 'e2') module.has_named_enums('e1', enum) The order is irrelevant. If you want to check that only the given named enums appear in the module and no other named enums are present, use :func:`has_just_named_enums()` instead. If you call this method without any arguments, it checks whether there is at least one enum in the module: .. code-block:: python module.has_named_enums() """ names = get_set_of_names(enums) if not names: return self.has_any_named_enums() return names.issubset(set(self.enum_names)) def has_no_enums(self): """Are there no enums?""" return self.enum_count == 0 def has_no_unnamed_enums(self): """Are there no unnamed enums?""" return self.unnamed_enum_count == 0 def has_no_named_enums(self): """Are there no named enums?""" return self.named_enum_count == 0 def has_just_named_enums(self, *enums): """Are there only given named enums? :param enums: Enum names or instances of :class:`.EnumType`. Example: .. code-block:: python module.has_just_named_enums('e1', 'e2') module.has_just_named_enums('e1', enum) The order is irrelevant. """ return set(self.enum_names) == get_set_of_names(enums) def has_named_enum(self, enum): """Is there specified named enum? :param enum: Enum name or instance of :class:`.EnumType`. """ return get_name(enum) in self.enum_names @property @memoize def enum_item_names(self): """Items in enums (list of `str`).""" enum_item_names = [] for node in self._tu.cursor.get_children(): if self._is_enum(node): enum = EnumType(node.type, node) enum_item_names += enum.item_names return enum_item_names @property def enum_item_count(self): """Sum of item in all enums in module.""" return len(self.enum_item_names) @property def empty_enums(self): """Empty enums (list of :class:`.EnumType`).""" return [enum for enum in self.enums if enum.is_empty()] @property def empty_enum_count(self): """Number of empty enums.""" return len(self.empty_enums) def has_any_empty_enums(self): """Are there any empty enums (at least one)?""" return self.empty_enum_count > 0 def has_no_empty_enums(self): """Are there no empty enums?""" return self.empty_enum_count == 0 def dump(self, verbose=False): """Dumps information about the module to ``stdout``. The dumped content is same as for :func:`dump_to()`. :param verbose: Add dumps of functions? """ self.dump_to(sys.stdout, verbose) def dump_to(self, stream, verbose=False): """Dumps information about the module to `stream`. :param stream: Stream to dump information to. :param verbose: Add dumps of functions? Content: * includes * global variables * structures * unions * enums * functions * string literals """ s = [] s.append(self.file_name) s.append('') s.append(underline('Includes:')) s.extend(map(str, self.includes)) s.append('') s.append(underline('Global vars:')) s.extend(map(lambda gv: gv.str_with_type(), self.global_vars)) s.append('') s.append(underline('Structs:')) s.extend(map(str, self.structs)) s.append('') s.append(underline('Unions:')) s.extend(map(str, self.unions)) s.append('') s.append(underline('Enums:')) s.extend(map(str, self.enums)) s.append('') s.append(underline('Functions:')) s.extend(map(str, self.funcs)) s.append('') s.append(underline('String literals:')) s.extend(self.string_literal_values) s.append('') if verbose and self.has_funcs(): for func in self.funcs: header = 'Dump of {}:'.format(func.name) s.append(header) s.append('=' * len(header)) with io.StringIO() as func_stream: func.dump_to(func_stream) s.append(func_stream.getvalue()) stream.write('\n'.join(s)) def _is_global_var(self, node): """Checks if the given node is a global variable. External global variables (coming from included headers) are not considered to be global variables. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.VAR_DECL ) def _is_func(self, node): """Checks if the given node is a function. External functions or function declarations are not considered to be functions. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.FUNCTION_DECL and node.is_definition() ) def _is_struct(self, node): """Checks if the given node is a structure. External structures (coming from included headers) are not considered to be structures. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.STRUCT_DECL ) def _is_union(self, node): """Checks if the given node is a union. External unions (coming from included headers) are not considered to be unions. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.UNION_DECL ) def _is_enum(self, node): """Checks if the given node is an enum. External enums (coming from included headers) are not considered to be enums. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.ENUM_DECL ) def _is_from_current_file(self, node): """Checks if the node is in the current file, i.e. not coming from an included file. """ return ( node.location.file is not None and node.location.file.name == self.file_name ) def _try_read_next_include(self, tokens, i): """Tries to read the next include from the given list of tokens, starting at index `i`. :returns: A pair (include or ``None``, next `i`). """ # There are two possible formats: # # (1) # include < FILE > # i i + 1 i + 2 i + 3 i + X # # (2) # include "file" # i i + 1 i + 2 # # where FILE may be composed of identifiers and punctuation (e.g. # "stdio.h" is composed of two identifiers and a punctuation) and X # depends on the number of tokens in FILE. # Try format (1) first. if (i + 4 < len(tokens) and tokens[i].kind == cindex.TokenKind.PUNCTUATION and tokens[i].spelling == '#' and tokens[i + 1].kind == cindex.TokenKind.IDENTIFIER and tokens[i + 1].spelling == 'include' and tokens[i + 2].kind == cindex.TokenKind.PUNCTUATION and tokens[i + 2].spelling == '<'): include_text = '#include ' + tokens[i + 2].spelling i += 3 # for # include ["|<] while (tokens[i].kind != cindex.TokenKind.PUNCTUATION or tokens[i].spelling not in ['"', '>']): include_text += tokens[i].spelling i += 1 include_text += tokens[i].spelling return Include(include_text), i + 1 # Try format (2). elif (i + 2 < len(tokens) and tokens[i].kind == cindex.TokenKind.PUNCTUATION and tokens[i].spelling == '#' and tokens[i + 1].kind == cindex.TokenKind.IDENTIFIER and tokens[i + 1].spelling == 'include' and tokens[i + 2].kind == cindex.TokenKind.LITERAL): include_text = '#include ' + tokens[i + 2].spelling return Include(include_text), i + 3 # No include. return (None, i + 1) def _has_string_literal_value_matching(self, regexp): """Checks if :attr:`string_literal_values` contains a string literal matching the given regular expression. """ for value in self.string_literal_values: if re.fullmatch(regexp, value) is not None: return True return False def _contains_string_literal_matching(self, regexp): """Checks if the module contains a string literal matching the given regular expression by calling :func:`contains()`. """ regexp = self._get_pattern_from(regexp) # We need to correctly handle situations when the regular expression # starts with a caret ('^') or ends with a dollar ('$'). If we did not # do this, the regular expression would not match after we surround it # with quotes. if regexp.startswith('^'): regexp = regexp[1:] if regexp.endswith('$'): regexp = regexp[:-1] return self.contains('"{}"'.format(regexp)) def _get_pattern_from(self, regexp): """Returns the pattern (`str`) from the given regular expression (either `str` or a compiled regular expression). """ # Compiled regular expressions have a 'pattern' attribute containing # the pattern. return regexp.pattern if hasattr(regexp, 'pattern') else regexp def __repr__(self): return '<{} file_name={!r}>'.format( self.__class__.__name__, self.file_name, ) from regression_tests.parsers.c_parser.exprs.literals.string_literal import StringLiteral from regression_tests.parsers.c_parser.exprs.variable import Variable from regression_tests.parsers.c_parser.function import Function
<filename>regression_tests/parsers/c_parser/module.py """ A module (translation unit). """ import io import re import sys from clang import cindex from regression_tests.parsers.c_parser.comment import Comment from regression_tests.parsers.c_parser.include import Include from regression_tests.parsers.c_parser.types.enum_type import EnumType from regression_tests.parsers.c_parser.types.struct_type import StructType from regression_tests.parsers.c_parser.types.union_type import UnionType from regression_tests.parsers.c_parser.utils import get_name from regression_tests.parsers.c_parser.utils import get_parse_errors from regression_tests.parsers.c_parser.utils import get_set_of_names from regression_tests.parsers.c_parser.utils import has_tokens from regression_tests.parsers.c_parser.utils import underline from regression_tests.parsers.c_parser.utils import visit_node from regression_tests.parsers.text_parser import Text from regression_tests.utils import memoize from regression_tests.utils.list import NamedObjectList from regression_tests.utils.list import names_of class Module(Text): """A module (translation unit). The instances of this class behave like strings with additional properties and methods. """ def __new__(cls, code, tu): """Constructs a new parsed C code. :param str code: The original C code. :param clang.TranslationUnit tu: The underlying translation unit. """ c_code = Text.__new__(cls, code) return c_code def __init__(self, code, tu): """ :param str code: The original C code. :param clang.TranslationUnit tu: The underlying translation unit. """ self._code = code self._tu = tu @property def code(self): """The original C code (`str`).""" return self._code @property def file_name(self): """Name of the original source file (`str`).""" return self._tu.spelling def has_parse_errors(self): """Does the module contain some parsing errors?""" parse_errors = get_parse_errors(self._tu.diagnostics) return bool(parse_errors) @property @memoize def global_vars(self): """Global variables (list of :class:`.Variable`). The returned list can be indexed by either positions (0, 1, ...) or names. Example: .. code-block:: python module.global_vars[0] # Returns the first global variable. module.global_vars['g'] # Returns the global variable named 'g'. When there is no such global variable, it raises ``IndexError``. """ var_nodes = filter(self._is_global_var, self._tu.cursor.get_children()) return NamedObjectList(map(Variable, var_nodes)) @property @memoize def global_var_names(self): """Names of the global variables (list of `str`).""" return names_of(self.global_vars) @property def global_var_count(self): """Number of global variables.""" return len(self.global_vars) def has_any_global_vars(self): """Are there any global variables (at least one)?""" return self.global_var_count > 0 def has_global_vars(self, *vars): """Are there given global variables? :param vars: Variable names or instances of :class:`.Variable`. Example: .. code-block:: python module.has_global_vars('g1', 'g2') module.has_global_vars('g1', var1) The order is irrelevant. If you want to check that only the given global variables appear in the module and no other other global variables are present, use :func:`has_global_vars()` instead. If you call this method without any arguments, it checks whether there is at least one global variable in the module: .. code-block:: python module.has_global_vars() """ names = get_set_of_names(vars) if not names: return self.global_var_count > 0 return names.issubset(set(self.global_var_names)) def has_no_global_vars(self): """Are there no global variables?""" return self.global_var_count == 0 def has_just_global_vars(self, *vars): """Are there only specified global variables? :param vars: Variable names or instances of :class:`.Variable`. Example: .. code-block:: python module.has_just_global_vars('g1', 'g2') module.has_just_global_vars('g', var) The order is irrelevant. """ return set(self.global_var_names) == get_set_of_names(vars) def has_global_var(self, var): """Is there specified global variable? :param var: Variable name or instance of :class:`.Variable`. """ return get_name(var) in self.global_var_names @property @memoize def funcs(self): """Functions (list of :class:`.Function`). The returned list can be indexed by either positions (0, 1, ...) or function names. Example: .. code-block:: python module.funcs[0] # Returns the first function. module.funcs['main'] # Returns the function named 'main'. When there is no such function, it raises ``IndexError``. """ func_nodes = filter(self._is_func, self._tu.cursor.get_children()) return NamedObjectList(map(Function, func_nodes)) @property @memoize def func_names(self): """Names of the functions (list of `str`).""" return names_of(self.funcs) @property def func_count(self): """Number of functions.""" return len(self.funcs) def func(self, *functions): """Returns the first function corresponding to an item in `functions`. Names as strings or objects of :class:`.Function` can be used as parameters. This is useful because on x86 + PE, functions may be prefixed with ``_``. Instead of using an if/else (ELF vs PE), you can simply obtain the function in the following way: .. code-block:: python my_func = module.func('my_func', '_my_func') my_func = module.func(foo, '_foo') When there is no such function, it raises ``AssertionError``. """ if not functions: raise AssertionError('at least one function name has to be given') for name in map(get_name, functions): for func in self.funcs: if func.name == name: return func raise AssertionError('no such function') def has_funcs(self, *functions): """Are there given functions? :param functions: Function names or instances of :class:`.Function`. Example: .. code-block:: python module.has_funcs('func1', 'func2') module.has_funcs('func1', foo) The order is irrelevant. If you want to check that only the given functions appear in the module and no other functions, use :func:`has_just_funcs()` instead. If you call this method without any arguments, it checks whether there is at least one function in the module: .. code-block:: python module.has_funcs() """ names = get_set_of_names(functions) if not names: return self.func_count > 0 return names.issubset(set(self.func_names)) def has_no_funcs(self): """Are there no functions?""" return self.func_count == 0 def has_just_funcs(self, *functions): """Are there only given functions? Names as strings or objects of :class:`.Function` can be used as parameters. Example: .. code-block:: python module.has_just_funcs('func1', 'func2') module.has_just_funcs('func1', foo) The order is irrelevant. """ return set(self.func_names) == get_set_of_names(functions) def has_func(self, name): """Is there a function with the given name (`str`)?""" return name in self.func_names def has_func_matching(self, regexp): """Is there a function with a name matching the given regular expression? `regexp` can be either a string or a compiled regular expression. The standard function ``re.fullmatch()`` is used to perform the matching. """ for name in self.func_names: if re.fullmatch(regexp, name) is not None: return True return False @property @memoize def comments(self): """Comments in the code (list of :class:`.Comment`).""" comments = [] for token in self._tu.cursor.get_tokens(): if token.kind == cindex.TokenKind.COMMENT: comments.append(Comment(token.spelling)) return comments def has_comment_matching(self, regexp): """Is there a comment matching the given regular expression? See the description of :func:`~regression_tests.parsers.c_parser.comment.Comment.matches()` for more info. """ for comment in self.comments: if comment.matches(regexp): return True return False @property @memoize def includes(self): """Includes in the code (list of :class:`.Include`). Only direct includes are considered (i.e. nested includes are discarded). """ # We have to iterate through the tokens because # # (1) includes are not available through self._tu.cursor.get_children(), # # (2) file inclusions from self._tu.get_includes() have just # absolute paths to the included files. includes = [] tokens = list(self._tu.cursor.get_tokens()) i = 0 while i < len(tokens): include, i = self._try_read_next_include(tokens, i) if include is not None: includes.append(include) return includes def has_include_of_file(self, file): """Is there an include of the given file (`str`)?""" for include in self.includes: if include.file == file: return True return False @property @memoize def string_literal_values(self): """Returns a set of values of all string literals (a set of `str`).""" values = set() def add_to_values_if_string_literal(node): if node.kind != cindex.CursorKind.STRING_LITERAL: return # There seems to be a bug in clang (cindex) that causes NAN, # which expands to __builtin_nanf, to be considered a string # literal with no tokens. As a workaround, do not consider # nodes without tokens to be valid string literals. if not has_tokens(node): return values.add(StringLiteral(node).value) # We have to visit all the global variables and functions. for node in self._tu.cursor.get_children(): if self._is_func(node) or self._is_global_var(node): visit_node(node, add_to_values_if_string_literal) return values def has_string_literal(self, value): """Is there a string literal of the given value? It searches through the whole module (global variables and function bodies). Example: .. code-block:: python module.has_string_literal('Result is: %d') When the literal is not found in :attr:`string_literal_values`, :func:`~regression_tests.parsers.text_parser.Text.contains()` is called to check whether the literal exists in the module. This behavior is needed because there may be a syntax error near the string literal. In such cases, the literal is not present in the module because the code that contains it is skipped during parsing. """ if value in self.string_literal_values: return True return self.contains('"{}"'.format(re.escape(value))) def has_string_literal_matching(self, regexp): """Is there a string literal matching the given regular expression? `regexp` can be either a string or a compiled regular expression. The standard function ``re.fullmatch()`` is used to perform the matching. When the literal is not found in :attr:`string_literal_values`, :func:`~regression_tests.parsers.text_parser.Text.contains()` is called to check whether a matching literal exists in the module. See the description of :func:`has_string_literal()` for the reason. """ if self._has_string_literal_value_matching(regexp): return True return self._contains_string_literal_matching(regexp) @property @memoize def structs(self): """Structures (list of :class:`.StructType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ struct_nodes = filter(self._is_struct, self._tu.cursor.get_children()) return [StructType(node.type) for node in struct_nodes] @property @memoize def unnamed_structs(self): """Unnamed structures (list of :class:`.StructType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ return [struct for struct in self.structs if not struct.has_name()] @property @memoize def named_structs(self): """Named structures (list of :class:`.StructType`). The returned list can be indexed by either positions (0, 1, ...) or structure names. Example: .. code-block:: python module.named_structs[0] # Returns the first structure. module.named_structs['node'] # Returns the structure named 'node'. When there is no such structure, it raises ``IndexError``. """ return NamedObjectList([x for x in self.structs if x.has_name()]) @property @memoize def struct_names(self): """Names of the structures (list of `str`).""" return names_of(self.named_structs) @property def struct_count(self): """Number of structures.""" return len(self.structs) @property def unnamed_struct_count(self): """Number of unnamed structures.""" return len(self.unnamed_structs) @property def named_struct_count(self): """Number of named structures.""" return len(self.named_structs) def has_any_structs(self): """Are there any structures (at least one)?""" return self.struct_count > 0 def has_any_unnamed_structs(self): """Are there any unnamed structures (at least one)?""" return self.unnamed_struct_count > 0 def has_any_named_structs(self): """Are there any named structures (at least one)?""" return self.named_struct_count > 0 def has_named_structs(self, *structs): """Are there given named structures? :param structs: Structure names or instances of :class:`.StructType`. Example: .. code-block:: python module.has_named_structs('s1', 's2') module.has_named_structs('s1', struct) The order is irrelevant. If you want to check that only the given named structures appear in the module and no other named structures are present, use :func:`has_just_named_structs()` instead. If you call this method without any arguments, it checks whether there is at least one struct in the module: .. code-block:: python module.has_named_structs() """ names = get_set_of_names(structs) if not names: return self.has_any_named_structs() return names.issubset(set(self.struct_names)) def has_no_structs(self): """Are there no structures?""" return self.struct_count == 0 def has_no_unnamed_structs(self): """Are there no unnamed structures?""" return self.unnamed_struct_count == 0 def has_no_named_structs(self): """Are there no named structures?""" return self.named_struct_count == 0 def has_just_named_structs(self, *structs): """Are there only given named structures? :param structs: Structure names or instances of :class:`.StructType`. Example: .. code-block:: python module.has_just_named_structs('s1', 's2') module.has_just_named_structs('s1', struct) The order is irrelevant. """ return set(self.struct_names) == get_set_of_names(structs) def has_named_struct(self, struct): """Is there specified named structure? :param struct: Structure name or instance of :class:`.StructType`. """ return get_name(struct) in self.struct_names @property @memoize def unions(self): """Unions (list of :class:`.UnionType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ union_nodes = filter(self._is_union, self._tu.cursor.get_children()) return [UnionType(node.type) for node in union_nodes] @property @memoize def unnamed_unions(self): """Unnamed unions (list of :class:`.UnionType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ return [union for union in self.unions if not union.has_name()] @property @memoize def named_unions(self): """Named unions (list of :class:`.UnionType`). The returned list can be indexed by either positions (0, 1, ...) or union names. Example: .. code-block:: python module.named_unions[0] # Returns the first union. module.named_unions['node'] # Returns the union named 'node'. When there is no such union, it raises ``IndexError``. """ return NamedObjectList([x for x in self.unions if x.has_name()]) @property @memoize def union_names(self): """Names of the unions (list of `str`).""" return names_of(self.named_unions) @property def union_count(self): """Number of unions.""" return len(self.unions) @property def unnamed_union_count(self): """Number of unnamed unions.""" return len(self.unnamed_unions) @property def named_union_count(self): """Number of named unions.""" return len(self.named_unions) def has_any_unions(self): """Are there any unions (at least one)?""" return self.union_count > 0 def has_any_unnamed_unions(self): """Are there any unnamed unions (at least one)?""" return self.unnamed_union_count > 0 def has_any_named_unions(self): """Are there any named unions (at least one)?""" return self.named_union_count > 0 def has_named_unions(self, *unions): """Are there given named unions? :param unions: Union names or instances of :class:`.UnionType`. Example: .. code-block:: python module.has_named_unions('u1', 'u2') module.has_named_unions('u1', union) The order is irrelevant. If you want to check that only the given named unions appear in the module and no other named unions are present, use :func:`has_just_named_unions()` instead. If you call this method without any arguments, it checks whether there is at least one union in the module: .. code-block:: python module.has_named_unions() """ names = get_set_of_names(unions) if not names: return self.has_any_named_unions() return names.issubset(set(self.union_names)) def has_no_unions(self): """Are there no unions?""" return self.union_count == 0 def has_no_unnamed_unions(self): """Are there no unnamed unions?""" return self.unnamed_union_count == 0 def has_no_named_unions(self): """Are there no named unions?""" return self.named_union_count == 0 def has_just_named_unions(self, *unions): """Are there only given named unions? :param unions: Union names or instances of :class:`.UnionType`. Example: .. code-block:: python module.has_just_named_unions('u1', 'u2') module.has_just_named_unions('u1', union) The order is irrelevant. """ return set(self.union_names) == get_set_of_names(unions) def has_named_union(self, union): """Is there specified named union? :param union: Union name or instance of :class:`.UnionType`. """ return get_name(union) in self.union_names @property @memoize def enums(self): """Enums (list of :class:`.EnumType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ enum_nodes = filter(self._is_enum, self._tu.cursor.get_children()) return [EnumType(node.type, node) for node in enum_nodes] @property @memoize def unnamed_enums(self): """Unnamed enums (list of :class:`.EnumType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. """ return [enum for enum in self.enums if not enum.has_name()] @property @memoize def named_enums(self): """Named enums (list of :class:`.EnumType`). The returned list can be indexed by either positions (0, 1, ...) or enum names. Example: .. code-block:: python module.named_enums[0] # Returns the first enum. module.named_enums['node'] # Returns the enum named 'node'. When there is no such enum, it raises ``IndexError``. """ return NamedObjectList([x for x in self.enums if x.has_name()]) @property @memoize def enum_names(self): """Names of the enums (list of `str`).""" return names_of(self.named_enums) @property def enum_count(self): """Number of enums.""" return len(self.enums) @property def unnamed_enum_count(self): """Number of unnamed enums.""" return len(self.unnamed_enums) @property def named_enum_count(self): """Number of named enums.""" return len(self.named_enums) def has_any_enums(self): """Are there any enums (at least one)?""" return self.enum_count > 0 def has_any_unnamed_enums(self): """Are there any unnamed enums (at least one)?""" return self.unnamed_enum_count > 0 def has_any_named_enums(self): """Are there any named enums (at least one)?""" return self.named_enum_count > 0 def has_named_enums(self, *enums): """Are there given named enums? :param enums: Enum names or instances of :class:`.EnumType`. Example: .. code-block:: python module.has_named_enums('e1', 'e2') module.has_named_enums('e1', enum) The order is irrelevant. If you want to check that only the given named enums appear in the module and no other named enums are present, use :func:`has_just_named_enums()` instead. If you call this method without any arguments, it checks whether there is at least one enum in the module: .. code-block:: python module.has_named_enums() """ names = get_set_of_names(enums) if not names: return self.has_any_named_enums() return names.issubset(set(self.enum_names)) def has_no_enums(self): """Are there no enums?""" return self.enum_count == 0 def has_no_unnamed_enums(self): """Are there no unnamed enums?""" return self.unnamed_enum_count == 0 def has_no_named_enums(self): """Are there no named enums?""" return self.named_enum_count == 0 def has_just_named_enums(self, *enums): """Are there only given named enums? :param enums: Enum names or instances of :class:`.EnumType`. Example: .. code-block:: python module.has_just_named_enums('e1', 'e2') module.has_just_named_enums('e1', enum) The order is irrelevant. """ return set(self.enum_names) == get_set_of_names(enums) def has_named_enum(self, enum): """Is there specified named enum? :param enum: Enum name or instance of :class:`.EnumType`. """ return get_name(enum) in self.enum_names @property @memoize def enum_item_names(self): """Items in enums (list of `str`).""" enum_item_names = [] for node in self._tu.cursor.get_children(): if self._is_enum(node): enum = EnumType(node.type, node) enum_item_names += enum.item_names return enum_item_names @property def enum_item_count(self): """Sum of item in all enums in module.""" return len(self.enum_item_names) @property def empty_enums(self): """Empty enums (list of :class:`.EnumType`).""" return [enum for enum in self.enums if enum.is_empty()] @property def empty_enum_count(self): """Number of empty enums.""" return len(self.empty_enums) def has_any_empty_enums(self): """Are there any empty enums (at least one)?""" return self.empty_enum_count > 0 def has_no_empty_enums(self): """Are there no empty enums?""" return self.empty_enum_count == 0 def dump(self, verbose=False): """Dumps information about the module to ``stdout``. The dumped content is same as for :func:`dump_to()`. :param verbose: Add dumps of functions? """ self.dump_to(sys.stdout, verbose) def dump_to(self, stream, verbose=False): """Dumps information about the module to `stream`. :param stream: Stream to dump information to. :param verbose: Add dumps of functions? Content: * includes * global variables * structures * unions * enums * functions * string literals """ s = [] s.append(self.file_name) s.append('') s.append(underline('Includes:')) s.extend(map(str, self.includes)) s.append('') s.append(underline('Global vars:')) s.extend(map(lambda gv: gv.str_with_type(), self.global_vars)) s.append('') s.append(underline('Structs:')) s.extend(map(str, self.structs)) s.append('') s.append(underline('Unions:')) s.extend(map(str, self.unions)) s.append('') s.append(underline('Enums:')) s.extend(map(str, self.enums)) s.append('') s.append(underline('Functions:')) s.extend(map(str, self.funcs)) s.append('') s.append(underline('String literals:')) s.extend(self.string_literal_values) s.append('') if verbose and self.has_funcs(): for func in self.funcs: header = 'Dump of {}:'.format(func.name) s.append(header) s.append('=' * len(header)) with io.StringIO() as func_stream: func.dump_to(func_stream) s.append(func_stream.getvalue()) stream.write('\n'.join(s)) def _is_global_var(self, node): """Checks if the given node is a global variable. External global variables (coming from included headers) are not considered to be global variables. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.VAR_DECL ) def _is_func(self, node): """Checks if the given node is a function. External functions or function declarations are not considered to be functions. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.FUNCTION_DECL and node.is_definition() ) def _is_struct(self, node): """Checks if the given node is a structure. External structures (coming from included headers) are not considered to be structures. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.STRUCT_DECL ) def _is_union(self, node): """Checks if the given node is a union. External unions (coming from included headers) are not considered to be unions. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.UNION_DECL ) def _is_enum(self, node): """Checks if the given node is an enum. External enums (coming from included headers) are not considered to be enums. """ return ( self._is_from_current_file(node) and node.kind == cindex.CursorKind.ENUM_DECL ) def _is_from_current_file(self, node): """Checks if the node is in the current file, i.e. not coming from an included file. """ return ( node.location.file is not None and node.location.file.name == self.file_name ) def _try_read_next_include(self, tokens, i): """Tries to read the next include from the given list of tokens, starting at index `i`. :returns: A pair (include or ``None``, next `i`). """ # There are two possible formats: # # (1) # include < FILE > # i i + 1 i + 2 i + 3 i + X # # (2) # include "file" # i i + 1 i + 2 # # where FILE may be composed of identifiers and punctuation (e.g. # "stdio.h" is composed of two identifiers and a punctuation) and X # depends on the number of tokens in FILE. # Try format (1) first. if (i + 4 < len(tokens) and tokens[i].kind == cindex.TokenKind.PUNCTUATION and tokens[i].spelling == '#' and tokens[i + 1].kind == cindex.TokenKind.IDENTIFIER and tokens[i + 1].spelling == 'include' and tokens[i + 2].kind == cindex.TokenKind.PUNCTUATION and tokens[i + 2].spelling == '<'): include_text = '#include ' + tokens[i + 2].spelling i += 3 # for # include ["|<] while (tokens[i].kind != cindex.TokenKind.PUNCTUATION or tokens[i].spelling not in ['"', '>']): include_text += tokens[i].spelling i += 1 include_text += tokens[i].spelling return Include(include_text), i + 1 # Try format (2). elif (i + 2 < len(tokens) and tokens[i].kind == cindex.TokenKind.PUNCTUATION and tokens[i].spelling == '#' and tokens[i + 1].kind == cindex.TokenKind.IDENTIFIER and tokens[i + 1].spelling == 'include' and tokens[i + 2].kind == cindex.TokenKind.LITERAL): include_text = '#include ' + tokens[i + 2].spelling return Include(include_text), i + 3 # No include. return (None, i + 1) def _has_string_literal_value_matching(self, regexp): """Checks if :attr:`string_literal_values` contains a string literal matching the given regular expression. """ for value in self.string_literal_values: if re.fullmatch(regexp, value) is not None: return True return False def _contains_string_literal_matching(self, regexp): """Checks if the module contains a string literal matching the given regular expression by calling :func:`contains()`. """ regexp = self._get_pattern_from(regexp) # We need to correctly handle situations when the regular expression # starts with a caret ('^') or ends with a dollar ('$'). If we did not # do this, the regular expression would not match after we surround it # with quotes. if regexp.startswith('^'): regexp = regexp[1:] if regexp.endswith('$'): regexp = regexp[:-1] return self.contains('"{}"'.format(regexp)) def _get_pattern_from(self, regexp): """Returns the pattern (`str`) from the given regular expression (either `str` or a compiled regular expression). """ # Compiled regular expressions have a 'pattern' attribute containing # the pattern. return regexp.pattern if hasattr(regexp, 'pattern') else regexp def __repr__(self): return '<{} file_name={!r}>'.format( self.__class__.__name__, self.file_name, ) from regression_tests.parsers.c_parser.exprs.literals.string_literal import StringLiteral from regression_tests.parsers.c_parser.exprs.variable import Variable from regression_tests.parsers.c_parser.function import Function
en
0.631625
A module (translation unit). A module (translation unit). The instances of this class behave like strings with additional properties and methods. Constructs a new parsed C code. :param str code: The original C code. :param clang.TranslationUnit tu: The underlying translation unit. :param str code: The original C code. :param clang.TranslationUnit tu: The underlying translation unit. The original C code (`str`). Name of the original source file (`str`). Does the module contain some parsing errors? Global variables (list of :class:`.Variable`). The returned list can be indexed by either positions (0, 1, ...) or names. Example: .. code-block:: python module.global_vars[0] # Returns the first global variable. module.global_vars['g'] # Returns the global variable named 'g'. When there is no such global variable, it raises ``IndexError``. Names of the global variables (list of `str`). Number of global variables. Are there any global variables (at least one)? Are there given global variables? :param vars: Variable names or instances of :class:`.Variable`. Example: .. code-block:: python module.has_global_vars('g1', 'g2') module.has_global_vars('g1', var1) The order is irrelevant. If you want to check that only the given global variables appear in the module and no other other global variables are present, use :func:`has_global_vars()` instead. If you call this method without any arguments, it checks whether there is at least one global variable in the module: .. code-block:: python module.has_global_vars() Are there no global variables? Are there only specified global variables? :param vars: Variable names or instances of :class:`.Variable`. Example: .. code-block:: python module.has_just_global_vars('g1', 'g2') module.has_just_global_vars('g', var) The order is irrelevant. Is there specified global variable? :param var: Variable name or instance of :class:`.Variable`. Functions (list of :class:`.Function`). The returned list can be indexed by either positions (0, 1, ...) or function names. Example: .. code-block:: python module.funcs[0] # Returns the first function. module.funcs['main'] # Returns the function named 'main'. When there is no such function, it raises ``IndexError``. Names of the functions (list of `str`). Number of functions. Returns the first function corresponding to an item in `functions`. Names as strings or objects of :class:`.Function` can be used as parameters. This is useful because on x86 + PE, functions may be prefixed with ``_``. Instead of using an if/else (ELF vs PE), you can simply obtain the function in the following way: .. code-block:: python my_func = module.func('my_func', '_my_func') my_func = module.func(foo, '_foo') When there is no such function, it raises ``AssertionError``. Are there given functions? :param functions: Function names or instances of :class:`.Function`. Example: .. code-block:: python module.has_funcs('func1', 'func2') module.has_funcs('func1', foo) The order is irrelevant. If you want to check that only the given functions appear in the module and no other functions, use :func:`has_just_funcs()` instead. If you call this method without any arguments, it checks whether there is at least one function in the module: .. code-block:: python module.has_funcs() Are there no functions? Are there only given functions? Names as strings or objects of :class:`.Function` can be used as parameters. Example: .. code-block:: python module.has_just_funcs('func1', 'func2') module.has_just_funcs('func1', foo) The order is irrelevant. Is there a function with the given name (`str`)? Is there a function with a name matching the given regular expression? `regexp` can be either a string or a compiled regular expression. The standard function ``re.fullmatch()`` is used to perform the matching. Comments in the code (list of :class:`.Comment`). Is there a comment matching the given regular expression? See the description of :func:`~regression_tests.parsers.c_parser.comment.Comment.matches()` for more info. Includes in the code (list of :class:`.Include`). Only direct includes are considered (i.e. nested includes are discarded). # We have to iterate through the tokens because # # (1) includes are not available through self._tu.cursor.get_children(), # # (2) file inclusions from self._tu.get_includes() have just # absolute paths to the included files. Is there an include of the given file (`str`)? Returns a set of values of all string literals (a set of `str`). # There seems to be a bug in clang (cindex) that causes NAN, # which expands to __builtin_nanf, to be considered a string # literal with no tokens. As a workaround, do not consider # nodes without tokens to be valid string literals. # We have to visit all the global variables and functions. Is there a string literal of the given value? It searches through the whole module (global variables and function bodies). Example: .. code-block:: python module.has_string_literal('Result is: %d') When the literal is not found in :attr:`string_literal_values`, :func:`~regression_tests.parsers.text_parser.Text.contains()` is called to check whether the literal exists in the module. This behavior is needed because there may be a syntax error near the string literal. In such cases, the literal is not present in the module because the code that contains it is skipped during parsing. Is there a string literal matching the given regular expression? `regexp` can be either a string or a compiled regular expression. The standard function ``re.fullmatch()`` is used to perform the matching. When the literal is not found in :attr:`string_literal_values`, :func:`~regression_tests.parsers.text_parser.Text.contains()` is called to check whether a matching literal exists in the module. See the description of :func:`has_string_literal()` for the reason. Structures (list of :class:`.StructType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. Unnamed structures (list of :class:`.StructType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. Named structures (list of :class:`.StructType`). The returned list can be indexed by either positions (0, 1, ...) or structure names. Example: .. code-block:: python module.named_structs[0] # Returns the first structure. module.named_structs['node'] # Returns the structure named 'node'. When there is no such structure, it raises ``IndexError``. Names of the structures (list of `str`). Number of structures. Number of unnamed structures. Number of named structures. Are there any structures (at least one)? Are there any unnamed structures (at least one)? Are there any named structures (at least one)? Are there given named structures? :param structs: Structure names or instances of :class:`.StructType`. Example: .. code-block:: python module.has_named_structs('s1', 's2') module.has_named_structs('s1', struct) The order is irrelevant. If you want to check that only the given named structures appear in the module and no other named structures are present, use :func:`has_just_named_structs()` instead. If you call this method without any arguments, it checks whether there is at least one struct in the module: .. code-block:: python module.has_named_structs() Are there no structures? Are there no unnamed structures? Are there no named structures? Are there only given named structures? :param structs: Structure names or instances of :class:`.StructType`. Example: .. code-block:: python module.has_just_named_structs('s1', 's2') module.has_just_named_structs('s1', struct) The order is irrelevant. Is there specified named structure? :param struct: Structure name or instance of :class:`.StructType`. Unions (list of :class:`.UnionType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. Unnamed unions (list of :class:`.UnionType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. Named unions (list of :class:`.UnionType`). The returned list can be indexed by either positions (0, 1, ...) or union names. Example: .. code-block:: python module.named_unions[0] # Returns the first union. module.named_unions['node'] # Returns the union named 'node'. When there is no such union, it raises ``IndexError``. Names of the unions (list of `str`). Number of unions. Number of unnamed unions. Number of named unions. Are there any unions (at least one)? Are there any unnamed unions (at least one)? Are there any named unions (at least one)? Are there given named unions? :param unions: Union names or instances of :class:`.UnionType`. Example: .. code-block:: python module.has_named_unions('u1', 'u2') module.has_named_unions('u1', union) The order is irrelevant. If you want to check that only the given named unions appear in the module and no other named unions are present, use :func:`has_just_named_unions()` instead. If you call this method without any arguments, it checks whether there is at least one union in the module: .. code-block:: python module.has_named_unions() Are there no unions? Are there no unnamed unions? Are there no named unions? Are there only given named unions? :param unions: Union names or instances of :class:`.UnionType`. Example: .. code-block:: python module.has_just_named_unions('u1', 'u2') module.has_just_named_unions('u1', union) The order is irrelevant. Is there specified named union? :param union: Union name or instance of :class:`.UnionType`. Enums (list of :class:`.EnumType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. Unnamed enums (list of :class:`.EnumType`). The returned type is plain list, not :class:`~regression_tests.utils.list.NamedObjectList`. Named enums (list of :class:`.EnumType`). The returned list can be indexed by either positions (0, 1, ...) or enum names. Example: .. code-block:: python module.named_enums[0] # Returns the first enum. module.named_enums['node'] # Returns the enum named 'node'. When there is no such enum, it raises ``IndexError``. Names of the enums (list of `str`). Number of enums. Number of unnamed enums. Number of named enums. Are there any enums (at least one)? Are there any unnamed enums (at least one)? Are there any named enums (at least one)? Are there given named enums? :param enums: Enum names or instances of :class:`.EnumType`. Example: .. code-block:: python module.has_named_enums('e1', 'e2') module.has_named_enums('e1', enum) The order is irrelevant. If you want to check that only the given named enums appear in the module and no other named enums are present, use :func:`has_just_named_enums()` instead. If you call this method without any arguments, it checks whether there is at least one enum in the module: .. code-block:: python module.has_named_enums() Are there no enums? Are there no unnamed enums? Are there no named enums? Are there only given named enums? :param enums: Enum names or instances of :class:`.EnumType`. Example: .. code-block:: python module.has_just_named_enums('e1', 'e2') module.has_just_named_enums('e1', enum) The order is irrelevant. Is there specified named enum? :param enum: Enum name or instance of :class:`.EnumType`. Items in enums (list of `str`). Sum of item in all enums in module. Empty enums (list of :class:`.EnumType`). Number of empty enums. Are there any empty enums (at least one)? Are there no empty enums? Dumps information about the module to ``stdout``. The dumped content is same as for :func:`dump_to()`. :param verbose: Add dumps of functions? Dumps information about the module to `stream`. :param stream: Stream to dump information to. :param verbose: Add dumps of functions? Content: * includes * global variables * structures * unions * enums * functions * string literals Checks if the given node is a global variable. External global variables (coming from included headers) are not considered to be global variables. Checks if the given node is a function. External functions or function declarations are not considered to be functions. Checks if the given node is a structure. External structures (coming from included headers) are not considered to be structures. Checks if the given node is a union. External unions (coming from included headers) are not considered to be unions. Checks if the given node is an enum. External enums (coming from included headers) are not considered to be enums. Checks if the node is in the current file, i.e. not coming from an included file. Tries to read the next include from the given list of tokens, starting at index `i`. :returns: A pair (include or ``None``, next `i`). # There are two possible formats: # # (1) # include < FILE > # i i + 1 i + 2 i + 3 i + X # # (2) # include "file" # i i + 1 i + 2 # # where FILE may be composed of identifiers and punctuation (e.g. # "stdio.h" is composed of two identifiers and a punctuation) and X # depends on the number of tokens in FILE. # Try format (1) first. # for # include ["|<] # Try format (2). # No include. Checks if :attr:`string_literal_values` contains a string literal matching the given regular expression. Checks if the module contains a string literal matching the given regular expression by calling :func:`contains()`. # We need to correctly handle situations when the regular expression # starts with a caret ('^') or ends with a dollar ('$'). If we did not # do this, the regular expression would not match after we surround it # with quotes. Returns the pattern (`str`) from the given regular expression (either `str` or a compiled regular expression). # Compiled regular expressions have a 'pattern' attribute containing # the pattern.
2.289425
2
paperA/lbfgs_routine.py
sixin-zh/kymatio_wph
0
6615509
import os,gc import numpy as np import scipy.optimize as opt import scipy.io as sio import torch from torch.autograd import Variable, grad # ---- Reconstruct marks. At initiation, every point has the average value of the marks.----# #---- Trying scipy L-BFGS ----# def obj_fun(x,wph_ops,factr_ops,Sims,op_id): if x.grad is not None: x.grad.data.zero_() wph_op = wph_ops[op_id] p = wph_op(x) diff = p-Sims[op_id] diff = diff * factr_ops[op_id] loss = torch.mul(diff,diff).sum() return loss def grad_obj_fun(x_gpu,grad_err,wph_ops,factr_ops,Sims): loss = 0 grad_err[:] = 0 for op_id in range(len(wph_ops)): x_t = x_gpu.clone().requires_grad_(True) # TODO loss_t = obj_fun(x_t,wph_ops,factr_ops,Sims,op_id) grad_err_t, = grad([loss_t],[x_t], retain_graph=False) loss = loss + loss_t grad_err = grad_err + grad_err_t return loss, grad_err from time import time def fun_and_grad_conv(x,grad_err,wph_ops,factr_ops,Sims,size): x_float = torch.reshape(torch.tensor(x,dtype=torch.float),(1,1,size,size)) x_gpu = x_float.cuda() # TODO loss, grad_err = grad_obj_fun(x_gpu,grad_err,wph_ops,factr_ops,Sims) return loss.cpu().item(), np.asarray(grad_err.reshape(size**2).cpu().numpy(), dtype=np.float64) def callback_print(x): return def call_lbfgs_routine(FOLOUT,labelname,im,wph_ops,Sims,N,Krec,nb_restarts,maxite,factr,factr_ops,\ maxcor=20,gtol=1e-14,ftol=1e-14,init='normal',toskip=True): grad_err = im.clone() size = N for krec in range(Krec): if init=='normal': print('init normal') x = torch.Tensor(1, 1, N, N).normal_() elif init=='normal00105': print('init normal00105') x = torch.Tensor(1, 1, N, N).normal_(std=0.01)+0.5 elif "maxent" in init: print('load init from ' + init) xinit = sio.loadmat('./data/maxent/' + init + '.mat') x = torch.from_numpy(xinit['imgs'][:,:,krec]) # .shape) #assert(false) elif init=='normalstdbarx': stdbarx = im.std() print('init normal with std barx ' + str(stdbarx)) x = torch.Tensor(1, 1, N, N).normal_(std=stdbarx) else: assert(false) x0 = x.reshape(size**2).numpy() x0 = np.asarray(x0, dtype=np.float64) x_opt = None for start in range(nb_restarts+1): time0 = time() datname = FOLOUT + '/' + labelname + '_krec' + str(krec) + '_start' + str(start) + '.pt' if os.path.isfile(datname) and toskip: print('skip', datname) continue else: print('save to',datname) if start==0: x_opt = x0 elif x_opt is None: # load from previous saved file prename = FOLOUT + '/' + labelname + '_krec' + str(krec) + '_start' + str(start-1) + '.pt' print('load x_opt from',prename) saved_result = torch.load(prename) im_opt = saved_result['tensor_opt'].numpy() x_opt = im_opt.reshape(size**2) x_opt = np.asarray(x_opt,dtype=np.float64) res = opt.minimize(fun_and_grad_conv, x_opt,args=(grad_err,wph_ops,factr_ops,Sims,size),\ method='L-BFGS-B', jac=True, tol=None,\ callback=callback_print,\ options={'maxiter': maxite, 'gtol': gtol, 'ftol': ftol, 'maxcor': maxcor}) final_loss, x_opt, niter, msg = res['fun'], res['x'], res['nit'], res['message'] print('OPT fini avec:', final_loss,niter,msg) im_opt = np.reshape(x_opt, (size,size)) tensor_opt = torch.tensor(im_opt, dtype=torch.float).unsqueeze(0).unsqueeze(0) ret = dict() ret['tensor_opt'] = tensor_opt ret['normalized_loss'] = final_loss/(factr**2) torch.save(ret, datname) gc.collect() print('krec',krec,'strat', start, 'using time (sec):' , time()-time0) time0 = time()
import os,gc import numpy as np import scipy.optimize as opt import scipy.io as sio import torch from torch.autograd import Variable, grad # ---- Reconstruct marks. At initiation, every point has the average value of the marks.----# #---- Trying scipy L-BFGS ----# def obj_fun(x,wph_ops,factr_ops,Sims,op_id): if x.grad is not None: x.grad.data.zero_() wph_op = wph_ops[op_id] p = wph_op(x) diff = p-Sims[op_id] diff = diff * factr_ops[op_id] loss = torch.mul(diff,diff).sum() return loss def grad_obj_fun(x_gpu,grad_err,wph_ops,factr_ops,Sims): loss = 0 grad_err[:] = 0 for op_id in range(len(wph_ops)): x_t = x_gpu.clone().requires_grad_(True) # TODO loss_t = obj_fun(x_t,wph_ops,factr_ops,Sims,op_id) grad_err_t, = grad([loss_t],[x_t], retain_graph=False) loss = loss + loss_t grad_err = grad_err + grad_err_t return loss, grad_err from time import time def fun_and_grad_conv(x,grad_err,wph_ops,factr_ops,Sims,size): x_float = torch.reshape(torch.tensor(x,dtype=torch.float),(1,1,size,size)) x_gpu = x_float.cuda() # TODO loss, grad_err = grad_obj_fun(x_gpu,grad_err,wph_ops,factr_ops,Sims) return loss.cpu().item(), np.asarray(grad_err.reshape(size**2).cpu().numpy(), dtype=np.float64) def callback_print(x): return def call_lbfgs_routine(FOLOUT,labelname,im,wph_ops,Sims,N,Krec,nb_restarts,maxite,factr,factr_ops,\ maxcor=20,gtol=1e-14,ftol=1e-14,init='normal',toskip=True): grad_err = im.clone() size = N for krec in range(Krec): if init=='normal': print('init normal') x = torch.Tensor(1, 1, N, N).normal_() elif init=='normal00105': print('init normal00105') x = torch.Tensor(1, 1, N, N).normal_(std=0.01)+0.5 elif "maxent" in init: print('load init from ' + init) xinit = sio.loadmat('./data/maxent/' + init + '.mat') x = torch.from_numpy(xinit['imgs'][:,:,krec]) # .shape) #assert(false) elif init=='normalstdbarx': stdbarx = im.std() print('init normal with std barx ' + str(stdbarx)) x = torch.Tensor(1, 1, N, N).normal_(std=stdbarx) else: assert(false) x0 = x.reshape(size**2).numpy() x0 = np.asarray(x0, dtype=np.float64) x_opt = None for start in range(nb_restarts+1): time0 = time() datname = FOLOUT + '/' + labelname + '_krec' + str(krec) + '_start' + str(start) + '.pt' if os.path.isfile(datname) and toskip: print('skip', datname) continue else: print('save to',datname) if start==0: x_opt = x0 elif x_opt is None: # load from previous saved file prename = FOLOUT + '/' + labelname + '_krec' + str(krec) + '_start' + str(start-1) + '.pt' print('load x_opt from',prename) saved_result = torch.load(prename) im_opt = saved_result['tensor_opt'].numpy() x_opt = im_opt.reshape(size**2) x_opt = np.asarray(x_opt,dtype=np.float64) res = opt.minimize(fun_and_grad_conv, x_opt,args=(grad_err,wph_ops,factr_ops,Sims,size),\ method='L-BFGS-B', jac=True, tol=None,\ callback=callback_print,\ options={'maxiter': maxite, 'gtol': gtol, 'ftol': ftol, 'maxcor': maxcor}) final_loss, x_opt, niter, msg = res['fun'], res['x'], res['nit'], res['message'] print('OPT fini avec:', final_loss,niter,msg) im_opt = np.reshape(x_opt, (size,size)) tensor_opt = torch.tensor(im_opt, dtype=torch.float).unsqueeze(0).unsqueeze(0) ret = dict() ret['tensor_opt'] = tensor_opt ret['normalized_loss'] = final_loss/(factr**2) torch.save(ret, datname) gc.collect() print('krec',krec,'strat', start, 'using time (sec):' , time()-time0) time0 = time()
en
0.602035
# ---- Reconstruct marks. At initiation, every point has the average value of the marks.----# #---- Trying scipy L-BFGS ----# # TODO # TODO # .shape) #assert(false) # load from previous saved file
2.077132
2
src/fosslight_source/run_scanoss.py
fosslight/fosslight_source
20
6615510
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2020 LG Electronics Inc. # SPDX-License-Identifier: Apache-2.0 import os import pkg_resources import warnings import logging import json from datetime import datetime import fosslight_util.constant as constant from fosslight_util.set_log import init_log from fosslight_util.output_format import check_output_format # , write_output_file from ._parsing_scanoss_file import parsing_scanResult # scanoss # from ._help import print_help_msg_source logger = logging.getLogger(constant.LOGGER_NAME) warnings.filterwarnings("ignore", category=FutureWarning) _PKG_NAME = "fosslight_source" def run_scanoss_py(path_to_scan, output_file_name="", format="", called_by_cli=False, write_json_file=False, num_threads=-1): """ Run scanoss.py for the given path. :param path_to_scan: path of sourcecode to scan. :param output_file_name: file name for the output. :param format: Output file format (not being used except when calling check_output_format). :param called_by_cli: if not called by cli, initialize logger. :param write_json_file: if requested, keep the raw files. :return scanoss_file_list: list of ScanItem (scanned result by files). """ if not called_by_cli: global logger scanoss_file_list = [] try: pkg_resources.get_distribution("scanoss") except Exception as error: logger.warning(str(error) + ". Skipping scan with scanoss.") return scanoss_file_list scan_command = "scanoss-py scan -o " start_time = datetime.now().strftime('%Y%m%d_%H%M%S') success, msg, output_path, output_file, output_extension = check_output_format(output_file_name, format) if not called_by_cli: logger, _result_log = init_log(os.path.join(output_path, "fosslight_src_log_"+start_time+".txt"), True, logging.INFO, logging.DEBUG, _PKG_NAME, path_to_scan) if output_path == "": # if json output with _write_json_file not used, output_path won't be needed. output_path = os.getcwd() else: output_path = os.path.abspath(output_path) output_file = "scanoss_raw_result.json" output_json_file = os.path.join(output_path, output_file) scan_command += output_json_file + " " + path_to_scan if num_threads > 0: scan_command += " -T " + str(num_threads) else: scan_command += " -T " + "30" try: os.system(scan_command) st_json = open(output_json_file, "r") logger.info("SCANOSS Start parsing " + path_to_scan) with open(output_json_file, "r") as st_json: st_python = json.load(st_json) scanoss_file_list = parsing_scanResult(st_python) except Exception as error: logger.warning("Parsing " + path_to_scan + ":" + str(error)) logger.info("|---Number of files detected with SCANOSS: " + str(len(scanoss_file_list))) if not write_json_file: try: os.system("rm " + output_json_file) os.system("rm scanner_output.wfp") except Exception as error: logger.debug("Deleting scanoss result failed.:" + str(error)) else: try: os.system("mv scanner_output.wfp " + output_path + "/scanoss_fingerprint.wfp") except Exception as error: logger.debug("Moving scanoss fingerprint file failed.:" + str(error)) return scanoss_file_list
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2020 LG Electronics Inc. # SPDX-License-Identifier: Apache-2.0 import os import pkg_resources import warnings import logging import json from datetime import datetime import fosslight_util.constant as constant from fosslight_util.set_log import init_log from fosslight_util.output_format import check_output_format # , write_output_file from ._parsing_scanoss_file import parsing_scanResult # scanoss # from ._help import print_help_msg_source logger = logging.getLogger(constant.LOGGER_NAME) warnings.filterwarnings("ignore", category=FutureWarning) _PKG_NAME = "fosslight_source" def run_scanoss_py(path_to_scan, output_file_name="", format="", called_by_cli=False, write_json_file=False, num_threads=-1): """ Run scanoss.py for the given path. :param path_to_scan: path of sourcecode to scan. :param output_file_name: file name for the output. :param format: Output file format (not being used except when calling check_output_format). :param called_by_cli: if not called by cli, initialize logger. :param write_json_file: if requested, keep the raw files. :return scanoss_file_list: list of ScanItem (scanned result by files). """ if not called_by_cli: global logger scanoss_file_list = [] try: pkg_resources.get_distribution("scanoss") except Exception as error: logger.warning(str(error) + ". Skipping scan with scanoss.") return scanoss_file_list scan_command = "scanoss-py scan -o " start_time = datetime.now().strftime('%Y%m%d_%H%M%S') success, msg, output_path, output_file, output_extension = check_output_format(output_file_name, format) if not called_by_cli: logger, _result_log = init_log(os.path.join(output_path, "fosslight_src_log_"+start_time+".txt"), True, logging.INFO, logging.DEBUG, _PKG_NAME, path_to_scan) if output_path == "": # if json output with _write_json_file not used, output_path won't be needed. output_path = os.getcwd() else: output_path = os.path.abspath(output_path) output_file = "scanoss_raw_result.json" output_json_file = os.path.join(output_path, output_file) scan_command += output_json_file + " " + path_to_scan if num_threads > 0: scan_command += " -T " + str(num_threads) else: scan_command += " -T " + "30" try: os.system(scan_command) st_json = open(output_json_file, "r") logger.info("SCANOSS Start parsing " + path_to_scan) with open(output_json_file, "r") as st_json: st_python = json.load(st_json) scanoss_file_list = parsing_scanResult(st_python) except Exception as error: logger.warning("Parsing " + path_to_scan + ":" + str(error)) logger.info("|---Number of files detected with SCANOSS: " + str(len(scanoss_file_list))) if not write_json_file: try: os.system("rm " + output_json_file) os.system("rm scanner_output.wfp") except Exception as error: logger.debug("Deleting scanoss result failed.:" + str(error)) else: try: os.system("mv scanner_output.wfp " + output_path + "/scanoss_fingerprint.wfp") except Exception as error: logger.debug("Moving scanoss fingerprint file failed.:" + str(error)) return scanoss_file_list
en
0.68634
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2020 LG Electronics Inc. # SPDX-License-Identifier: Apache-2.0 # , write_output_file # scanoss # from ._help import print_help_msg_source Run scanoss.py for the given path. :param path_to_scan: path of sourcecode to scan. :param output_file_name: file name for the output. :param format: Output file format (not being used except when calling check_output_format). :param called_by_cli: if not called by cli, initialize logger. :param write_json_file: if requested, keep the raw files. :return scanoss_file_list: list of ScanItem (scanned result by files). # if json output with _write_json_file not used, output_path won't be needed.
2.194669
2
save_cup_data_CV_SULI.py
pennelise/POWER
9
6615511
# -*- coding: utf-8 -*- """ Created on Thu Oct 15 11:09:56 2015 @author: jnewman """ from datetime import datetime from datetime import timedelta import numpy as np def get_array(column): var_temp = np.loadtxt(filename, delimiter=',', usecols=(column,),skiprows=1,dtype=str) var = np.zeros(len(var_temp)) for k in range(len(var_temp)): try: var[k] = float(var_temp[k]) except: var[k] = np.nan return var months = [1] tower_loc = "B5" dir_name = '/Users/jnewman/Desktop/Data for Elise/' + tower_loc + ' Data/Processed Python Files/' data_dir = '/Users/jnewman/Desktop/Dissertation Data/Chisholm_View_Data/Chisholm_View_OU_LLNL_Shared_Data/Met Tower Data/' for j in months: if j == 11: filename = data_dir + 'Met ' + tower_loc + ' Data 2013 1107-1130.csv' if j == 12: filename = data_dir + 'Met ' + tower_loc + ' Data 2013 1201-1231.csv' if j == 1: filename = data_dir + 'Met ' + tower_loc + ' Data 2014 0101-0114.csv' if j == 5 or j==6: filename = data_dir + 'Met ' + tower_loc + ' Data 2014 0501-0630.csv' timestamp = np.loadtxt(filename, delimiter=',', usecols=(0,),dtype=str, unpack=True,skiprows=1) time_datenum = [] for i in timestamp: try: time_datenum.append(datetime.strptime(i,"%m/%d/%Y %H:%M")- timedelta(minutes=20)+ timedelta(hours=6)) except: time_datenum.append(datetime.strptime(i,"%m/%d/%y %H:%M")- timedelta(minutes=20)+ timedelta(hours=6)) pressure = np.loadtxt(filename, delimiter=',', usecols=(2,),skiprows=1) rain_rate = np.loadtxt(filename, delimiter=',', usecols=(8,),skiprows=1) RH_76 = np.loadtxt(filename, delimiter=',', usecols=(9,),skiprows=1) temp_76 = get_array(13) temp_10 = get_array(17) wd_76_1 = get_array(25) wd_76_2 = get_array(29) wd_43 = get_array(33) ws_78 = np.loadtxt(filename, delimiter=',', usecols=(37,),skiprows=1) ws_78_std_dev = np.loadtxt(filename, delimiter=',', usecols=(40,),skiprows=1) ws_80 = np.loadtxt(filename, delimiter=',', usecols=(41,),skiprows=1) ws_80_std_dev = np.loadtxt(filename, delimiter=',', usecols=(44,),skiprows=1) ws_74 = np.loadtxt(filename, delimiter=',', usecols=(45,),skiprows=1) ws_74_std_dev = np.loadtxt(filename, delimiter=',', usecols=(48,),skiprows=1) ws_38 = np.loadtxt(filename, delimiter=',', usecols=(49,),skiprows=1) ws_38_std_dev = np.loadtxt(filename, delimiter=',', usecols=(52,),skiprows=1) time_all = [] pressure_all = [] rain_rate_all = [] RH_76_all = [] temp_76_all = [] temp_10_all = [] wd_76_1_all = [] wd_76_2_all = [] wd_43_all = [] ws_78_all = [] ws_78_std_dev_all = [] ws_80_all = [] ws_80_std_dev_all = [] ws_74_all = [] ws_74_std_dev_all = [] ws_38_all = [] ws_38_std_dev_all = [] for mm in months: for dd in range(32): for ii in range(len(time_datenum)): if time_datenum[ii].month == mm and time_datenum[ii].day == dd: time_all.append(time_datenum[ii]) pressure_all.append(pressure[ii]) rain_rate_all.append(rain_rate[ii]) RH_76_all.append(RH_76[ii]) temp_76_all.append(temp_76[ii]) temp_10_all.append(temp_10[ii]) wd_76_1_all.append(wd_76_1[ii]) wd_76_2_all.append(wd_76_2[ii]) wd_43_all.append(wd_43[ii]) ws_78_all.append(ws_78[ii]) ws_78_std_dev_all.append(ws_78_std_dev[ii]) ws_80_all.append(ws_80[ii]) ws_80_std_dev_all.append(ws_80_std_dev[ii]) ws_74_all.append(ws_74[ii]) ws_74_std_dev_all.append(ws_74_std_dev[ii]) ws_38_all.append(ws_38[ii]) ws_38_std_dev_all.append(ws_38_std_dev[ii]) if len(pressure_all) > 3: filename = dir_name + '2014' + str(mm).zfill(2) + str(dd).zfill(2) np.savez(filename,time = time_all,pressure=pressure_all,rain_rate = rain_rate_all,RH_76 = RH_76_all,temp_76 = temp_76_all,temp_10=temp_10_all,wd_76_1 = wd_76_1_all,\ wd_76_2 = wd_76_2_all,wd_43 = wd_43_all,ws_78 = ws_78_all,ws_78_std_dev = ws_78_std_dev_all,ws_80 = ws_80_all,ws_80_std_dev = ws_80_std_dev_all,\ ws_74 = ws_74_all,ws_74_std_dev = ws_74_std_dev_all,ws_38 = ws_38_all,ws_38_std_dev = ws_38_std_dev_all) time_all = [] pressure_all = [] rain_rate_all = [] RH_76_all = [] temp_76_all = [] temp_10_all = [] wd_76_1_all = [] wd_76_2_all = [] wd_43_all = [] ws_78_all = [] ws_78_std_dev_all = [] ws_80_all = [] ws_80_std_dev_all = [] ws_74_all = [] ws_74_std_dev_all = [] ws_38_all = [] ws_38_std_dev_all = []
# -*- coding: utf-8 -*- """ Created on Thu Oct 15 11:09:56 2015 @author: jnewman """ from datetime import datetime from datetime import timedelta import numpy as np def get_array(column): var_temp = np.loadtxt(filename, delimiter=',', usecols=(column,),skiprows=1,dtype=str) var = np.zeros(len(var_temp)) for k in range(len(var_temp)): try: var[k] = float(var_temp[k]) except: var[k] = np.nan return var months = [1] tower_loc = "B5" dir_name = '/Users/jnewman/Desktop/Data for Elise/' + tower_loc + ' Data/Processed Python Files/' data_dir = '/Users/jnewman/Desktop/Dissertation Data/Chisholm_View_Data/Chisholm_View_OU_LLNL_Shared_Data/Met Tower Data/' for j in months: if j == 11: filename = data_dir + 'Met ' + tower_loc + ' Data 2013 1107-1130.csv' if j == 12: filename = data_dir + 'Met ' + tower_loc + ' Data 2013 1201-1231.csv' if j == 1: filename = data_dir + 'Met ' + tower_loc + ' Data 2014 0101-0114.csv' if j == 5 or j==6: filename = data_dir + 'Met ' + tower_loc + ' Data 2014 0501-0630.csv' timestamp = np.loadtxt(filename, delimiter=',', usecols=(0,),dtype=str, unpack=True,skiprows=1) time_datenum = [] for i in timestamp: try: time_datenum.append(datetime.strptime(i,"%m/%d/%Y %H:%M")- timedelta(minutes=20)+ timedelta(hours=6)) except: time_datenum.append(datetime.strptime(i,"%m/%d/%y %H:%M")- timedelta(minutes=20)+ timedelta(hours=6)) pressure = np.loadtxt(filename, delimiter=',', usecols=(2,),skiprows=1) rain_rate = np.loadtxt(filename, delimiter=',', usecols=(8,),skiprows=1) RH_76 = np.loadtxt(filename, delimiter=',', usecols=(9,),skiprows=1) temp_76 = get_array(13) temp_10 = get_array(17) wd_76_1 = get_array(25) wd_76_2 = get_array(29) wd_43 = get_array(33) ws_78 = np.loadtxt(filename, delimiter=',', usecols=(37,),skiprows=1) ws_78_std_dev = np.loadtxt(filename, delimiter=',', usecols=(40,),skiprows=1) ws_80 = np.loadtxt(filename, delimiter=',', usecols=(41,),skiprows=1) ws_80_std_dev = np.loadtxt(filename, delimiter=',', usecols=(44,),skiprows=1) ws_74 = np.loadtxt(filename, delimiter=',', usecols=(45,),skiprows=1) ws_74_std_dev = np.loadtxt(filename, delimiter=',', usecols=(48,),skiprows=1) ws_38 = np.loadtxt(filename, delimiter=',', usecols=(49,),skiprows=1) ws_38_std_dev = np.loadtxt(filename, delimiter=',', usecols=(52,),skiprows=1) time_all = [] pressure_all = [] rain_rate_all = [] RH_76_all = [] temp_76_all = [] temp_10_all = [] wd_76_1_all = [] wd_76_2_all = [] wd_43_all = [] ws_78_all = [] ws_78_std_dev_all = [] ws_80_all = [] ws_80_std_dev_all = [] ws_74_all = [] ws_74_std_dev_all = [] ws_38_all = [] ws_38_std_dev_all = [] for mm in months: for dd in range(32): for ii in range(len(time_datenum)): if time_datenum[ii].month == mm and time_datenum[ii].day == dd: time_all.append(time_datenum[ii]) pressure_all.append(pressure[ii]) rain_rate_all.append(rain_rate[ii]) RH_76_all.append(RH_76[ii]) temp_76_all.append(temp_76[ii]) temp_10_all.append(temp_10[ii]) wd_76_1_all.append(wd_76_1[ii]) wd_76_2_all.append(wd_76_2[ii]) wd_43_all.append(wd_43[ii]) ws_78_all.append(ws_78[ii]) ws_78_std_dev_all.append(ws_78_std_dev[ii]) ws_80_all.append(ws_80[ii]) ws_80_std_dev_all.append(ws_80_std_dev[ii]) ws_74_all.append(ws_74[ii]) ws_74_std_dev_all.append(ws_74_std_dev[ii]) ws_38_all.append(ws_38[ii]) ws_38_std_dev_all.append(ws_38_std_dev[ii]) if len(pressure_all) > 3: filename = dir_name + '2014' + str(mm).zfill(2) + str(dd).zfill(2) np.savez(filename,time = time_all,pressure=pressure_all,rain_rate = rain_rate_all,RH_76 = RH_76_all,temp_76 = temp_76_all,temp_10=temp_10_all,wd_76_1 = wd_76_1_all,\ wd_76_2 = wd_76_2_all,wd_43 = wd_43_all,ws_78 = ws_78_all,ws_78_std_dev = ws_78_std_dev_all,ws_80 = ws_80_all,ws_80_std_dev = ws_80_std_dev_all,\ ws_74 = ws_74_all,ws_74_std_dev = ws_74_std_dev_all,ws_38 = ws_38_all,ws_38_std_dev = ws_38_std_dev_all) time_all = [] pressure_all = [] rain_rate_all = [] RH_76_all = [] temp_76_all = [] temp_10_all = [] wd_76_1_all = [] wd_76_2_all = [] wd_43_all = [] ws_78_all = [] ws_78_std_dev_all = [] ws_80_all = [] ws_80_std_dev_all = [] ws_74_all = [] ws_74_std_dev_all = [] ws_38_all = [] ws_38_std_dev_all = []
en
0.699972
# -*- coding: utf-8 -*- Created on Thu Oct 15 11:09:56 2015 @author: jnewman
2.375196
2
lib/rest_api.py
doino-gretchenliev/handbreak-auto-processing
0
6615512
<reponame>doino-gretchenliev/handbreak-auto-processing from lib import logger from flask import Flask, Blueprint from flask_restplus import Api from lib.JSONEncoder import JSONEncoder from lib.flask_thread import FlaskAppWrapper from lib.namespaces import nodes from lib.namespaces import queue app = Flask(__name__) app.json_encoder = JSONEncoder app.config.SWAGGER_UI_JSONEDITOR = True blueprint = Blueprint('api', __name__) api = Api(blueprint, version='0.0.1', title='Handbreak auto processing tool API') api.add_namespace(queue.api) api.add_namespace(nodes.api) app.register_blueprint(blueprint) class RestApi(object): def __init__(self, media_processing, node_inventory): queue.mp = media_processing nodes.ni = node_inventory self.flask_process = FlaskAppWrapper(app) self.flask_process.start() def stop(self): self.flask_process.join()
from lib import logger from flask import Flask, Blueprint from flask_restplus import Api from lib.JSONEncoder import JSONEncoder from lib.flask_thread import FlaskAppWrapper from lib.namespaces import nodes from lib.namespaces import queue app = Flask(__name__) app.json_encoder = JSONEncoder app.config.SWAGGER_UI_JSONEDITOR = True blueprint = Blueprint('api', __name__) api = Api(blueprint, version='0.0.1', title='Handbreak auto processing tool API') api.add_namespace(queue.api) api.add_namespace(nodes.api) app.register_blueprint(blueprint) class RestApi(object): def __init__(self, media_processing, node_inventory): queue.mp = media_processing nodes.ni = node_inventory self.flask_process = FlaskAppWrapper(app) self.flask_process.start() def stop(self): self.flask_process.join()
none
1
2.105602
2
hamming_code/hamming_code_runme_old.py
kishoreudata/hammingcode_tool
0
6615513
import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QFileDialog, QFileSystemModel, QTreeView import numpy as np from hamming import Ui_MainWindow class MainClassStart(Ui_MainWindow): def __init__(self, Form): print("\n --------Start Program--------") Ui_MainWindow.__init__(self) self.setupUi(Form) self.pushButton.clicked.connect(self.gen_ham) self.pushButton_2.clicked.connect(self.correct_ham) print("\n --------End Program--------") def binToHexa(self,n): bnum = int(n) temp = 0 mul = 1 # counter to check group of 4 count = 1 # char array to store hexadecimal number hexaDeciNum = ['0'] * 100 # counter for hexadecimal number array i = 0 while bnum != 0: rem = bnum % 10 temp = temp + (rem*mul) # check if group of 4 completed if count % 4 == 0: # check if temp < 10 if temp < 10: hexaDeciNum[i] = chr(temp+48) else: hexaDeciNum[i] = chr(temp+55) mul = 1 temp = 0 count = 1 i = i+1 # group of 4 is not completed else: mul = mul*2 count = count+1 bnum = int(bnum/10) # check if at end the group of 4 is not # completed if count != 1: hexaDeciNum[i] = chr(temp+48) # check at end the group of 4 is completed if count == 1: i = i-1 # printing hexadecimal number # array in reverse order print("\n Hexadecimal equivalent of {}: ".format(n), end="") while i >= 0: print(end=hexaDeciNum[i]) i = i-1 print('\n') #print(hexaDeciNum.decode()) #byte_array=bytearray(hexaDeciNum) #byte_array = bytearray.fromhex(hexaDeciNum) #print(byte_array.decode()) str1 = "" # traverse in the string for ele in hexaDeciNum: str1 += ele byte_array = bytearray.fromhex(str1) print("corresponding ascii value is: ",byte_array.decode()) ascii_val=byte_array.decode() #print(byte_array.decode()) return hexaDeciNum.reverse(),ascii_val def gen_ham(self): print("\n --------gen_ham Started--------") d = self.textEdit.toPlainText() data=list(d) data.reverse() c,ch,j,r,h=0,0,0,0,[] while ((len(d)+r+1)>(pow(2,r))): r=r+1 for i in range(0,(r+len(data))): p=(2**c) if(p==(i+1)): h.append(0) c=c+1 else: h.append(int(data[j])) j=j+1 for parity in range(0,(len(h))): ph=(2**ch) if(ph==(parity+1)): startIndex=ph-1 i=startIndex toXor=[] while(i<len(h)): block=h[i:i+ph] toXor.extend(block) i+=2*ph for z in range(1,len(toXor)): h[startIndex]=h[startIndex]^toXor[z] ch+=1 h.reverse() print('Hamming code generated would be:- ', end="") print(int(''.join(map(str, h)))) h_generated=int(''.join(map(str, h))) hex_val,ascii_val=self.binToHexa(h_generated) self.label.setText(str(h_generated)) self.label_3.setText(str(hex_val)) self.label_4.setText(str(ascii_val)) '''path = self.openFile() print(path) csvFileName = path self.label_4.setText(path)''' print("\n ------- gen_ham Completed -------") def correct_ham(self): print("\n ------- correct_ham Started -------") thread1 = videoThread(self.videofileName, self.pushButton_4) thread1.start() self.pushButton_4.setText('Please Wait.... Notify When Completed') if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) mainObject = MainClassStart(MainWindow) MainWindow.show() sys.exit(app.exec_()) # # End Of Program
import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QFileDialog, QFileSystemModel, QTreeView import numpy as np from hamming import Ui_MainWindow class MainClassStart(Ui_MainWindow): def __init__(self, Form): print("\n --------Start Program--------") Ui_MainWindow.__init__(self) self.setupUi(Form) self.pushButton.clicked.connect(self.gen_ham) self.pushButton_2.clicked.connect(self.correct_ham) print("\n --------End Program--------") def binToHexa(self,n): bnum = int(n) temp = 0 mul = 1 # counter to check group of 4 count = 1 # char array to store hexadecimal number hexaDeciNum = ['0'] * 100 # counter for hexadecimal number array i = 0 while bnum != 0: rem = bnum % 10 temp = temp + (rem*mul) # check if group of 4 completed if count % 4 == 0: # check if temp < 10 if temp < 10: hexaDeciNum[i] = chr(temp+48) else: hexaDeciNum[i] = chr(temp+55) mul = 1 temp = 0 count = 1 i = i+1 # group of 4 is not completed else: mul = mul*2 count = count+1 bnum = int(bnum/10) # check if at end the group of 4 is not # completed if count != 1: hexaDeciNum[i] = chr(temp+48) # check at end the group of 4 is completed if count == 1: i = i-1 # printing hexadecimal number # array in reverse order print("\n Hexadecimal equivalent of {}: ".format(n), end="") while i >= 0: print(end=hexaDeciNum[i]) i = i-1 print('\n') #print(hexaDeciNum.decode()) #byte_array=bytearray(hexaDeciNum) #byte_array = bytearray.fromhex(hexaDeciNum) #print(byte_array.decode()) str1 = "" # traverse in the string for ele in hexaDeciNum: str1 += ele byte_array = bytearray.fromhex(str1) print("corresponding ascii value is: ",byte_array.decode()) ascii_val=byte_array.decode() #print(byte_array.decode()) return hexaDeciNum.reverse(),ascii_val def gen_ham(self): print("\n --------gen_ham Started--------") d = self.textEdit.toPlainText() data=list(d) data.reverse() c,ch,j,r,h=0,0,0,0,[] while ((len(d)+r+1)>(pow(2,r))): r=r+1 for i in range(0,(r+len(data))): p=(2**c) if(p==(i+1)): h.append(0) c=c+1 else: h.append(int(data[j])) j=j+1 for parity in range(0,(len(h))): ph=(2**ch) if(ph==(parity+1)): startIndex=ph-1 i=startIndex toXor=[] while(i<len(h)): block=h[i:i+ph] toXor.extend(block) i+=2*ph for z in range(1,len(toXor)): h[startIndex]=h[startIndex]^toXor[z] ch+=1 h.reverse() print('Hamming code generated would be:- ', end="") print(int(''.join(map(str, h)))) h_generated=int(''.join(map(str, h))) hex_val,ascii_val=self.binToHexa(h_generated) self.label.setText(str(h_generated)) self.label_3.setText(str(hex_val)) self.label_4.setText(str(ascii_val)) '''path = self.openFile() print(path) csvFileName = path self.label_4.setText(path)''' print("\n ------- gen_ham Completed -------") def correct_ham(self): print("\n ------- correct_ham Started -------") thread1 = videoThread(self.videofileName, self.pushButton_4) thread1.start() self.pushButton_4.setText('Please Wait.... Notify When Completed') if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) mainObject = MainClassStart(MainWindow) MainWindow.show() sys.exit(app.exec_()) # # End Of Program
en
0.532376
# counter to check group of 4 # char array to store hexadecimal number # counter for hexadecimal number array # check if group of 4 completed # check if temp < 10 # group of 4 is not completed # check if at end the group of 4 is not # completed # check at end the group of 4 is completed # printing hexadecimal number # array in reverse order #print(hexaDeciNum.decode()) #byte_array=bytearray(hexaDeciNum) #byte_array = bytearray.fromhex(hexaDeciNum) #print(byte_array.decode()) # traverse in the string #print(byte_array.decode()) path = self.openFile() print(path) csvFileName = path self.label_4.setText(path) # # End Of Program
3.094868
3
socshop/views.py
qs/socshop
0
6615514
from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.core.urlresolvers import reverse from paypal.standard.forms import PayPalPaymentsForm def home(request): """ Home page with auth links. """ if request.user.is_authenticated(): return HttpResponse("{0} <a href='/accounts/logout'>exit</a>".format(request.user)) else: return HttpResponse("<a href='/login/vk-oauth2/'>login with VK</a>") @login_required def account_profile(request): """ Show user greetings. ONly for logged in users. """ return HttpResponse("Hi, {0}! Nice to meet you.".format(request.user.first_name)) def account_logout(request): """ Logout and redirect to the main page. """ logout(request) return redirect('/') @csrf_exempt def paypal_success(request): """ Tell user we got the payment. """ return HttpResponse("Money is mine. Thanks.") @login_required def paypal_pay(request): """ Page where we ask user to pay with paypal. """ paypal_dict = { "business": "<EMAIL>", "amount": "100.00", "currency_code": "RUB", "item_name": "products in socshop", "invoice": "INV-00001", "notify_url": reverse('paypal-ipn'), "return_url": "http://localhost:8000/payment/success/", "cancel_return": "http://localhost:8000/payment/cart/", "custom": str(request.user.id) } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form, "paypal_dict": paypal_dict} return render(request, "payment.html", context)
from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import logout from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.core.urlresolvers import reverse from paypal.standard.forms import PayPalPaymentsForm def home(request): """ Home page with auth links. """ if request.user.is_authenticated(): return HttpResponse("{0} <a href='/accounts/logout'>exit</a>".format(request.user)) else: return HttpResponse("<a href='/login/vk-oauth2/'>login with VK</a>") @login_required def account_profile(request): """ Show user greetings. ONly for logged in users. """ return HttpResponse("Hi, {0}! Nice to meet you.".format(request.user.first_name)) def account_logout(request): """ Logout and redirect to the main page. """ logout(request) return redirect('/') @csrf_exempt def paypal_success(request): """ Tell user we got the payment. """ return HttpResponse("Money is mine. Thanks.") @login_required def paypal_pay(request): """ Page where we ask user to pay with paypal. """ paypal_dict = { "business": "<EMAIL>", "amount": "100.00", "currency_code": "RUB", "item_name": "products in socshop", "invoice": "INV-00001", "notify_url": reverse('paypal-ipn'), "return_url": "http://localhost:8000/payment/success/", "cancel_return": "http://localhost:8000/payment/cart/", "custom": str(request.user.id) } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": form, "paypal_dict": paypal_dict} return render(request, "payment.html", context)
en
0.887842
Home page with auth links. Show user greetings. ONly for logged in users. Logout and redirect to the main page. Tell user we got the payment. Page where we ask user to pay with paypal. # Create the instance.
2.300881
2
web/premises/sitemaps.py
mehrdad-shokri/arguman.org
1
6615515
from django.contrib.sitemaps import Sitemap from django.utils.translation import get_language from i18n.utils import normalize_language_code from premises.models import Contention, Premise class ArgumentSitemap(Sitemap): changefreq = "never" priority = 0.9 def items(self): language = normalize_language_code(get_language()) return Contention.objects.filter( language=language, is_published=True ) def location(self, obj): return obj.get_absolute_url() def lastmod(self, obj): return obj.date_modification class PremiseSitemap(Sitemap): changefreq = "never" priority = 0.8 def items(self): language = normalize_language_code(get_language()) return Premise.objects.filter( argument__language=language, is_approved=True ) def location(self, obj): return obj.get_list_url()
from django.contrib.sitemaps import Sitemap from django.utils.translation import get_language from i18n.utils import normalize_language_code from premises.models import Contention, Premise class ArgumentSitemap(Sitemap): changefreq = "never" priority = 0.9 def items(self): language = normalize_language_code(get_language()) return Contention.objects.filter( language=language, is_published=True ) def location(self, obj): return obj.get_absolute_url() def lastmod(self, obj): return obj.date_modification class PremiseSitemap(Sitemap): changefreq = "never" priority = 0.8 def items(self): language = normalize_language_code(get_language()) return Premise.objects.filter( argument__language=language, is_approved=True ) def location(self, obj): return obj.get_list_url()
none
1
2.007248
2
prog_vae/prog_decoder/tree_walker.py
Hanjun-Dai/sdvae
70
6615516
<gh_stars>10-100 #!/usr/bin/env python from __future__ import print_function import os import sys import csv import numpy as np import math import random from collections import defaultdict sys.path.append( '%s/../prog_common' % os.path.dirname(os.path.realpath(__file__)) ) from prog_util import prod, MAX_VARS, rule_ranges, MAX_NUM_STATEMENTS, TOTAL_NUM_RULES, DECISION_DIM class DecodingLimitExceeded(Exception): def __init__(self): pass def __str__(self): return 'DecodingLimitExceeded' class ProgramOnehotBuilder(object): def __init__(self): super(ProgramOnehotBuilder, self).__init__() self.reset() def reset(self): self.num_steps = 0 self.global_rule_used = [] self.mask_list = [] def sample_index_with_mask(self, node, idxes): assert node.rule_used is not None g_range = rule_ranges[node.symbol] global_idx = g_range[0] + node.rule_used self.global_rule_used.append(global_idx) self.mask_list.append(np.array(idxes)) self.num_steps += 1 result = None for i in range(len(idxes)): if idxes[i] == global_idx: result = i if result is None: print(node.symbol, idxes, global_idx) assert result is not None return result def sample_att(self, node, candidates): assert hasattr(node, 'var_id') assert node.var_id in candidates global_idx = TOTAL_NUM_RULES + node.var_id self.global_rule_used.append(global_idx) self.mask_list.append(np.array(candidates) + TOTAL_NUM_RULES) self.num_steps += 1 return node.var_id class ConditionalProgramDecoder(object): def __init__(self, raw_logits, use_random): super(ConditionalProgramDecoder, self).__init__() self.raw_logits = raw_logits self.use_random = use_random assert len(raw_logits.shape) == 2 and raw_logits.shape[1] == DECISION_DIM self.reset() def reset(self): self.num_steps = 0 def _get_idx(self, cur_logits): if self.use_random: cur_prob = np.exp(cur_logits) cur_prob = cur_prob / np.sum(cur_prob) result = np.random.choice(len(cur_prob), 1, p=cur_prob)[0] result = int(result) # enusre it's converted to int else: result = np.argmax(cur_logits) self.num_steps += 1 return result def sample_index_with_mask(self, node, idxes): if self.num_steps >= self.raw_logits.shape[0]: raise DecodingLimitExceeded() cur_logits = self.raw_logits[self.num_steps][idxes] return self._get_idx(cur_logits) def sample_att(self, node, candidates): if self.num_steps >= self.raw_logits.shape[0]: raise DecodingLimitExceeded() cur_logits = self.raw_logits[self.num_steps][np.array(candidates) + TOTAL_NUM_RULES] idx = self._get_idx(cur_logits) return candidates[idx] class PurelyRandomProgramDecoder(object): def __init__(self): super(PurelyRandomProgramDecoder, self).__init__() self.reset() def reset(self): pass def sample_in_candidates(self, raw_p, idxes): sub_p = np.array(raw_p)[ np.array(idxes) ] sub_p /= np.sum(sub_p) idx = np.random.choice(len(sub_p), 1, p=sub_p)[0] idx = int(idx) return idx def sample_index_with_mask(self, node, idxes): assert len(idxes) non_terminal = node.symbol p = [1] if non_terminal == 'stat_list': p = [0.5, 0.5] elif non_terminal == 'stat': p = [0.8, 0.2] elif non_terminal == 'expr': p = [0.2, 0.8] elif non_terminal == 'unary_expr': p = [0.5, 0.5] elif non_terminal == 'unary_func': p = [0.3, 0.3, 0.4] elif non_terminal == 'binary_op': p = [0.3, 0.3, 0.3, 0.1] elif non_terminal == 'operand': p = [0.5, 0.5] elif non_terminal == 'digit': p = [0.2] + [0.1] * 8 if len(p) != len(prod[non_terminal]): print(non_terminal, len(p), len(prod[non_terminal])) assert len(p) == len(prod[non_terminal]) assert len(p) >= len(idxes) if len(p) > len(idxes): g_range = rule_ranges[non_terminal] result = self.sample_in_candidates(p, np.array( idxes ) - g_range[0]) else: result = np.random.choice(len(p), 1, p=p)[0] result = int(result) # enusre it's converted to int assert result < len(idxes) return result def sample_att(self, node, candidates): p = [0.1] * 10 assert len(p) >= len(candidates) idx = self.sample_in_candidates(p, candidates) assert idx < len(candidates) return candidates[idx]
#!/usr/bin/env python from __future__ import print_function import os import sys import csv import numpy as np import math import random from collections import defaultdict sys.path.append( '%s/../prog_common' % os.path.dirname(os.path.realpath(__file__)) ) from prog_util import prod, MAX_VARS, rule_ranges, MAX_NUM_STATEMENTS, TOTAL_NUM_RULES, DECISION_DIM class DecodingLimitExceeded(Exception): def __init__(self): pass def __str__(self): return 'DecodingLimitExceeded' class ProgramOnehotBuilder(object): def __init__(self): super(ProgramOnehotBuilder, self).__init__() self.reset() def reset(self): self.num_steps = 0 self.global_rule_used = [] self.mask_list = [] def sample_index_with_mask(self, node, idxes): assert node.rule_used is not None g_range = rule_ranges[node.symbol] global_idx = g_range[0] + node.rule_used self.global_rule_used.append(global_idx) self.mask_list.append(np.array(idxes)) self.num_steps += 1 result = None for i in range(len(idxes)): if idxes[i] == global_idx: result = i if result is None: print(node.symbol, idxes, global_idx) assert result is not None return result def sample_att(self, node, candidates): assert hasattr(node, 'var_id') assert node.var_id in candidates global_idx = TOTAL_NUM_RULES + node.var_id self.global_rule_used.append(global_idx) self.mask_list.append(np.array(candidates) + TOTAL_NUM_RULES) self.num_steps += 1 return node.var_id class ConditionalProgramDecoder(object): def __init__(self, raw_logits, use_random): super(ConditionalProgramDecoder, self).__init__() self.raw_logits = raw_logits self.use_random = use_random assert len(raw_logits.shape) == 2 and raw_logits.shape[1] == DECISION_DIM self.reset() def reset(self): self.num_steps = 0 def _get_idx(self, cur_logits): if self.use_random: cur_prob = np.exp(cur_logits) cur_prob = cur_prob / np.sum(cur_prob) result = np.random.choice(len(cur_prob), 1, p=cur_prob)[0] result = int(result) # enusre it's converted to int else: result = np.argmax(cur_logits) self.num_steps += 1 return result def sample_index_with_mask(self, node, idxes): if self.num_steps >= self.raw_logits.shape[0]: raise DecodingLimitExceeded() cur_logits = self.raw_logits[self.num_steps][idxes] return self._get_idx(cur_logits) def sample_att(self, node, candidates): if self.num_steps >= self.raw_logits.shape[0]: raise DecodingLimitExceeded() cur_logits = self.raw_logits[self.num_steps][np.array(candidates) + TOTAL_NUM_RULES] idx = self._get_idx(cur_logits) return candidates[idx] class PurelyRandomProgramDecoder(object): def __init__(self): super(PurelyRandomProgramDecoder, self).__init__() self.reset() def reset(self): pass def sample_in_candidates(self, raw_p, idxes): sub_p = np.array(raw_p)[ np.array(idxes) ] sub_p /= np.sum(sub_p) idx = np.random.choice(len(sub_p), 1, p=sub_p)[0] idx = int(idx) return idx def sample_index_with_mask(self, node, idxes): assert len(idxes) non_terminal = node.symbol p = [1] if non_terminal == 'stat_list': p = [0.5, 0.5] elif non_terminal == 'stat': p = [0.8, 0.2] elif non_terminal == 'expr': p = [0.2, 0.8] elif non_terminal == 'unary_expr': p = [0.5, 0.5] elif non_terminal == 'unary_func': p = [0.3, 0.3, 0.4] elif non_terminal == 'binary_op': p = [0.3, 0.3, 0.3, 0.1] elif non_terminal == 'operand': p = [0.5, 0.5] elif non_terminal == 'digit': p = [0.2] + [0.1] * 8 if len(p) != len(prod[non_terminal]): print(non_terminal, len(p), len(prod[non_terminal])) assert len(p) == len(prod[non_terminal]) assert len(p) >= len(idxes) if len(p) > len(idxes): g_range = rule_ranges[non_terminal] result = self.sample_in_candidates(p, np.array( idxes ) - g_range[0]) else: result = np.random.choice(len(p), 1, p=p)[0] result = int(result) # enusre it's converted to int assert result < len(idxes) return result def sample_att(self, node, candidates): p = [0.1] * 10 assert len(p) >= len(candidates) idx = self.sample_in_candidates(p, candidates) assert idx < len(candidates) return candidates[idx]
en
0.85249
#!/usr/bin/env python # enusre it's converted to int # enusre it's converted to int
2.212896
2
chain_reaction/graphics/window.py
davidkowalk/chain-reaction-ai
95
6615517
<filename>chain_reaction/graphics/window.py from abc import ABC, abstractmethod import pygame import pygame.font as font import pygame.gfxdraw as gfxdraw import chain_reaction.graphics.sprites as sprites import chain_reaction.wrappers.engine as engine # ----------- COLORS ------------- COL_BACK = (0, 0, 0) COL_FORE = (255, 255, 255) COL_PLR1 = (250, 100, 40) COL_PLR2 = (40, 200, 100) # --------- DIMS ----------- R_THIC = 10 R_VOFF = 40 G_HOFF = 50 G_VOFF = 70 G_WIDC = 50 G_WALL = 2 # -------- ON INIT ---------- G_SHAP = None G_DIMS = None R_DIMS = None W_DIMS = None ORB_PL1 = None ORB_PL2 = None # ----------- INIT --------------- def init(g_shape=(9, 6)): """ Calculate dimensions and construct sprites Input : g_shape (rows, cols) """ global G_SHAP, G_DIMS, R_DIMS, W_DIMS global ORB_PL1, ORB_PL2 # pygame modules font.init() # calculate dims G_SHAP = (g_shape[1], g_shape[0]) G_DIMS = (G_SHAP[0] * G_WIDC + G_WALL, G_SHAP[1] * G_WIDC + G_WALL) R_DIMS = (G_DIMS[0], R_THIC) W_DIMS = (G_DIMS[0] + (2 * G_HOFF), G_DIMS[1] + G_HOFF + G_VOFF) # construct sprites ORB_SIZ = G_WIDC - G_WALL ORB_PL1 = sprites.construct_orbs(COL_PLR1, COL_BACK, ORB_SIZ) ORB_PL2 = sprites.construct_orbs(COL_PLR2, COL_BACK, ORB_SIZ) # ---------- CLASSES ------------- class BaseGameWindow(ABC): def __init__(self, fps): """ Most Basic Game Window """ # window pointers self.surface = pygame.display.set_mode(W_DIMS) self.clock = pygame.time.Clock() self.fps = fps # status self.locked = False self.open = True # mouse click and index self.mclk = False self.midx = None def clear(self): self.surface.fill(COL_BACK) def update(self): pygame.display.update() def event_flush(self): pygame.event.clear() def event_handler(self): """ Handle events in window """ # Refresh values self.mclk = False self.midx = None for event in pygame.event.get(): if event.type == pygame.QUIT: self.open = False return elif event.type == pygame.MOUSEBUTTONUP: # if locked, do nothing if self.locked: continue self.mclk = True crx, cry = pygame.mouse.get_pos() idx = ((cry - G_VOFF) // G_WIDC, (crx - G_HOFF) // G_WIDC) val = (0 <= idx[0] < G_SHAP[1]) * (0 <= idx[1] < G_SHAP[0]) self.midx = idx if val else None def draw_indicator(self, player): """ Draw rectangle to indicate next player """ pcolor = COL_PLR2 if player else COL_PLR1 nxrect = (G_HOFF, R_VOFF, G_DIMS[0], R_THIC) pygame.draw.rect(self.surface, pcolor, nxrect) def draw_grid(self): """ Draw grid on screen """ gwid, ghgt = G_DIMS # horizontal lines for j in range(G_SHAP[1] + 1): grect = (G_HOFF, G_VOFF + j * G_WIDC, gwid, G_WALL) pygame.draw.rect(self.surface, COL_FORE, grect) # vertical lines for i in range(G_SHAP[0] + 1): grect = (G_HOFF + i * G_WIDC, G_VOFF, G_WALL, ghgt) pygame.draw.rect(self.surface, COL_FORE, grect) def draw_orbs(self, board, ignore=[]): """ Draw orb sprites on the surface """ gcol, grow = G_SHAP offx, offy = (G_HOFF + G_WALL, G_VOFF + G_WALL) for idx in range(grow * gcol): # ignore index if idx in ignore: continue # blit appropriate sprite on surface ccount = board[idx] if ccount != 0: i_y, i_x = idx // gcol, idx % gcol pos = (G_WIDC * i_x + offx, G_WIDC * i_y + offy) psprite = ORB_PL1 if ccount > 0 else ORB_PL2 self.surface.blit(psprite[abs(ccount) - 1], pos) def draw_all(self, board, player): """ Draw all drawable elements """ self.clear() self.draw_grid() self.draw_indicator(player) self.draw_orbs(board) self.update() @abstractmethod def on_game_start(self): """ Splash Screen Callback """ return @abstractmethod def on_game_move(self, game, move): """ Game Piece Move Callback """ return @abstractmethod def on_game_end(self, game): """ Game Over Callback """ return class StaticGameWindow(BaseGameWindow): def __init__(self, fps): """ Display static graphics Very light on resources """ super().__init__(fps) def on_game_start(self): """ Splash Screen Callback """ return def on_game_move(self, game: engine.ChainReactionGame, move): """ Game Piece Move Callback """ # draw if no move specified if move is None: self.draw_all(game.board, game.player) return # play game.make_move(move) self.draw_all(game.board, game.player) def on_game_end(self, game): """ Game Over Callback """ if game.winner == 0: print("Red Wins!") elif game.winner == 1: print("Green Wins!") elif game.winner == 2: print("Sorry to see you go :(") # quit pygame pygame.quit() class AnimatedGameWindow(BaseGameWindow): def __init__(self, fps, flight_steps=10): """ Window that displays animations ------------------------------- - fps - frame rate limit - flight_steps - steps in a flight animation """ super().__init__(fps) self.flight_steps = flight_steps def draw_flights(self, flights, progress, player): # setup gcol, grow = G_SHAP offx, offy = (G_HOFF + G_WALL, G_VOFF + G_WALL) pcolor = COL_PLR2 if player else COL_PLR1 prog_frac = progress / self.flight_steps for origin, dest in flights: # indices orig_posx = G_WIDC * (origin % gcol) + offx + G_WIDC // 2 orig_posy = G_WIDC * (origin // gcol) + offy + G_WIDC // 2 dest_posx = G_WIDC * (dest % gcol) + offx + G_WIDC // 2 dest_posy = G_WIDC * (dest // gcol) + offy + G_WIDC // 2 # calculate positions pos_x = int(orig_posx + prog_frac * (dest_posx - orig_posx)) pos_y = int(orig_posy + prog_frac * (dest_posy - orig_posy)) # draw in present position gfxdraw.aacircle(self.surface, pos_x, pos_y, 10, pcolor) gfxdraw.filled_circle(self.surface, pos_x, pos_y, 10, pcolor) def explode_orbs(self, board, explosions, player, callback=None): """ Show orb explosion animation Does not return until animation is over Internal event handling """ # immediate return if explosions are absent if not explosions: return # set up origin and final indices for flight flights = [ (origin, dest) for origin in explosions for dest in engine.NTABLE[origin] ] # uniform speed for progress in range(self.flight_steps): self.clear() self.draw_grid() self.draw_indicator(player) self.draw_orbs(board, ignore=explosions) self.draw_flights(flights, progress, player) callback() if callback else None # optional callback self.update() self.event_handler() self.clock.tick(self.fps) def on_game_start(self): """ Splash Screen """ return def on_game_move(self, game: engine.ChainReactionAnimated, move): """ Function to execute when move specified """ # draw if no move specified if move is None: self.draw_all(game.board, game.player) return # invalid move if not game.make_move(move): return # lock to not respond to mouse clicks self.locked = True player = game.player # get steps until stable or game over while game.pending_moves and not game.game_over and self.open: # get board and explosions for animation prev_board, explosions = game.get_next_step() # draw explosions self.explode_orbs(prev_board, explosions, player) self.draw_all(game.board, game.player) # unlock window after handling events self.event_handler() self.locked = False def on_game_end(self, game: engine.ChainReactionAnimated): """ Game over screen """ global ORB_PL1, ORB_PL2 global COL_PLR1, COL_PLR2 global COL_FORE # convert colors to grayscale COL_PLR1 = (30, 30, 30) COL_PLR2 = (30, 30, 30) COL_FORE = (30, 30, 30) ORB_PL1 = [sprites.grayscale(x, 0.2) for x in ORB_PL1] ORB_PL2 = [sprites.grayscale(x, 0.2) for x in ORB_PL2] # save player player = game.player self.flight_steps = 20 # slow-mo # construct game over text font_instance = font.SysFont("Ubuntu Mono", 50, True, False) message = "GREEN WINS!" if game.winner else "RED WINS!" mscolor = (100, 255, 50) if game.winner else (255, 100, 50) game_over_text = font_instance.render(message, True, mscolor) text_w, text_h = game_over_text.get_size() text_dest = ((W_DIMS[0] - text_w) // 2, (W_DIMS[1] - text_h) // 2) blit_text = lambda: self.surface.blit(game_over_text, text_dest) # keep exploding for cool end-graphics while self.open and game.pending_moves: prev_board, explosions = game.get_next_step() self.explode_orbs(prev_board, explosions, player, blit_text) self.clear() self.draw_grid() self.draw_indicator(game.player) self.draw_orbs(game.board) blit_text() self.update() # draw static if pending moves are over if not game.pending_moves: self.clear() self.draw_grid() self.draw_indicator(game.player) self.draw_orbs(game.board) blit_text() self.update() while self.open: self.event_handler() self.clock.tick(self.fps) # voluntary close if not game.game_over and not self.open: print("Sorry to see you go :(") font.quit() pygame.quit()
<filename>chain_reaction/graphics/window.py from abc import ABC, abstractmethod import pygame import pygame.font as font import pygame.gfxdraw as gfxdraw import chain_reaction.graphics.sprites as sprites import chain_reaction.wrappers.engine as engine # ----------- COLORS ------------- COL_BACK = (0, 0, 0) COL_FORE = (255, 255, 255) COL_PLR1 = (250, 100, 40) COL_PLR2 = (40, 200, 100) # --------- DIMS ----------- R_THIC = 10 R_VOFF = 40 G_HOFF = 50 G_VOFF = 70 G_WIDC = 50 G_WALL = 2 # -------- ON INIT ---------- G_SHAP = None G_DIMS = None R_DIMS = None W_DIMS = None ORB_PL1 = None ORB_PL2 = None # ----------- INIT --------------- def init(g_shape=(9, 6)): """ Calculate dimensions and construct sprites Input : g_shape (rows, cols) """ global G_SHAP, G_DIMS, R_DIMS, W_DIMS global ORB_PL1, ORB_PL2 # pygame modules font.init() # calculate dims G_SHAP = (g_shape[1], g_shape[0]) G_DIMS = (G_SHAP[0] * G_WIDC + G_WALL, G_SHAP[1] * G_WIDC + G_WALL) R_DIMS = (G_DIMS[0], R_THIC) W_DIMS = (G_DIMS[0] + (2 * G_HOFF), G_DIMS[1] + G_HOFF + G_VOFF) # construct sprites ORB_SIZ = G_WIDC - G_WALL ORB_PL1 = sprites.construct_orbs(COL_PLR1, COL_BACK, ORB_SIZ) ORB_PL2 = sprites.construct_orbs(COL_PLR2, COL_BACK, ORB_SIZ) # ---------- CLASSES ------------- class BaseGameWindow(ABC): def __init__(self, fps): """ Most Basic Game Window """ # window pointers self.surface = pygame.display.set_mode(W_DIMS) self.clock = pygame.time.Clock() self.fps = fps # status self.locked = False self.open = True # mouse click and index self.mclk = False self.midx = None def clear(self): self.surface.fill(COL_BACK) def update(self): pygame.display.update() def event_flush(self): pygame.event.clear() def event_handler(self): """ Handle events in window """ # Refresh values self.mclk = False self.midx = None for event in pygame.event.get(): if event.type == pygame.QUIT: self.open = False return elif event.type == pygame.MOUSEBUTTONUP: # if locked, do nothing if self.locked: continue self.mclk = True crx, cry = pygame.mouse.get_pos() idx = ((cry - G_VOFF) // G_WIDC, (crx - G_HOFF) // G_WIDC) val = (0 <= idx[0] < G_SHAP[1]) * (0 <= idx[1] < G_SHAP[0]) self.midx = idx if val else None def draw_indicator(self, player): """ Draw rectangle to indicate next player """ pcolor = COL_PLR2 if player else COL_PLR1 nxrect = (G_HOFF, R_VOFF, G_DIMS[0], R_THIC) pygame.draw.rect(self.surface, pcolor, nxrect) def draw_grid(self): """ Draw grid on screen """ gwid, ghgt = G_DIMS # horizontal lines for j in range(G_SHAP[1] + 1): grect = (G_HOFF, G_VOFF + j * G_WIDC, gwid, G_WALL) pygame.draw.rect(self.surface, COL_FORE, grect) # vertical lines for i in range(G_SHAP[0] + 1): grect = (G_HOFF + i * G_WIDC, G_VOFF, G_WALL, ghgt) pygame.draw.rect(self.surface, COL_FORE, grect) def draw_orbs(self, board, ignore=[]): """ Draw orb sprites on the surface """ gcol, grow = G_SHAP offx, offy = (G_HOFF + G_WALL, G_VOFF + G_WALL) for idx in range(grow * gcol): # ignore index if idx in ignore: continue # blit appropriate sprite on surface ccount = board[idx] if ccount != 0: i_y, i_x = idx // gcol, idx % gcol pos = (G_WIDC * i_x + offx, G_WIDC * i_y + offy) psprite = ORB_PL1 if ccount > 0 else ORB_PL2 self.surface.blit(psprite[abs(ccount) - 1], pos) def draw_all(self, board, player): """ Draw all drawable elements """ self.clear() self.draw_grid() self.draw_indicator(player) self.draw_orbs(board) self.update() @abstractmethod def on_game_start(self): """ Splash Screen Callback """ return @abstractmethod def on_game_move(self, game, move): """ Game Piece Move Callback """ return @abstractmethod def on_game_end(self, game): """ Game Over Callback """ return class StaticGameWindow(BaseGameWindow): def __init__(self, fps): """ Display static graphics Very light on resources """ super().__init__(fps) def on_game_start(self): """ Splash Screen Callback """ return def on_game_move(self, game: engine.ChainReactionGame, move): """ Game Piece Move Callback """ # draw if no move specified if move is None: self.draw_all(game.board, game.player) return # play game.make_move(move) self.draw_all(game.board, game.player) def on_game_end(self, game): """ Game Over Callback """ if game.winner == 0: print("Red Wins!") elif game.winner == 1: print("Green Wins!") elif game.winner == 2: print("Sorry to see you go :(") # quit pygame pygame.quit() class AnimatedGameWindow(BaseGameWindow): def __init__(self, fps, flight_steps=10): """ Window that displays animations ------------------------------- - fps - frame rate limit - flight_steps - steps in a flight animation """ super().__init__(fps) self.flight_steps = flight_steps def draw_flights(self, flights, progress, player): # setup gcol, grow = G_SHAP offx, offy = (G_HOFF + G_WALL, G_VOFF + G_WALL) pcolor = COL_PLR2 if player else COL_PLR1 prog_frac = progress / self.flight_steps for origin, dest in flights: # indices orig_posx = G_WIDC * (origin % gcol) + offx + G_WIDC // 2 orig_posy = G_WIDC * (origin // gcol) + offy + G_WIDC // 2 dest_posx = G_WIDC * (dest % gcol) + offx + G_WIDC // 2 dest_posy = G_WIDC * (dest // gcol) + offy + G_WIDC // 2 # calculate positions pos_x = int(orig_posx + prog_frac * (dest_posx - orig_posx)) pos_y = int(orig_posy + prog_frac * (dest_posy - orig_posy)) # draw in present position gfxdraw.aacircle(self.surface, pos_x, pos_y, 10, pcolor) gfxdraw.filled_circle(self.surface, pos_x, pos_y, 10, pcolor) def explode_orbs(self, board, explosions, player, callback=None): """ Show orb explosion animation Does not return until animation is over Internal event handling """ # immediate return if explosions are absent if not explosions: return # set up origin and final indices for flight flights = [ (origin, dest) for origin in explosions for dest in engine.NTABLE[origin] ] # uniform speed for progress in range(self.flight_steps): self.clear() self.draw_grid() self.draw_indicator(player) self.draw_orbs(board, ignore=explosions) self.draw_flights(flights, progress, player) callback() if callback else None # optional callback self.update() self.event_handler() self.clock.tick(self.fps) def on_game_start(self): """ Splash Screen """ return def on_game_move(self, game: engine.ChainReactionAnimated, move): """ Function to execute when move specified """ # draw if no move specified if move is None: self.draw_all(game.board, game.player) return # invalid move if not game.make_move(move): return # lock to not respond to mouse clicks self.locked = True player = game.player # get steps until stable or game over while game.pending_moves and not game.game_over and self.open: # get board and explosions for animation prev_board, explosions = game.get_next_step() # draw explosions self.explode_orbs(prev_board, explosions, player) self.draw_all(game.board, game.player) # unlock window after handling events self.event_handler() self.locked = False def on_game_end(self, game: engine.ChainReactionAnimated): """ Game over screen """ global ORB_PL1, ORB_PL2 global COL_PLR1, COL_PLR2 global COL_FORE # convert colors to grayscale COL_PLR1 = (30, 30, 30) COL_PLR2 = (30, 30, 30) COL_FORE = (30, 30, 30) ORB_PL1 = [sprites.grayscale(x, 0.2) for x in ORB_PL1] ORB_PL2 = [sprites.grayscale(x, 0.2) for x in ORB_PL2] # save player player = game.player self.flight_steps = 20 # slow-mo # construct game over text font_instance = font.SysFont("Ubuntu Mono", 50, True, False) message = "GREEN WINS!" if game.winner else "RED WINS!" mscolor = (100, 255, 50) if game.winner else (255, 100, 50) game_over_text = font_instance.render(message, True, mscolor) text_w, text_h = game_over_text.get_size() text_dest = ((W_DIMS[0] - text_w) // 2, (W_DIMS[1] - text_h) // 2) blit_text = lambda: self.surface.blit(game_over_text, text_dest) # keep exploding for cool end-graphics while self.open and game.pending_moves: prev_board, explosions = game.get_next_step() self.explode_orbs(prev_board, explosions, player, blit_text) self.clear() self.draw_grid() self.draw_indicator(game.player) self.draw_orbs(game.board) blit_text() self.update() # draw static if pending moves are over if not game.pending_moves: self.clear() self.draw_grid() self.draw_indicator(game.player) self.draw_orbs(game.board) blit_text() self.update() while self.open: self.event_handler() self.clock.tick(self.fps) # voluntary close if not game.game_over and not self.open: print("Sorry to see you go :(") font.quit() pygame.quit()
en
0.651185
# ----------- COLORS ------------- # --------- DIMS ----------- # -------- ON INIT ---------- # ----------- INIT --------------- Calculate dimensions and construct sprites Input : g_shape (rows, cols) # pygame modules # calculate dims # construct sprites # ---------- CLASSES ------------- Most Basic Game Window # window pointers # status # mouse click and index Handle events in window # Refresh values # if locked, do nothing Draw rectangle to indicate next player Draw grid on screen # horizontal lines # vertical lines Draw orb sprites on the surface # ignore index # blit appropriate sprite on surface Draw all drawable elements Splash Screen Callback Game Piece Move Callback Game Over Callback Display static graphics Very light on resources Splash Screen Callback Game Piece Move Callback # draw if no move specified # play Game Over Callback # quit pygame Window that displays animations ------------------------------- - fps - frame rate limit - flight_steps - steps in a flight animation # setup # indices # calculate positions # draw in present position Show orb explosion animation Does not return until animation is over Internal event handling # immediate return if explosions are absent # set up origin and final indices for flight # uniform speed # optional callback Splash Screen Function to execute when move specified # draw if no move specified # invalid move # lock to not respond to mouse clicks # get steps until stable or game over # get board and explosions for animation # draw explosions # unlock window after handling events Game over screen # convert colors to grayscale # save player # slow-mo # construct game over text # keep exploding for cool end-graphics # draw static if pending moves are over # voluntary close
3.039771
3
awacs/elemental_appliances_software.py
alanjjenkins/awacs
358
6615518
# Copyright (c) 2012-2021, <NAME> <<EMAIL>> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Elemental Appliances and Software" prefix = "elemental-appliances-software" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateQuote = Action("CreateQuote") GetQuote = Action("GetQuote") ListQuotes = Action("ListQuotes") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateQuote = Action("UpdateQuote")
# Copyright (c) 2012-2021, <NAME> <<EMAIL>> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Elemental Appliances and Software" prefix = "elemental-appliances-software" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) CreateQuote = Action("CreateQuote") GetQuote = Action("GetQuote") ListQuotes = Action("ListQuotes") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateQuote = Action("UpdateQuote")
en
0.745275
# Copyright (c) 2012-2021, <NAME> <<EMAIL>> # All rights reserved. # # See LICENSE file for full license.
2.365107
2
packages/conan/recipes/python/conanfile.py
boberfly/aswf-docker
3
6615519
<gh_stars>1-10 from conans import AutoToolsBuildEnvironment, ConanFile, tools from contextlib import contextmanager import os class PythonConan(ConanFile): name = "python" description = "Python is a programming language that lets you work quickly and integrate systems more effectively." topics = ("conan", "python") license = "Python (PSF-2.0 license) and numpy (BSD-3-Clause license)" homepage = "https://python.org/" url = "https://github.com/AcademySoftwareFoundation/aswf-docker" settings = ( "os", "arch", "compiler", "build_type", "python", ) options = {"with_numpy": [True, False]} default_options = {"with_numpy": True} generators = "pkg_config" _autotools = None def configure(self): python_version = tools.Version(self.version) self.major_minor = f"{python_version.major}.{python_version.minor}" if "ASWF_NUMPY_VERSION" not in os.environ: self.options.with_numpy.value = False @property def _source_subfolder(self): return "source_subfolder" def source(self): tools.get( f"https://www.python.org/ftp/python/{self.version}/Python-{self.version}.tgz" ) os.rename(f"Python-{self.version}", self._source_subfolder) def export_sources(self): self.copy("run-with-system-python") self.copy("yum") @contextmanager def _build_context(self): if self.settings.compiler == "Visual Studio": with tools.vcvars(self.settings): env = { "AR": "{} lib".format( tools.unix_path(self.deps_user_info["automake"].ar_lib) ), "CC": "{} cl -nologo".format( tools.unix_path(self.deps_user_info["automake"].compile) ), "CXX": "{} cl -nologo".format( tools.unix_path(self.deps_user_info["automake"].compile) ), "NM": "dumpbin -symbols", "OBJDUMP": ":", "RANLIB": ":", "STRIP": ":", } with tools.environment_append(env): yield else: yield def _configure_autotools(self): if self._autotools: return self._autotools self._autotools = AutoToolsBuildEnvironment( self, win_bash=tools.os_info.is_windows ) if self.settings.os == "Windows": self._autotools.defines.append("PYTHON_BUILD_DLL") if self.settings.compiler == "Visual Studio": self._autotools.flags.append("-FS") self._autotools.cxx_flags.append("-EHsc") yes_no = lambda v: "yes" if v else "no" conf_args = [ "--enable-shared=yes", "--enable-static=no", "--enable-debug={}".format(yes_no(self.settings.build_type == "Debug")), "--enable-doxygen=no", "--enable-dot=no", "--enable-werror=no", "--enable-html-docs=no", ] self._autotools.configure(args=conf_args, configure_dir=self._source_subfolder) return self._autotools def build(self): with self._build_context(): autotools = self._configure_autotools() autotools.make() def package(self): self.copy("COPYING", src=self._source_subfolder, dst="licenses") self.copy("yum", dst="bin") self.copy("run-with-system-python", dst="bin") with self._build_context(): autotools = self._configure_autotools() autotools.install() python_version = tools.Version(self.version) if python_version.major == "3": tools.download( "https://bootstrap.pypa.io/get-pip.py", "get-pip.py", overwrite=True ) else: tools.download( "https://bootstrap.pypa.io/pip/2.7/get-pip.py", "get-pip.py", overwrite=True, ) py_exe = os.path.join(self.package_folder, "bin", f"python{self.major_minor}") with tools.environment_append( { "PATH": os.path.join(self.package_folder, "bin"), "LD_LIBRARY_PATH": os.path.join(self.package_folder, "lib"), } ): self.run(f"{py_exe} get-pip.py") self.run(f"{py_exe} -m pip install nose coverage docutils epydoc") if self.options.get_safe("with_numpy"): self.run( f"{py_exe} -m pip install numpy=={os.environ['ASWF_NUMPY_VERSION']}" ) def package_info(self): self.cpp_info.filenames["pkg_config"] = "python" self.user_info.python_interp = f"python{self.major_minor}" self.cpp_info.components["PythonInterp"].bindirs = ["bin"] self.cpp_info.components["PythonLibs"].requires = ["PythonInterp"] python_version = tools.Version(self.version) if python_version > "3.6" and python_version < 3.9: suffix = "m" else: suffix = "" self.cpp_info.components["PythonLibs"].includedirs = [ f"include/python{self.major_minor}{suffix}" ] self.cpp_info.components["PythonLibs"].libs = [ f"python{self.major_minor}{suffix}" ] if self.settings.os == "Windows": self.cpp_info.components["PythonLibs"].defines.append("PYTHON_DLL")
from conans import AutoToolsBuildEnvironment, ConanFile, tools from contextlib import contextmanager import os class PythonConan(ConanFile): name = "python" description = "Python is a programming language that lets you work quickly and integrate systems more effectively." topics = ("conan", "python") license = "Python (PSF-2.0 license) and numpy (BSD-3-Clause license)" homepage = "https://python.org/" url = "https://github.com/AcademySoftwareFoundation/aswf-docker" settings = ( "os", "arch", "compiler", "build_type", "python", ) options = {"with_numpy": [True, False]} default_options = {"with_numpy": True} generators = "pkg_config" _autotools = None def configure(self): python_version = tools.Version(self.version) self.major_minor = f"{python_version.major}.{python_version.minor}" if "ASWF_NUMPY_VERSION" not in os.environ: self.options.with_numpy.value = False @property def _source_subfolder(self): return "source_subfolder" def source(self): tools.get( f"https://www.python.org/ftp/python/{self.version}/Python-{self.version}.tgz" ) os.rename(f"Python-{self.version}", self._source_subfolder) def export_sources(self): self.copy("run-with-system-python") self.copy("yum") @contextmanager def _build_context(self): if self.settings.compiler == "Visual Studio": with tools.vcvars(self.settings): env = { "AR": "{} lib".format( tools.unix_path(self.deps_user_info["automake"].ar_lib) ), "CC": "{} cl -nologo".format( tools.unix_path(self.deps_user_info["automake"].compile) ), "CXX": "{} cl -nologo".format( tools.unix_path(self.deps_user_info["automake"].compile) ), "NM": "dumpbin -symbols", "OBJDUMP": ":", "RANLIB": ":", "STRIP": ":", } with tools.environment_append(env): yield else: yield def _configure_autotools(self): if self._autotools: return self._autotools self._autotools = AutoToolsBuildEnvironment( self, win_bash=tools.os_info.is_windows ) if self.settings.os == "Windows": self._autotools.defines.append("PYTHON_BUILD_DLL") if self.settings.compiler == "Visual Studio": self._autotools.flags.append("-FS") self._autotools.cxx_flags.append("-EHsc") yes_no = lambda v: "yes" if v else "no" conf_args = [ "--enable-shared=yes", "--enable-static=no", "--enable-debug={}".format(yes_no(self.settings.build_type == "Debug")), "--enable-doxygen=no", "--enable-dot=no", "--enable-werror=no", "--enable-html-docs=no", ] self._autotools.configure(args=conf_args, configure_dir=self._source_subfolder) return self._autotools def build(self): with self._build_context(): autotools = self._configure_autotools() autotools.make() def package(self): self.copy("COPYING", src=self._source_subfolder, dst="licenses") self.copy("yum", dst="bin") self.copy("run-with-system-python", dst="bin") with self._build_context(): autotools = self._configure_autotools() autotools.install() python_version = tools.Version(self.version) if python_version.major == "3": tools.download( "https://bootstrap.pypa.io/get-pip.py", "get-pip.py", overwrite=True ) else: tools.download( "https://bootstrap.pypa.io/pip/2.7/get-pip.py", "get-pip.py", overwrite=True, ) py_exe = os.path.join(self.package_folder, "bin", f"python{self.major_minor}") with tools.environment_append( { "PATH": os.path.join(self.package_folder, "bin"), "LD_LIBRARY_PATH": os.path.join(self.package_folder, "lib"), } ): self.run(f"{py_exe} get-pip.py") self.run(f"{py_exe} -m pip install nose coverage docutils epydoc") if self.options.get_safe("with_numpy"): self.run( f"{py_exe} -m pip install numpy=={os.environ['ASWF_NUMPY_VERSION']}" ) def package_info(self): self.cpp_info.filenames["pkg_config"] = "python" self.user_info.python_interp = f"python{self.major_minor}" self.cpp_info.components["PythonInterp"].bindirs = ["bin"] self.cpp_info.components["PythonLibs"].requires = ["PythonInterp"] python_version = tools.Version(self.version) if python_version > "3.6" and python_version < 3.9: suffix = "m" else: suffix = "" self.cpp_info.components["PythonLibs"].includedirs = [ f"include/python{self.major_minor}{suffix}" ] self.cpp_info.components["PythonLibs"].libs = [ f"python{self.major_minor}{suffix}" ] if self.settings.os == "Windows": self.cpp_info.components["PythonLibs"].defines.append("PYTHON_DLL")
none
1
2.242002
2
dmscripts/upload_dos_opportunities_email_list.py
alphagov-mirror/digitalmarketplace-scripts
1
6615520
<reponame>alphagov-mirror/digitalmarketplace-scripts from dmscripts.helpers.supplier_data_helpers import SupplierFrameworkData def find_user_emails(supplier_users, services): """Return email addresses for any supplier who has a service in services.""" email_addresses = [] for service in services: for user in supplier_users.get(service['supplierId'], []): email_addresses.append(user['email address']) return email_addresses def main(data_api_client, mailchimp_client, lot_data, logger): logger.info( "Begin mailchimp email list updating process for {} lot".format(lot_data["lot_slug"]), extra={"lot_data": lot_data} ) data_helper = SupplierFrameworkData(data_api_client, lot_data["framework_slug"]) supplier_users = data_helper.get_supplier_users() framework_services = data_api_client.find_services_iter( framework=lot_data["framework_slug"], lot=lot_data["lot_slug"] ) emails = frozenset(x.lower() for x in find_user_emails(supplier_users, framework_services)) logger.info( "{} emails have been found for lot {}".format(len(emails), lot_data["lot_slug"]) ) existing_mailchimp_emails = mailchimp_client.get_email_addresses_from_list(lot_data["list_id"]) # lowercase required because mailchimp may capatalise emails addresses returned from the mailchimp API based on it's # on how it stores both the lowercase hash but also the original (potentially capatilised) email address new_emails = set(emails).difference(x.lower() for x in existing_mailchimp_emails) logger.info( "Subscribing {} new emails to mailchimp list {}".format(len(new_emails), lot_data["list_id"]) ) if not mailchimp_client.subscribe_new_emails_to_list(lot_data["list_id"], new_emails): return False return True
from dmscripts.helpers.supplier_data_helpers import SupplierFrameworkData def find_user_emails(supplier_users, services): """Return email addresses for any supplier who has a service in services.""" email_addresses = [] for service in services: for user in supplier_users.get(service['supplierId'], []): email_addresses.append(user['email address']) return email_addresses def main(data_api_client, mailchimp_client, lot_data, logger): logger.info( "Begin mailchimp email list updating process for {} lot".format(lot_data["lot_slug"]), extra={"lot_data": lot_data} ) data_helper = SupplierFrameworkData(data_api_client, lot_data["framework_slug"]) supplier_users = data_helper.get_supplier_users() framework_services = data_api_client.find_services_iter( framework=lot_data["framework_slug"], lot=lot_data["lot_slug"] ) emails = frozenset(x.lower() for x in find_user_emails(supplier_users, framework_services)) logger.info( "{} emails have been found for lot {}".format(len(emails), lot_data["lot_slug"]) ) existing_mailchimp_emails = mailchimp_client.get_email_addresses_from_list(lot_data["list_id"]) # lowercase required because mailchimp may capatalise emails addresses returned from the mailchimp API based on it's # on how it stores both the lowercase hash but also the original (potentially capatilised) email address new_emails = set(emails).difference(x.lower() for x in existing_mailchimp_emails) logger.info( "Subscribing {} new emails to mailchimp list {}".format(len(new_emails), lot_data["list_id"]) ) if not mailchimp_client.subscribe_new_emails_to_list(lot_data["list_id"], new_emails): return False return True
en
0.931789
Return email addresses for any supplier who has a service in services. # lowercase required because mailchimp may capatalise emails addresses returned from the mailchimp API based on it's # on how it stores both the lowercase hash but also the original (potentially capatilised) email address
2.55109
3
imperiumab/subsidy_wiki.py
vlki/imperiumab-scripts
0
6615521
import json from pprint import pprint import urllib.parse from imperiumab.subsidy import Subsidy from imperiumab.wiki import parse_wiki_date, format_wiki_str def get_subsidy_page_names(wiki): subsidy_category = wiki.site.categories['Dotace'] list(map(lambda p: p.name, subsidy_category.members())) def get_subsidies(wiki): subsidy_category = wiki.site.categories['Dotace'] return map(lambda subsidy_page: map_subsidy_page_to_subsidy(wiki, subsidy_page), subsidy_category.members()) def get_subsidies_for_company(wiki, company_name): query = "[[Category:Dotace]][[Has beneficiary::{company_name}]]|limit=2000".format(company_name=company_name) subsidies = [] for answer in wiki.site.ask(query): for property_name, property_data in answer.items(): if property_name == 'fulltext': subsidies.append(map_subsidy_page_to_subsidy(wiki, wiki.site.pages[property_data])) return subsidies def map_subsidy_page_to_subsidy(wiki, subsidy_page): subsidy = Subsidy() subsidy.id = subsidy_page.name print(subsidy.id) subsidy_structured_data = wiki.site.raw_api(action='smwbrowse', browse='subject', params=json.dumps( {'subject': subsidy_page.name, 'ns': 0, 'iw': '', 'subobject': ''})) # pprint(subsidy_structured_data) for structured_data_item in subsidy_structured_data['query']['data']: property_name = structured_data_item['property'] property_data = structured_data_item['dataitem'] if property_name == 'Has_beneficiary': beneficiary_encoded_page_name = property_data[0]['item'] beneficiary_structured_data = wiki.site.raw_api(action='smwbrowse', browse='subject', params=json.dumps( {'subject': beneficiary_encoded_page_name, 'ns': 0, 'iw': '', 'subobject': ''})) for beneficiary_structured_data_item in beneficiary_structured_data['query']['data']: if beneficiary_structured_data_item['property'] == '_SKEY': subsidy.beneficiary = beneficiary_structured_data_item['dataitem'][0]['item'] if property_name == 'Has_beneficiary_original_name': subsidy.beneficiary_original_name = property_data[0]['item'] if property_name == 'Has_country_code': subsidy.country_code = property_data[0]['item'] if property_name == 'Has_project_code': subsidy.project_code = property_data[0]['item'] if property_name == 'Has_project_name': subsidy.project_name = property_data[0]['item'] if property_name == 'Has_programme_code': subsidy.programme_code = property_data[0]['item'] if property_name == 'Has_programme_name': subsidy.programme_name = property_data[0]['item'] if property_name == 'Was_signed_on': subsidy.signed_on = parse_wiki_date(property_data[0]['item']) if property_name == 'Was_in_year': subsidy.year = property_data[0]['item'] if property_name == 'Has_source': subsidy.source = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_from_fund': subsidy.eu_cofinancing_from_fund = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_from_period': subsidy.eu_cofinancing_from_period = property_data[0]['item'] if property_name == 'Has_original_currency': subsidy.original_currency = property_data[0]['item'] if property_name == 'Has_amount_in_original_currency': subsidy.amount_in_original_currency = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_amount_in_original_currency': subsidy.eu_cofinancing_amount_in_original_currency = property_data[0]['item'] if property_name == 'Has_currency_exchange_to_EUR': subsidy.currency_exchange_to_eur = property_data[0]['item'] if property_name == 'Has_amount_in_EUR': subsidy.amount_in_eur = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_amount_in_EUR': subsidy.eu_cofinancing_amount_in_eur = property_data[0]['item'] if property_name == 'Has_currency_exchange_to_CZK': subsidy.currency_exchange_to_czk = property_data[0]['item'] if property_name == 'Has_amount_in_CZK': subsidy.amount_in_czk = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_amount_in_CZK': subsidy.eu_cofinancing_amount_in_czk = property_data[0]['item'] # print(subsidy) # pprint(vars(subsidy)) # exit(1) return subsidy page_template = """ {{| class="wikitable" |- !Identifikátor |{subsidy[id]} |- !Příjemce |[[Has beneficiary::{subsidy[beneficiary]}]] |- !Příjemce (jak je uveden v datech) |[[Has beneficiary original name::{subsidy[beneficiary_original_name]}]] |- !Země příjemce |[[Has country code::{subsidy[country_code]}]] |- !Kód projektu |[[Has project code::{subsidy[project_code]}]] |- !Název projektu |[[Has project name::{subsidy[project_name]}]] |- !Kód programu |[[Has programme code::{subsidy[programme_code]}]] |- !Název programu |[[Has programme name::{subsidy[programme_name]}]] |- !Datum podpisu |[[Was signed on::{subsidy[signed_on]}]] |- !Rok (podpisu, či začátku projektu) |[[Was in year::{subsidy[year]}]] |- !Původní měna |[[Has original currency::{subsidy[original_currency]}]] |- !Celková částka dotace v původní měně |[[Has amount in original currency::{subsidy[amount_in_original_currency]}]] |- !Částka z rozpočtu EU v původní měně |[[Has EU cofinancing amount in original currency::{subsidy[eu_cofinancing_amount_in_original_currency]}]] |- !Převod na EUR |[[Has currency exchange to EUR::{subsidy[currency_exchange_to_eur]}]] |- !Celková částka dotace (EUR) |[[Has amount in EUR::{subsidy[amount_in_eur]}]] |- !Částka z rozpočtu EU (EUR) |[[Has EU cofinancing amount in EUR::{subsidy[eu_cofinancing_amount_in_eur]}]] |- !Převod na CZK |[[Has currency exchange to CZK::{subsidy[currency_exchange_to_czk]}]] |- !Celková částka dotace (CZK) |[[Has amount in CZK::{subsidy[amount_in_czk]}]] |- !Částka z rozpočtu EU (CZK) |[[Has EU cofinancing amount in CZK::{subsidy[eu_cofinancing_amount_in_czk]}]] |- !EU fond |[[Has EU cofinancing from fund::{subsidy[eu_cofinancing_from_fund]}]] |- !EU dotační období |[[Has EU cofinancing from period::{subsidy[eu_cofinancing_from_period]}]] |- !Zdroj |{{{{#set: Has source = {subsidy[source]} |template=BySetTemplateSimpleValueOutput }}}} |}} [[Category:Dotace]] """ def build_subsidy_page(subsidy): subsidy_obj = vars(subsidy) for subsidy_attr in subsidy_obj.keys(): if subsidy_obj[subsidy_attr] is None: subsidy_obj[subsidy_attr] = '' return page_template.format(subsidy=subsidy_obj) def exists_subsidy_page(wiki, subsidy): page = wiki.site.pages[subsidy.id] return page.exists def create_subsidy_page(wiki, subsidy, change_text): page = wiki.site.pages[subsidy.id] if page.exists: raise Exception('Could not create as the page already exists') page.edit(build_subsidy_page(subsidy), change_text)
import json from pprint import pprint import urllib.parse from imperiumab.subsidy import Subsidy from imperiumab.wiki import parse_wiki_date, format_wiki_str def get_subsidy_page_names(wiki): subsidy_category = wiki.site.categories['Dotace'] list(map(lambda p: p.name, subsidy_category.members())) def get_subsidies(wiki): subsidy_category = wiki.site.categories['Dotace'] return map(lambda subsidy_page: map_subsidy_page_to_subsidy(wiki, subsidy_page), subsidy_category.members()) def get_subsidies_for_company(wiki, company_name): query = "[[Category:Dotace]][[Has beneficiary::{company_name}]]|limit=2000".format(company_name=company_name) subsidies = [] for answer in wiki.site.ask(query): for property_name, property_data in answer.items(): if property_name == 'fulltext': subsidies.append(map_subsidy_page_to_subsidy(wiki, wiki.site.pages[property_data])) return subsidies def map_subsidy_page_to_subsidy(wiki, subsidy_page): subsidy = Subsidy() subsidy.id = subsidy_page.name print(subsidy.id) subsidy_structured_data = wiki.site.raw_api(action='smwbrowse', browse='subject', params=json.dumps( {'subject': subsidy_page.name, 'ns': 0, 'iw': '', 'subobject': ''})) # pprint(subsidy_structured_data) for structured_data_item in subsidy_structured_data['query']['data']: property_name = structured_data_item['property'] property_data = structured_data_item['dataitem'] if property_name == 'Has_beneficiary': beneficiary_encoded_page_name = property_data[0]['item'] beneficiary_structured_data = wiki.site.raw_api(action='smwbrowse', browse='subject', params=json.dumps( {'subject': beneficiary_encoded_page_name, 'ns': 0, 'iw': '', 'subobject': ''})) for beneficiary_structured_data_item in beneficiary_structured_data['query']['data']: if beneficiary_structured_data_item['property'] == '_SKEY': subsidy.beneficiary = beneficiary_structured_data_item['dataitem'][0]['item'] if property_name == 'Has_beneficiary_original_name': subsidy.beneficiary_original_name = property_data[0]['item'] if property_name == 'Has_country_code': subsidy.country_code = property_data[0]['item'] if property_name == 'Has_project_code': subsidy.project_code = property_data[0]['item'] if property_name == 'Has_project_name': subsidy.project_name = property_data[0]['item'] if property_name == 'Has_programme_code': subsidy.programme_code = property_data[0]['item'] if property_name == 'Has_programme_name': subsidy.programme_name = property_data[0]['item'] if property_name == 'Was_signed_on': subsidy.signed_on = parse_wiki_date(property_data[0]['item']) if property_name == 'Was_in_year': subsidy.year = property_data[0]['item'] if property_name == 'Has_source': subsidy.source = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_from_fund': subsidy.eu_cofinancing_from_fund = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_from_period': subsidy.eu_cofinancing_from_period = property_data[0]['item'] if property_name == 'Has_original_currency': subsidy.original_currency = property_data[0]['item'] if property_name == 'Has_amount_in_original_currency': subsidy.amount_in_original_currency = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_amount_in_original_currency': subsidy.eu_cofinancing_amount_in_original_currency = property_data[0]['item'] if property_name == 'Has_currency_exchange_to_EUR': subsidy.currency_exchange_to_eur = property_data[0]['item'] if property_name == 'Has_amount_in_EUR': subsidy.amount_in_eur = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_amount_in_EUR': subsidy.eu_cofinancing_amount_in_eur = property_data[0]['item'] if property_name == 'Has_currency_exchange_to_CZK': subsidy.currency_exchange_to_czk = property_data[0]['item'] if property_name == 'Has_amount_in_CZK': subsidy.amount_in_czk = property_data[0]['item'] if property_name == 'Has_EU_cofinancing_amount_in_CZK': subsidy.eu_cofinancing_amount_in_czk = property_data[0]['item'] # print(subsidy) # pprint(vars(subsidy)) # exit(1) return subsidy page_template = """ {{| class="wikitable" |- !Identifikátor |{subsidy[id]} |- !Příjemce |[[Has beneficiary::{subsidy[beneficiary]}]] |- !Příjemce (jak je uveden v datech) |[[Has beneficiary original name::{subsidy[beneficiary_original_name]}]] |- !Země příjemce |[[Has country code::{subsidy[country_code]}]] |- !Kód projektu |[[Has project code::{subsidy[project_code]}]] |- !Název projektu |[[Has project name::{subsidy[project_name]}]] |- !Kód programu |[[Has programme code::{subsidy[programme_code]}]] |- !Název programu |[[Has programme name::{subsidy[programme_name]}]] |- !Datum podpisu |[[Was signed on::{subsidy[signed_on]}]] |- !Rok (podpisu, či začátku projektu) |[[Was in year::{subsidy[year]}]] |- !Původní měna |[[Has original currency::{subsidy[original_currency]}]] |- !Celková částka dotace v původní měně |[[Has amount in original currency::{subsidy[amount_in_original_currency]}]] |- !Částka z rozpočtu EU v původní měně |[[Has EU cofinancing amount in original currency::{subsidy[eu_cofinancing_amount_in_original_currency]}]] |- !Převod na EUR |[[Has currency exchange to EUR::{subsidy[currency_exchange_to_eur]}]] |- !Celková částka dotace (EUR) |[[Has amount in EUR::{subsidy[amount_in_eur]}]] |- !Částka z rozpočtu EU (EUR) |[[Has EU cofinancing amount in EUR::{subsidy[eu_cofinancing_amount_in_eur]}]] |- !Převod na CZK |[[Has currency exchange to CZK::{subsidy[currency_exchange_to_czk]}]] |- !Celková částka dotace (CZK) |[[Has amount in CZK::{subsidy[amount_in_czk]}]] |- !Částka z rozpočtu EU (CZK) |[[Has EU cofinancing amount in CZK::{subsidy[eu_cofinancing_amount_in_czk]}]] |- !EU fond |[[Has EU cofinancing from fund::{subsidy[eu_cofinancing_from_fund]}]] |- !EU dotační období |[[Has EU cofinancing from period::{subsidy[eu_cofinancing_from_period]}]] |- !Zdroj |{{{{#set: Has source = {subsidy[source]} |template=BySetTemplateSimpleValueOutput }}}} |}} [[Category:Dotace]] """ def build_subsidy_page(subsidy): subsidy_obj = vars(subsidy) for subsidy_attr in subsidy_obj.keys(): if subsidy_obj[subsidy_attr] is None: subsidy_obj[subsidy_attr] = '' return page_template.format(subsidy=subsidy_obj) def exists_subsidy_page(wiki, subsidy): page = wiki.site.pages[subsidy.id] return page.exists def create_subsidy_page(wiki, subsidy, change_text): page = wiki.site.pages[subsidy.id] if page.exists: raise Exception('Could not create as the page already exists') page.edit(build_subsidy_page(subsidy), change_text)
cs
0.2298
# pprint(subsidy_structured_data) # print(subsidy) # pprint(vars(subsidy)) # exit(1) {{| class="wikitable" |- !Identifikátor |{subsidy[id]} |- !Příjemce |[[Has beneficiary::{subsidy[beneficiary]}]] |- !Příjemce (jak je uveden v datech) |[[Has beneficiary original name::{subsidy[beneficiary_original_name]}]] |- !Země příjemce |[[Has country code::{subsidy[country_code]}]] |- !Kód projektu |[[Has project code::{subsidy[project_code]}]] |- !Název projektu |[[Has project name::{subsidy[project_name]}]] |- !Kód programu |[[Has programme code::{subsidy[programme_code]}]] |- !Název programu |[[Has programme name::{subsidy[programme_name]}]] |- !Datum podpisu |[[Was signed on::{subsidy[signed_on]}]] |- !Rok (podpisu, či začátku projektu) |[[Was in year::{subsidy[year]}]] |- !Původní měna |[[Has original currency::{subsidy[original_currency]}]] |- !Celková částka dotace v původní měně |[[Has amount in original currency::{subsidy[amount_in_original_currency]}]] |- !Částka z rozpočtu EU v původní měně |[[Has EU cofinancing amount in original currency::{subsidy[eu_cofinancing_amount_in_original_currency]}]] |- !Převod na EUR |[[Has currency exchange to EUR::{subsidy[currency_exchange_to_eur]}]] |- !Celková částka dotace (EUR) |[[Has amount in EUR::{subsidy[amount_in_eur]}]] |- !Částka z rozpočtu EU (EUR) |[[Has EU cofinancing amount in EUR::{subsidy[eu_cofinancing_amount_in_eur]}]] |- !Převod na CZK |[[Has currency exchange to CZK::{subsidy[currency_exchange_to_czk]}]] |- !Celková částka dotace (CZK) |[[Has amount in CZK::{subsidy[amount_in_czk]}]] |- !Částka z rozpočtu EU (CZK) |[[Has EU cofinancing amount in CZK::{subsidy[eu_cofinancing_amount_in_czk]}]] |- !EU fond |[[Has EU cofinancing from fund::{subsidy[eu_cofinancing_from_fund]}]] |- !EU dotační období |[[Has EU cofinancing from period::{subsidy[eu_cofinancing_from_period]}]] |- !Zdroj |{{{{#set: Has source = {subsidy[source]} |template=BySetTemplateSimpleValueOutput }}}} |}} [[Category:Dotace]]
3.08309
3
llesync.py
atzm/llesync
0
6615522
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import abc import errno import fcntl import fnmatch import logging import argparse import contextlib from concurrent import futures import llehash class File(metaclass=abc.ABCMeta): @property @abc.abstractmethod def openflag(self): pass @property @abc.abstractmethod def lockmode(self): pass def __init__(self, path, encoding, hasher): self.path = os.path.realpath(path) self.encoding = encoding self.hasher = hasher self.fileno = -1 self.statc = self.stat0 def __eq__(self, other): for attr in ['st_size', 'st_mtime']: if getattr(self.stat, attr) != getattr(other.stat, attr): return False for attr in ['basename', 'digest']: if getattr(self, attr) != getattr(other, attr): return False return True def __ne__(self, other): return not self.__eq__(other) def __str__(self): return self.path @property def encoded(self): return str(self).encode(self.encoding, 'surrogateescape') @property def basename(self): return os.path.basename(str(self)) @property def digest(self): if self.opened: with self.hasher.open() as desc: return desc.digest(self.fileno) @property def opened(self): return self.fileno >= 0 @property def stat(self): if self.opened and self.statc == self.stat0: self.statc = os.stat_result(int(s) for s in os.fstat(self.fileno)) return self.statc @property def stat0(self): return os.stat_result((-1,) * 10) @property def errnoignore(self): return [] @property def isdir(self): return os.path.isdir(self.encoded) def iterdir(self): for f in os.listdir(self.encoded): yield self.join(f.decode(self.encoding, 'surrogateescape')) def join(self, f): path = os.path.join(str(self), f) return type(self)(path, self.encoding, self.hasher) @contextlib.contextmanager def open(self, mode=0o0644): try: try: self.fileno = os.open(self.encoded, self.openflag, mode) fcntl.flock(self.fileno, self.lockmode | fcntl.LOCK_NB) except OSError as e: if e.errno not in self.errnoignore: raise yield self finally: if self.opened: os.close(self.fileno) self.fileno = -1 @contextlib.contextmanager def mkdir(self, src): yield def seek(self, *args, **kwargs): if self.opened: os.lseek(self.fileno, *args, **kwargs) def truncate(self, *args, **kwargs): pass def copyfrom(self, src): pass class FileRD(File): @property def openflag(self): return os.O_LARGEFILE | os.O_RDONLY @property def lockmode(self): return fcntl.LOCK_SH class FileRDWR(File): @property def openflag(self): return os.O_LARGEFILE | os.O_RDWR | os.O_CREAT @property def lockmode(self): return fcntl.LOCK_EX @contextlib.contextmanager def mkdir(self, src): try: os.mkdir(self.encoded, src.stat.st_mode & 0o0777) except OSError as e: if e.errno != errno.EEXIST: raise yield os.utime(self.encoded, (src.stat.st_atime, src.stat.st_mtime)) def truncate(self, *args, **kwargs): if self.opened: os.ftruncate(self.fileno, *args, **kwargs) def copyfrom(self, src): if not (self.opened and src.opened): return size = src.stat.st_size while size > 0: size -= os.sendfile(self.fileno, src.fileno, None, size) os.utime(self.fileno, (src.stat.st_atime, src.stat.st_mtime)) class FileStat(FileRD): @property def errnoignore(self): return [errno.ENOENT] @contextlib.contextmanager def umask(mask): try: oldmask = -1 oldmask = os.umask(mask) yield finally: if oldmask > 0: os.umask(oldmask) def copy(args, src, dst): with src.open(), dst.open(src.stat.st_mode & 0o0777): if args.sync and src == dst: logging.debug('skip: %s', src) return dst.seek(0, os.SEEK_SET) dst.truncate(0) dst.copyfrom(src) logging.info('copy: %s -> %s', src, dst) def xfnmatch(path, patterns): return any(fnmatch.fnmatch(path, p) for p in patterns) def walk(args, src, dst): match = str(src) + os.sep if src.isdir else str(src) if not xfnmatch(match, args.include) or xfnmatch(match, args.exclude): logging.debug('skip: %s', src) return if dst.isdir: dst = dst.join(src.basename) if not src.isdir: yield args.executor.submit(copy, args, src, dst) return with src.open(), dst.mkdir(src): for xsrc in src.iterdir(): for future in walk(args, xsrc, dst): yield future def run(args): nfiles = len(args.files) if nfiles < 2: logging.error('two files required at least') return if nfiles == 2: src = args.reader(args.files[0], args.src_enc, args.hasher) dst = args.reader(args.files[1], args.dst_enc, args.hasher) if src.isdir and not dst.isdir: logging.error('last file must be a directory') return if nfiles > 2: dst = args.reader(args.files[-1], args.dst_enc, args.hasher) if not dst.isdir: logging.error('last file must be a directory') return dst = args.writer(args.files.pop(), args.dst_enc, args.hasher) while args.files: src = args.reader(args.files.pop(0), args.src_enc, args.hasher) for future in walk(args, src, dst): yield future def prepare(args): args.reader = FileRD args.writer = FileStat if args.dry_run else FileRDWR args.hasher = llehash.Hash.instance(args.digest_algo, args.digest_key) args.executor = futures.ThreadPoolExecutor(max_workers=args.threads) if args.verbose > 1: loglevel = logging.DEBUG elif args.verbose > 0 or args.dry_run: loglevel = logging.INFO else: loglevel = logging.WARN logging.basicConfig(level=loglevel, format='[%(levelname)s] %(message)s') def main(): digs = sorted(llehash.Hash.algorithm().keys()) argp = argparse.ArgumentParser() argp.add_argument('-v', '--verbose', action='count', default=0) argp.add_argument('-n', '--dry-run', action='store_true', default=False) argp.add_argument('-S', '--sync', action='store_true', default=False) argp.add_argument('-I', '--include', nargs='+', default=['*/', '*']) argp.add_argument('-X', '--exclude', nargs='+', default=[]) argp.add_argument('-s', '--src-enc', default=sys.getfilesystemencoding()) argp.add_argument('-d', '--dst-enc', default='utf-8') argp.add_argument('-a', '--digest-algo', choices=digs, default='dummy') argp.add_argument('-k', '--digest-key', type=os.fsencode) argp.add_argument('-t', '--threads', type=int, default=os.cpu_count()) argp.add_argument('files', nargs=argparse.REMAINDER) args = argp.parse_args() prepare(args) with umask(0), args.executor: for future in futures.as_completed(run(args)): try: future.result() except Exception as e: logging.error(str(e)) if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import abc import errno import fcntl import fnmatch import logging import argparse import contextlib from concurrent import futures import llehash class File(metaclass=abc.ABCMeta): @property @abc.abstractmethod def openflag(self): pass @property @abc.abstractmethod def lockmode(self): pass def __init__(self, path, encoding, hasher): self.path = os.path.realpath(path) self.encoding = encoding self.hasher = hasher self.fileno = -1 self.statc = self.stat0 def __eq__(self, other): for attr in ['st_size', 'st_mtime']: if getattr(self.stat, attr) != getattr(other.stat, attr): return False for attr in ['basename', 'digest']: if getattr(self, attr) != getattr(other, attr): return False return True def __ne__(self, other): return not self.__eq__(other) def __str__(self): return self.path @property def encoded(self): return str(self).encode(self.encoding, 'surrogateescape') @property def basename(self): return os.path.basename(str(self)) @property def digest(self): if self.opened: with self.hasher.open() as desc: return desc.digest(self.fileno) @property def opened(self): return self.fileno >= 0 @property def stat(self): if self.opened and self.statc == self.stat0: self.statc = os.stat_result(int(s) for s in os.fstat(self.fileno)) return self.statc @property def stat0(self): return os.stat_result((-1,) * 10) @property def errnoignore(self): return [] @property def isdir(self): return os.path.isdir(self.encoded) def iterdir(self): for f in os.listdir(self.encoded): yield self.join(f.decode(self.encoding, 'surrogateescape')) def join(self, f): path = os.path.join(str(self), f) return type(self)(path, self.encoding, self.hasher) @contextlib.contextmanager def open(self, mode=0o0644): try: try: self.fileno = os.open(self.encoded, self.openflag, mode) fcntl.flock(self.fileno, self.lockmode | fcntl.LOCK_NB) except OSError as e: if e.errno not in self.errnoignore: raise yield self finally: if self.opened: os.close(self.fileno) self.fileno = -1 @contextlib.contextmanager def mkdir(self, src): yield def seek(self, *args, **kwargs): if self.opened: os.lseek(self.fileno, *args, **kwargs) def truncate(self, *args, **kwargs): pass def copyfrom(self, src): pass class FileRD(File): @property def openflag(self): return os.O_LARGEFILE | os.O_RDONLY @property def lockmode(self): return fcntl.LOCK_SH class FileRDWR(File): @property def openflag(self): return os.O_LARGEFILE | os.O_RDWR | os.O_CREAT @property def lockmode(self): return fcntl.LOCK_EX @contextlib.contextmanager def mkdir(self, src): try: os.mkdir(self.encoded, src.stat.st_mode & 0o0777) except OSError as e: if e.errno != errno.EEXIST: raise yield os.utime(self.encoded, (src.stat.st_atime, src.stat.st_mtime)) def truncate(self, *args, **kwargs): if self.opened: os.ftruncate(self.fileno, *args, **kwargs) def copyfrom(self, src): if not (self.opened and src.opened): return size = src.stat.st_size while size > 0: size -= os.sendfile(self.fileno, src.fileno, None, size) os.utime(self.fileno, (src.stat.st_atime, src.stat.st_mtime)) class FileStat(FileRD): @property def errnoignore(self): return [errno.ENOENT] @contextlib.contextmanager def umask(mask): try: oldmask = -1 oldmask = os.umask(mask) yield finally: if oldmask > 0: os.umask(oldmask) def copy(args, src, dst): with src.open(), dst.open(src.stat.st_mode & 0o0777): if args.sync and src == dst: logging.debug('skip: %s', src) return dst.seek(0, os.SEEK_SET) dst.truncate(0) dst.copyfrom(src) logging.info('copy: %s -> %s', src, dst) def xfnmatch(path, patterns): return any(fnmatch.fnmatch(path, p) for p in patterns) def walk(args, src, dst): match = str(src) + os.sep if src.isdir else str(src) if not xfnmatch(match, args.include) or xfnmatch(match, args.exclude): logging.debug('skip: %s', src) return if dst.isdir: dst = dst.join(src.basename) if not src.isdir: yield args.executor.submit(copy, args, src, dst) return with src.open(), dst.mkdir(src): for xsrc in src.iterdir(): for future in walk(args, xsrc, dst): yield future def run(args): nfiles = len(args.files) if nfiles < 2: logging.error('two files required at least') return if nfiles == 2: src = args.reader(args.files[0], args.src_enc, args.hasher) dst = args.reader(args.files[1], args.dst_enc, args.hasher) if src.isdir and not dst.isdir: logging.error('last file must be a directory') return if nfiles > 2: dst = args.reader(args.files[-1], args.dst_enc, args.hasher) if not dst.isdir: logging.error('last file must be a directory') return dst = args.writer(args.files.pop(), args.dst_enc, args.hasher) while args.files: src = args.reader(args.files.pop(0), args.src_enc, args.hasher) for future in walk(args, src, dst): yield future def prepare(args): args.reader = FileRD args.writer = FileStat if args.dry_run else FileRDWR args.hasher = llehash.Hash.instance(args.digest_algo, args.digest_key) args.executor = futures.ThreadPoolExecutor(max_workers=args.threads) if args.verbose > 1: loglevel = logging.DEBUG elif args.verbose > 0 or args.dry_run: loglevel = logging.INFO else: loglevel = logging.WARN logging.basicConfig(level=loglevel, format='[%(levelname)s] %(message)s') def main(): digs = sorted(llehash.Hash.algorithm().keys()) argp = argparse.ArgumentParser() argp.add_argument('-v', '--verbose', action='count', default=0) argp.add_argument('-n', '--dry-run', action='store_true', default=False) argp.add_argument('-S', '--sync', action='store_true', default=False) argp.add_argument('-I', '--include', nargs='+', default=['*/', '*']) argp.add_argument('-X', '--exclude', nargs='+', default=[]) argp.add_argument('-s', '--src-enc', default=sys.getfilesystemencoding()) argp.add_argument('-d', '--dst-enc', default='utf-8') argp.add_argument('-a', '--digest-algo', choices=digs, default='dummy') argp.add_argument('-k', '--digest-key', type=os.fsencode) argp.add_argument('-t', '--threads', type=int, default=os.cpu_count()) argp.add_argument('files', nargs=argparse.REMAINDER) args = argp.parse_args() prepare(args) with umask(0), args.executor: for future in futures.as_completed(run(args)): try: future.result() except Exception as e: logging.error(str(e)) if __name__ == '__main__': main()
en
0.308914
#!/usr/bin/env python3 # -*- coding: utf-8 -*-
2.533164
3
rgw/v1/lib/io_info.py
rpratap-bot/ceph-qe-scripts
0
6615523
import v1.utils.log as log from v1.utils.utils import FileOps IO_INFO_FNAME = 'io_info.yaml' # class to generate the yaml structure. class IOInfoStructure(object): def __init__(self): self.initial = lambda: {'users': list()} self.user = lambda **args: {'user_id': args['user_id'], 'access_key': args['access_key'], 'secret_key': args['secret_key'], 'bucket': list() } self.bucket = lambda **args: {'name': args['bucket_name'], 'keys': list(), 'test_op_code': args['test_op_code']} self.key = lambda **args: {'name': args['key_name'], 'size': args['size'], 'md5_on_s3': args['md5_on_s3'], 'upload_type': args['upload_type'], 'test_op_code': args['test_op_code']} # class to add io info to yaml file class AddIOInfo(object): def __init__(self, yaml_fname=IO_INFO_FNAME): self.yaml_fname = yaml_fname self.file_op = FileOps(self.yaml_fname, type='yaml') self.io_structure = IOInfoStructure() def initialize(self): initial_data = self.io_structure.initial() log.info('initial_data: %s' % (initial_data)) self.file_op.add_data(initial_data) def add_user_info(self, **user): user_info = self.io_structure.user(**user) log.info('got user info structure: %s' % user_info) yaml_data = self.file_op.get_data() log.info('got yaml data %s' % yaml_data) yaml_data['users'].append(user_info) log.info('data to add: %s' % yaml_data) self.file_op.add_data(yaml_data) def add_bucket_info(self, access_key, **bucket): bucket_info = self.io_structure.bucket(**bucket) yaml_data = self.file_op.get_data() indx = None for i, k in enumerate(yaml_data['users']): if k['access_key'] == access_key: indx = i break yaml_data['users'][indx]['bucket'].append(bucket_info) self.file_op.add_data(yaml_data) def add_keys_info(self, access_key, bucket_name, **key): yaml_data = self.file_op.get_data() access_key_indx = None bucket_indx = None for i, k in enumerate(yaml_data['users']): if k['access_key'] == access_key: access_key_indx = i break for i, k in enumerate(yaml_data['users'][access_key_indx]['bucket']): if k['name'] == bucket_name: bucket_indx = i break key_info = self.io_structure.key(**key) yaml_data['users'][access_key_indx]['bucket'][bucket_indx]['keys'].append(key_info) self.file_op.add_data(yaml_data) if __name__ == '__main__': # test data user_data1 = {'user_id': 'batman', 'access_key': '235sff34', 'secret_key': '<KEY>', } user_data2 = {'user_id': 'heman', 'access_key': 'sfssf', 'secret_key': '<KEY>', } user_data3 = {'user_id': 'antman', 'access_key': 'fwg435', 'secret_key': '<KEY>', } io_info = AddIOInfo('io_info.yaml') io_info.initialize() io_info.add_user_info(**user_data1) io_info.add_bucket_info(access_key='235sff34', **{'bucket_name': 'b1'}) io_info.add_bucket_info(access_key='235sff34', **{'bucket_name': 'b2'}) io_info.add_bucket_info(access_key='235sff34', **{'bucket_name': 'b3'}) key_info1 = {'key_name': 'k1', 'size': 374, 'md5_on_s3': 'sfsf734', 'upload_type': 'normal'} key_info2 = {'key_name': 'k2', 'size': 242, 'md5_on_s3': 'sgg345', 'upload_type': 'normal'} key_info3 = {'key_name': 'k3', 'size': 3563, 'md5_on_s3': 'sfy4hfd', 'upload_type': 'normal'} key_info4 = {'key_name': 'k4', 'size': 2342, 'md5_on_s3': 'sfsf3534', 'upload_type': 'normal'} io_info.add_keys_info(access_key='235sff34', bucket_name='b1', **key_info1) io_info.add_keys_info(access_key='235sff34', bucket_name='b3', **key_info2) io_info.add_keys_info(access_key='235sff34', bucket_name='b3', **key_info3) io_info.add_keys_info(access_key='235sff34', bucket_name='b3', **key_info4)
import v1.utils.log as log from v1.utils.utils import FileOps IO_INFO_FNAME = 'io_info.yaml' # class to generate the yaml structure. class IOInfoStructure(object): def __init__(self): self.initial = lambda: {'users': list()} self.user = lambda **args: {'user_id': args['user_id'], 'access_key': args['access_key'], 'secret_key': args['secret_key'], 'bucket': list() } self.bucket = lambda **args: {'name': args['bucket_name'], 'keys': list(), 'test_op_code': args['test_op_code']} self.key = lambda **args: {'name': args['key_name'], 'size': args['size'], 'md5_on_s3': args['md5_on_s3'], 'upload_type': args['upload_type'], 'test_op_code': args['test_op_code']} # class to add io info to yaml file class AddIOInfo(object): def __init__(self, yaml_fname=IO_INFO_FNAME): self.yaml_fname = yaml_fname self.file_op = FileOps(self.yaml_fname, type='yaml') self.io_structure = IOInfoStructure() def initialize(self): initial_data = self.io_structure.initial() log.info('initial_data: %s' % (initial_data)) self.file_op.add_data(initial_data) def add_user_info(self, **user): user_info = self.io_structure.user(**user) log.info('got user info structure: %s' % user_info) yaml_data = self.file_op.get_data() log.info('got yaml data %s' % yaml_data) yaml_data['users'].append(user_info) log.info('data to add: %s' % yaml_data) self.file_op.add_data(yaml_data) def add_bucket_info(self, access_key, **bucket): bucket_info = self.io_structure.bucket(**bucket) yaml_data = self.file_op.get_data() indx = None for i, k in enumerate(yaml_data['users']): if k['access_key'] == access_key: indx = i break yaml_data['users'][indx]['bucket'].append(bucket_info) self.file_op.add_data(yaml_data) def add_keys_info(self, access_key, bucket_name, **key): yaml_data = self.file_op.get_data() access_key_indx = None bucket_indx = None for i, k in enumerate(yaml_data['users']): if k['access_key'] == access_key: access_key_indx = i break for i, k in enumerate(yaml_data['users'][access_key_indx]['bucket']): if k['name'] == bucket_name: bucket_indx = i break key_info = self.io_structure.key(**key) yaml_data['users'][access_key_indx]['bucket'][bucket_indx]['keys'].append(key_info) self.file_op.add_data(yaml_data) if __name__ == '__main__': # test data user_data1 = {'user_id': 'batman', 'access_key': '235sff34', 'secret_key': '<KEY>', } user_data2 = {'user_id': 'heman', 'access_key': 'sfssf', 'secret_key': '<KEY>', } user_data3 = {'user_id': 'antman', 'access_key': 'fwg435', 'secret_key': '<KEY>', } io_info = AddIOInfo('io_info.yaml') io_info.initialize() io_info.add_user_info(**user_data1) io_info.add_bucket_info(access_key='235sff34', **{'bucket_name': 'b1'}) io_info.add_bucket_info(access_key='235sff34', **{'bucket_name': 'b2'}) io_info.add_bucket_info(access_key='235sff34', **{'bucket_name': 'b3'}) key_info1 = {'key_name': 'k1', 'size': 374, 'md5_on_s3': 'sfsf734', 'upload_type': 'normal'} key_info2 = {'key_name': 'k2', 'size': 242, 'md5_on_s3': 'sgg345', 'upload_type': 'normal'} key_info3 = {'key_name': 'k3', 'size': 3563, 'md5_on_s3': 'sfy4hfd', 'upload_type': 'normal'} key_info4 = {'key_name': 'k4', 'size': 2342, 'md5_on_s3': 'sfsf3534', 'upload_type': 'normal'} io_info.add_keys_info(access_key='235sff34', bucket_name='b1', **key_info1) io_info.add_keys_info(access_key='235sff34', bucket_name='b3', **key_info2) io_info.add_keys_info(access_key='235sff34', bucket_name='b3', **key_info3) io_info.add_keys_info(access_key='235sff34', bucket_name='b3', **key_info4)
en
0.746005
# class to generate the yaml structure. # class to add io info to yaml file # test data
2.421099
2
scripts/aws_elb.py
JaccyLi/zabbix
8
6615524
<reponame>JaccyLi/zabbix #!/usr/bin/python # vim: set expandtab: import boto import boto.ec2.elb import argparse def main(): cmd_parser = argparse.ArgumentParser(description='Send ELB Info To Zabbix') cmd_parser.add_argument( '-k', '--aws_access_key_id', dest='key', help='AWS Access Key ID', required=True) cmd_parser.add_argument( '-s', '--aws_secret_key_id', dest='secret', help='AWS Secret Access Key', required=True) cmd_parser.add_argument( '-r', '--region', dest='region', help='AWS Region', required=True) cmd_parser.add_argument( '-n', '--name', dest='name', help='Zabbix Name', required=True) args = cmd_parser.parse_args() conn = boto.ec2.elb.connect_to_region( args.region, aws_access_key_id=args.key, aws_secret_access_key=args.secret) elbs = conn.get_all_load_balancers() total_elbs = len(elbs) outofservice = 0 outofservice_elbs = [] outofservice_instance = [] for elb in elbs: inst_health = conn.describe_instance_health(elb.name) for inst_h in inst_health: if inst_h.state != 'InService': outofservice = outofservice + 1 outofservice_elbs.append(elb.name) outofservice_instance.append(inst_h.instance_id) if not outofservice_elbs: outofservice_elbs = 'none' if not outofservice_instance: outofservice_instance = 'none' outofservice = str(outofservice) total_elbs = str(total_elbs) outofservice_elbs = str(outofservice_elbs).strip('[]').strip('u') outofservice_instance = str(outofservice_instance).strip('[]').strip('u') print(args.name + ' total_elbs ' + total_elbs) print(args.name + ' num_out_of_service ' + outofservice) print(args.name + ' elbs_with_out_of_service_instances ' + outofservice_elbs) print(args.name + ' instance_id ' + outofservice_instance) if __name__ == "__main__": main()
#!/usr/bin/python # vim: set expandtab: import boto import boto.ec2.elb import argparse def main(): cmd_parser = argparse.ArgumentParser(description='Send ELB Info To Zabbix') cmd_parser.add_argument( '-k', '--aws_access_key_id', dest='key', help='AWS Access Key ID', required=True) cmd_parser.add_argument( '-s', '--aws_secret_key_id', dest='secret', help='AWS Secret Access Key', required=True) cmd_parser.add_argument( '-r', '--region', dest='region', help='AWS Region', required=True) cmd_parser.add_argument( '-n', '--name', dest='name', help='Zabbix Name', required=True) args = cmd_parser.parse_args() conn = boto.ec2.elb.connect_to_region( args.region, aws_access_key_id=args.key, aws_secret_access_key=args.secret) elbs = conn.get_all_load_balancers() total_elbs = len(elbs) outofservice = 0 outofservice_elbs = [] outofservice_instance = [] for elb in elbs: inst_health = conn.describe_instance_health(elb.name) for inst_h in inst_health: if inst_h.state != 'InService': outofservice = outofservice + 1 outofservice_elbs.append(elb.name) outofservice_instance.append(inst_h.instance_id) if not outofservice_elbs: outofservice_elbs = 'none' if not outofservice_instance: outofservice_instance = 'none' outofservice = str(outofservice) total_elbs = str(total_elbs) outofservice_elbs = str(outofservice_elbs).strip('[]').strip('u') outofservice_instance = str(outofservice_instance).strip('[]').strip('u') print(args.name + ' total_elbs ' + total_elbs) print(args.name + ' num_out_of_service ' + outofservice) print(args.name + ' elbs_with_out_of_service_instances ' + outofservice_elbs) print(args.name + ' instance_id ' + outofservice_instance) if __name__ == "__main__": main()
en
0.154121
#!/usr/bin/python # vim: set expandtab:
2.20855
2
hyperlink_complex.py
kessler-frost/complex-word-tagging
0
6615525
<reponame>kessler-frost/complex-word-tagging import docx from nltk.tokenize import word_tokenize import classifier as clf import string import sys import subprocess as sp filename = sys.argv[1] def file_check(filename): e, output = sp.getstatusoutput('ls | grep ' + filename + ';') if e != 0: print("No such file in the current directory.") return None, -1 else: print("File imported succesfully...") return output, 1 def add_hyperlink_to_doc(complex_list, document): paragraph = document.add_paragraph() gen_url = 'https://www.merriam-webster.com/dictionary/' num = 1 for c in complex_list: url = gen_url + c # This gets access to the document.xml.rels file and gets a new relation id value part = paragraph.part r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True) # Create the w:hyperlink tag and add needed values hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink') hyperlink.set(docx.oxml.shared.qn('r:id'), r_id) # Create a w:r element new_run = docx.oxml.shared.OxmlElement('w:r') # Create a new w:rPr element rPr = docx.oxml.shared.OxmlElement('w:rPr') # Join all the xml elements together and add the required text to the w:r element blank_space_and_num = docx.oxml.shared.OxmlElement('w:r') blank_space_and_num.text = '\n\t' + str(num) + '. ' paragraph._p.append(blank_space_and_num) new_run.append(rPr) new_run.text = c hyperlink.append(new_run) paragraph._p.append(hyperlink) num += 1 def save_complex_total(input_file): file_as_text = open(input_file, 'r').read() file_as_string = file_as_text.translate(str.maketrans('', '', string.punctuation)) all_words_list = word_tokenize(file_as_string) complex_list = [] for w in all_words_list: word = w.strip().lower() if clf.classifier(word) == 1: if word not in complex_list: complex_list.append(word) document = docx.Document() para_original_text = document.add_paragraph() original_text = file_as_text + '\n\nThe following are hyperlinks to meanings of complex words found :- ' text_element = docx.oxml.shared.OxmlElement('w:r') text_element.text = original_text para_original_text._p.append(text_element) add_hyperlink_to_doc(complex_list = complex_list, document = document) document.save(str(input_file.split('.')[0]) + "_tagged_words.docx") filename, status = file_check(filename) if status == -1: print("Exiting...") exit() else: save_complex_total(filename) print("The doc file has been saved by the name :" + str(filename.split('.')[0]) + "_tagged_words.docx") # punc = [ele for ele in string.punctuation] # print(punc)
import docx from nltk.tokenize import word_tokenize import classifier as clf import string import sys import subprocess as sp filename = sys.argv[1] def file_check(filename): e, output = sp.getstatusoutput('ls | grep ' + filename + ';') if e != 0: print("No such file in the current directory.") return None, -1 else: print("File imported succesfully...") return output, 1 def add_hyperlink_to_doc(complex_list, document): paragraph = document.add_paragraph() gen_url = 'https://www.merriam-webster.com/dictionary/' num = 1 for c in complex_list: url = gen_url + c # This gets access to the document.xml.rels file and gets a new relation id value part = paragraph.part r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True) # Create the w:hyperlink tag and add needed values hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink') hyperlink.set(docx.oxml.shared.qn('r:id'), r_id) # Create a w:r element new_run = docx.oxml.shared.OxmlElement('w:r') # Create a new w:rPr element rPr = docx.oxml.shared.OxmlElement('w:rPr') # Join all the xml elements together and add the required text to the w:r element blank_space_and_num = docx.oxml.shared.OxmlElement('w:r') blank_space_and_num.text = '\n\t' + str(num) + '. ' paragraph._p.append(blank_space_and_num) new_run.append(rPr) new_run.text = c hyperlink.append(new_run) paragraph._p.append(hyperlink) num += 1 def save_complex_total(input_file): file_as_text = open(input_file, 'r').read() file_as_string = file_as_text.translate(str.maketrans('', '', string.punctuation)) all_words_list = word_tokenize(file_as_string) complex_list = [] for w in all_words_list: word = w.strip().lower() if clf.classifier(word) == 1: if word not in complex_list: complex_list.append(word) document = docx.Document() para_original_text = document.add_paragraph() original_text = file_as_text + '\n\nThe following are hyperlinks to meanings of complex words found :- ' text_element = docx.oxml.shared.OxmlElement('w:r') text_element.text = original_text para_original_text._p.append(text_element) add_hyperlink_to_doc(complex_list = complex_list, document = document) document.save(str(input_file.split('.')[0]) + "_tagged_words.docx") filename, status = file_check(filename) if status == -1: print("Exiting...") exit() else: save_complex_total(filename) print("The doc file has been saved by the name :" + str(filename.split('.')[0]) + "_tagged_words.docx") # punc = [ele for ele in string.punctuation] # print(punc)
en
0.546992
# This gets access to the document.xml.rels file and gets a new relation id value # Create the w:hyperlink tag and add needed values # Create a w:r element # Create a new w:rPr element # Join all the xml elements together and add the required text to the w:r element # punc = [ele for ele in string.punctuation] # print(punc)
2.870733
3
2019/Round1A/exo1_2019-round_1A.py
victor-paltz/code-jam
1
6615526
<reponame>victor-paltz/code-jam T = int(input()) for t in range(1, T+1): row, col = [int(x) for x in input().split()] if row < 5 and col < 5 and (row, col) not in [(3, 4), (4, 3), (4, 4)]: print("Case #{}: IMPOSSIBLE".format(t)) continue else: print("Case #{}: POSSIBLE".format(t)) rev = False if col < 5 and row != 3: row, col = col, row rev = True data = [] if (row, col) == (4, 4): for j in [0, 3, 2, 1]: for i in range(4): data.append((i, (j+1 + (1 if i % 2 else -1) + 4) % 4)) else: x, y = 0, 0 if row % 2: x, y = 1, 0 for _ in range(col): data.append((x % col, y)) data.append(((x+1) % col, y+2)) data.append(((x+3) % col, y+1)) x += 1 y += 3 x = 0 for _ in range((row-y)//2): for _ in range(col): data.append((x % col, y)) data.append(((x+3) % col, y+1)) x += 1 y += 2 if rev: row, col = col, row data = [(y, x) for (x, y) in data] for x, y in data: print(y+1, x+1) # Test part assert len(set(data)) == row*col for (x1, y1), (x2, y2) in zip(data, data[1:]): assert x1 != x2 assert y1 != y2 if x1-y1 == x2-y2: print((x1, y1), (x2, y2)) if x1+y1 == x2+y2: print((x1, y1), (x2, y2)) assert x1-y1 != x2-y2 assert x1+y1 != x2+y2 for (x1, y1) in data: assert 0 <= x1 <= col assert 0 <= y1 <= row
T = int(input()) for t in range(1, T+1): row, col = [int(x) for x in input().split()] if row < 5 and col < 5 and (row, col) not in [(3, 4), (4, 3), (4, 4)]: print("Case #{}: IMPOSSIBLE".format(t)) continue else: print("Case #{}: POSSIBLE".format(t)) rev = False if col < 5 and row != 3: row, col = col, row rev = True data = [] if (row, col) == (4, 4): for j in [0, 3, 2, 1]: for i in range(4): data.append((i, (j+1 + (1 if i % 2 else -1) + 4) % 4)) else: x, y = 0, 0 if row % 2: x, y = 1, 0 for _ in range(col): data.append((x % col, y)) data.append(((x+1) % col, y+2)) data.append(((x+3) % col, y+1)) x += 1 y += 3 x = 0 for _ in range((row-y)//2): for _ in range(col): data.append((x % col, y)) data.append(((x+3) % col, y+1)) x += 1 y += 2 if rev: row, col = col, row data = [(y, x) for (x, y) in data] for x, y in data: print(y+1, x+1) # Test part assert len(set(data)) == row*col for (x1, y1), (x2, y2) in zip(data, data[1:]): assert x1 != x2 assert y1 != y2 if x1-y1 == x2-y2: print((x1, y1), (x2, y2)) if x1+y1 == x2+y2: print((x1, y1), (x2, y2)) assert x1-y1 != x2-y2 assert x1+y1 != x2+y2 for (x1, y1) in data: assert 0 <= x1 <= col assert 0 <= y1 <= row
es
0.141026
#{}: IMPOSSIBLE".format(t)) #{}: POSSIBLE".format(t)) # Test part
3.109479
3
tests/conftest.py
jonodrew/digitalmarketplace-scripts
0
6615527
# -*- coding: utf-8 -*- """Config for py.test: Defining fixtures in here makes them available to test functions.""" import json import os import pytest from mock import Mock import requests_mock FIXTURES_DIR = os.path.join(os.path.dirname(__file__), 'fixtures') @pytest.fixture def mock_data_client(): """Mock data client for use in tests. These can be overwritten in individual tests.""" mock_data_client = Mock() mock_data_client.get_framework.return_value = dict(frameworks=dict(lots=[ {'slug': 'test_lot_slug_1'}, {'slug': 'test_lot_slug_2'}, ])) mock_data_client.find_draft_services_iter.return_value = {} mock_data_client.export_users.return_value = { 'users': [ {'supplier_id': 12345, 'application_status': 'application', 'extraneous_field': 'foo'}, {'supplier_id': 23456, 'application_status': 'no_application', 'extraneous_field': 'foo'}, {'supplier_id': 123, 'application_status': 'application', 'extraneous_field': 'foo'}, {'supplier_id': 456, 'application_status': 'application', 'extraneous_field': 'foo'}, {'supplier_id': 789, 'application_status': 'no_application', 'extraneous_field': 'foo'}, {'supplier_id': 101, 'application_status': 'no_application', 'extraneous_field': 'foo'} ] } with open(os.path.join(FIXTURES_DIR, 'test_supplier_frameworks_response.json')) as supplier_frameworks_response: mock_data_client.find_framework_suppliers.return_value = json.loads(supplier_frameworks_response.read()) return mock_data_client @pytest.yield_fixture def rmock(): with requests_mock.mock() as rmock: real_register_uri = rmock.register_uri def register_uri_with_complete_qs(*args, **kwargs): if 'complete_qs' not in kwargs: kwargs['complete_qs'] = True return real_register_uri(*args, **kwargs) rmock.register_uri = register_uri_with_complete_qs yield rmock
# -*- coding: utf-8 -*- """Config for py.test: Defining fixtures in here makes them available to test functions.""" import json import os import pytest from mock import Mock import requests_mock FIXTURES_DIR = os.path.join(os.path.dirname(__file__), 'fixtures') @pytest.fixture def mock_data_client(): """Mock data client for use in tests. These can be overwritten in individual tests.""" mock_data_client = Mock() mock_data_client.get_framework.return_value = dict(frameworks=dict(lots=[ {'slug': 'test_lot_slug_1'}, {'slug': 'test_lot_slug_2'}, ])) mock_data_client.find_draft_services_iter.return_value = {} mock_data_client.export_users.return_value = { 'users': [ {'supplier_id': 12345, 'application_status': 'application', 'extraneous_field': 'foo'}, {'supplier_id': 23456, 'application_status': 'no_application', 'extraneous_field': 'foo'}, {'supplier_id': 123, 'application_status': 'application', 'extraneous_field': 'foo'}, {'supplier_id': 456, 'application_status': 'application', 'extraneous_field': 'foo'}, {'supplier_id': 789, 'application_status': 'no_application', 'extraneous_field': 'foo'}, {'supplier_id': 101, 'application_status': 'no_application', 'extraneous_field': 'foo'} ] } with open(os.path.join(FIXTURES_DIR, 'test_supplier_frameworks_response.json')) as supplier_frameworks_response: mock_data_client.find_framework_suppliers.return_value = json.loads(supplier_frameworks_response.read()) return mock_data_client @pytest.yield_fixture def rmock(): with requests_mock.mock() as rmock: real_register_uri = rmock.register_uri def register_uri_with_complete_qs(*args, **kwargs): if 'complete_qs' not in kwargs: kwargs['complete_qs'] = True return real_register_uri(*args, **kwargs) rmock.register_uri = register_uri_with_complete_qs yield rmock
en
0.870429
# -*- coding: utf-8 -*- Config for py.test: Defining fixtures in here makes them available to test functions. Mock data client for use in tests. These can be overwritten in individual tests.
2.323365
2
iom/migrations/0026_akvoflow_last_update.py
acaciawater/iom
0
6615528
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('iom', '0025_auto_20151103_2348'), ] operations = [ migrations.AddField( model_name='akvoflow', name='last_update', field=models.DateTimeField(null=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('iom', '0025_auto_20151103_2348'), ] operations = [ migrations.AddField( model_name='akvoflow', name='last_update', field=models.DateTimeField(null=True), ), ]
en
0.769321
# -*- coding: utf-8 -*-
1.415985
1
app/routers/stats.py
bernikr/citybike-api
0
6615529
from fastapi import APIRouter from app.apis.globalAPI import get_global_stats, GlobalStats router = APIRouter() @router.get("", response_model=GlobalStats) def get_global_statistics(): return get_global_stats()
from fastapi import APIRouter from app.apis.globalAPI import get_global_stats, GlobalStats router = APIRouter() @router.get("", response_model=GlobalStats) def get_global_statistics(): return get_global_stats()
none
1
2.021216
2
build/BuildService.py
403712387/ggf
0
6615530
import os import stat import copy import shutil import time import sys currentTime = time.localtime() strTime = "%d-%02d-%02d %02d:%02d:%02d" % (currentTime.tm_year, currentTime.tm_mon, currentTime.tm_mday, currentTime.tm_hour, currentTime.tm_min,currentTime.tm_sec) # 服务模块 serviceName = "ggf" # git信息 gitBranch = "unknown" gitCommitId = "unknown" #编译参数,支持debug,race compileArg = "" #------------------------函数的定义-------------------------# #清理 def cleanFiles(path): if os.path.exists(path): shutil.rmtree(path) #解析参数 def parseArgs(): global compileArg if "race" in sys.argv: compileArg = "-race" if "debug" in sys.argv: compileArg = '''-gcflags "-N -l"''' #下载依赖的包 def downloadThirdLibrary(): librarys = ["github.com/btfak/sntp", "github.com/sirupsen/logrus", "github.com/shirou/gopsutil", "github.com/segmentio/kafka-go", "github.com/mattn/go-sqlite3"] for library in librarys: os.system("go get %s"%library) #获取git的信息(获取当前分支以及commit id) def getGitInfo(): global gitBranch, gitCommitId gitDir = "../.git" #获取分支信息 branchFile = os.path.join(gitDir, "HEAD") if os.path.exists(branchFile): with open(branchFile, "r") as f: line = f.readline() line = line.strip() splits = line.split("/") if len(splits) > 0: gitBranch = splits[-1] # 获取commit id commitIdFile = os.path.join(gitDir + "/refs/heads" , gitBranch) if os.path.exists(commitIdFile): with open(commitIdFile) as f: line = f.readline() line = line.strip() gitCommitId = line #编译各个模块 def compileService(): global serviceName, compileArg, gitBranch, gitCommitId compileSuccessful = False # 切换目录 currentPath = os.getcwd() os.chdir("../src") # 格式话git信息 git = "-X HostServiceModule.GitBranch=%s -X HostServiceModule.GitCommitID=%s"%(gitBranch, gitCommitId) # 获取当前GOPATH currentGoPath = "" pipe = os.popen("go env GOPATH") lines = pipe.readlines() if len(lines) > 0 : currentGoPath = lines[0].strip("\n") # 编译 projectPath = os.getcwd()[:-4] goPathEnv = "export GOPATH=%s:%s"%(currentGoPath,projectPath) os.system(goPathEnv + " && go clean") os.system(goPathEnv + " && go clean -r") os.system(goPathEnv + " && go clean -cache") compile = '''go build -ldflags "%s" %s -o ./bin/%s/%s main.go'''%(git, compileArg, serviceName, serviceName) print(goPathEnv + " && " + compile) if os.system(goPathEnv + " && " + compile) == 0: compileSuccessful = True os.chdir(currentPath) return compileSuccessful # 拷贝配置文件 def copyConfigFile(): global serviceName src = "../config" dst = "../src/bin/%s"%serviceName copyFiles(src, dst) # 配置文件要放在config目录下 src = "../src/bin/%s/config.json"%serviceName dst = "../src/bin/%s/config"%serviceName copyFiles(src, dst) os.remove(src) #修改文件的权限 def processFilePromission(path): files = os.listdir(path) for file in files: fileName = os.path.join(path, file) if not os.path.isfile(fileName): continue #对于sh结束的文件,修改权限 if fileName.endswith(".sh"): os.chmod(fileName, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) #拷贝文件或者目录 def copyFiles(source, destination): #复制文件(要注意权限和软连接这种情况) def copyFile(sourceFile, destDir): if not os.path.exists(sourceFile): return if not os.path.exists(destDir): os.makedirs(destDir) if os.path.islink(sourceFile): #复制软连接 currentPath = os.getcwd() symbolLink = os.readlink(sourceFile) os.chdir(destDir) os.symlink(symbolLink, os.path.basename(sourceFile)) os.chdir(currentPath) elif os.path.isfile(sourceFile): #复制文件 with open(sourceFile, "rb") as input: with open(os.path.join(destDir, os.path.basename(sourceFile)), "wb") as output: output.write(input.read()) os.chmod(os.path.join(destDir, os.path.basename(sourceFile)), os.stat(sourceFile).st_mode) if not os.path.exists(source): print("copy %s to %s fail, not find %s"%(source, destination, source)) return # 目标文件夹一定要存在 if not os.path.exists(destination): os.makedirs(destination) if os.path.isdir(source): #复制整个目录下的文件 for path, directorys, files in os.walk(source): subPath = path[len(source): ] # 创建目录 if subPath.startswith("/"): subPath = subPath[1:] destinationPath = os.path.join(destination, subPath) if not os.path.exists(destinationPath): os.makedirs(destinationPath) # 复制目录下中的文件 for file in files: copyFile(os.path.join(path, file), destinationPath) elif os.path.isfile(source): # 复制单个文件 copyFile(source, destination) #修改脚本中的结束符,\r\n换为\n def formatLineBrak(): global serviceName fileNames = ["../src/bin/" + serviceName + "/start.sh", "../src/bin/" + serviceName + "/stop.sh"] for fileName in fileNames: if not os.path.exists(fileName): continue fileData = "" with open(fileName, "r") as file: for lineData in file: lineData = lineData.replace("\r\n", "\n") fileData += lineData # 向启动脚本中写入内容 with open(fileName, "w") as file: file.write(fileData) #构建服务 def buildService(): global serviceName outputDir = "../src/bin/" + serviceName serviceDir = "./" + serviceName parseArgs() downloadThirdLibrary() cleanFiles(outputDir) cleanFiles(serviceDir) getGitInfo() #编译各个模块 if not compileService(): print("\n--------------compile fail at %s--------------" % (strTime)) return -1 #拷贝文件 copyConfigFile() #处理脚本 formatLineBrak() #修改文件的权限 processFilePromission(outputDir) #移动到当前目录 print("move dir %s to %s"%(outputDir, serviceDir)) copyFiles(outputDir, serviceDir) print("\n--------------compile successful at %s--------------"%(strTime)) return 0 #------------------------函数的调用-------------------------# buildService()
import os import stat import copy import shutil import time import sys currentTime = time.localtime() strTime = "%d-%02d-%02d %02d:%02d:%02d" % (currentTime.tm_year, currentTime.tm_mon, currentTime.tm_mday, currentTime.tm_hour, currentTime.tm_min,currentTime.tm_sec) # 服务模块 serviceName = "ggf" # git信息 gitBranch = "unknown" gitCommitId = "unknown" #编译参数,支持debug,race compileArg = "" #------------------------函数的定义-------------------------# #清理 def cleanFiles(path): if os.path.exists(path): shutil.rmtree(path) #解析参数 def parseArgs(): global compileArg if "race" in sys.argv: compileArg = "-race" if "debug" in sys.argv: compileArg = '''-gcflags "-N -l"''' #下载依赖的包 def downloadThirdLibrary(): librarys = ["github.com/btfak/sntp", "github.com/sirupsen/logrus", "github.com/shirou/gopsutil", "github.com/segmentio/kafka-go", "github.com/mattn/go-sqlite3"] for library in librarys: os.system("go get %s"%library) #获取git的信息(获取当前分支以及commit id) def getGitInfo(): global gitBranch, gitCommitId gitDir = "../.git" #获取分支信息 branchFile = os.path.join(gitDir, "HEAD") if os.path.exists(branchFile): with open(branchFile, "r") as f: line = f.readline() line = line.strip() splits = line.split("/") if len(splits) > 0: gitBranch = splits[-1] # 获取commit id commitIdFile = os.path.join(gitDir + "/refs/heads" , gitBranch) if os.path.exists(commitIdFile): with open(commitIdFile) as f: line = f.readline() line = line.strip() gitCommitId = line #编译各个模块 def compileService(): global serviceName, compileArg, gitBranch, gitCommitId compileSuccessful = False # 切换目录 currentPath = os.getcwd() os.chdir("../src") # 格式话git信息 git = "-X HostServiceModule.GitBranch=%s -X HostServiceModule.GitCommitID=%s"%(gitBranch, gitCommitId) # 获取当前GOPATH currentGoPath = "" pipe = os.popen("go env GOPATH") lines = pipe.readlines() if len(lines) > 0 : currentGoPath = lines[0].strip("\n") # 编译 projectPath = os.getcwd()[:-4] goPathEnv = "export GOPATH=%s:%s"%(currentGoPath,projectPath) os.system(goPathEnv + " && go clean") os.system(goPathEnv + " && go clean -r") os.system(goPathEnv + " && go clean -cache") compile = '''go build -ldflags "%s" %s -o ./bin/%s/%s main.go'''%(git, compileArg, serviceName, serviceName) print(goPathEnv + " && " + compile) if os.system(goPathEnv + " && " + compile) == 0: compileSuccessful = True os.chdir(currentPath) return compileSuccessful # 拷贝配置文件 def copyConfigFile(): global serviceName src = "../config" dst = "../src/bin/%s"%serviceName copyFiles(src, dst) # 配置文件要放在config目录下 src = "../src/bin/%s/config.json"%serviceName dst = "../src/bin/%s/config"%serviceName copyFiles(src, dst) os.remove(src) #修改文件的权限 def processFilePromission(path): files = os.listdir(path) for file in files: fileName = os.path.join(path, file) if not os.path.isfile(fileName): continue #对于sh结束的文件,修改权限 if fileName.endswith(".sh"): os.chmod(fileName, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) #拷贝文件或者目录 def copyFiles(source, destination): #复制文件(要注意权限和软连接这种情况) def copyFile(sourceFile, destDir): if not os.path.exists(sourceFile): return if not os.path.exists(destDir): os.makedirs(destDir) if os.path.islink(sourceFile): #复制软连接 currentPath = os.getcwd() symbolLink = os.readlink(sourceFile) os.chdir(destDir) os.symlink(symbolLink, os.path.basename(sourceFile)) os.chdir(currentPath) elif os.path.isfile(sourceFile): #复制文件 with open(sourceFile, "rb") as input: with open(os.path.join(destDir, os.path.basename(sourceFile)), "wb") as output: output.write(input.read()) os.chmod(os.path.join(destDir, os.path.basename(sourceFile)), os.stat(sourceFile).st_mode) if not os.path.exists(source): print("copy %s to %s fail, not find %s"%(source, destination, source)) return # 目标文件夹一定要存在 if not os.path.exists(destination): os.makedirs(destination) if os.path.isdir(source): #复制整个目录下的文件 for path, directorys, files in os.walk(source): subPath = path[len(source): ] # 创建目录 if subPath.startswith("/"): subPath = subPath[1:] destinationPath = os.path.join(destination, subPath) if not os.path.exists(destinationPath): os.makedirs(destinationPath) # 复制目录下中的文件 for file in files: copyFile(os.path.join(path, file), destinationPath) elif os.path.isfile(source): # 复制单个文件 copyFile(source, destination) #修改脚本中的结束符,\r\n换为\n def formatLineBrak(): global serviceName fileNames = ["../src/bin/" + serviceName + "/start.sh", "../src/bin/" + serviceName + "/stop.sh"] for fileName in fileNames: if not os.path.exists(fileName): continue fileData = "" with open(fileName, "r") as file: for lineData in file: lineData = lineData.replace("\r\n", "\n") fileData += lineData # 向启动脚本中写入内容 with open(fileName, "w") as file: file.write(fileData) #构建服务 def buildService(): global serviceName outputDir = "../src/bin/" + serviceName serviceDir = "./" + serviceName parseArgs() downloadThirdLibrary() cleanFiles(outputDir) cleanFiles(serviceDir) getGitInfo() #编译各个模块 if not compileService(): print("\n--------------compile fail at %s--------------" % (strTime)) return -1 #拷贝文件 copyConfigFile() #处理脚本 formatLineBrak() #修改文件的权限 processFilePromission(outputDir) #移动到当前目录 print("move dir %s to %s"%(outputDir, serviceDir)) copyFiles(outputDir, serviceDir) print("\n--------------compile successful at %s--------------"%(strTime)) return 0 #------------------------函数的调用-------------------------# buildService()
zh
0.951143
# 服务模块 # git信息 #编译参数,支持debug,race #------------------------函数的定义-------------------------# #清理 #解析参数 -gcflags "-N -l" #下载依赖的包 #获取git的信息(获取当前分支以及commit id) #获取分支信息 # 获取commit id #编译各个模块 # 切换目录 # 格式话git信息 # 获取当前GOPATH # 编译 go build -ldflags "%s" %s -o ./bin/%s/%s main.go # 拷贝配置文件 # 配置文件要放在config目录下 #修改文件的权限 #对于sh结束的文件,修改权限 #拷贝文件或者目录 #复制文件(要注意权限和软连接这种情况) #复制软连接 #复制文件 # 目标文件夹一定要存在 #复制整个目录下的文件 # 创建目录 # 复制目录下中的文件 # 复制单个文件 #修改脚本中的结束符,\r\n换为\n # 向启动脚本中写入内容 #构建服务 #编译各个模块 #拷贝文件 #处理脚本 #修改文件的权限 #移动到当前目录 #------------------------函数的调用-------------------------#
2.1084
2
testing/prime_sense/dataset.py
orestis-z/Mask_RCNN
13
6615531
import os, sys import math import numpy as np import skimage.io import cv2 from PIL import Image # Root directory of the project ROOT_DIR = os.path.abspath("../..") if ROOT_DIR not in sys.path: sys.path.insert(0, ROOT_DIR) from instance_segmentation.object_config import Config import utils class ObjectsConfig(Config): NAME = "prime_sense" # NAME = "seg_ADE20K" MODE = 'RGBD' IMAGE_MIN_DIM = 512 IMAGE_MAX_DIM = 640 # IMAGES_PER_GPU = 2 # LEARNING_RATE = 0.02 # Image mean (RGBD) MEAN_PIXEL = np.array([123.7, 116.8, 103.9, 1220.7]) class ObjectsDataset(utils.Dataset): def load(self, dataset_dir, skip=19): # Add classes self.add_class("prime_sense", 1, "object") count = 0 # Add images for i, (root, dirs, files) in enumerate(os.walk(dataset_dir)): root_split = root.split('/') if root_split[-1] == 'image': # and subset in root_split: for j, file in enumerate(files): if j % (skip + 1) == 0: parentRoot = '/'.join(root.split('/')[:-1]) depth_path = os.path.join(parentRoot, 'depth', file) # only add if corresponding mask exists path = os.path.join(root, file) if os.path.isfile(depth_path): if (os.stat(path).st_size): im = Image.open(path) width, height = im.size self.add_image( "prime_sense", image_id=i, path=path, depth_path=depth_path, width=width, height=height) count += 1 else: print('Warning: No depth or mask found for ' + path) print('added {} images'.format(count)) def load_image(self, image_id, depth=True): """Load the specified image and return a [H,W,3+1] Numpy array. """ # Load image & depth image = super(ObjectsDataset, self).load_image(image_id) if depth: depth = skimage.io.imread(self.image_info[image_id]['depth_path']) rgbd = np.dstack((image, depth)) return rgbd else: return image if __name__ == '__main__': dataset = ObjectsDataset() dataset.load('/home/orestisz/data/ADE20K_2016_07_26', 'validation') masks, class_ids = dataset.load_mask(0)
import os, sys import math import numpy as np import skimage.io import cv2 from PIL import Image # Root directory of the project ROOT_DIR = os.path.abspath("../..") if ROOT_DIR not in sys.path: sys.path.insert(0, ROOT_DIR) from instance_segmentation.object_config import Config import utils class ObjectsConfig(Config): NAME = "prime_sense" # NAME = "seg_ADE20K" MODE = 'RGBD' IMAGE_MIN_DIM = 512 IMAGE_MAX_DIM = 640 # IMAGES_PER_GPU = 2 # LEARNING_RATE = 0.02 # Image mean (RGBD) MEAN_PIXEL = np.array([123.7, 116.8, 103.9, 1220.7]) class ObjectsDataset(utils.Dataset): def load(self, dataset_dir, skip=19): # Add classes self.add_class("prime_sense", 1, "object") count = 0 # Add images for i, (root, dirs, files) in enumerate(os.walk(dataset_dir)): root_split = root.split('/') if root_split[-1] == 'image': # and subset in root_split: for j, file in enumerate(files): if j % (skip + 1) == 0: parentRoot = '/'.join(root.split('/')[:-1]) depth_path = os.path.join(parentRoot, 'depth', file) # only add if corresponding mask exists path = os.path.join(root, file) if os.path.isfile(depth_path): if (os.stat(path).st_size): im = Image.open(path) width, height = im.size self.add_image( "prime_sense", image_id=i, path=path, depth_path=depth_path, width=width, height=height) count += 1 else: print('Warning: No depth or mask found for ' + path) print('added {} images'.format(count)) def load_image(self, image_id, depth=True): """Load the specified image and return a [H,W,3+1] Numpy array. """ # Load image & depth image = super(ObjectsDataset, self).load_image(image_id) if depth: depth = skimage.io.imread(self.image_info[image_id]['depth_path']) rgbd = np.dstack((image, depth)) return rgbd else: return image if __name__ == '__main__': dataset = ObjectsDataset() dataset.load('/home/orestisz/data/ADE20K_2016_07_26', 'validation') masks, class_ids = dataset.load_mask(0)
en
0.554383
# Root directory of the project # NAME = "seg_ADE20K" # IMAGES_PER_GPU = 2 # LEARNING_RATE = 0.02 # Image mean (RGBD) # Add classes # Add images # and subset in root_split: # only add if corresponding mask exists Load the specified image and return a [H,W,3+1] Numpy array. # Load image & depth
2.516256
3
nnu/nn_utils.py
piterbarg/altnnpub
10
6615532
<filename>nnu/nn_utils.py import os import random import numpy as np import pandas as pd import tensorflow as tf from datetime import datetime def set_seed_for_keras(seed=31415926): """ Set all the seeds needed, for results reproducibility, see https://stackoverflow.com/a/52897289/14551426 """ os.environ['PYTHONHASHSEED'] = str(seed) # 2. Set `python` built-in pseudo-random generator at a fixed value random.seed(seed) # 3. Set `numpy` pseudo-random generator at a fixed value np.random.seed(seed) # 4. Set the `tensorflow` pseudo-random generator at a fixed value tf.random.set_seed(seed) # for later versions: # tf.compat.v1.set_random_seed(seed) def get_nonexistent_path(fname_path: str, datestamp: str = ''): """ Get the path to a filename which does not exist by incrementing path. adapted from https://stackoverflow.com/a/43167607 Examples with empty datestamp -------- >>> get_nonexistent_path('/etc/issue') '/etc/issue-001' >>> get_nonexistent_path('whatever/1337bla.py') 'whatever/1337bla.py' """ filename, file_extension = os.path.splitext(fname_path) if datestamp: filename = f'{filename}-{datestamp}' fname_path = f'{filename}{file_extension}' if not os.path.exists(fname_path): return fname_path i = 1 while True: new_fname = f'{filename}-{i:03d}{file_extension}' if not os.path.exists(new_fname): return new_fname i += 1 def df_save_to_results(df: pd.DataFrame, file_name: str, suffix: str = '', add_date=True): if file_name is None: return if suffix: file_base, file_extension = os.path.splitext(file_name) file_base += '_' file_base += suffix file_name = file_base + file_extension nnu_python_nnu_folder = os.path.dirname(os.path.abspath(__file__)) nnu_python_folder = os.path.join(nnu_python_nnu_folder, os.path.pardir) nnu_results_folder = os.path.join(nnu_python_folder, 'results') results_file = os.path.join(nnu_results_folder, file_name) datestring = '' if add_date: filename_date_fmt = '%Y%m%d' today = datetime.now() datestring = today.strftime(filename_date_fmt) results_file = get_nonexistent_path( results_file, datestamp=datestring) df.to_csv(results_file)
<filename>nnu/nn_utils.py import os import random import numpy as np import pandas as pd import tensorflow as tf from datetime import datetime def set_seed_for_keras(seed=31415926): """ Set all the seeds needed, for results reproducibility, see https://stackoverflow.com/a/52897289/14551426 """ os.environ['PYTHONHASHSEED'] = str(seed) # 2. Set `python` built-in pseudo-random generator at a fixed value random.seed(seed) # 3. Set `numpy` pseudo-random generator at a fixed value np.random.seed(seed) # 4. Set the `tensorflow` pseudo-random generator at a fixed value tf.random.set_seed(seed) # for later versions: # tf.compat.v1.set_random_seed(seed) def get_nonexistent_path(fname_path: str, datestamp: str = ''): """ Get the path to a filename which does not exist by incrementing path. adapted from https://stackoverflow.com/a/43167607 Examples with empty datestamp -------- >>> get_nonexistent_path('/etc/issue') '/etc/issue-001' >>> get_nonexistent_path('whatever/1337bla.py') 'whatever/1337bla.py' """ filename, file_extension = os.path.splitext(fname_path) if datestamp: filename = f'{filename}-{datestamp}' fname_path = f'{filename}{file_extension}' if not os.path.exists(fname_path): return fname_path i = 1 while True: new_fname = f'{filename}-{i:03d}{file_extension}' if not os.path.exists(new_fname): return new_fname i += 1 def df_save_to_results(df: pd.DataFrame, file_name: str, suffix: str = '', add_date=True): if file_name is None: return if suffix: file_base, file_extension = os.path.splitext(file_name) file_base += '_' file_base += suffix file_name = file_base + file_extension nnu_python_nnu_folder = os.path.dirname(os.path.abspath(__file__)) nnu_python_folder = os.path.join(nnu_python_nnu_folder, os.path.pardir) nnu_results_folder = os.path.join(nnu_python_folder, 'results') results_file = os.path.join(nnu_results_folder, file_name) datestring = '' if add_date: filename_date_fmt = '%Y%m%d' today = datetime.now() datestring = today.strftime(filename_date_fmt) results_file = get_nonexistent_path( results_file, datestamp=datestring) df.to_csv(results_file)
en
0.596759
Set all the seeds needed, for results reproducibility, see https://stackoverflow.com/a/52897289/14551426 # 2. Set `python` built-in pseudo-random generator at a fixed value # 3. Set `numpy` pseudo-random generator at a fixed value # 4. Set the `tensorflow` pseudo-random generator at a fixed value # for later versions: # tf.compat.v1.set_random_seed(seed) Get the path to a filename which does not exist by incrementing path. adapted from https://stackoverflow.com/a/43167607 Examples with empty datestamp -------- >>> get_nonexistent_path('/etc/issue') '/etc/issue-001' >>> get_nonexistent_path('whatever/1337bla.py') 'whatever/1337bla.py'
3.090672
3
StudyPlans/Data Structures/Data Structures 1/max_sum_subarray.py
Sinha-Ujjawal/LeetCode-Solutions
0
6615533
from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: assert len(nums) max_sum = -float("inf") s = 0 for num in nums: s = max(s + num, num) max_sum = max(max_sum, s) return max_sum if __name__ == "__main__": solver = Solution() nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(solver.maxSubArray(nums=nums))
from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: assert len(nums) max_sum = -float("inf") s = 0 for num in nums: s = max(s + num, num) max_sum = max(max_sum, s) return max_sum if __name__ == "__main__": solver = Solution() nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(solver.maxSubArray(nums=nums))
none
1
3.771957
4
bdd100k/eval/run.py
bdd100k/bdd100k
193
6615534
<filename>bdd100k/eval/run.py """Evaluation helper functoins.""" import argparse import json import os from scalabel.common.parallel import NPROC from scalabel.eval.detect import evaluate_det from scalabel.eval.mot import acc_single_video_mot, evaluate_track from scalabel.eval.result import Result from scalabel.label.io import group_and_sort, load from ..common.logger import logger from ..common.utils import ( group_and_sort_files, list_files, load_bdd100k_config, ) from ..label.to_scalabel import bdd100k_to_scalabel from .ins_seg import evaluate_ins_seg from .lane import evaluate_lane_marking from .mots import acc_single_video_mots from .pan_seg import evaluate_pan_seg from .seg import evaluate_drivable, evaluate_sem_seg def parse_args() -> argparse.Namespace: """Use argparse to get command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "--task", "-t", choices=[ "det", "sem_seg", "ins_seg", "pan_seg", "drivable", "lane_mark", "box_track", "seg_track", ], required=True, ) parser.add_argument( "--gt", "-g", required=True, help="path to ground truth" ) parser.add_argument( "--result", "-r", required=True, help="path to results to be evaluated" ) parser.add_argument( "--config", "-c", default=None, help="path to the config file", ) parser.add_argument( "--iou-thr", type=float, default=0.5, help="iou threshold for mot evaluation", ) parser.add_argument( "--ignore-iof-thr", type=float, default=0.5, help="ignore iof threshold for mot evaluation", ) parser.add_argument( "--nproc", type=int, default=NPROC, help="number of processes for evaluation", ) # Flags for detection and instance segmentation parser.add_argument( "--out-file", type=str, default=None, help="Path to store output files" ) # Flags for instance segmentation parser.add_argument( "--score-file", type=str, default=".", help="Path to store the prediction scoring file", ) parser.add_argument( "--quiet", "-q", action="store_true", help="without logging", ) args = parser.parse_args() return args def run() -> None: """Main.""" args = parse_args() if args.config is not None: bdd100k_config = load_bdd100k_config(args.config) elif args.task in ["det", "ins_seg", "box_track", "seg_track"]: bdd100k_config = load_bdd100k_config(args.task) if args.task == "det": results: Result = evaluate_det( bdd100k_to_scalabel( load(args.gt, args.nproc).frames, bdd100k_config ), bdd100k_to_scalabel( load(args.result, args.nproc).frames, bdd100k_config ), bdd100k_config.scalabel, nproc=args.nproc, ) elif args.task == "ins_seg": results = evaluate_ins_seg( args.gt, args.result, args.score_file, bdd100k_config.scalabel, nproc=args.nproc, ) elif args.task == "box_track": results = evaluate_track( acc_single_video_mot, gts=group_and_sort( bdd100k_to_scalabel( load(args.gt, args.nproc).frames, bdd100k_config ) ), results=group_and_sort( bdd100k_to_scalabel( load(args.result, args.nproc).frames, bdd100k_config ) ), config=bdd100k_config.scalabel, iou_thr=args.iou_thr, ignore_iof_thr=args.ignore_iof_thr, nproc=args.nproc, ) elif args.task == "seg_track": results = evaluate_track( acc_single_video_mots, gts=group_and_sort_files( list_files(args.gt, ".png", with_prefix=True) ), results=group_and_sort_files( list_files(args.result, ".png", with_prefix=True) ), config=bdd100k_config.scalabel, iou_thr=args.iou_thr, ignore_iof_thr=args.ignore_iof_thr, nproc=args.nproc, ) gt_paths = list_files(args.gt, ".png", with_prefix=True) pred_paths = list_files(args.result, ".png", with_prefix=True) if args.task == "drivable": results = evaluate_drivable( gt_paths, pred_paths, nproc=args.nproc, with_logs=not args.quiet ) elif args.task == "lane_mark": results = evaluate_lane_marking( gt_paths, pred_paths, nproc=args.nproc, with_logs=not args.quiet ) elif args.task == "sem_seg": results = evaluate_sem_seg( gt_paths, pred_paths, nproc=args.nproc, with_logs=not args.quiet ) elif args.task == "pan_seg": results = evaluate_pan_seg( gt_paths, pred_paths, nproc=args.nproc, with_logs=not args.quiet ) logger.info(results) if args.out_file: out_folder = os.path.split(args.out_file)[0] if not os.path.exists(out_folder): os.makedirs(out_folder) with open(args.out_file, "w", encoding="utf-8") as fp: json.dump(dict(results), fp, indent=2) if __name__ == "__main__": run()
<filename>bdd100k/eval/run.py """Evaluation helper functoins.""" import argparse import json import os from scalabel.common.parallel import NPROC from scalabel.eval.detect import evaluate_det from scalabel.eval.mot import acc_single_video_mot, evaluate_track from scalabel.eval.result import Result from scalabel.label.io import group_and_sort, load from ..common.logger import logger from ..common.utils import ( group_and_sort_files, list_files, load_bdd100k_config, ) from ..label.to_scalabel import bdd100k_to_scalabel from .ins_seg import evaluate_ins_seg from .lane import evaluate_lane_marking from .mots import acc_single_video_mots from .pan_seg import evaluate_pan_seg from .seg import evaluate_drivable, evaluate_sem_seg def parse_args() -> argparse.Namespace: """Use argparse to get command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "--task", "-t", choices=[ "det", "sem_seg", "ins_seg", "pan_seg", "drivable", "lane_mark", "box_track", "seg_track", ], required=True, ) parser.add_argument( "--gt", "-g", required=True, help="path to ground truth" ) parser.add_argument( "--result", "-r", required=True, help="path to results to be evaluated" ) parser.add_argument( "--config", "-c", default=None, help="path to the config file", ) parser.add_argument( "--iou-thr", type=float, default=0.5, help="iou threshold for mot evaluation", ) parser.add_argument( "--ignore-iof-thr", type=float, default=0.5, help="ignore iof threshold for mot evaluation", ) parser.add_argument( "--nproc", type=int, default=NPROC, help="number of processes for evaluation", ) # Flags for detection and instance segmentation parser.add_argument( "--out-file", type=str, default=None, help="Path to store output files" ) # Flags for instance segmentation parser.add_argument( "--score-file", type=str, default=".", help="Path to store the prediction scoring file", ) parser.add_argument( "--quiet", "-q", action="store_true", help="without logging", ) args = parser.parse_args() return args def run() -> None: """Main.""" args = parse_args() if args.config is not None: bdd100k_config = load_bdd100k_config(args.config) elif args.task in ["det", "ins_seg", "box_track", "seg_track"]: bdd100k_config = load_bdd100k_config(args.task) if args.task == "det": results: Result = evaluate_det( bdd100k_to_scalabel( load(args.gt, args.nproc).frames, bdd100k_config ), bdd100k_to_scalabel( load(args.result, args.nproc).frames, bdd100k_config ), bdd100k_config.scalabel, nproc=args.nproc, ) elif args.task == "ins_seg": results = evaluate_ins_seg( args.gt, args.result, args.score_file, bdd100k_config.scalabel, nproc=args.nproc, ) elif args.task == "box_track": results = evaluate_track( acc_single_video_mot, gts=group_and_sort( bdd100k_to_scalabel( load(args.gt, args.nproc).frames, bdd100k_config ) ), results=group_and_sort( bdd100k_to_scalabel( load(args.result, args.nproc).frames, bdd100k_config ) ), config=bdd100k_config.scalabel, iou_thr=args.iou_thr, ignore_iof_thr=args.ignore_iof_thr, nproc=args.nproc, ) elif args.task == "seg_track": results = evaluate_track( acc_single_video_mots, gts=group_and_sort_files( list_files(args.gt, ".png", with_prefix=True) ), results=group_and_sort_files( list_files(args.result, ".png", with_prefix=True) ), config=bdd100k_config.scalabel, iou_thr=args.iou_thr, ignore_iof_thr=args.ignore_iof_thr, nproc=args.nproc, ) gt_paths = list_files(args.gt, ".png", with_prefix=True) pred_paths = list_files(args.result, ".png", with_prefix=True) if args.task == "drivable": results = evaluate_drivable( gt_paths, pred_paths, nproc=args.nproc, with_logs=not args.quiet ) elif args.task == "lane_mark": results = evaluate_lane_marking( gt_paths, pred_paths, nproc=args.nproc, with_logs=not args.quiet ) elif args.task == "sem_seg": results = evaluate_sem_seg( gt_paths, pred_paths, nproc=args.nproc, with_logs=not args.quiet ) elif args.task == "pan_seg": results = evaluate_pan_seg( gt_paths, pred_paths, nproc=args.nproc, with_logs=not args.quiet ) logger.info(results) if args.out_file: out_folder = os.path.split(args.out_file)[0] if not os.path.exists(out_folder): os.makedirs(out_folder) with open(args.out_file, "w", encoding="utf-8") as fp: json.dump(dict(results), fp, indent=2) if __name__ == "__main__": run()
en
0.548294
Evaluation helper functoins. Use argparse to get command line arguments. # Flags for detection and instance segmentation # Flags for instance segmentation Main.
2.161016
2
notes/reference/moocs/udacity/ud617-intro-to-hadoop-and-mapreduce/search-implementation/mapper.py
aav789/study-notes
43
6615535
#!/usr/bin/python import sys import csv from datetime import datetime import re def mapper(): """ Print the post length and all the answers to stdout """ reader = csv.reader(sys.stdin, delimiter='\t', quotechar='"') writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL) for line in reader: # Ignore any line that's not a forum post (like the header, for example) if not line[0].isdigit(): continue # Skip lines that don't match the expected format if len(line) != 19: continue node_id = line[0] body = line[4] score = line[9] split_regex = re.compile('[\s\.\!\?\:\;\"\(\)\<\>\[\]\$\#\=\-\/\,]') for word in split_regex.split(body): if word: print "{0}\t{1}\t{2}".format(word, score, node_id) if __name__ == '__main__': mapper()
#!/usr/bin/python import sys import csv from datetime import datetime import re def mapper(): """ Print the post length and all the answers to stdout """ reader = csv.reader(sys.stdin, delimiter='\t', quotechar='"') writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL) for line in reader: # Ignore any line that's not a forum post (like the header, for example) if not line[0].isdigit(): continue # Skip lines that don't match the expected format if len(line) != 19: continue node_id = line[0] body = line[4] score = line[9] split_regex = re.compile('[\s\.\!\?\:\;\"\(\)\<\>\[\]\$\#\=\-\/\,]') for word in split_regex.split(body): if word: print "{0}\t{1}\t{2}".format(word, score, node_id) if __name__ == '__main__': mapper()
en
0.761005
#!/usr/bin/python Print the post length and all the answers to stdout # Ignore any line that's not a forum post (like the header, for example) # Skip lines that don't match the expected format #\=\-\/\,]')
3.025653
3
icevision/all.py
ai-fast-track/mantisshrimp
580
6615536
from icevision.imports import * from icevision import * # soft import icedata try: import icedata except ModuleNotFoundError as e: if str(e) != f"No module named 'icedata'": raise e
from icevision.imports import * from icevision import * # soft import icedata try: import icedata except ModuleNotFoundError as e: if str(e) != f"No module named 'icedata'": raise e
en
0.204541
# soft import icedata
1.817989
2
test/python/LIM2Metrics/py2/base/common/Python032/Python032.py
sagodiz/SonarQube-plug-in
20
6615537
<filename>test/python/LIM2Metrics/py2/base/common/Python032/Python032.py<gh_stars>10-100 for n in range(1, 3): try: print 'before' continue print 'error' except StandardError: print 'error'
<filename>test/python/LIM2Metrics/py2/base/common/Python032/Python032.py<gh_stars>10-100 for n in range(1, 3): try: print 'before' continue print 'error' except StandardError: print 'error'
none
1
2.344633
2
evaluation/admin.py
AppraiseDev/OCELoT
6
6615538
<reponame>AppraiseDev/OCELoT """ Project OCELoT: Open, Competitive Evaluation Leaderboard of Translations """ from django.contrib import admin # Register your models here.
""" Project OCELoT: Open, Competitive Evaluation Leaderboard of Translations """ from django.contrib import admin # Register your models here.
en
0.820258
Project OCELoT: Open, Competitive Evaluation Leaderboard of Translations # Register your models here.
1.004652
1
utils/10pcov.py
prosyslab/bayesmith-artifact
0
6615539
# calculate 10% test case coverage and total coverage # current line coverage. can migrate to block or function coverage import sys BENCHMARKS=sys.argv[1:] for x in BENCHMARKS: try: f=open('/tmp/'+x+'/cov/covratio.txt').readlines() print(x,end=' ') for i in range(10): print(f[len(f)*i//10].strip(),end=' ') print() except: print(x,'ERROR') pass
# calculate 10% test case coverage and total coverage # current line coverage. can migrate to block or function coverage import sys BENCHMARKS=sys.argv[1:] for x in BENCHMARKS: try: f=open('/tmp/'+x+'/cov/covratio.txt').readlines() print(x,end=' ') for i in range(10): print(f[len(f)*i//10].strip(),end=' ') print() except: print(x,'ERROR') pass
en
0.896786
# calculate 10% test case coverage and total coverage # current line coverage. can migrate to block or function coverage
2.754942
3
taarifa_api/schemas.py
taarifa/TaarifaAPI
15
6615540
<gh_stars>10-100 boolean_field_false = {'type': 'boolean', 'default': False} boolean_field_true = {'type': 'boolean', 'default': True} integer_field = {'type': 'integer'} float_field = {'type': 'float'} list_field = {'type': 'list'} string_field = {'type': 'string'} unique_string_field = {'type': 'string', 'unique': True} required_string_field = {'type': 'string', 'required': True} unique_req_string_field = {'type': 'string', 'required': True, 'unique': True} dict_field = {'type': 'dict'} data_relation = {'type': 'dict', 'schema': {'resource': string_field, 'field': string_field, 'embeddable': boolean_field_false, 'version': boolean_field_false}} field_schema = { 'type': { 'type': 'string', 'allowed': ['string', 'boolean', 'integer', 'float', 'number', 'datetime', 'dict', 'list', 'objectid', 'file', 'point'], }, 'required': boolean_field_false, 'readonly': boolean_field_false, 'minlength': integer_field, 'maxlength': integer_field, 'min': integer_field, 'max': integer_field, 'allowed': list_field, 'empty': boolean_field_true, 'items': list_field, 'schema': dict_field, 'unique': boolean_field_false, 'data_relation': data_relation, 'nullable': boolean_field_false, 'default': {}, 'versioned': boolean_field_true, 'label': string_field, } # Service attributes conforming to the Open311 GeoReport v2 service definition: # http://wiki.open311.org/GeoReport_v2#Response_2 attribute_schema = { 'variable': boolean_field_true, 'code': unique_string_field, 'datatype': { 'type': 'string', 'allowed': ['string', 'number', 'datetime', 'text', 'singlevaluelist', 'multivaluelist'], }, 'required': boolean_field_false, 'datatype_description': string_field, 'order': integer_field, 'description': string_field, 'values': { 'type': 'list', 'schema': { 'key': string_field, 'name': string_field, }, }, # This field is not part of the Open311 service definition, but allows to # enforce foreign key constraints in the API 'relation': data_relation, } # Service conforming to the Open311 GeoReport v2 service definition: # http://wiki.open311.org/GeoReport_v2#Response # endpoint is an extra fields to denote the dynamically created endpoint for # the service service_schema = { 'jurisdiction_id': string_field, 'service_code': unique_req_string_field, 'service_name': required_string_field, 'description': string_field, 'metadata': boolean_field_false, 'type': { 'type': 'string', 'allowed': ['realtime', 'batch', 'blackbox'], 'default': 'realtime', }, 'keywords': { 'type': 'list', 'schema': string_field, }, 'group': string_field, 'attributes': { 'type': 'list', 'schema': attribute_schema, }, 'endpoint': string_field, } def attributes2schema(attributes): """Transform the list of Open311 service attributes into a valid Cerberus schema (see: http://wiki.open311.org/GeoReport_v2#Response_2).""" schema = {} for attr in attributes: if attr['variable']: typ = attr['datatype'] # Attributes of type 'text', 'singlevaluelist', 'multivaluelist' # are represented as strings if typ in ['text', 'singlevaluelist', 'multivaluelist']: typ = 'string' field = attr['code'] schema[field] = {'type': typ, 'required': attr['required']} # If the attribute has a list of values, use their keys as allowed # values for this attribute if 'values' in attr: schema[field]['allowed'] = [v['key'] for v in attr['values']] # If the attribute has a data relation, enforce the foreign key # constraint on it if 'relation' in attr: schema[field]['data_relation'] = attr['relation'] return schema # Service request conforming to the Open311 GeoReport v2 request definition: # http://wiki.open311.org/GeoReport_v2#POST_Service_Request # http://wiki.open311.org/GeoReport_v2#GET_Service_Requests request_schema = { 'jurisdiction_id': string_field, 'service_code': { 'type': 'string', 'required': True, 'data_relation': { 'resource': 'services', 'field': 'service_code', } }, 'attribute': { 'type': 'dict', 'dynamicschema': { 'resource': 'services', 'field': 'service_code', 'schema': 'attributes', 'transform': attributes2schema, }, }, # FIXME: at least one of the location fields is required 'lat': float_field, 'long': float_field, 'address_string': string_field, 'address_id': string_field, 'zipcode': string_field, 'email': string_field, 'device_id': string_field, 'account_id': string_field, 'first_name': string_field, 'last_name': string_field, 'phone': string_field, 'description': string_field, 'media_url': string_field, 'status': { 'type': 'string', 'allowed': ['open', 'closed'], 'default': 'open', }, 'status_notes': string_field, 'agency_responsible': string_field, 'service_notice': string_field, # requested_datetime = _created # updated_datetime = _updated 'expected_datetime': { 'type': 'datetime', }, } facility_schema = { 'jurisdiction_id': string_field, 'facility_code': unique_req_string_field, 'facility_name': required_string_field, 'description': string_field, 'keywords': { 'type': 'list', 'schema': string_field, }, 'group': string_field, 'attributes': { 'type': 'list', 'schema': attribute_schema, }, 'endpoint': string_field, 'fields': { 'required': True, 'type': 'dict', 'keyschema': field_schema, }, } resource_schema = { 'facility_code': { 'type': 'string', 'required': True, 'data_relation': { 'resource': 'facilities', 'field': 'facility_code', } }, }
boolean_field_false = {'type': 'boolean', 'default': False} boolean_field_true = {'type': 'boolean', 'default': True} integer_field = {'type': 'integer'} float_field = {'type': 'float'} list_field = {'type': 'list'} string_field = {'type': 'string'} unique_string_field = {'type': 'string', 'unique': True} required_string_field = {'type': 'string', 'required': True} unique_req_string_field = {'type': 'string', 'required': True, 'unique': True} dict_field = {'type': 'dict'} data_relation = {'type': 'dict', 'schema': {'resource': string_field, 'field': string_field, 'embeddable': boolean_field_false, 'version': boolean_field_false}} field_schema = { 'type': { 'type': 'string', 'allowed': ['string', 'boolean', 'integer', 'float', 'number', 'datetime', 'dict', 'list', 'objectid', 'file', 'point'], }, 'required': boolean_field_false, 'readonly': boolean_field_false, 'minlength': integer_field, 'maxlength': integer_field, 'min': integer_field, 'max': integer_field, 'allowed': list_field, 'empty': boolean_field_true, 'items': list_field, 'schema': dict_field, 'unique': boolean_field_false, 'data_relation': data_relation, 'nullable': boolean_field_false, 'default': {}, 'versioned': boolean_field_true, 'label': string_field, } # Service attributes conforming to the Open311 GeoReport v2 service definition: # http://wiki.open311.org/GeoReport_v2#Response_2 attribute_schema = { 'variable': boolean_field_true, 'code': unique_string_field, 'datatype': { 'type': 'string', 'allowed': ['string', 'number', 'datetime', 'text', 'singlevaluelist', 'multivaluelist'], }, 'required': boolean_field_false, 'datatype_description': string_field, 'order': integer_field, 'description': string_field, 'values': { 'type': 'list', 'schema': { 'key': string_field, 'name': string_field, }, }, # This field is not part of the Open311 service definition, but allows to # enforce foreign key constraints in the API 'relation': data_relation, } # Service conforming to the Open311 GeoReport v2 service definition: # http://wiki.open311.org/GeoReport_v2#Response # endpoint is an extra fields to denote the dynamically created endpoint for # the service service_schema = { 'jurisdiction_id': string_field, 'service_code': unique_req_string_field, 'service_name': required_string_field, 'description': string_field, 'metadata': boolean_field_false, 'type': { 'type': 'string', 'allowed': ['realtime', 'batch', 'blackbox'], 'default': 'realtime', }, 'keywords': { 'type': 'list', 'schema': string_field, }, 'group': string_field, 'attributes': { 'type': 'list', 'schema': attribute_schema, }, 'endpoint': string_field, } def attributes2schema(attributes): """Transform the list of Open311 service attributes into a valid Cerberus schema (see: http://wiki.open311.org/GeoReport_v2#Response_2).""" schema = {} for attr in attributes: if attr['variable']: typ = attr['datatype'] # Attributes of type 'text', 'singlevaluelist', 'multivaluelist' # are represented as strings if typ in ['text', 'singlevaluelist', 'multivaluelist']: typ = 'string' field = attr['code'] schema[field] = {'type': typ, 'required': attr['required']} # If the attribute has a list of values, use their keys as allowed # values for this attribute if 'values' in attr: schema[field]['allowed'] = [v['key'] for v in attr['values']] # If the attribute has a data relation, enforce the foreign key # constraint on it if 'relation' in attr: schema[field]['data_relation'] = attr['relation'] return schema # Service request conforming to the Open311 GeoReport v2 request definition: # http://wiki.open311.org/GeoReport_v2#POST_Service_Request # http://wiki.open311.org/GeoReport_v2#GET_Service_Requests request_schema = { 'jurisdiction_id': string_field, 'service_code': { 'type': 'string', 'required': True, 'data_relation': { 'resource': 'services', 'field': 'service_code', } }, 'attribute': { 'type': 'dict', 'dynamicschema': { 'resource': 'services', 'field': 'service_code', 'schema': 'attributes', 'transform': attributes2schema, }, }, # FIXME: at least one of the location fields is required 'lat': float_field, 'long': float_field, 'address_string': string_field, 'address_id': string_field, 'zipcode': string_field, 'email': string_field, 'device_id': string_field, 'account_id': string_field, 'first_name': string_field, 'last_name': string_field, 'phone': string_field, 'description': string_field, 'media_url': string_field, 'status': { 'type': 'string', 'allowed': ['open', 'closed'], 'default': 'open', }, 'status_notes': string_field, 'agency_responsible': string_field, 'service_notice': string_field, # requested_datetime = _created # updated_datetime = _updated 'expected_datetime': { 'type': 'datetime', }, } facility_schema = { 'jurisdiction_id': string_field, 'facility_code': unique_req_string_field, 'facility_name': required_string_field, 'description': string_field, 'keywords': { 'type': 'list', 'schema': string_field, }, 'group': string_field, 'attributes': { 'type': 'list', 'schema': attribute_schema, }, 'endpoint': string_field, 'fields': { 'required': True, 'type': 'dict', 'keyschema': field_schema, }, } resource_schema = { 'facility_code': { 'type': 'string', 'required': True, 'data_relation': { 'resource': 'facilities', 'field': 'facility_code', } }, }
en
0.696295
# Service attributes conforming to the Open311 GeoReport v2 service definition: # http://wiki.open311.org/GeoReport_v2#Response_2 # This field is not part of the Open311 service definition, but allows to # enforce foreign key constraints in the API # Service conforming to the Open311 GeoReport v2 service definition: # http://wiki.open311.org/GeoReport_v2#Response # endpoint is an extra fields to denote the dynamically created endpoint for # the service Transform the list of Open311 service attributes into a valid Cerberus schema (see: http://wiki.open311.org/GeoReport_v2#Response_2). # Attributes of type 'text', 'singlevaluelist', 'multivaluelist' # are represented as strings # If the attribute has a list of values, use their keys as allowed # values for this attribute # If the attribute has a data relation, enforce the foreign key # constraint on it # Service request conforming to the Open311 GeoReport v2 request definition: # http://wiki.open311.org/GeoReport_v2#POST_Service_Request # http://wiki.open311.org/GeoReport_v2#GET_Service_Requests # FIXME: at least one of the location fields is required # requested_datetime = _created # updated_datetime = _updated
1.971434
2
dashboard_viewer/uploader/actions.py
EHDEN/NetworkDashboards
4
6615541
from django.contrib import messages from django.contrib.admin import helpers from django.contrib.admin.utils import model_ngettext from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.utils.translation import gettext as _, gettext_lazy def custom_delete_selected(modeladmin, request, queryset): """ Based on https://github.com/django/django/blob/2.2.17/django/contrib/admin/actions.py#L13 The only change was the message returned after deletion since the deletion process is sent to a background task """ opts = modeladmin.model._meta ( deletable_objects, model_count, perms_needed, protected, ) = modeladmin.get_deleted_objects(queryset, request) if request.POST.get("post") and not protected: if perms_needed: raise PermissionDenied n = queryset.count() if n: for obj in queryset: obj_display = str(obj) modeladmin.log_deletion(request, obj, obj_display) modeladmin.delete_queryset(request, queryset) # ONLY CHANGE vv modeladmin.message_user( request, _( "Deleting %(count)d %(items)s on background. " "In a few minutes they will stop showing on the objects list." ) % {"count": n, "items": model_ngettext(modeladmin.opts, n)}, messages.SUCCESS, ) # Return None to display the change list page again. return None objects_name = model_ngettext(queryset) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": objects_name} else: title = _("Are you sure?") context = { **modeladmin.admin_site.each_context(request), "title": title, "objects_name": str(objects_name), "deletable_objects": [deletable_objects], "model_count": dict(model_count).items(), "queryset": queryset, "perms_lacking": perms_needed, "protected": protected, "opts": opts, "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME, "media": modeladmin.media, } request.current_app = modeladmin.admin_site.name # Display the confirmation page return TemplateResponse( request, "admin/datasource/delete_selected_confirmation.html", context ) custom_delete_selected.allowed_permissions = ("delete",) custom_delete_selected.short_description = gettext_lazy( "Delete selected %(verbose_name_plural)s" )
from django.contrib import messages from django.contrib.admin import helpers from django.contrib.admin.utils import model_ngettext from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.utils.translation import gettext as _, gettext_lazy def custom_delete_selected(modeladmin, request, queryset): """ Based on https://github.com/django/django/blob/2.2.17/django/contrib/admin/actions.py#L13 The only change was the message returned after deletion since the deletion process is sent to a background task """ opts = modeladmin.model._meta ( deletable_objects, model_count, perms_needed, protected, ) = modeladmin.get_deleted_objects(queryset, request) if request.POST.get("post") and not protected: if perms_needed: raise PermissionDenied n = queryset.count() if n: for obj in queryset: obj_display = str(obj) modeladmin.log_deletion(request, obj, obj_display) modeladmin.delete_queryset(request, queryset) # ONLY CHANGE vv modeladmin.message_user( request, _( "Deleting %(count)d %(items)s on background. " "In a few minutes they will stop showing on the objects list." ) % {"count": n, "items": model_ngettext(modeladmin.opts, n)}, messages.SUCCESS, ) # Return None to display the change list page again. return None objects_name = model_ngettext(queryset) if perms_needed or protected: title = _("Cannot delete %(name)s") % {"name": objects_name} else: title = _("Are you sure?") context = { **modeladmin.admin_site.each_context(request), "title": title, "objects_name": str(objects_name), "deletable_objects": [deletable_objects], "model_count": dict(model_count).items(), "queryset": queryset, "perms_lacking": perms_needed, "protected": protected, "opts": opts, "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME, "media": modeladmin.media, } request.current_app = modeladmin.admin_site.name # Display the confirmation page return TemplateResponse( request, "admin/datasource/delete_selected_confirmation.html", context ) custom_delete_selected.allowed_permissions = ("delete",) custom_delete_selected.short_description = gettext_lazy( "Delete selected %(verbose_name_plural)s" )
en
0.820176
Based on https://github.com/django/django/blob/2.2.17/django/contrib/admin/actions.py#L13 The only change was the message returned after deletion since the deletion process is sent to a background task # ONLY CHANGE vv # Return None to display the change list page again. # Display the confirmation page
1.996689
2
hemp/workspace.py
Addvilz/hemp
1
6615542
from os import chmod from os import mkdir from os.path import join from tempfile import mkdtemp def create_temporary_workspace(version=None, mode=0700): # type: (str, int) -> str """ Create a temporary directory, optionally by placing a subdirectory: version :rtype: str :return: Directory path """ workspace = mkdtemp('hemp_') if version is not None: workspace = join(workspace, version) mkdir(workspace, mode) chmod(workspace, mode) return workspace
from os import chmod from os import mkdir from os.path import join from tempfile import mkdtemp def create_temporary_workspace(version=None, mode=0700): # type: (str, int) -> str """ Create a temporary directory, optionally by placing a subdirectory: version :rtype: str :return: Directory path """ workspace = mkdtemp('hemp_') if version is not None: workspace = join(workspace, version) mkdir(workspace, mode) chmod(workspace, mode) return workspace
en
0.753444
# type: (str, int) -> str Create a temporary directory, optionally by placing a subdirectory: version :rtype: str :return: Directory path
2.733788
3
Darlington/phase2/LIST/day 40 challenge/qtn10.py
CodedLadiesInnovateTech/-python-challenge-solutions
6
6615543
<reponame>CodedLadiesInnovateTech/-python-challenge-solutions #Python program access the index of a list. nums = [5, 15, 35, 8, 98] for num_index, num_val in enumerate(nums): print(num_index, num_val) # #key = [4, 7, 9, 45, 34,56] #for index
#Python program access the index of a list. nums = [5, 15, 35, 8, 98] for num_index, num_val in enumerate(nums): print(num_index, num_val) # #key = [4, 7, 9, 45, 34,56] #for index
en
0.662067
#Python program access the index of a list. # #key = [4, 7, 9, 45, 34,56] #for index
4.084037
4
aiomysensors/model/const.py
MartinHjelmare/aiomysensors
4
6615544
<filename>aiomysensors/model/const.py """Provide shared model constants.""" from marshmallow import fields, validate from .protocol import BROADCAST_ID NODE_ID_FIELD = fields.Int( required=True, validate=validate.Range( min=0, max=BROADCAST_ID, error="Not valid node_id: {input}", ), )
<filename>aiomysensors/model/const.py """Provide shared model constants.""" from marshmallow import fields, validate from .protocol import BROADCAST_ID NODE_ID_FIELD = fields.Int( required=True, validate=validate.Range( min=0, max=BROADCAST_ID, error="Not valid node_id: {input}", ), )
en
0.840646
Provide shared model constants.
1.58122
2
Packs/Malware/Scripts/CreateHashIndicatorWrapper/CreateHashIndicatorWrapper_test.py
mazmat-panw/content
2
6615545
"""Base Script for Cortex XSOAR - Unit Tests file Pytest Unit Tests: all funcion names must start with "test_" More details: https://xsoar.pan.dev/docs/integrations/unit-testing """ import pytest import CommonServerPython import CreateHashIndicatorWrapper test_data = [CommonServerPython.CommandRunner.Result(command='cs-falcon-search-custom-iocs', args={'values': 'hash1,hash2'}, brand='CrowdstrikeFalcon', instance='CrowdstrikeFalcon_instance_1', result={'errors': None, 'resources': [{ 'action': 'prevent', 'applied_globally': True, 'description': 'Blacklisted based on XSOAR inc 1', 'id': '12', 'platforms': [ 'linux', 'mac', 'windows'], 'severity': 'high', 'type': 'sha256', 'value': 'hash2'}]})] @pytest.mark.parametrize('action', ['allow', 'block']) def test_get_crowdstrike_commands_args(mocker, action): """ Given: the action to perform (allow or block) When: Getting the CrowdStrike commands and args list to run the action on Crowdstrike Then: Ensure the right commands and args_list are being returned. """ from CreateHashIndicatorWrapper import get_crowdstrike_commands_args, demisto, CROWDSTRIKE_ACTIONS ioc_metadata = CROWDSTRIKE_ACTIONS.get(action) hashes_dct = {'hash1': ('cs-falcon-upload-custom-ioc', {'ioc_type': 'sha256', 'platforms': 'linux,mac,windows', 'applied_globally': 'true', 'value': 'hash1', **ioc_metadata}), 'hash2': ('cs-falcon-update-custom-ioc', {'ioc_id': '12', **ioc_metadata})} ioc_to_hash = { '12': 'hash2'} mocker.patch.object(CreateHashIndicatorWrapper.CommandRunner, 'execute_commands', return_value=(test_data, [])) mocker.patch.object(demisto, 'incident', return_value={'id': 1}) commands, args_lst = get_crowdstrike_commands_args(list(hashes_dct.keys()), action) for command, args in zip(commands, args_lst): h = args.get('value') or ioc_to_hash.get(args.get('ioc_id')) assert h in hashes_dct expected_command, expected_args = hashes_dct.get(h) assert command == expected_command assert args == expected_args @pytest.mark.parametrize('action', ['allow', 'block']) def test_create_command_executers(mocker, action): """ Given: the action to perform (allow or block) When: Calling `create_command_wrappers` to get all the command wrappers for the script. Then: Ensure the right commands wrappers are being returned. """ from CreateHashIndicatorWrapper import demisto, create_commands, MSDE_ACTIONS, XDR_ACTIONS, \ CROWDSTRIKE_ACTIONS hashes = ['hash1', 'hash2'] mocker.patch.object(CreateHashIndicatorWrapper.CommandRunner, 'execute_commands', return_value=(test_data, [])) mocker.patch.object(demisto, 'incident', return_value={'id': 1}) commands = create_commands(hashes, action) ioc_metadata = CROWDSTRIKE_ACTIONS.get(action) for command in commands: command_names = set(command.commands) if 'microsoft-atp-sc-indicator-create' in command_names: assert command_names == {'microsoft-atp-sc-indicator-create'} assert {args.get('action') for args in command.args_lst} == {MSDE_ACTIONS.get(action)} if XDR_ACTIONS.get(action) in command_names: assert command_names == {XDR_ACTIONS.get(action)} assert command.args_lst == [{'hash_list': ','.join(hashes)}] if 'cs-falcon-upload-custom-ioc' in command_names or 'cs-falcon-update-custom-ioc' in command_names: assert command_names == {'cs-falcon-upload-custom-ioc', 'cs-falcon-update-custom-ioc'} assert command.args_lst == [ {'ioc_type': 'sha256', 'platforms': 'linux,mac,windows', 'applied_globally': 'true', 'value': 'hash1', **ioc_metadata}, {'ioc_id': '12', **ioc_metadata} ]
"""Base Script for Cortex XSOAR - Unit Tests file Pytest Unit Tests: all funcion names must start with "test_" More details: https://xsoar.pan.dev/docs/integrations/unit-testing """ import pytest import CommonServerPython import CreateHashIndicatorWrapper test_data = [CommonServerPython.CommandRunner.Result(command='cs-falcon-search-custom-iocs', args={'values': 'hash1,hash2'}, brand='CrowdstrikeFalcon', instance='CrowdstrikeFalcon_instance_1', result={'errors': None, 'resources': [{ 'action': 'prevent', 'applied_globally': True, 'description': 'Blacklisted based on XSOAR inc 1', 'id': '12', 'platforms': [ 'linux', 'mac', 'windows'], 'severity': 'high', 'type': 'sha256', 'value': 'hash2'}]})] @pytest.mark.parametrize('action', ['allow', 'block']) def test_get_crowdstrike_commands_args(mocker, action): """ Given: the action to perform (allow or block) When: Getting the CrowdStrike commands and args list to run the action on Crowdstrike Then: Ensure the right commands and args_list are being returned. """ from CreateHashIndicatorWrapper import get_crowdstrike_commands_args, demisto, CROWDSTRIKE_ACTIONS ioc_metadata = CROWDSTRIKE_ACTIONS.get(action) hashes_dct = {'hash1': ('cs-falcon-upload-custom-ioc', {'ioc_type': 'sha256', 'platforms': 'linux,mac,windows', 'applied_globally': 'true', 'value': 'hash1', **ioc_metadata}), 'hash2': ('cs-falcon-update-custom-ioc', {'ioc_id': '12', **ioc_metadata})} ioc_to_hash = { '12': 'hash2'} mocker.patch.object(CreateHashIndicatorWrapper.CommandRunner, 'execute_commands', return_value=(test_data, [])) mocker.patch.object(demisto, 'incident', return_value={'id': 1}) commands, args_lst = get_crowdstrike_commands_args(list(hashes_dct.keys()), action) for command, args in zip(commands, args_lst): h = args.get('value') or ioc_to_hash.get(args.get('ioc_id')) assert h in hashes_dct expected_command, expected_args = hashes_dct.get(h) assert command == expected_command assert args == expected_args @pytest.mark.parametrize('action', ['allow', 'block']) def test_create_command_executers(mocker, action): """ Given: the action to perform (allow or block) When: Calling `create_command_wrappers` to get all the command wrappers for the script. Then: Ensure the right commands wrappers are being returned. """ from CreateHashIndicatorWrapper import demisto, create_commands, MSDE_ACTIONS, XDR_ACTIONS, \ CROWDSTRIKE_ACTIONS hashes = ['hash1', 'hash2'] mocker.patch.object(CreateHashIndicatorWrapper.CommandRunner, 'execute_commands', return_value=(test_data, [])) mocker.patch.object(demisto, 'incident', return_value={'id': 1}) commands = create_commands(hashes, action) ioc_metadata = CROWDSTRIKE_ACTIONS.get(action) for command in commands: command_names = set(command.commands) if 'microsoft-atp-sc-indicator-create' in command_names: assert command_names == {'microsoft-atp-sc-indicator-create'} assert {args.get('action') for args in command.args_lst} == {MSDE_ACTIONS.get(action)} if XDR_ACTIONS.get(action) in command_names: assert command_names == {XDR_ACTIONS.get(action)} assert command.args_lst == [{'hash_list': ','.join(hashes)}] if 'cs-falcon-upload-custom-ioc' in command_names or 'cs-falcon-update-custom-ioc' in command_names: assert command_names == {'cs-falcon-upload-custom-ioc', 'cs-falcon-update-custom-ioc'} assert command.args_lst == [ {'ioc_type': 'sha256', 'platforms': 'linux,mac,windows', 'applied_globally': 'true', 'value': 'hash1', **ioc_metadata}, {'ioc_id': '12', **ioc_metadata} ]
en
0.767047
Base Script for Cortex XSOAR - Unit Tests file Pytest Unit Tests: all funcion names must start with "test_" More details: https://xsoar.pan.dev/docs/integrations/unit-testing Given: the action to perform (allow or block) When: Getting the CrowdStrike commands and args list to run the action on Crowdstrike Then: Ensure the right commands and args_list are being returned. Given: the action to perform (allow or block) When: Calling `create_command_wrappers` to get all the command wrappers for the script. Then: Ensure the right commands wrappers are being returned.
2.215601
2
py_test_simple_timesort.py
guchengxi1994/pyLikeTypes
0
6615546
"""https://github.com/RonTang/SimpleTimsort/blob/master/SimpleTimsort.py """ import time import random """ 二分搜索用于插入排序寻找插入位置 """ def binary_search(the_array, item, start, end): if start == end: if the_array[start] > item: return start else: return start + 1 if start > end: return start mid = round((start + end)/ 2) if the_array[mid] < item: return binary_search(the_array, item, mid + 1, end) elif the_array[mid] > item: return binary_search(the_array, item, start, mid - 1) else: return mid """ 插入排序用于生成mini run """ def insertion_sort(the_array): l = len(the_array) for index in range(1, l): value = the_array[index] pos = binary_search(the_array, value, 0, index - 1) the_array[pos+1:index+1] = the_array[pos:index] the_array[pos] = value return the_array """ 归并,将两个有序的list合并成新的有序list """ def merge(left, right): if not left: return right if not right: return left l_len = len(left) r_len = len(right) result = [None]*(l_len+r_len) i, j, k= 0,0,0 while i < l_len and j< r_len: if left[i] <= right[j]: result[k] = left[i] i+=1 else: result[k] = right[j] j+=1 k+=1 while i<l_len: result[k]=left[i]; k+=1 i+=1 while j<r_len: result[k]=right[j] k+=1 j+=1 return result def timsort(the_array): runs = [] length = len(the_array) new_run = [the_array[0]] new_run_reverse = False # 将the_array拆分成多了(递增或严格递减)list并将严格递减的list反转后存入runs。 for i in range(1, length): if len(new_run) == 1: if the_array[i] < the_array[i-1]: new_run_reverse = True else: new_run_reverse = False new_run.append(the_array[i]) elif new_run_reverse: if the_array[i] < the_array[i-1]: new_run.append(the_array[i]) else: new_run.reverse() runs.append(new_run) #print(new_run) new_run=[] new_run.append(the_array[i]) else: if the_array[i] >= the_array[i-1]: new_run.append(the_array[i]) else: runs.append(new_run) #print(new_run) new_run=[] new_run.append(the_array[i]) if i == length - 1: runs.append(new_run) #print(new_run) mini_run = 32 sorted_runs=[] cur_run=[] # 对runs中的每一项list长度不足mini_run用插入排序进行扩充,存入sorted_runs for item in runs: if len(cur_run) > mini_run: sorted_runs.append(insertion_sort(cur_run)) cur_run = item else: cur_run.extend(item) sorted_runs.append(insertion_sort(cur_run)) # 依次将run压入栈中,若栈顶run X,Y,Z。 # 违反了X>Y+Z 或 Y>Z 则Y与较小长度的run合并,并再次放入栈中。 # 依据这个法则,能够尽量使得大小相同的run合并,以提高性能。 # Timsort是稳定排序故只有相邻的run才能归并。 run_stack = [] sorted_array = [] for run in sorted_runs: run_stack.append(run) stop = False while len(run_stack) >= 3 and not stop: X = run_stack[len(run_stack)-1] Y = run_stack[len(run_stack)-2] Z = run_stack[len(run_stack)-3] if (not len(X)>len(Y)+len(Z)) or (not len(Y)>len(Z)): run_stack.pop() run_stack.pop() run_stack.pop() if len(X) < len(Z): YX = merge(Y,X) run_stack.append(Z) run_stack.append(YX) else: ZY = merge(Z,Y) run_stack.append(ZY) run_stack.append(X) else: stop =True #将栈中剩余的run归并 for run in run_stack: sorted_array = merge(sorted_array, run) return sorted_array #print(sorted_array) l = timsort([3,1,5,7,9,2,4,6,8]) print(timsort(l)) # for x in range(0,100): # data.append(random.randint(0,10000)) # start = time.process_time() # timsort(data) # end = time.process_time() # print(end-start)
"""https://github.com/RonTang/SimpleTimsort/blob/master/SimpleTimsort.py """ import time import random """ 二分搜索用于插入排序寻找插入位置 """ def binary_search(the_array, item, start, end): if start == end: if the_array[start] > item: return start else: return start + 1 if start > end: return start mid = round((start + end)/ 2) if the_array[mid] < item: return binary_search(the_array, item, mid + 1, end) elif the_array[mid] > item: return binary_search(the_array, item, start, mid - 1) else: return mid """ 插入排序用于生成mini run """ def insertion_sort(the_array): l = len(the_array) for index in range(1, l): value = the_array[index] pos = binary_search(the_array, value, 0, index - 1) the_array[pos+1:index+1] = the_array[pos:index] the_array[pos] = value return the_array """ 归并,将两个有序的list合并成新的有序list """ def merge(left, right): if not left: return right if not right: return left l_len = len(left) r_len = len(right) result = [None]*(l_len+r_len) i, j, k= 0,0,0 while i < l_len and j< r_len: if left[i] <= right[j]: result[k] = left[i] i+=1 else: result[k] = right[j] j+=1 k+=1 while i<l_len: result[k]=left[i]; k+=1 i+=1 while j<r_len: result[k]=right[j] k+=1 j+=1 return result def timsort(the_array): runs = [] length = len(the_array) new_run = [the_array[0]] new_run_reverse = False # 将the_array拆分成多了(递增或严格递减)list并将严格递减的list反转后存入runs。 for i in range(1, length): if len(new_run) == 1: if the_array[i] < the_array[i-1]: new_run_reverse = True else: new_run_reverse = False new_run.append(the_array[i]) elif new_run_reverse: if the_array[i] < the_array[i-1]: new_run.append(the_array[i]) else: new_run.reverse() runs.append(new_run) #print(new_run) new_run=[] new_run.append(the_array[i]) else: if the_array[i] >= the_array[i-1]: new_run.append(the_array[i]) else: runs.append(new_run) #print(new_run) new_run=[] new_run.append(the_array[i]) if i == length - 1: runs.append(new_run) #print(new_run) mini_run = 32 sorted_runs=[] cur_run=[] # 对runs中的每一项list长度不足mini_run用插入排序进行扩充,存入sorted_runs for item in runs: if len(cur_run) > mini_run: sorted_runs.append(insertion_sort(cur_run)) cur_run = item else: cur_run.extend(item) sorted_runs.append(insertion_sort(cur_run)) # 依次将run压入栈中,若栈顶run X,Y,Z。 # 违反了X>Y+Z 或 Y>Z 则Y与较小长度的run合并,并再次放入栈中。 # 依据这个法则,能够尽量使得大小相同的run合并,以提高性能。 # Timsort是稳定排序故只有相邻的run才能归并。 run_stack = [] sorted_array = [] for run in sorted_runs: run_stack.append(run) stop = False while len(run_stack) >= 3 and not stop: X = run_stack[len(run_stack)-1] Y = run_stack[len(run_stack)-2] Z = run_stack[len(run_stack)-3] if (not len(X)>len(Y)+len(Z)) or (not len(Y)>len(Z)): run_stack.pop() run_stack.pop() run_stack.pop() if len(X) < len(Z): YX = merge(Y,X) run_stack.append(Z) run_stack.append(YX) else: ZY = merge(Z,Y) run_stack.append(ZY) run_stack.append(X) else: stop =True #将栈中剩余的run归并 for run in run_stack: sorted_array = merge(sorted_array, run) return sorted_array #print(sorted_array) l = timsort([3,1,5,7,9,2,4,6,8]) print(timsort(l)) # for x in range(0,100): # data.append(random.randint(0,10000)) # start = time.process_time() # timsort(data) # end = time.process_time() # print(end-start)
zh
0.571865
https://github.com/RonTang/SimpleTimsort/blob/master/SimpleTimsort.py 二分搜索用于插入排序寻找插入位置 插入排序用于生成mini run 归并,将两个有序的list合并成新的有序list # 将the_array拆分成多了(递增或严格递减)list并将严格递减的list反转后存入runs。 #print(new_run) #print(new_run) #print(new_run) # 对runs中的每一项list长度不足mini_run用插入排序进行扩充,存入sorted_runs # 依次将run压入栈中,若栈顶run X,Y,Z。 # 违反了X>Y+Z 或 Y>Z 则Y与较小长度的run合并,并再次放入栈中。 # 依据这个法则,能够尽量使得大小相同的run合并,以提高性能。 # Timsort是稳定排序故只有相邻的run才能归并。 #将栈中剩余的run归并 #print(sorted_array) # for x in range(0,100): # data.append(random.randint(0,10000)) # start = time.process_time() # timsort(data) # end = time.process_time() # print(end-start)
3.914083
4
app.py
tekeburak/dam-occupancy-model
8
6615547
import streamlit as st import streamlit_theme as stt from utils.multiapp import MultiApp from pages import home, arima, lstm, cnn, team, contact app = MultiApp() CONV_WIDTH = 3 LABEL_WIDTH = 30 INPUT_WIDTH = 7 app.add_app("HOME", home.app) app.add_app("ARIMA MODEL", arima.app) app.add_app("LSTM MODEL", lstm.app) app.add_app("CNN MODEL", cnn.app) app.add_app("OUR TEAM", team.app) app.add_app("CONTACT US", contact.app) app.run()
import streamlit as st import streamlit_theme as stt from utils.multiapp import MultiApp from pages import home, arima, lstm, cnn, team, contact app = MultiApp() CONV_WIDTH = 3 LABEL_WIDTH = 30 INPUT_WIDTH = 7 app.add_app("HOME", home.app) app.add_app("ARIMA MODEL", arima.app) app.add_app("LSTM MODEL", lstm.app) app.add_app("CNN MODEL", cnn.app) app.add_app("OUR TEAM", team.app) app.add_app("CONTACT US", contact.app) app.run()
none
1
1.600101
2
tareas/3/ManzanaresJorge-SalazarJesus/fcfs.py
jorgelmp/sistop-2022-1
6
6615548
from scheduler import Scheduler from collections import deque class Fcfs(Scheduler): name = "First Come First Serve (FCFS)" def __init__(self,procesos): self.ejecutados = [] self.ejecutados_visual = "" self.fcfs_queue = deque(procesos) self.t = self.fcfs_queue[0].arrvl_time def execute(self): while len(self.fcfs_queue)>0: if self.fcfs_queue[0].arrvl_time > self.t: self.emptyExec() else: ejecutando = self.fcfs_queue.popleft() while ejecutando.timeLeft > 0 : self.ejecutados_visual+=ejecutando.id ejecutando.execute(1) self.t +=1 ejecutando.compl_time = self.t self.ejecutados.append(ejecutando)
from scheduler import Scheduler from collections import deque class Fcfs(Scheduler): name = "First Come First Serve (FCFS)" def __init__(self,procesos): self.ejecutados = [] self.ejecutados_visual = "" self.fcfs_queue = deque(procesos) self.t = self.fcfs_queue[0].arrvl_time def execute(self): while len(self.fcfs_queue)>0: if self.fcfs_queue[0].arrvl_time > self.t: self.emptyExec() else: ejecutando = self.fcfs_queue.popleft() while ejecutando.timeLeft > 0 : self.ejecutados_visual+=ejecutando.id ejecutando.execute(1) self.t +=1 ejecutando.compl_time = self.t self.ejecutados.append(ejecutando)
none
1
2.913161
3
image_augmentation/image_aug.py
tobyloby12/Faster-RCNN-Mask-and-Social-Distancing-Network
1
6615549
import imgaug as ia from xml_test import * from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage from imgaug import augmenters as iaa # imageio library will be used for image input/output import imageio import pandas as pd import numpy as np import re import os import glob # this library is needed to read XML files for converting it into CSV import xml.etree.ElementTree as ET import shutil from xml.etree.ElementTree import Element, SubElement, tostring, XML # converting xml to csv def xml_to_csv(path): xml_list = [] for xml_file in glob.glob(path + '/*.xml'): tree = ET.parse(xml_file) root = tree.getroot() for member in root.findall('object'): try: value = (root.find('filename').text, int(root.find('size')[0].text), int(root.find('size')[1].text), member[0].text, int(member[5][0].text), int(member[5][1].text), int(member[5][2].text), int(member[5][3].text) ) xml_list.append(value) except: pass column_names = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax'] df = pd.DataFrame(xml_list, columns=column_names) return df # function to convert BoundingBoxesOnImage object into DataFrame def bbs_obj_to_df(bbs_object): # convert BoundingBoxesOnImage object into array bbs_array = bbs_object.to_xyxy_array() # convert array into a DataFrame ['xmin', 'ymin', 'xmax', 'ymax'] columns df_bbs = pd.DataFrame(bbs_array, columns=['xmin', 'ymin', 'xmax', 'ymax']) return df_bbs # augmenting images # function to transform images and augment. Adapted from blog post https://medium.com/@a.karazhay/guide-augment-images-and-multiple-bounding-boxes-for-deep-learning-in-4-steps-with-the-notebook-9b263e414dac def image_aug(df, images_path, aug_images_path, image_prefix, augmentor, annotations_path, aug_annotations_path): # create data frame which we're going to populate with augmented image info aug_bbs_xy = pd.DataFrame(columns= ['filename','width','height','class', 'xmin', 'ymin', 'xmax', 'ymax'] ) grouped = df.groupby('filename') i=0 for filename in df['filename'].unique(): # get separate data frame grouped by file name img_name = aug_images_path+image_prefix+filename group_df = grouped.get_group(filename) group_df = group_df.reset_index() group_df = group_df.drop(['index'], axis=1) xml_file = file_creator('aug1_images', img_name, str(group_df['width'][0]), str(group_df['height'][0]) , 3) # read the image image = imageio.imread(images_path+filename) # get bounding boxes coordinates and write into array bb_array = group_df.drop(['filename', 'width', 'height', 'class'], axis=1).values # pass the array of bounding boxes coordinates to the imgaug library bbs = BoundingBoxesOnImage.from_xyxy_array(bb_array, shape=image.shape) # apply augmentation on image and on the bounding boxes image_aug, bbs_aug = augmentor(image=image, bounding_boxes=bbs) # disregard bounding boxes which have fallen out of image pane bbs_aug = bbs_aug.remove_out_of_image() # clip bounding boxes which are partially outside of image pane bbs_aug = bbs_aug.clip_out_of_image() # don't perform any actions with the image if there are no bounding boxes left in it if re.findall('Image...', str(bbs_aug)) == ['Image([]']: pass # otherwise continue else: # write augmented image to a file imageio.imwrite(aug_images_path+image_prefix+filename, image_aug) # create a data frame with augmented values of image width and height for index, line in group_df.iterrows(): xmin = line['xmin'] ymin = line['ymin'] xmax = line['xmax'] ymax = line['ymax'] label = line['class'] object_creator(xml_file, label, xmin, ymin, xmax, ymax) info_df = group_df.drop(['xmin', 'ymin', 'xmax', 'ymax'], axis=1) for index, _ in info_df.iterrows(): info_df.at[index, 'width'] = image_aug.shape[1] info_df.at[index, 'height'] = image_aug.shape[0] # rename filenames by adding the predifined prefix info_df['filename'] = info_df['filename'].apply(lambda x: image_prefix+x) # create a data frame with augmented bounding boxes coordinates using the function we created earlier bbs_df = bbs_obj_to_df(bbs_aug) # concat all new augmented info into new data frame aug_df = pd.concat([info_df, bbs_df], axis=1) # append rows to aug_bbs_xy data frame aug_bbs_xy = pd.concat([aug_bbs_xy, aug_df]) data = ET.tostring(xml_file, encoding = 'unicode') xml_path = os.path.join(aug_annotations_path, image_prefix + filename[:-4] + '.xml') myfile = open(xml_path, 'w') myfile.write(data) print(i) i += 1 # return dataframe with updated images and bounding boxes annotations aug_bbs_xy = aug_bbs_xy.reset_index() aug_bbs_xy = aug_bbs_xy.drop(['index'], axis=1) return aug_bbs_xy # useful augments for masks dataset. # gaussian noise for blur as images can be blurry # resize and cropping to give more variety # colour saturation changes to mimic different environments such as overcast day or bright lights augmentor = iaa.SomeOf(1, [ iaa.Affine(scale=(0.5, 1.5)), iaa.Affine(rotate=(-60, 60)), iaa.Affine(translate_percent={"x":(-0.3, 0.3),"y":(-0.3, 0.3)}), iaa.GaussianBlur(sigma=(1.0, 3.0)), iaa.AdditiveGaussianNoise(scale=(0.03*255, 0.05*255)) ] ) # applying to training data training_labels_df = xml_to_csv('masks-dataset\\train\\annotations\\') training_labels_df.to_csv('masks-dataset/training_labels.csv') test_labels_df = xml_to_csv('masks-dataset\\test\\annotations\\') test_labels_df.to_csv('masks-dataset/test_labels.csv') # print(image_aug( # training_labels_df, # 'masks-dataset\\train\\images\\', # 'masks-dataset\\train\\aug1_images\\', # 'aug1_', # augmentor, # 'masks-dataset\\train\\annotations\\', # 'masks-dataset\\train\\aug1_annotations') # )
import imgaug as ia from xml_test import * from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage from imgaug import augmenters as iaa # imageio library will be used for image input/output import imageio import pandas as pd import numpy as np import re import os import glob # this library is needed to read XML files for converting it into CSV import xml.etree.ElementTree as ET import shutil from xml.etree.ElementTree import Element, SubElement, tostring, XML # converting xml to csv def xml_to_csv(path): xml_list = [] for xml_file in glob.glob(path + '/*.xml'): tree = ET.parse(xml_file) root = tree.getroot() for member in root.findall('object'): try: value = (root.find('filename').text, int(root.find('size')[0].text), int(root.find('size')[1].text), member[0].text, int(member[5][0].text), int(member[5][1].text), int(member[5][2].text), int(member[5][3].text) ) xml_list.append(value) except: pass column_names = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax'] df = pd.DataFrame(xml_list, columns=column_names) return df # function to convert BoundingBoxesOnImage object into DataFrame def bbs_obj_to_df(bbs_object): # convert BoundingBoxesOnImage object into array bbs_array = bbs_object.to_xyxy_array() # convert array into a DataFrame ['xmin', 'ymin', 'xmax', 'ymax'] columns df_bbs = pd.DataFrame(bbs_array, columns=['xmin', 'ymin', 'xmax', 'ymax']) return df_bbs # augmenting images # function to transform images and augment. Adapted from blog post https://medium.com/@a.karazhay/guide-augment-images-and-multiple-bounding-boxes-for-deep-learning-in-4-steps-with-the-notebook-9b263e414dac def image_aug(df, images_path, aug_images_path, image_prefix, augmentor, annotations_path, aug_annotations_path): # create data frame which we're going to populate with augmented image info aug_bbs_xy = pd.DataFrame(columns= ['filename','width','height','class', 'xmin', 'ymin', 'xmax', 'ymax'] ) grouped = df.groupby('filename') i=0 for filename in df['filename'].unique(): # get separate data frame grouped by file name img_name = aug_images_path+image_prefix+filename group_df = grouped.get_group(filename) group_df = group_df.reset_index() group_df = group_df.drop(['index'], axis=1) xml_file = file_creator('aug1_images', img_name, str(group_df['width'][0]), str(group_df['height'][0]) , 3) # read the image image = imageio.imread(images_path+filename) # get bounding boxes coordinates and write into array bb_array = group_df.drop(['filename', 'width', 'height', 'class'], axis=1).values # pass the array of bounding boxes coordinates to the imgaug library bbs = BoundingBoxesOnImage.from_xyxy_array(bb_array, shape=image.shape) # apply augmentation on image and on the bounding boxes image_aug, bbs_aug = augmentor(image=image, bounding_boxes=bbs) # disregard bounding boxes which have fallen out of image pane bbs_aug = bbs_aug.remove_out_of_image() # clip bounding boxes which are partially outside of image pane bbs_aug = bbs_aug.clip_out_of_image() # don't perform any actions with the image if there are no bounding boxes left in it if re.findall('Image...', str(bbs_aug)) == ['Image([]']: pass # otherwise continue else: # write augmented image to a file imageio.imwrite(aug_images_path+image_prefix+filename, image_aug) # create a data frame with augmented values of image width and height for index, line in group_df.iterrows(): xmin = line['xmin'] ymin = line['ymin'] xmax = line['xmax'] ymax = line['ymax'] label = line['class'] object_creator(xml_file, label, xmin, ymin, xmax, ymax) info_df = group_df.drop(['xmin', 'ymin', 'xmax', 'ymax'], axis=1) for index, _ in info_df.iterrows(): info_df.at[index, 'width'] = image_aug.shape[1] info_df.at[index, 'height'] = image_aug.shape[0] # rename filenames by adding the predifined prefix info_df['filename'] = info_df['filename'].apply(lambda x: image_prefix+x) # create a data frame with augmented bounding boxes coordinates using the function we created earlier bbs_df = bbs_obj_to_df(bbs_aug) # concat all new augmented info into new data frame aug_df = pd.concat([info_df, bbs_df], axis=1) # append rows to aug_bbs_xy data frame aug_bbs_xy = pd.concat([aug_bbs_xy, aug_df]) data = ET.tostring(xml_file, encoding = 'unicode') xml_path = os.path.join(aug_annotations_path, image_prefix + filename[:-4] + '.xml') myfile = open(xml_path, 'w') myfile.write(data) print(i) i += 1 # return dataframe with updated images and bounding boxes annotations aug_bbs_xy = aug_bbs_xy.reset_index() aug_bbs_xy = aug_bbs_xy.drop(['index'], axis=1) return aug_bbs_xy # useful augments for masks dataset. # gaussian noise for blur as images can be blurry # resize and cropping to give more variety # colour saturation changes to mimic different environments such as overcast day or bright lights augmentor = iaa.SomeOf(1, [ iaa.Affine(scale=(0.5, 1.5)), iaa.Affine(rotate=(-60, 60)), iaa.Affine(translate_percent={"x":(-0.3, 0.3),"y":(-0.3, 0.3)}), iaa.GaussianBlur(sigma=(1.0, 3.0)), iaa.AdditiveGaussianNoise(scale=(0.03*255, 0.05*255)) ] ) # applying to training data training_labels_df = xml_to_csv('masks-dataset\\train\\annotations\\') training_labels_df.to_csv('masks-dataset/training_labels.csv') test_labels_df = xml_to_csv('masks-dataset\\test\\annotations\\') test_labels_df.to_csv('masks-dataset/test_labels.csv') # print(image_aug( # training_labels_df, # 'masks-dataset\\train\\images\\', # 'masks-dataset\\train\\aug1_images\\', # 'aug1_', # augmentor, # 'masks-dataset\\train\\annotations\\', # 'masks-dataset\\train\\aug1_annotations') # )
en
0.719156
# imageio library will be used for image input/output # this library is needed to read XML files for converting it into CSV # converting xml to csv # function to convert BoundingBoxesOnImage object into DataFrame # convert BoundingBoxesOnImage object into array # convert array into a DataFrame ['xmin', 'ymin', 'xmax', 'ymax'] columns # augmenting images # function to transform images and augment. Adapted from blog post https://medium.com/@a.karazhay/guide-augment-images-and-multiple-bounding-boxes-for-deep-learning-in-4-steps-with-the-notebook-9b263e414dac # create data frame which we're going to populate with augmented image info # get separate data frame grouped by file name # read the image # get bounding boxes coordinates and write into array # pass the array of bounding boxes coordinates to the imgaug library # apply augmentation on image and on the bounding boxes # disregard bounding boxes which have fallen out of image pane # clip bounding boxes which are partially outside of image pane # don't perform any actions with the image if there are no bounding boxes left in it # otherwise continue # write augmented image to a file # create a data frame with augmented values of image width and height # rename filenames by adding the predifined prefix # create a data frame with augmented bounding boxes coordinates using the function we created earlier # concat all new augmented info into new data frame # append rows to aug_bbs_xy data frame # return dataframe with updated images and bounding boxes annotations # useful augments for masks dataset. # gaussian noise for blur as images can be blurry # resize and cropping to give more variety # colour saturation changes to mimic different environments such as overcast day or bright lights # applying to training data # print(image_aug( # training_labels_df, # 'masks-dataset\\train\\images\\', # 'masks-dataset\\train\\aug1_images\\', # 'aug1_', # augmentor, # 'masks-dataset\\train\\annotations\\', # 'masks-dataset\\train\\aug1_annotations') # )
2.961354
3
Chapter6/Cubic Spline.py
southparkkids/NumericalAnalysis
0
6615550
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import matplotlib.pyplot as plt # In[37]: # Spline3_Coef pseudocode p.271 def Spline3_Coef(n, t, y, z): h = np.zeros(n-1) b = np.zeros(n-1) u = np.zeros(n-1) v = np.zeros(n-1) for i in range(0, n-1): h[i] = t[i+1] - t[i] b[i] = (y[i+1] - y[i])/h[i] u[1] = 2*(h[0] + h[1]) v[1] = 6*(b[1] - b[0]) for i in range(2, n-1): u[i] = 2*(h[i] + h[i-1]) - (h[i-1]**2/u[i-1]) v[i] = 6*(b[i] - b[i-1]) - (h[i-1]*v[i-1]/u[i-1]) z[n] = 0 for i in range(n-2, 0, -1): z[i] = (v[i] - h[i]*z[i+1])/u[i] z[0] = 0 return z # In[38]: # Spline3_Eval pseudocode p.271 def Spline3_Eval(n, t, y, z, x): for i in range(n-2, -1, -1): if x - t[i] >= 0: break h = t[i+1] - t[i] tmp = z[i]/2 + (x - t[i])*(z[i+1] - z[i])/(6*h) tmp = -(h/6)*(z[i+1] + 2*z[i]) + (y[i+1] - y[i])/h + (x - t[i])*tmp return y[i] + (x-t[i])*tmp # In[39]: X = np.zeros(20) Y = np.zeros(20) X = [0.0, 0.6, 1.5, 1.7, 1.9, 2.1, 2.3, 2.6, 2.8, 3.0, 3.6, 4.7, 5.2, 5.7, 5.8, 6.0, 6.4, 6.9, 7.6, 8.0] Y = [-0.8, -0.34, 0.59, 0.59, 0.23, 0.1, 0.28, 1.03, 1.5, 1.44, 0.74, -0.82, -1.27, -0.92, -0.92, -1.04, -0.79, -0.06, 1.0, 0.0] Z = np.zeros(21) Spline3_Coef(20, X, Y, Z) XS = np.arange(0, 8, 0.01) YS = np.zeros(len(XS)) for i in range(0, len(XS)): YS[i] = Spline3_Eval(19, X, Y, Z, XS[i]) # 6.2 Figure 5.8 # Format plot figure fig = plt.figure(figsize=(10, 6)) ax1 = fig.add_subplot(111) # Add f(x) line and points used by Simpson approximation ax1.scatter(X,Y, label = 'y = S(x)') ax1.plot(XS,YS, label = 'y = S(x)') #ax1.scatter(XP,PP) # Set title of plot plt.title('f(x) = 1/(1+x^2) from 0 to 1') # Give x axis label plt.xlabel('x') plt.ylabel('f(x)') # Format the plot plt.legend(loc='upper right') plt.grid(True, which='both') plt.axhline(y=0) plt.show() # In[41]: # Test_Spline3 pseudocode p.272 n = 9 a = 0 b = 1.6875 h = (b - a)/n t = np.zeros(n+1) y = np.zeros(n+1) for i in range(0, n): t[i] = a + i*h y[i] = np.sin(t[i]) z = np.zeros(n+1) Spline3_Coef(n, t, y, z) temp = 0 for j in range(0, 4*n): x = a + j*h/4 e = np.abs(np.sin(x) - Spline3_Eval(n, t, y, z, x)) if j == 19: print("j =", j, "\nx =", x, "\ne =", e) if e > temp: temp = e #print(j) print("j =", j, "\nx =", x, "\ne =", e) #Book solution j = 19, x = 0.890625, and d = 0.930 x 10^-5. # In[56]: def f(x): return (x**2 + 1)**(-1) n = 41 t = np.linspace(-5, 5, n) y = f(t) print(t) print(y) z = np.zeros(n+1) Spline3_Coef(n, t, y, z) XS = np.linspace(0, 5, 101) YS = np.zeros(len(XS)) for i in range(0, len(XS)): YS[i] = Spline3_Eval(40, t, y, z, XS[i]) # Format plot figure fig = plt.figure(figsize=(10, 6)) ax1 = fig.add_subplot(111) # Add f(x) line and points used by Simpson approximation ax1.scatter(t,y, label = 'f(x) = (x^2 + 1)^-1') ax1.plot(XS,YS, label = 'S(x)') #ax1.scatter(XP,PP) # Set title of plot plt.title('f(x) = 1/(1+x^2) from 0 to 1') # Give x axis label plt.xlabel('x') plt.ylabel('f(x)') # Format the plot plt.legend(loc='upper right') plt.grid(True, which='both') plt.axhline(y=0) plt.show() Y = f(XS) Dif = YS - Y print(Dif) print("Max difference: ", max(Dif), "\nAverage difference: ", np.average(Dif), "\nStandard Deviation: ", np.std(Dif)) # In[ ]:
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import matplotlib.pyplot as plt # In[37]: # Spline3_Coef pseudocode p.271 def Spline3_Coef(n, t, y, z): h = np.zeros(n-1) b = np.zeros(n-1) u = np.zeros(n-1) v = np.zeros(n-1) for i in range(0, n-1): h[i] = t[i+1] - t[i] b[i] = (y[i+1] - y[i])/h[i] u[1] = 2*(h[0] + h[1]) v[1] = 6*(b[1] - b[0]) for i in range(2, n-1): u[i] = 2*(h[i] + h[i-1]) - (h[i-1]**2/u[i-1]) v[i] = 6*(b[i] - b[i-1]) - (h[i-1]*v[i-1]/u[i-1]) z[n] = 0 for i in range(n-2, 0, -1): z[i] = (v[i] - h[i]*z[i+1])/u[i] z[0] = 0 return z # In[38]: # Spline3_Eval pseudocode p.271 def Spline3_Eval(n, t, y, z, x): for i in range(n-2, -1, -1): if x - t[i] >= 0: break h = t[i+1] - t[i] tmp = z[i]/2 + (x - t[i])*(z[i+1] - z[i])/(6*h) tmp = -(h/6)*(z[i+1] + 2*z[i]) + (y[i+1] - y[i])/h + (x - t[i])*tmp return y[i] + (x-t[i])*tmp # In[39]: X = np.zeros(20) Y = np.zeros(20) X = [0.0, 0.6, 1.5, 1.7, 1.9, 2.1, 2.3, 2.6, 2.8, 3.0, 3.6, 4.7, 5.2, 5.7, 5.8, 6.0, 6.4, 6.9, 7.6, 8.0] Y = [-0.8, -0.34, 0.59, 0.59, 0.23, 0.1, 0.28, 1.03, 1.5, 1.44, 0.74, -0.82, -1.27, -0.92, -0.92, -1.04, -0.79, -0.06, 1.0, 0.0] Z = np.zeros(21) Spline3_Coef(20, X, Y, Z) XS = np.arange(0, 8, 0.01) YS = np.zeros(len(XS)) for i in range(0, len(XS)): YS[i] = Spline3_Eval(19, X, Y, Z, XS[i]) # 6.2 Figure 5.8 # Format plot figure fig = plt.figure(figsize=(10, 6)) ax1 = fig.add_subplot(111) # Add f(x) line and points used by Simpson approximation ax1.scatter(X,Y, label = 'y = S(x)') ax1.plot(XS,YS, label = 'y = S(x)') #ax1.scatter(XP,PP) # Set title of plot plt.title('f(x) = 1/(1+x^2) from 0 to 1') # Give x axis label plt.xlabel('x') plt.ylabel('f(x)') # Format the plot plt.legend(loc='upper right') plt.grid(True, which='both') plt.axhline(y=0) plt.show() # In[41]: # Test_Spline3 pseudocode p.272 n = 9 a = 0 b = 1.6875 h = (b - a)/n t = np.zeros(n+1) y = np.zeros(n+1) for i in range(0, n): t[i] = a + i*h y[i] = np.sin(t[i]) z = np.zeros(n+1) Spline3_Coef(n, t, y, z) temp = 0 for j in range(0, 4*n): x = a + j*h/4 e = np.abs(np.sin(x) - Spline3_Eval(n, t, y, z, x)) if j == 19: print("j =", j, "\nx =", x, "\ne =", e) if e > temp: temp = e #print(j) print("j =", j, "\nx =", x, "\ne =", e) #Book solution j = 19, x = 0.890625, and d = 0.930 x 10^-5. # In[56]: def f(x): return (x**2 + 1)**(-1) n = 41 t = np.linspace(-5, 5, n) y = f(t) print(t) print(y) z = np.zeros(n+1) Spline3_Coef(n, t, y, z) XS = np.linspace(0, 5, 101) YS = np.zeros(len(XS)) for i in range(0, len(XS)): YS[i] = Spline3_Eval(40, t, y, z, XS[i]) # Format plot figure fig = plt.figure(figsize=(10, 6)) ax1 = fig.add_subplot(111) # Add f(x) line and points used by Simpson approximation ax1.scatter(t,y, label = 'f(x) = (x^2 + 1)^-1') ax1.plot(XS,YS, label = 'S(x)') #ax1.scatter(XP,PP) # Set title of plot plt.title('f(x) = 1/(1+x^2) from 0 to 1') # Give x axis label plt.xlabel('x') plt.ylabel('f(x)') # Format the plot plt.legend(loc='upper right') plt.grid(True, which='both') plt.axhline(y=0) plt.show() Y = f(XS) Dif = YS - Y print(Dif) print("Max difference: ", max(Dif), "\nAverage difference: ", np.average(Dif), "\nStandard Deviation: ", np.std(Dif)) # In[ ]:
en
0.654084
#!/usr/bin/env python # coding: utf-8 # In[1]: # In[37]: # Spline3_Coef pseudocode p.271 # In[38]: # Spline3_Eval pseudocode p.271 # In[39]: # 6.2 Figure 5.8 # Format plot figure # Add f(x) line and points used by Simpson approximation #ax1.scatter(XP,PP) # Set title of plot # Give x axis label # Format the plot # In[41]: # Test_Spline3 pseudocode p.272 #print(j) #Book solution j = 19, x = 0.890625, and d = 0.930 x 10^-5. # In[56]: # Format plot figure # Add f(x) line and points used by Simpson approximation #ax1.scatter(XP,PP) # Set title of plot # Give x axis label # Format the plot # In[ ]:
3.399889
3