file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
bootstrap.py
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. """ import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c):
else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() has_broken_dash_S = bool(int(stdout.strip())) # In order to be more robust in the face of system Pythons, we want to # run without site-packages loaded. This is somewhat tricky, in # particular because Python 2.6's distutils imports site, so starting # with the -S flag is not sufficient. However, we'll start with that: if not has_broken_dash_S and 'site' in sys.modules: # We will restart with python -S. args = sys.argv[:] args[0:0] = [sys.executable, '-S'] args = map(quote, args) os.execv(sys.executable, args) # Now we are running with -S. We'll get the clean sys.path, import site # because distutils will do it later, and then reset the path and clean # out any namespace packages from site-packages that might have been # loaded by .pth files. clean_path = sys.path[:] import site # imported because of its side effects sys.path[:] = clean_path for k, v in sys.modules.items(): if k in ('setuptools', 'pkg_resources') or ( hasattr(v, '__path__') and len(v.__path__) == 1 and not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))): # This is a namespace package. Remove it. sys.modules.pop(k) is_jython = sys.platform.startswith('java') setuptools_source = 'https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' distribute_source = 'http://python-distribute.org/distribute_setup.py' # parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--download-base' and not value.endswith('/'): # Download base needs a trailing slash to make the world happy. value += '/' else: value = None name = opt_str[2:].replace('-', '_') setattr(parser.values, name, value) usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="use_distribute", default=False, help="Use Distribute rather than Setuptools.") parser.add_option("--setup-source", action="callback", dest="setup_source", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or file location for the setup file. " "If you use Setuptools, this will default to " + setuptools_source + "; if you use Distribute, this " "will default to " + distribute_source + ".")) parser.add_option("--download-base", action="callback", dest="download_base", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or directory for downloading " "zc.buildout and either Setuptools or Distribute. " "Defaults to PyPI.")) parser.add_option("--eggs", help=("Specify a directory for storing eggs. Defaults to " "a temporary directory that is deleted when the " "bootstrap script completes.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout's main function if options.config_file is not None: args += ['-c', options.config_file] if options.eggs: eggs_dir = os.path.abspath(os.path.expanduser(options.eggs)) else: eggs_dir = tempfile.mkdtemp() if options.setup_source is None: if options.use_distribute: options.setup_source = distribute_source else: options.setup_source = setuptools_source if options.accept_buildout_test_releases: args.append('buildout:accept-buildout-test-releases=true') args.append('bootstrap') try: import pkg_resources import setuptools # A flag. Sometimes pkg_resources is installed alone. if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez_code = urllib2.urlopen( options.setup_source).read().replace('\r\n', '\n') ez = {} exec ez_code in ez setup_args = dict(to_dir=eggs_dir, download_delay=0) if options.download_base: setup_args['download_base'] = options.download_base if options.use_distribute: setup_args['no_fake'] = True ez['use_setuptools'](**setup_args) if 'pkg_resources' in sys.modules: reload(sys.modules['pkg_resources']) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(eggs_dir)] if not has_broken_dash_S: cmd.insert(1, '-S') find_links = options.download_base if not find_links: find_links = os.environ.get('bootstrap-testing-find-links') if find_links: cmd.extend(['-f', quote(find_links)]) if options.use_distribute: setup_requirement = 'distribute' else: setup_requirement = 'setuptools' ws = pkg_resources.working_set setup_requirement_path = ws.find( pkg_resources.Requirement.parse(setup_requirement)).location env = dict( os.environ, PYTHONPATH=setup_requirement_path) requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setup_requirement_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) if exitcode != 0: sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode) ws.add_entry(eggs_dir) ws.require(requirement) import zc.buildout.buildout zc.buildout.buildout.main(args) if not options.eggs: # clean up temporary egg directory shutil.rmtree(eggs_dir)
if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c
identifier_body
bootstrap.py
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. """ import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() has_broken_dash_S = bool(int(stdout.strip())) # In order to be more robust in the face of system Pythons, we want to # run without site-packages loaded. This is somewhat tricky, in # particular because Python 2.6's distutils imports site, so starting # with the -S flag is not sufficient. However, we'll start with that: if not has_broken_dash_S and 'site' in sys.modules: # We will restart with python -S. args = sys.argv[:] args[0:0] = [sys.executable, '-S'] args = map(quote, args) os.execv(sys.executable, args) # Now we are running with -S. We'll get the clean sys.path, import site # because distutils will do it later, and then reset the path and clean # out any namespace packages from site-packages that might have been # loaded by .pth files. clean_path = sys.path[:] import site # imported because of its side effects sys.path[:] = clean_path for k, v in sys.modules.items(): if k in ('setuptools', 'pkg_resources') or ( hasattr(v, '__path__') and len(v.__path__) == 1 and not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))): # This is a namespace package. Remove it. sys.modules.pop(k) is_jython = sys.platform.startswith('java') setuptools_source = 'https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' distribute_source = 'http://python-distribute.org/distribute_setup.py' # parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--download-base' and not value.endswith('/'): # Download base needs a trailing slash to make the world happy. value += '/' else: value = None name = opt_str[2:].replace('-', '_') setattr(parser.values, name, value) usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="use_distribute", default=False, help="Use Distribute rather than Setuptools.") parser.add_option("--setup-source", action="callback", dest="setup_source", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or file location for the setup file. " "If you use Setuptools, this will default to " + setuptools_source + "; if you use Distribute, this " "will default to " + distribute_source + ".")) parser.add_option("--download-base", action="callback", dest="download_base", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or directory for downloading " "zc.buildout and either Setuptools or Distribute. " "Defaults to PyPI.")) parser.add_option("--eggs", help=("Specify a directory for storing eggs. Defaults to " "a temporary directory that is deleted when the " "bootstrap script completes.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout's main function if options.config_file is not None: args += ['-c', options.config_file] if options.eggs: eggs_dir = os.path.abspath(os.path.expanduser(options.eggs)) else: eggs_dir = tempfile.mkdtemp() if options.setup_source is None: if options.use_distribute: options.setup_source = distribute_source else: options.setup_source = setuptools_source if options.accept_buildout_test_releases: args.append('buildout:accept-buildout-test-releases=true') args.append('bootstrap') try: import pkg_resources import setuptools # A flag. Sometimes pkg_resources is installed alone. if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez_code = urllib2.urlopen( options.setup_source).read().replace('\r\n', '\n') ez = {} exec ez_code in ez setup_args = dict(to_dir=eggs_dir, download_delay=0) if options.download_base: setup_args['download_base'] = options.download_base if options.use_distribute: setup_args['no_fake'] = True ez['use_setuptools'](**setup_args) if 'pkg_resources' in sys.modules: reload(sys.modules['pkg_resources']) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) cmd = [quote(sys.executable), '-c', quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(eggs_dir)] if not has_broken_dash_S: cmd.insert(1, '-S') find_links = options.download_base if not find_links: find_links = os.environ.get('bootstrap-testing-find-links') if find_links: cmd.extend(['-f', quote(find_links)]) if options.use_distribute: setup_requirement = 'distribute' else: setup_requirement = 'setuptools' ws = pkg_resources.working_set setup_requirement_path = ws.find( pkg_resources.Requirement.parse(setup_requirement)).location env = dict( os.environ, PYTHONPATH=setup_requirement_path) requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def
(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setup_requirement_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) if exitcode != 0: sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode) ws.add_entry(eggs_dir) ws.require(requirement) import zc.buildout.buildout zc.buildout.buildout.main(args) if not options.eggs: # clean up temporary egg directory shutil.rmtree(eggs_dir)
_final_version
identifier_name
meteorite.js
// meteorite namespace var Meteorite = Meteorite || {}; // initialize websocket Meteorite.websocket = new WebSocket("ws://" + location.hostname + ":8080/"); console.log('starting meteorite websockets. . .'); // when a new websocket message is received Meteorite.websocket.onmessage = function(msg) { // parse the json message // todo: handle non-json messages var json = JSON.parse(msg.data); // log the data console.log(json); // if this is a delete if (json.bind_data === 'delete') { // remove the item $('#' + json.bind_key).remove(); // halt further processing return false; } // for each meteorite class $('.meteorite').each(function() { // if the bind keys match if ($(this).data('bind-key') === json.bind_key) { console.log('bind found'); // if there is no bind-attr present, this is a collection if ($(this).data('bind-attr') === undefined)
else { Meteorite.update(json, $(this)); } } }); } // add an item Meteorite.add = function(json, $element) { // add to the dom $element.append(json.bind_data); // listen to subscribe events Meteorite.subscribe($(json.bind_data).find('.meteorite').data('bind-key')); } // update a single attribute Meteorite.update = function(json, $element) { // get the bind data var bind_data = JSON.parse(json.bind_data); // desired attribute var bind_attr = $element.data('bind-attr'); // get the attribute data var attr_data = bind_data[bind_attr]; // update the property $element.prop('checked', attr_data); // update the text $element.text(attr_data); // notify event handlers that a change has occurred $element.trigger('change'); } // subscribe to all bind keys of meteorite classes Meteorite.subscribeAll = function() { // for each meteorite class $('.meteorite').each(function() { // if there is a bind key if ($(this).data('bind-key') !== undefined) { // subscribe Meteorite.subscribe($(this).data('bind-key')); } }); } // wait for websocket to be ready, then subscribe all Meteorite.subscribeAfterWebsocket = function() { // set a 5ms timeout setTimeout(function() { // if the websocket is ready if (Meteorite.websocket.readyState === 1) { // send the subscribe notices Meteorite.subscribeAll(); // try again if not ready } else { Meteorite.subscribeAfterWebsocket(); } }, 5); } // subscribe to events when the websocket is ready Meteorite.subscribe = function(bind_key) { // send the subscribe notice Meteorite.websocket.send(JSON.stringify({ action: 'subscribe', key: bind_key })); } // when the document is ready $(document).on('page:load ready', function() { Meteorite.subscribeAfterWebsocket(); });
{ Meteorite.add(json, $(this)); // else update the element }
conditional_block
meteorite.js
// meteorite namespace var Meteorite = Meteorite || {}; // initialize websocket Meteorite.websocket = new WebSocket("ws://" + location.hostname + ":8080/"); console.log('starting meteorite websockets. . .'); // when a new websocket message is received Meteorite.websocket.onmessage = function(msg) { // parse the json message // todo: handle non-json messages var json = JSON.parse(msg.data); // log the data console.log(json); // if this is a delete if (json.bind_data === 'delete') { // remove the item $('#' + json.bind_key).remove(); // halt further processing return false; } // for each meteorite class $('.meteorite').each(function() { // if the bind keys match if ($(this).data('bind-key') === json.bind_key) { console.log('bind found'); // if there is no bind-attr present, this is a collection if ($(this).data('bind-attr') === undefined) { Meteorite.add(json, $(this)); // else update the element } else { Meteorite.update(json, $(this)); } } }); }
Meteorite.subscribe($(json.bind_data).find('.meteorite').data('bind-key')); } // update a single attribute Meteorite.update = function(json, $element) { // get the bind data var bind_data = JSON.parse(json.bind_data); // desired attribute var bind_attr = $element.data('bind-attr'); // get the attribute data var attr_data = bind_data[bind_attr]; // update the property $element.prop('checked', attr_data); // update the text $element.text(attr_data); // notify event handlers that a change has occurred $element.trigger('change'); } // subscribe to all bind keys of meteorite classes Meteorite.subscribeAll = function() { // for each meteorite class $('.meteorite').each(function() { // if there is a bind key if ($(this).data('bind-key') !== undefined) { // subscribe Meteorite.subscribe($(this).data('bind-key')); } }); } // wait for websocket to be ready, then subscribe all Meteorite.subscribeAfterWebsocket = function() { // set a 5ms timeout setTimeout(function() { // if the websocket is ready if (Meteorite.websocket.readyState === 1) { // send the subscribe notices Meteorite.subscribeAll(); // try again if not ready } else { Meteorite.subscribeAfterWebsocket(); } }, 5); } // subscribe to events when the websocket is ready Meteorite.subscribe = function(bind_key) { // send the subscribe notice Meteorite.websocket.send(JSON.stringify({ action: 'subscribe', key: bind_key })); } // when the document is ready $(document).on('page:load ready', function() { Meteorite.subscribeAfterWebsocket(); });
// add an item Meteorite.add = function(json, $element) { // add to the dom $element.append(json.bind_data); // listen to subscribe events
random_line_split
instr_cvtdq2ps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn cvtdq2ps_1()
#[test] fn cvtdq2ps_2() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 829617393, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 52, 77, 241, 244, 114, 49], OperandSize::Dword) } #[test] fn cvtdq2ps_3() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 244], OperandSize::Qword) } #[test] fn cvtdq2ps_4() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Two, 1952076968, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 20, 93, 168, 84, 90, 116], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 210], OperandSize::Dword) }
identifier_body
instr_cvtdq2ps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn cvtdq2ps_1() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 210], OperandSize::Dword) } #[test] fn cvtdq2ps_2() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 829617393, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 52, 77, 241, 244, 114, 49], OperandSize::Dword) } #[test] fn cvtdq2ps_3() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 244], OperandSize::Qword) } #[test] fn
() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Two, 1952076968, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 20, 93, 168, 84, 90, 116], OperandSize::Qword) }
cvtdq2ps_4
identifier_name
instr_cvtdq2ps.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test]
fn cvtdq2ps_1() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM2)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 210], OperandSize::Dword) } #[test] fn cvtdq2ps_2() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledDisplaced(ECX, Two, 829617393, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 52, 77, 241, 244, 114, 49], OperandSize::Dword) } #[test] fn cvtdq2ps_3() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 244], OperandSize::Qword) } #[test] fn cvtdq2ps_4() { run_test(&Instruction { mnemonic: Mnemonic::CVTDQ2PS, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Two, 1952076968, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[15, 91, 20, 93, 168, 84, 90, 116], OperandSize::Qword) }
random_line_split
node.js
'use strict'; var i18n = require('./i18n.js') i18n.add_translation("pt-BR", {
welcome: 'Bem vindo' } }); i18n.locale = 'pt-BR'; console.log(i18n.t('greetings.hello')); console.log(i18n.t('greetings.welcome')); console.log("Hallo"); // Example 2 i18n.add_translation("pt-BR", { greetings: { hello: 'Olá', welcome: 'Bem vindo' } }); console.log(i18n.t('greetings.hello')); i18n.add_translation("pt-BR", { test: 'OK', greetings: { hello: 'Oi', bye: 'Tchau' } }); console.log(i18n.t('greetings.hello')); console.log(i18n.t('test'));
test: 'OK', greetings: { hello: 'Olá',
random_line_split
decorators.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Red Hat, Inc # # 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. import datetime import json import logging from functools import wraps import flask import dci.auth_mechanism as am from dci.common import exceptions as dci_exc logger = logging.getLogger(__name__)
def reject(): """Sends a 401 reject response that enables basic auth.""" auth_message = ( "Could not verify your access level for that URL." "Please login with proper credentials." ) auth_message = json.dumps({"_status": "Unauthorized", "message": auth_message}) headers = {"WWW-Authenticate": 'Basic realm="Login required"'} logger.info(auth_message) return flask.Response( auth_message, 401, headers=headers, content_type="application/json" ) def _get_auth_class_from_headers(headers): if "Authorization" not in headers: raise dci_exc.DCIException("Authorization header missing", status_code=401) auth_type = headers.get("Authorization").split(" ")[0] if auth_type == "Bearer": return am.OpenIDCAuth elif auth_type == "DCI-HMAC-SHA256": return am.HmacMechanism elif auth_type in ["DCI2-HMAC-SHA256", "AWS4-HMAC-SHA256"]: return am.Hmac2Mechanism elif auth_type == "Basic": return am.BasicAuthMechanism raise dci_exc.DCIException( "Authorization scheme %s unknown" % auth_type, status_code=401 ) def login_required(f): @wraps(f) def decorated(*args, **kwargs): auth_class = _get_auth_class_from_headers(flask.request.headers) auth_scheme = auth_class(flask.request) auth_scheme.authenticate() return f(auth_scheme.identity, *args, **kwargs) return decorated def log(f): @wraps(f) def decorated(*args, **kwargs): user = args[0] try: log = models2.Log( **{ "user_id": user.id, "action": f.__name__, "created_at": datetime.datetime.utcnow().isoformat(), } ) flask.g.session.add(log) flask.g.session.commit() except Exception as e: flask.g.session.rollback() logger.error("cannot save audit log") logger.error(str(e)) return f(*args, **kwargs) return decorated
from dci.db import models2
random_line_split
decorators.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Red Hat, Inc # # 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. import datetime import json import logging from functools import wraps import flask import dci.auth_mechanism as am from dci.common import exceptions as dci_exc logger = logging.getLogger(__name__) from dci.db import models2 def reject(): """Sends a 401 reject response that enables basic auth.""" auth_message = ( "Could not verify your access level for that URL." "Please login with proper credentials." ) auth_message = json.dumps({"_status": "Unauthorized", "message": auth_message}) headers = {"WWW-Authenticate": 'Basic realm="Login required"'} logger.info(auth_message) return flask.Response( auth_message, 401, headers=headers, content_type="application/json" ) def _get_auth_class_from_headers(headers): if "Authorization" not in headers: raise dci_exc.DCIException("Authorization header missing", status_code=401) auth_type = headers.get("Authorization").split(" ")[0] if auth_type == "Bearer": return am.OpenIDCAuth elif auth_type == "DCI-HMAC-SHA256": return am.HmacMechanism elif auth_type in ["DCI2-HMAC-SHA256", "AWS4-HMAC-SHA256"]: return am.Hmac2Mechanism elif auth_type == "Basic": return am.BasicAuthMechanism raise dci_exc.DCIException( "Authorization scheme %s unknown" % auth_type, status_code=401 ) def login_required(f):
def log(f): @wraps(f) def decorated(*args, **kwargs): user = args[0] try: log = models2.Log( **{ "user_id": user.id, "action": f.__name__, "created_at": datetime.datetime.utcnow().isoformat(), } ) flask.g.session.add(log) flask.g.session.commit() except Exception as e: flask.g.session.rollback() logger.error("cannot save audit log") logger.error(str(e)) return f(*args, **kwargs) return decorated
@wraps(f) def decorated(*args, **kwargs): auth_class = _get_auth_class_from_headers(flask.request.headers) auth_scheme = auth_class(flask.request) auth_scheme.authenticate() return f(auth_scheme.identity, *args, **kwargs) return decorated
identifier_body
decorators.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Red Hat, Inc # # 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. import datetime import json import logging from functools import wraps import flask import dci.auth_mechanism as am from dci.common import exceptions as dci_exc logger = logging.getLogger(__name__) from dci.db import models2 def reject(): """Sends a 401 reject response that enables basic auth.""" auth_message = ( "Could not verify your access level for that URL." "Please login with proper credentials." ) auth_message = json.dumps({"_status": "Unauthorized", "message": auth_message}) headers = {"WWW-Authenticate": 'Basic realm="Login required"'} logger.info(auth_message) return flask.Response( auth_message, 401, headers=headers, content_type="application/json" ) def _get_auth_class_from_headers(headers): if "Authorization" not in headers: raise dci_exc.DCIException("Authorization header missing", status_code=401) auth_type = headers.get("Authorization").split(" ")[0] if auth_type == "Bearer": return am.OpenIDCAuth elif auth_type == "DCI-HMAC-SHA256": return am.HmacMechanism elif auth_type in ["DCI2-HMAC-SHA256", "AWS4-HMAC-SHA256"]: return am.Hmac2Mechanism elif auth_type == "Basic":
raise dci_exc.DCIException( "Authorization scheme %s unknown" % auth_type, status_code=401 ) def login_required(f): @wraps(f) def decorated(*args, **kwargs): auth_class = _get_auth_class_from_headers(flask.request.headers) auth_scheme = auth_class(flask.request) auth_scheme.authenticate() return f(auth_scheme.identity, *args, **kwargs) return decorated def log(f): @wraps(f) def decorated(*args, **kwargs): user = args[0] try: log = models2.Log( **{ "user_id": user.id, "action": f.__name__, "created_at": datetime.datetime.utcnow().isoformat(), } ) flask.g.session.add(log) flask.g.session.commit() except Exception as e: flask.g.session.rollback() logger.error("cannot save audit log") logger.error(str(e)) return f(*args, **kwargs) return decorated
return am.BasicAuthMechanism
conditional_block
decorators.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Red Hat, Inc # # 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. import datetime import json import logging from functools import wraps import flask import dci.auth_mechanism as am from dci.common import exceptions as dci_exc logger = logging.getLogger(__name__) from dci.db import models2 def reject(): """Sends a 401 reject response that enables basic auth.""" auth_message = ( "Could not verify your access level for that URL." "Please login with proper credentials." ) auth_message = json.dumps({"_status": "Unauthorized", "message": auth_message}) headers = {"WWW-Authenticate": 'Basic realm="Login required"'} logger.info(auth_message) return flask.Response( auth_message, 401, headers=headers, content_type="application/json" ) def _get_auth_class_from_headers(headers): if "Authorization" not in headers: raise dci_exc.DCIException("Authorization header missing", status_code=401) auth_type = headers.get("Authorization").split(" ")[0] if auth_type == "Bearer": return am.OpenIDCAuth elif auth_type == "DCI-HMAC-SHA256": return am.HmacMechanism elif auth_type in ["DCI2-HMAC-SHA256", "AWS4-HMAC-SHA256"]: return am.Hmac2Mechanism elif auth_type == "Basic": return am.BasicAuthMechanism raise dci_exc.DCIException( "Authorization scheme %s unknown" % auth_type, status_code=401 ) def login_required(f): @wraps(f) def decorated(*args, **kwargs): auth_class = _get_auth_class_from_headers(flask.request.headers) auth_scheme = auth_class(flask.request) auth_scheme.authenticate() return f(auth_scheme.identity, *args, **kwargs) return decorated def
(f): @wraps(f) def decorated(*args, **kwargs): user = args[0] try: log = models2.Log( **{ "user_id": user.id, "action": f.__name__, "created_at": datetime.datetime.utcnow().isoformat(), } ) flask.g.session.add(log) flask.g.session.commit() except Exception as e: flask.g.session.rollback() logger.error("cannot save audit log") logger.error(str(e)) return f(*args, **kwargs) return decorated
log
identifier_name
scan.ts
import { isBrowser, target } from '@vue-devtools/shared-utils' const rootInstances = [] let rootUID = 0 /** * Scan the page for root level Vue instances. */ export function scan () { rootInstances.length = 0 let inFragment = false let currentFragment = null // eslint-disable-next-line no-inner-declarations function processInstance (instance) { if (instance) { if (rootInstances.indexOf(instance.$root) === -1) { instance = instance.$root } if (instance._isFragment) { inFragment = true currentFragment = instance } // respect Vue.config.devtools option let baseVue = instance.constructor while (baseVue.super) { baseVue = baseVue.super } if (baseVue.config && baseVue.config.devtools) { // give a unique id to root instance so we can // 'namespace' its children if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') { instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID } rootInstances.push(instance) } return true } } if (isBrowser) { const walkDocument = document => { walk(document, function (node) { if (inFragment) { if (node === currentFragment._fragmentEnd) { inFragment = false currentFragment = null } return true } const instance = node.__vue__ return processInstance(instance) }) } walkDocument(document) const iframes = document.querySelectorAll<HTMLIFrameElement>('iframe') for (const iframe of iframes) { try { walkDocument(iframe.contentDocument) } catch (e) { // Ignore } } } else { if (Array.isArray(target.__VUE_ROOT_INSTANCES__)) { target.__VUE_ROOT_INSTANCES__.map(processInstance) } } return rootInstances } /** * DOM walk helper * * @param {NodeList} nodes * @param {Function} fn */ function
(node, fn) { if (node.childNodes) { for (let i = 0, l = node.childNodes.length; i < l; i++) { const child = node.childNodes[i] const stop = fn(child) if (!stop) { walk(child, fn) } } } // also walk shadow DOM if (node.shadowRoot) { walk(node.shadowRoot, fn) } }
walk
identifier_name
scan.ts
import { isBrowser, target } from '@vue-devtools/shared-utils' const rootInstances = [] let rootUID = 0 /** * Scan the page for root level Vue instances. */ export function scan ()
/** * DOM walk helper * * @param {NodeList} nodes * @param {Function} fn */ function walk (node, fn) { if (node.childNodes) { for (let i = 0, l = node.childNodes.length; i < l; i++) { const child = node.childNodes[i] const stop = fn(child) if (!stop) { walk(child, fn) } } } // also walk shadow DOM if (node.shadowRoot) { walk(node.shadowRoot, fn) } }
{ rootInstances.length = 0 let inFragment = false let currentFragment = null // eslint-disable-next-line no-inner-declarations function processInstance (instance) { if (instance) { if (rootInstances.indexOf(instance.$root) === -1) { instance = instance.$root } if (instance._isFragment) { inFragment = true currentFragment = instance } // respect Vue.config.devtools option let baseVue = instance.constructor while (baseVue.super) { baseVue = baseVue.super } if (baseVue.config && baseVue.config.devtools) { // give a unique id to root instance so we can // 'namespace' its children if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') { instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID } rootInstances.push(instance) } return true } } if (isBrowser) { const walkDocument = document => { walk(document, function (node) { if (inFragment) { if (node === currentFragment._fragmentEnd) { inFragment = false currentFragment = null } return true } const instance = node.__vue__ return processInstance(instance) }) } walkDocument(document) const iframes = document.querySelectorAll<HTMLIFrameElement>('iframe') for (const iframe of iframes) { try { walkDocument(iframe.contentDocument) } catch (e) { // Ignore } } } else { if (Array.isArray(target.__VUE_ROOT_INSTANCES__)) { target.__VUE_ROOT_INSTANCES__.map(processInstance) } } return rootInstances }
identifier_body
scan.ts
import { isBrowser, target } from '@vue-devtools/shared-utils' const rootInstances = [] let rootUID = 0 /** * Scan the page for root level Vue instances. */ export function scan () { rootInstances.length = 0 let inFragment = false let currentFragment = null // eslint-disable-next-line no-inner-declarations function processInstance (instance) { if (instance) { if (rootInstances.indexOf(instance.$root) === -1) { instance = instance.$root } if (instance._isFragment) { inFragment = true currentFragment = instance } // respect Vue.config.devtools option let baseVue = instance.constructor while (baseVue.super) { baseVue = baseVue.super } if (baseVue.config && baseVue.config.devtools)
return true } } if (isBrowser) { const walkDocument = document => { walk(document, function (node) { if (inFragment) { if (node === currentFragment._fragmentEnd) { inFragment = false currentFragment = null } return true } const instance = node.__vue__ return processInstance(instance) }) } walkDocument(document) const iframes = document.querySelectorAll<HTMLIFrameElement>('iframe') for (const iframe of iframes) { try { walkDocument(iframe.contentDocument) } catch (e) { // Ignore } } } else { if (Array.isArray(target.__VUE_ROOT_INSTANCES__)) { target.__VUE_ROOT_INSTANCES__.map(processInstance) } } return rootInstances } /** * DOM walk helper * * @param {NodeList} nodes * @param {Function} fn */ function walk (node, fn) { if (node.childNodes) { for (let i = 0, l = node.childNodes.length; i < l; i++) { const child = node.childNodes[i] const stop = fn(child) if (!stop) { walk(child, fn) } } } // also walk shadow DOM if (node.shadowRoot) { walk(node.shadowRoot, fn) } }
{ // give a unique id to root instance so we can // 'namespace' its children if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') { instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID } rootInstances.push(instance) }
conditional_block
scan.ts
import { isBrowser, target } from '@vue-devtools/shared-utils' const rootInstances = [] let rootUID = 0 /** * Scan the page for root level Vue instances. */ export function scan () { rootInstances.length = 0 let inFragment = false let currentFragment = null // eslint-disable-next-line no-inner-declarations
function processInstance (instance) { if (instance) { if (rootInstances.indexOf(instance.$root) === -1) { instance = instance.$root } if (instance._isFragment) { inFragment = true currentFragment = instance } // respect Vue.config.devtools option let baseVue = instance.constructor while (baseVue.super) { baseVue = baseVue.super } if (baseVue.config && baseVue.config.devtools) { // give a unique id to root instance so we can // 'namespace' its children if (typeof instance.__VUE_DEVTOOLS_ROOT_UID__ === 'undefined') { instance.__VUE_DEVTOOLS_ROOT_UID__ = ++rootUID } rootInstances.push(instance) } return true } } if (isBrowser) { const walkDocument = document => { walk(document, function (node) { if (inFragment) { if (node === currentFragment._fragmentEnd) { inFragment = false currentFragment = null } return true } const instance = node.__vue__ return processInstance(instance) }) } walkDocument(document) const iframes = document.querySelectorAll<HTMLIFrameElement>('iframe') for (const iframe of iframes) { try { walkDocument(iframe.contentDocument) } catch (e) { // Ignore } } } else { if (Array.isArray(target.__VUE_ROOT_INSTANCES__)) { target.__VUE_ROOT_INSTANCES__.map(processInstance) } } return rootInstances } /** * DOM walk helper * * @param {NodeList} nodes * @param {Function} fn */ function walk (node, fn) { if (node.childNodes) { for (let i = 0, l = node.childNodes.length; i < l; i++) { const child = node.childNodes[i] const stop = fn(child) if (!stop) { walk(child, fn) } } } // also walk shadow DOM if (node.shadowRoot) { walk(node.shadowRoot, fn) } }
random_line_split
index.js
/* The MIT License (MIT) Copyright (c) 2015 Bryan Hughes <bryan@nebri.us> 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. */ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var fs_1 = require("fs"); var raspi_peripheral_1 = require("raspi-peripheral"); var hasLed = fs_1.existsSync('/sys/class/leds/led0') && fs_1.existsSync('/sys/class/leds/led0/trigger') && fs_1.existsSync('/sys/class/leds/led0/brightness'); exports.OFF = 0; exports.ON = 1; var LED = (function (_super) { __extends(LED, _super); function LED() { var _this = _super.call(this, []) || this; if (hasLed) { fs_1.writeFileSync('/sys/class/leds/led0/trigger', 'none'); } return _this; } LED.prototype.read = function () { if (hasLed) { return parseInt(fs_1.readFileSync('/sys/class/leds/led0/brightness').toString(), 10) ? exports.ON : exports.OFF; } return exports.OFF; }; LED.prototype.write = function (value) { this.validateAlive(); if ([exports.ON, exports.OFF].indexOf(value) === -1) { throw new Error("Invalid LED value " + value); } if (hasLed) { fs_1.writeFileSync('/sys/class/leds/led0/brightness', value ? '255' : '0'); } }; return LED; }(raspi_peripheral_1.Peripheral)); exports.LED = LED; //# sourceMappingURL=index.js.map
random_line_split
index.js
/* The MIT License (MIT) Copyright (c) 2015 Bryan Hughes <bryan@nebri.us> 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. */ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __()
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var fs_1 = require("fs"); var raspi_peripheral_1 = require("raspi-peripheral"); var hasLed = fs_1.existsSync('/sys/class/leds/led0') && fs_1.existsSync('/sys/class/leds/led0/trigger') && fs_1.existsSync('/sys/class/leds/led0/brightness'); exports.OFF = 0; exports.ON = 1; var LED = (function (_super) { __extends(LED, _super); function LED() { var _this = _super.call(this, []) || this; if (hasLed) { fs_1.writeFileSync('/sys/class/leds/led0/trigger', 'none'); } return _this; } LED.prototype.read = function () { if (hasLed) { return parseInt(fs_1.readFileSync('/sys/class/leds/led0/brightness').toString(), 10) ? exports.ON : exports.OFF; } return exports.OFF; }; LED.prototype.write = function (value) { this.validateAlive(); if ([exports.ON, exports.OFF].indexOf(value) === -1) { throw new Error("Invalid LED value " + value); } if (hasLed) { fs_1.writeFileSync('/sys/class/leds/led0/brightness', value ? '255' : '0'); } }; return LED; }(raspi_peripheral_1.Peripheral)); exports.LED = LED; //# sourceMappingURL=index.js.map
{ this.constructor = d; }
identifier_body
index.js
/* The MIT License (MIT) Copyright (c) 2015 Bryan Hughes <bryan@nebri.us> 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. */ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var fs_1 = require("fs"); var raspi_peripheral_1 = require("raspi-peripheral"); var hasLed = fs_1.existsSync('/sys/class/leds/led0') && fs_1.existsSync('/sys/class/leds/led0/trigger') && fs_1.existsSync('/sys/class/leds/led0/brightness'); exports.OFF = 0; exports.ON = 1; var LED = (function (_super) { __extends(LED, _super); function LED() { var _this = _super.call(this, []) || this; if (hasLed) { fs_1.writeFileSync('/sys/class/leds/led0/trigger', 'none'); } return _this; } LED.prototype.read = function () { if (hasLed) { return parseInt(fs_1.readFileSync('/sys/class/leds/led0/brightness').toString(), 10) ? exports.ON : exports.OFF; } return exports.OFF; }; LED.prototype.write = function (value) { this.validateAlive(); if ([exports.ON, exports.OFF].indexOf(value) === -1) { throw new Error("Invalid LED value " + value); } if (hasLed)
}; return LED; }(raspi_peripheral_1.Peripheral)); exports.LED = LED; //# sourceMappingURL=index.js.map
{ fs_1.writeFileSync('/sys/class/leds/led0/brightness', value ? '255' : '0'); }
conditional_block
index.js
/* The MIT License (MIT) Copyright (c) 2015 Bryan Hughes <bryan@nebri.us> 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. */ "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function
() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var fs_1 = require("fs"); var raspi_peripheral_1 = require("raspi-peripheral"); var hasLed = fs_1.existsSync('/sys/class/leds/led0') && fs_1.existsSync('/sys/class/leds/led0/trigger') && fs_1.existsSync('/sys/class/leds/led0/brightness'); exports.OFF = 0; exports.ON = 1; var LED = (function (_super) { __extends(LED, _super); function LED() { var _this = _super.call(this, []) || this; if (hasLed) { fs_1.writeFileSync('/sys/class/leds/led0/trigger', 'none'); } return _this; } LED.prototype.read = function () { if (hasLed) { return parseInt(fs_1.readFileSync('/sys/class/leds/led0/brightness').toString(), 10) ? exports.ON : exports.OFF; } return exports.OFF; }; LED.prototype.write = function (value) { this.validateAlive(); if ([exports.ON, exports.OFF].indexOf(value) === -1) { throw new Error("Invalid LED value " + value); } if (hasLed) { fs_1.writeFileSync('/sys/class/leds/led0/brightness', value ? '255' : '0'); } }; return LED; }(raspi_peripheral_1.Peripheral)); exports.LED = LED; //# sourceMappingURL=index.js.map
__
identifier_name
util.py
"""Contains utility methods used by and with the pyebnf package.""" import math def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False): """Escape-aware text splitting: Split text on on a delimiter, recognizing escaped delimiters.""" is_escaped = False split_count = 0 yval = [] for char in text: if is_escaped: is_escaped = False yval.append(char) else: if char == escape: is_escaped = True elif char in delimiter and split_count != maxsplit: if yval or not ignore_empty: yield "".join(yval) split_count += 1 yval = [] else: yval.append(char) yield "".join(yval) def esc_join(iterable, delimiter=" ", escape="\\"): """Join an iterable by a delimiter, replacing instances of delimiter in items with escape + delimiter. """ rep = escape + delimiter return delimiter.join(i.replace(delimiter, rep) for i in iterable) def get_newline_positions(text): """Returns a list of the positions in the text where all new lines occur. This is used by get_line_and_char to efficiently find coordinates represented by offset positions. """ pos = [] for i, c in enumerate(text): if c == "\n": pos.append(i) return pos def get_line_and_char(newline_positions, position): """Given a list of newline positions, and an offset from the start of the source code that newline_positions was pulled from, return a 2-tuple of (line, char) coordinates. """ if newline_positions: for line_no, nl_pos in enumerate(newline_positions): if nl_pos >= position: if line_no == 0: return (line_no, position) else: return (line_no, position - newline_positions[line_no - 1] - 1) return (line_no + 1, position - newline_positions[-1] - 1) else: return (0, position) def point_to_source(source, position, fmt=(2, True, "~~~~~", "^")):
"""Point to a position in source code. source is the text we're pointing in. position is a 2-tuple of (line_number, character_number) to point to. fmt is a 4-tuple of formatting parameters, they are: name default description ---- ------- ----------- surrounding_lines 2 the number of lines above and below the target line to print show_line_numbers True if true line numbers will be generated for the output_lines tail_body "~~~~~" the body of the tail pointer_char "^" the character that will point to the position """ surrounding_lines, show_line_numbers, tail_body, pointer_char = fmt line_no, char_no = position lines = source.split("\n") line = lines[line_no] if char_no >= len(tail_body): tail = " " * (char_no - len(tail_body)) + tail_body + pointer_char else: tail = " " * char_no + pointer_char + tail_body if show_line_numbers: line_no_width = int(math.ceil(math.log10(max(1, line_no + surrounding_lines))) + 1) line_fmt = "{0:" + str(line_no_width) + "}: {1}" else: line_fmt = "{1}" pivot = line_no + 1 output_lines = [(pivot, line), ("", tail)] for i in range(surrounding_lines): upper_ofst = i + 1 upper_idx = line_no + upper_ofst lower_ofst = -upper_ofst lower_idx = line_no + lower_ofst if lower_idx >= 0: output_lines.insert(0, (pivot + lower_ofst, lines[lower_idx])) if upper_idx < len(lines): output_lines.append((pivot + upper_ofst, lines[upper_idx])) return "\n".join(line_fmt.format(n, c) for n, c in output_lines)
identifier_body
util.py
"""Contains utility methods used by and with the pyebnf package.""" import math def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False): """Escape-aware text splitting: Split text on on a delimiter, recognizing escaped delimiters.""" is_escaped = False split_count = 0 yval = [] for char in text: if is_escaped: is_escaped = False yval.append(char) else: if char == escape: is_escaped = True elif char in delimiter and split_count != maxsplit: if yval or not ignore_empty: yield "".join(yval) split_count += 1 yval = [] else: yval.append(char) yield "".join(yval) def esc_join(iterable, delimiter=" ", escape="\\"): """Join an iterable by a delimiter, replacing instances of delimiter in items with escape + delimiter. """ rep = escape + delimiter return delimiter.join(i.replace(delimiter, rep) for i in iterable) def
(text): """Returns a list of the positions in the text where all new lines occur. This is used by get_line_and_char to efficiently find coordinates represented by offset positions. """ pos = [] for i, c in enumerate(text): if c == "\n": pos.append(i) return pos def get_line_and_char(newline_positions, position): """Given a list of newline positions, and an offset from the start of the source code that newline_positions was pulled from, return a 2-tuple of (line, char) coordinates. """ if newline_positions: for line_no, nl_pos in enumerate(newline_positions): if nl_pos >= position: if line_no == 0: return (line_no, position) else: return (line_no, position - newline_positions[line_no - 1] - 1) return (line_no + 1, position - newline_positions[-1] - 1) else: return (0, position) def point_to_source(source, position, fmt=(2, True, "~~~~~", "^")): """Point to a position in source code. source is the text we're pointing in. position is a 2-tuple of (line_number, character_number) to point to. fmt is a 4-tuple of formatting parameters, they are: name default description ---- ------- ----------- surrounding_lines 2 the number of lines above and below the target line to print show_line_numbers True if true line numbers will be generated for the output_lines tail_body "~~~~~" the body of the tail pointer_char "^" the character that will point to the position """ surrounding_lines, show_line_numbers, tail_body, pointer_char = fmt line_no, char_no = position lines = source.split("\n") line = lines[line_no] if char_no >= len(tail_body): tail = " " * (char_no - len(tail_body)) + tail_body + pointer_char else: tail = " " * char_no + pointer_char + tail_body if show_line_numbers: line_no_width = int(math.ceil(math.log10(max(1, line_no + surrounding_lines))) + 1) line_fmt = "{0:" + str(line_no_width) + "}: {1}" else: line_fmt = "{1}" pivot = line_no + 1 output_lines = [(pivot, line), ("", tail)] for i in range(surrounding_lines): upper_ofst = i + 1 upper_idx = line_no + upper_ofst lower_ofst = -upper_ofst lower_idx = line_no + lower_ofst if lower_idx >= 0: output_lines.insert(0, (pivot + lower_ofst, lines[lower_idx])) if upper_idx < len(lines): output_lines.append((pivot + upper_ofst, lines[upper_idx])) return "\n".join(line_fmt.format(n, c) for n, c in output_lines)
get_newline_positions
identifier_name
util.py
"""Contains utility methods used by and with the pyebnf package.""" import math def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False): """Escape-aware text splitting: Split text on on a delimiter, recognizing escaped delimiters.""" is_escaped = False split_count = 0 yval = [] for char in text: if is_escaped: is_escaped = False yval.append(char) else: if char == escape: is_escaped = True elif char in delimiter and split_count != maxsplit: if yval or not ignore_empty: yield "".join(yval) split_count += 1 yval = [] else: yval.append(char) yield "".join(yval) def esc_join(iterable, delimiter=" ", escape="\\"): """Join an iterable by a delimiter, replacing instances of delimiter in items with escape + delimiter. """ rep = escape + delimiter return delimiter.join(i.replace(delimiter, rep) for i in iterable) def get_newline_positions(text): """Returns a list of the positions in the text where all new lines occur. This is used by get_line_and_char to efficiently find coordinates represented by offset positions. """ pos = [] for i, c in enumerate(text): if c == "\n": pos.append(i)
return pos def get_line_and_char(newline_positions, position): """Given a list of newline positions, and an offset from the start of the source code that newline_positions was pulled from, return a 2-tuple of (line, char) coordinates. """ if newline_positions: for line_no, nl_pos in enumerate(newline_positions): if nl_pos >= position: if line_no == 0: return (line_no, position) else: return (line_no, position - newline_positions[line_no - 1] - 1) return (line_no + 1, position - newline_positions[-1] - 1) else: return (0, position) def point_to_source(source, position, fmt=(2, True, "~~~~~", "^")): """Point to a position in source code. source is the text we're pointing in. position is a 2-tuple of (line_number, character_number) to point to. fmt is a 4-tuple of formatting parameters, they are: name default description ---- ------- ----------- surrounding_lines 2 the number of lines above and below the target line to print show_line_numbers True if true line numbers will be generated for the output_lines tail_body "~~~~~" the body of the tail pointer_char "^" the character that will point to the position """ surrounding_lines, show_line_numbers, tail_body, pointer_char = fmt line_no, char_no = position lines = source.split("\n") line = lines[line_no] if char_no >= len(tail_body): tail = " " * (char_no - len(tail_body)) + tail_body + pointer_char else: tail = " " * char_no + pointer_char + tail_body if show_line_numbers: line_no_width = int(math.ceil(math.log10(max(1, line_no + surrounding_lines))) + 1) line_fmt = "{0:" + str(line_no_width) + "}: {1}" else: line_fmt = "{1}" pivot = line_no + 1 output_lines = [(pivot, line), ("", tail)] for i in range(surrounding_lines): upper_ofst = i + 1 upper_idx = line_no + upper_ofst lower_ofst = -upper_ofst lower_idx = line_no + lower_ofst if lower_idx >= 0: output_lines.insert(0, (pivot + lower_ofst, lines[lower_idx])) if upper_idx < len(lines): output_lines.append((pivot + upper_ofst, lines[upper_idx])) return "\n".join(line_fmt.format(n, c) for n, c in output_lines)
random_line_split
util.py
"""Contains utility methods used by and with the pyebnf package.""" import math def esc_split(text, delimiter=" ", maxsplit=-1, escape="\\", *, ignore_empty=False): """Escape-aware text splitting: Split text on on a delimiter, recognizing escaped delimiters.""" is_escaped = False split_count = 0 yval = [] for char in text: if is_escaped: is_escaped = False yval.append(char) else: if char == escape: is_escaped = True elif char in delimiter and split_count != maxsplit: if yval or not ignore_empty: yield "".join(yval) split_count += 1 yval = [] else:
yield "".join(yval) def esc_join(iterable, delimiter=" ", escape="\\"): """Join an iterable by a delimiter, replacing instances of delimiter in items with escape + delimiter. """ rep = escape + delimiter return delimiter.join(i.replace(delimiter, rep) for i in iterable) def get_newline_positions(text): """Returns a list of the positions in the text where all new lines occur. This is used by get_line_and_char to efficiently find coordinates represented by offset positions. """ pos = [] for i, c in enumerate(text): if c == "\n": pos.append(i) return pos def get_line_and_char(newline_positions, position): """Given a list of newline positions, and an offset from the start of the source code that newline_positions was pulled from, return a 2-tuple of (line, char) coordinates. """ if newline_positions: for line_no, nl_pos in enumerate(newline_positions): if nl_pos >= position: if line_no == 0: return (line_no, position) else: return (line_no, position - newline_positions[line_no - 1] - 1) return (line_no + 1, position - newline_positions[-1] - 1) else: return (0, position) def point_to_source(source, position, fmt=(2, True, "~~~~~", "^")): """Point to a position in source code. source is the text we're pointing in. position is a 2-tuple of (line_number, character_number) to point to. fmt is a 4-tuple of formatting parameters, they are: name default description ---- ------- ----------- surrounding_lines 2 the number of lines above and below the target line to print show_line_numbers True if true line numbers will be generated for the output_lines tail_body "~~~~~" the body of the tail pointer_char "^" the character that will point to the position """ surrounding_lines, show_line_numbers, tail_body, pointer_char = fmt line_no, char_no = position lines = source.split("\n") line = lines[line_no] if char_no >= len(tail_body): tail = " " * (char_no - len(tail_body)) + tail_body + pointer_char else: tail = " " * char_no + pointer_char + tail_body if show_line_numbers: line_no_width = int(math.ceil(math.log10(max(1, line_no + surrounding_lines))) + 1) line_fmt = "{0:" + str(line_no_width) + "}: {1}" else: line_fmt = "{1}" pivot = line_no + 1 output_lines = [(pivot, line), ("", tail)] for i in range(surrounding_lines): upper_ofst = i + 1 upper_idx = line_no + upper_ofst lower_ofst = -upper_ofst lower_idx = line_no + lower_ofst if lower_idx >= 0: output_lines.insert(0, (pivot + lower_ofst, lines[lower_idx])) if upper_idx < len(lines): output_lines.append((pivot + upper_ofst, lines[upper_idx])) return "\n".join(line_fmt.format(n, c) for n, c in output_lines)
yval.append(char)
conditional_block
SlackReader.spec.ts
import { API } from '@spinnaker/core'; import { ISlackChannel, SlackReader } from './SlackReader'; const mockSlackChannels: ISlackChannel[] = [ { id: '0-test', name: 'testchannel', is_channel: true, creator: 'creator', is_archived: false, name_normalized: 'testchannel', num_members: 25, }, { id: '1-test', name: 'fakechannel', is_channel: true, creator: 'creator2', is_archived: false, name_normalized: 'fakechannel', num_members: 25, }, ]; describe('SlackReader', () => { it('should fetch a list of public Slack channels', () => { spyOn(SlackReader, 'getChannels').and.callThrough(); spyOn(API, 'one') .and.callThrough() .and.returnValue({ getList: () => Promise.resolve(mockSlackChannels) }); SlackReader.getChannels().then((channels: ISlackChannel[]) => { expect(SlackReader.getChannels).toHaveBeenCalled(); expect(channels.length).toEqual(2);
expect(API.one).toHaveBeenCalledWith('slack/channels'); }); }); });
random_line_split
search_history_item.py
__author__ = 'bromix' from .directory_item import DirectoryItem from .. import constants class SearchHistoryItem(DirectoryItem): def
(self, context, query, image=None, fanart=None): if image is None: image = context.create_resource_path('media/search.png') pass DirectoryItem.__init__(self, query, context.create_uri([constants.paths.SEARCH, 'query'], {'q': query}), image=image) if fanart: self.set_fanart(fanart) pass else: self.set_fanart(context.get_fanart()) pass context_menu = [(context.localize(constants.localize.SEARCH_REMOVE), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'remove'], params={'q': query})), (context.localize(constants.localize.SEARCH_RENAME), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'rename'], params={'q': query})), (context.localize(constants.localize.SEARCH_CLEAR), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'clear']))] self.set_context_menu(context_menu) pass pass
__init__
identifier_name
search_history_item.py
__author__ = 'bromix' from .directory_item import DirectoryItem from .. import constants class SearchHistoryItem(DirectoryItem): def __init__(self, context, query, image=None, fanart=None): if image is None: image = context.create_resource_path('media/search.png') pass DirectoryItem.__init__(self, query, context.create_uri([constants.paths.SEARCH, 'query'], {'q': query}), image=image) if fanart: self.set_fanart(fanart) pass else: self.set_fanart(context.get_fanart()) pass
(context.localize(constants.localize.SEARCH_RENAME), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'rename'], params={'q': query})), (context.localize(constants.localize.SEARCH_CLEAR), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'clear']))] self.set_context_menu(context_menu) pass pass
context_menu = [(context.localize(constants.localize.SEARCH_REMOVE), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'remove'], params={'q': query})),
random_line_split
search_history_item.py
__author__ = 'bromix' from .directory_item import DirectoryItem from .. import constants class SearchHistoryItem(DirectoryItem): def __init__(self, context, query, image=None, fanart=None): if image is None:
DirectoryItem.__init__(self, query, context.create_uri([constants.paths.SEARCH, 'query'], {'q': query}), image=image) if fanart: self.set_fanart(fanart) pass else: self.set_fanart(context.get_fanart()) pass context_menu = [(context.localize(constants.localize.SEARCH_REMOVE), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'remove'], params={'q': query})), (context.localize(constants.localize.SEARCH_RENAME), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'rename'], params={'q': query})), (context.localize(constants.localize.SEARCH_CLEAR), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'clear']))] self.set_context_menu(context_menu) pass pass
image = context.create_resource_path('media/search.png') pass
conditional_block
search_history_item.py
__author__ = 'bromix' from .directory_item import DirectoryItem from .. import constants class SearchHistoryItem(DirectoryItem):
def __init__(self, context, query, image=None, fanart=None): if image is None: image = context.create_resource_path('media/search.png') pass DirectoryItem.__init__(self, query, context.create_uri([constants.paths.SEARCH, 'query'], {'q': query}), image=image) if fanart: self.set_fanart(fanart) pass else: self.set_fanart(context.get_fanart()) pass context_menu = [(context.localize(constants.localize.SEARCH_REMOVE), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'remove'], params={'q': query})), (context.localize(constants.localize.SEARCH_RENAME), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'rename'], params={'q': query})), (context.localize(constants.localize.SEARCH_CLEAR), 'RunPlugin(%s)' % context.create_uri([constants.paths.SEARCH, 'clear']))] self.set_context_menu(context_menu) pass pass
identifier_body
index.tsx
import React from 'react' import moment from 'moment' import { RouteComponentProps } from 'react-router-dom' import { DatePicker, Button, Form, Input } from 'antd' import { FormInstance } from 'antd/lib/form' import BaseContainer from 'ROOT_SOURCE/base/BaseContainer' import request from 'ROOT_SOURCE/utils/request' import Rules from 'ROOT_SOURCE/utils/validateRules' type IFormProps4Item = RouteComponentProps<{ id?: string }>
/** * 提交表单 */ submitForm = async (values: object) => { // 提交表单最好新起一个事务,不受其他事务影响 await this.sleep() // 提交请求 await request.post('/asset/updateAsset', values) // 提交后返回list页 this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`) } async componentDidMount() { let { data } = await request.get('/asset/viewAsset', { id: this.props.match.params.id /*itemId*/ }) if (this.formRef.current) { this.formRef.current.setFieldsValue({ ...data, contractDate: data.contractDate ? moment(data.contractDate) : undefined, }); } } render() { return ( <div className="ui-background"> <Form ref={this.formRef} onFinish={this.submitForm}> <Form.Item name='id' noStyle> <Input type='hidden' /> </Form.Item> <Form.Item name='assetName' label='资产方名称' rules={[{ required: true }]}> <Input disabled /> </Form.Item> <Form.Item name='contract' label='签约主体' rules={[{ required: true }]}> <Input disabled /> </Form.Item> <Form.Item name='contractDate' label='签约时间' rules={[{ required: true }]}> <DatePicker /> </Form.Item> <Form.Item name='contacts' label='联系人'> <Input /> </Form.Item> <Form.Item name='contactsPhone' label='联系电话' rules={[{ pattern: Rules.phone, message: '无效' }]}> <Input maxLength={11} /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> 提交 </Button> </Form.Item> <Form.Item> <Button type="primary" onClick={e => window.history.back()}> 取消/返回 </Button> </Form.Item> </Form> </div> ) } }
export default class extends BaseContainer<IFormProps4Item> { formRef = React.createRef<FormInstance>();
random_line_split
index.tsx
import React from 'react' import moment from 'moment' import { RouteComponentProps } from 'react-router-dom' import { DatePicker, Button, Form, Input } from 'antd' import { FormInstance } from 'antd/lib/form' import BaseContainer from 'ROOT_SOURCE/base/BaseContainer' import request from 'ROOT_SOURCE/utils/request' import Rules from 'ROOT_SOURCE/utils/validateRules' type IFormProps4Item = RouteComponentProps<{ id?: string }> export default class extends BaseContainer<IFormProps4Item> { formRef = React.createRef<FormInstance>(); /** * 提交表单 */ submitForm = async (values: object) => { // 提交表单最好新起一个事务,不受其他事务影响 await this.sleep() // 提交请求 await request.post('/asset/updateAsset', values) // 提交后返回list页 this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`) } async componentDidMount() { let { data } = await request.get('/asset/viewAsset', { id: this.props.match.params.id /*itemId*/ }) if (this.formRef.current) { this.formRef.current.setFieldsValue({ ...data, contractDate: data.contractDate ? moment(data.contractDate) : undefined, }); } } render() { return ( <div className="ui-background"
<Form ref={this.formRef} onFinish={this.submitForm}> <Form.Item name='id' noStyle> <Input type='hidden' /> </Form.Item> <Form.Item name='assetName' label='资产方名称' rules={[{ required: true }]}> <Input disabled /> </Form.Item> <Form.Item name='contract' label='签约主体' rules={[{ required: true }]}> <Input disabled /> </Form.Item> <Form.Item name='contractDate' label='签约时间' rules={[{ required: true }]}> <DatePicker /> </Form.Item> <Form.Item name='contacts' label='联系人'> <Input /> </Form.Item> <Form.Item name='contactsPhone' label='联系电话' rules={[{ pattern: Rules.phone, message: '无效' }]}> <Input maxLength={11} /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> 提交 </Button> </Form.Item> <Form.Item> <Button type="primary" onClick={e => window.history.back()}> 取消/返回 </Button> </Form.Item> </Form> </div> ) } }
>
identifier_name
index.tsx
import React from 'react' import moment from 'moment' import { RouteComponentProps } from 'react-router-dom' import { DatePicker, Button, Form, Input } from 'antd' import { FormInstance } from 'antd/lib/form' import BaseContainer from 'ROOT_SOURCE/base/BaseContainer' import request from 'ROOT_SOURCE/utils/request' import Rules from 'ROOT_SOURCE/utils/validateRules' type IFormProps4Item = RouteComponentProps<{ id?: string }> export default class extends BaseContainer<IFormProps4Item> { formRef = React.createRef<FormInstance>(); /** * 提交表单 */ submitForm = async (values: object) => { // 提交表单最好新起一个事务,不受其他事务影响 await this.sleep() // 提交请求 await request.post('/asset/updateAsset', values) // 提交后返回list页 this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`) } async componentDidMount() { let { data } = await request.get('/asset/viewAsset', { id: this.props.match.params.id /*itemId*/ }) if (this.formRef.current) { this.formRef.current.setFieldsValue({ ...data, contractDate: data.contractDate ? moment(data.contractDate) : undefined, }); } } render() { return ( <div className="ui-background">
<Form ref={this.formRef} onFinish={this.submitForm}> <Form.Item name='id' noStyle> <Input type='hidden' /> </Form.Item> <Form.Item name='assetName' label='资产方名称' rules={[{ required: true }]}> <Input disabled /> </Form.Item> <Form.Item name='contract' label='签约主体' rules={[{ required: true }]}> <Input disabled /> </Form.Item> <Form.Item name='contractDate' label='签约时间' rules={[{ required: true }]}> <DatePicker /> </Form.Item> <Form.Item name='contacts' label='联系人'> <Input /> </Form.Item> <Form.Item name='contactsPhone' label='联系电话' rules={[{ pattern: Rules.phone, message: '无效' }]}> <Input maxLength={11} /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> 提交 </Button> </Form.Item> <Form.Item> <Button type="primary" onClick={e => window.history.back()}> 取消/返回 </Button> </Form.Item> </Form> </div> ) } }
identifier_body
index.tsx
import React from 'react' import moment from 'moment' import { RouteComponentProps } from 'react-router-dom' import { DatePicker, Button, Form, Input } from 'antd' import { FormInstance } from 'antd/lib/form' import BaseContainer from 'ROOT_SOURCE/base/BaseContainer' import request from 'ROOT_SOURCE/utils/request' import Rules from 'ROOT_SOURCE/utils/validateRules' type IFormProps4Item = RouteComponentProps<{ id?: string }> export default class extends BaseContainer<IFormProps4Item> { formRef = React.createRef<FormInstance>(); /** * 提交表单 */ submitForm = async (values: object) => { // 提交表单最好新起一个事务,不受其他事务影响 await this.sleep() // 提交请求 await request.post('/asset/updateAsset', values) // 提交后返回list页 this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`) } async componentDidMount() { let { data } = await request.get('/asset/viewAsset', { id: this.props.match.params.id /*itemId*/ }) if (this.formRef.current) { this.formRef.current.setFieldsValue({ ..
i-background"> <Form ref={this.formRef} onFinish={this.submitForm}> <Form.Item name='id' noStyle> <Input type='hidden' /> </Form.Item> <Form.Item name='assetName' label='资产方名称' rules={[{ required: true }]}> <Input disabled /> </Form.Item> <Form.Item name='contract' label='签约主体' rules={[{ required: true }]}> <Input disabled /> </Form.Item> <Form.Item name='contractDate' label='签约时间' rules={[{ required: true }]}> <DatePicker /> </Form.Item> <Form.Item name='contacts' label='联系人'> <Input /> </Form.Item> <Form.Item name='contactsPhone' label='联系电话' rules={[{ pattern: Rules.phone, message: '无效' }]}> <Input maxLength={11} /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit"> 提交 </Button> </Form.Item> <Form.Item> <Button type="primary" onClick={e => window.history.back()}> 取消/返回 </Button> </Form.Item> </Form> </div> ) } }
.data, contractDate: data.contractDate ? moment(data.contractDate) : undefined, }); } } render() { return ( <div className="u
conditional_block
import_prescribing.py
""" Import prescribing data from CSV files into SQLite """ from collections import namedtuple import csv from itertools import groupby import logging import os import sqlite3 import gzip import heapq from matrixstore.matrix_ops import sparse_matrix, finalise_matrix from matrixstore.serializer import serialize_compressed from .common import get_prescribing_filename logger = logging.getLogger(__name__) MatrixRow = namedtuple("MatrixRow", "bnf_code items quantity actual_cost net_cost") class MissingHeaderError(Exception): pass def import_prescribing(filename): if not os.path.exists(filename): raise RuntimeError("No SQLite file at: {}".format(filename)) connection = sqlite3.connect(filename) # Trade crash-safety for insert speed connection.execute("PRAGMA synchronous=OFF") dates = [date for (date,) in connection.execute("SELECT date FROM date")] prescriptions = get_prescriptions_for_dates(dates) write_prescribing(connection, prescriptions) connection.commit() connection.close() def write_prescribing(connection, prescriptions): cursor = connection.cursor() # Map practice codes and date strings to their corresponding row/column # offset in the matrix practices = dict(cursor.execute("SELECT code, offset FROM practice")) dates = dict(cursor.execute("SELECT date, offset FROM date")) matrices = build_matrices(prescriptions, practices, dates) rows = format_as_sql_rows(matrices, connection) cursor.executemany( """ UPDATE presentation SET items=?, quantity=?, actual_cost=?, net_cost=? WHERE bnf_code=? """, rows, ) def get_prescriptions_for_dates(dates): """ Yield all prescribing data for the given dates as tuples of the form: bnf_code, practice_code, date, items, quantity, actual_cost, net_cost sorted by bnf_code, practice and date. """ dates = sorted(dates) filenames = [get_prescribing_filename(date) for date in dates] missing_files = [f for f in filenames if not os.path.exists(f)] if missing_files: raise RuntimeError( "Some required CSV files were missing:\n {}".format( "\n ".join(missing_files) ) ) prescribing_streams = [read_gzipped_prescribing_csv(f) for f in filenames] # We assume that the input files are already sorted by (bnf_code, practice, # month) so to ensure that the combined stream is sorted we just need to # merge them correctly, which heapq.merge handles nicely for us return heapq.merge(*prescribing_streams) def read_gzipped_prescribing_csv(filename): with gzip.open(filename, "rt") as f: for row in parse_prescribing_csv(f): yield row def parse_prescribing_csv(input_stream): """ Accepts a stream of CSV and yields prescribing data as tuples of the form: bnf_code, practice_code, date, items, quantity, actual_cost, net_cost """ reader = csv.reader(input_stream) headers = next(reader) try: bnf_code_col = headers.index("bnf_code") practice_col = headers.index("practice") date_col = headers.index("month") items_col = headers.index("items") quantity_col = headers.index("quantity") actual_cost_col = headers.index("actual_cost") net_cost_col = headers.index("net_cost") except ValueError as e: raise MissingHeaderError(str(e)) for row in reader: yield ( # These sometimes have trailing spaces in the CSV row[bnf_code_col].strip(), row[practice_col].strip(), # We only need the YYYY-MM-DD part of the date row[date_col][:10], int(row[items_col]), float(row[quantity_col]), pounds_to_pence(row[actual_cost_col]), pounds_to_pence(row[net_cost_col]), ) def pounds_to_pence(value): return int(round(float(value) * 100)) def
(prescriptions, practices, dates): """ Accepts an iterable of prescriptions plus mappings of pratice codes and date strings to their respective row/column offsets. Yields tuples of the form: bnf_code, items_matrix, quantity_matrix, actual_cost_matrix, net_cost_matrix Where the matrices contain the prescribed values for that presentation for every practice and date. """ max_row = max(practices.values()) max_col = max(dates.values()) shape = (max_row + 1, max_col + 1) grouped_by_bnf_code = groupby(prescriptions, lambda row: row[0]) for bnf_code, row_group in grouped_by_bnf_code: items_matrix = sparse_matrix(shape, integer=True) quantity_matrix = sparse_matrix(shape, integer=False) actual_cost_matrix = sparse_matrix(shape, integer=True) net_cost_matrix = sparse_matrix(shape, integer=True) for _, practice, date, items, quantity, actual_cost, net_cost in row_group: practice_offset = practices[practice] date_offset = dates[date] items_matrix[practice_offset, date_offset] = items quantity_matrix[practice_offset, date_offset] = quantity actual_cost_matrix[practice_offset, date_offset] = actual_cost net_cost_matrix[practice_offset, date_offset] = net_cost yield MatrixRow( bnf_code, finalise_matrix(items_matrix), finalise_matrix(quantity_matrix), finalise_matrix(actual_cost_matrix), finalise_matrix(net_cost_matrix), ) def format_as_sql_rows(matrices, connection): """ Given an iterable of MatrixRows (which contain a BNF code plus all prescribing data for that presentation) yield tuples of values ready for insertion into SQLite """ cursor = connection.cursor() num_presentations = next(cursor.execute("SELECT COUNT(*) FROM presentation"))[0] count = 0 for row in matrices: count += 1 # We make sure we have a row for every BNF code in the data, even ones # we didn't know about previously. This is a hack that we won't need # once we can use SQLite v3.24.0 which has proper UPSERT support. cursor.execute( "INSERT OR IGNORE INTO presentation (bnf_code) VALUES (?)", [row.bnf_code] ) if should_log_message(count): logger.info( "Writing data for %s (%s/%s)", row.bnf_code, count, num_presentations ) yield ( serialize_compressed(row.items), serialize_compressed(row.quantity), serialize_compressed(row.actual_cost), serialize_compressed(row.net_cost), row.bnf_code, ) logger.info("Finished writing data for %s presentations", count) def should_log_message(n): """ To avoid cluttering log output we don't log the insertion of every single presentation """ if n <= 10: return True if n == 100: return True return n % 200 == 0
build_matrices
identifier_name
import_prescribing.py
""" from collections import namedtuple import csv from itertools import groupby import logging import os import sqlite3 import gzip import heapq from matrixstore.matrix_ops import sparse_matrix, finalise_matrix from matrixstore.serializer import serialize_compressed from .common import get_prescribing_filename logger = logging.getLogger(__name__) MatrixRow = namedtuple("MatrixRow", "bnf_code items quantity actual_cost net_cost") class MissingHeaderError(Exception): pass def import_prescribing(filename): if not os.path.exists(filename): raise RuntimeError("No SQLite file at: {}".format(filename)) connection = sqlite3.connect(filename) # Trade crash-safety for insert speed connection.execute("PRAGMA synchronous=OFF") dates = [date for (date,) in connection.execute("SELECT date FROM date")] prescriptions = get_prescriptions_for_dates(dates) write_prescribing(connection, prescriptions) connection.commit() connection.close() def write_prescribing(connection, prescriptions): cursor = connection.cursor() # Map practice codes and date strings to their corresponding row/column # offset in the matrix practices = dict(cursor.execute("SELECT code, offset FROM practice")) dates = dict(cursor.execute("SELECT date, offset FROM date")) matrices = build_matrices(prescriptions, practices, dates) rows = format_as_sql_rows(matrices, connection) cursor.executemany( """ UPDATE presentation SET items=?, quantity=?, actual_cost=?, net_cost=? WHERE bnf_code=? """, rows, ) def get_prescriptions_for_dates(dates): """ Yield all prescribing data for the given dates as tuples of the form: bnf_code, practice_code, date, items, quantity, actual_cost, net_cost sorted by bnf_code, practice and date. """ dates = sorted(dates) filenames = [get_prescribing_filename(date) for date in dates] missing_files = [f for f in filenames if not os.path.exists(f)] if missing_files: raise RuntimeError( "Some required CSV files were missing:\n {}".format( "\n ".join(missing_files) ) ) prescribing_streams = [read_gzipped_prescribing_csv(f) for f in filenames] # We assume that the input files are already sorted by (bnf_code, practice, # month) so to ensure that the combined stream is sorted we just need to # merge them correctly, which heapq.merge handles nicely for us return heapq.merge(*prescribing_streams) def read_gzipped_prescribing_csv(filename): with gzip.open(filename, "rt") as f: for row in parse_prescribing_csv(f): yield row def parse_prescribing_csv(input_stream): """ Accepts a stream of CSV and yields prescribing data as tuples of the form: bnf_code, practice_code, date, items, quantity, actual_cost, net_cost """ reader = csv.reader(input_stream) headers = next(reader) try: bnf_code_col = headers.index("bnf_code") practice_col = headers.index("practice") date_col = headers.index("month") items_col = headers.index("items") quantity_col = headers.index("quantity") actual_cost_col = headers.index("actual_cost") net_cost_col = headers.index("net_cost") except ValueError as e: raise MissingHeaderError(str(e)) for row in reader: yield ( # These sometimes have trailing spaces in the CSV row[bnf_code_col].strip(), row[practice_col].strip(), # We only need the YYYY-MM-DD part of the date row[date_col][:10], int(row[items_col]), float(row[quantity_col]), pounds_to_pence(row[actual_cost_col]), pounds_to_pence(row[net_cost_col]), ) def pounds_to_pence(value): return int(round(float(value) * 100)) def build_matrices(prescriptions, practices, dates): """ Accepts an iterable of prescriptions plus mappings of pratice codes and date strings to their respective row/column offsets. Yields tuples of the form: bnf_code, items_matrix, quantity_matrix, actual_cost_matrix, net_cost_matrix Where the matrices contain the prescribed values for that presentation for every practice and date. """ max_row = max(practices.values()) max_col = max(dates.values()) shape = (max_row + 1, max_col + 1) grouped_by_bnf_code = groupby(prescriptions, lambda row: row[0]) for bnf_code, row_group in grouped_by_bnf_code: items_matrix = sparse_matrix(shape, integer=True) quantity_matrix = sparse_matrix(shape, integer=False) actual_cost_matrix = sparse_matrix(shape, integer=True) net_cost_matrix = sparse_matrix(shape, integer=True) for _, practice, date, items, quantity, actual_cost, net_cost in row_group: practice_offset = practices[practice] date_offset = dates[date] items_matrix[practice_offset, date_offset] = items quantity_matrix[practice_offset, date_offset] = quantity actual_cost_matrix[practice_offset, date_offset] = actual_cost net_cost_matrix[practice_offset, date_offset] = net_cost yield MatrixRow( bnf_code, finalise_matrix(items_matrix), finalise_matrix(quantity_matrix), finalise_matrix(actual_cost_matrix), finalise_matrix(net_cost_matrix), ) def format_as_sql_rows(matrices, connection): """ Given an iterable of MatrixRows (which contain a BNF code plus all prescribing data for that presentation) yield tuples of values ready for insertion into SQLite """ cursor = connection.cursor() num_presentations = next(cursor.execute("SELECT COUNT(*) FROM presentation"))[0] count = 0 for row in matrices: count += 1 # We make sure we have a row for every BNF code in the data, even ones # we didn't know about previously. This is a hack that we won't need # once we can use SQLite v3.24.0 which has proper UPSERT support. cursor.execute( "INSERT OR IGNORE INTO presentation (bnf_code) VALUES (?)", [row.bnf_code] ) if should_log_message(count): logger.info( "Writing data for %s (%s/%s)", row.bnf_code, count, num_presentations ) yield ( serialize_compressed(row.items), serialize_compressed(row.quantity), serialize_compressed(row.actual_cost), serialize_compressed(row.net_cost), row.bnf_code, ) logger.info("Finished writing data for %s presentations", count) def should_log_message(n): """ To avoid cluttering log output we don't log the insertion of every single presentation """ if n <= 10: return True if n == 100: return True return n % 200 == 0
""" Import prescribing data from CSV files into SQLite
random_line_split
import_prescribing.py
""" Import prescribing data from CSV files into SQLite """ from collections import namedtuple import csv from itertools import groupby import logging import os import sqlite3 import gzip import heapq from matrixstore.matrix_ops import sparse_matrix, finalise_matrix from matrixstore.serializer import serialize_compressed from .common import get_prescribing_filename logger = logging.getLogger(__name__) MatrixRow = namedtuple("MatrixRow", "bnf_code items quantity actual_cost net_cost") class MissingHeaderError(Exception): pass def import_prescribing(filename): if not os.path.exists(filename): raise RuntimeError("No SQLite file at: {}".format(filename)) connection = sqlite3.connect(filename) # Trade crash-safety for insert speed connection.execute("PRAGMA synchronous=OFF") dates = [date for (date,) in connection.execute("SELECT date FROM date")] prescriptions = get_prescriptions_for_dates(dates) write_prescribing(connection, prescriptions) connection.commit() connection.close() def write_prescribing(connection, prescriptions): cursor = connection.cursor() # Map practice codes and date strings to their corresponding row/column # offset in the matrix practices = dict(cursor.execute("SELECT code, offset FROM practice")) dates = dict(cursor.execute("SELECT date, offset FROM date")) matrices = build_matrices(prescriptions, practices, dates) rows = format_as_sql_rows(matrices, connection) cursor.executemany( """ UPDATE presentation SET items=?, quantity=?, actual_cost=?, net_cost=? WHERE bnf_code=? """, rows, ) def get_prescriptions_for_dates(dates): """ Yield all prescribing data for the given dates as tuples of the form: bnf_code, practice_code, date, items, quantity, actual_cost, net_cost sorted by bnf_code, practice and date. """ dates = sorted(dates) filenames = [get_prescribing_filename(date) for date in dates] missing_files = [f for f in filenames if not os.path.exists(f)] if missing_files: raise RuntimeError( "Some required CSV files were missing:\n {}".format( "\n ".join(missing_files) ) ) prescribing_streams = [read_gzipped_prescribing_csv(f) for f in filenames] # We assume that the input files are already sorted by (bnf_code, practice, # month) so to ensure that the combined stream is sorted we just need to # merge them correctly, which heapq.merge handles nicely for us return heapq.merge(*prescribing_streams) def read_gzipped_prescribing_csv(filename): with gzip.open(filename, "rt") as f: for row in parse_prescribing_csv(f): yield row def parse_prescribing_csv(input_stream): """ Accepts a stream of CSV and yields prescribing data as tuples of the form: bnf_code, practice_code, date, items, quantity, actual_cost, net_cost """ reader = csv.reader(input_stream) headers = next(reader) try: bnf_code_col = headers.index("bnf_code") practice_col = headers.index("practice") date_col = headers.index("month") items_col = headers.index("items") quantity_col = headers.index("quantity") actual_cost_col = headers.index("actual_cost") net_cost_col = headers.index("net_cost") except ValueError as e: raise MissingHeaderError(str(e)) for row in reader: yield ( # These sometimes have trailing spaces in the CSV row[bnf_code_col].strip(), row[practice_col].strip(), # We only need the YYYY-MM-DD part of the date row[date_col][:10], int(row[items_col]), float(row[quantity_col]), pounds_to_pence(row[actual_cost_col]), pounds_to_pence(row[net_cost_col]), ) def pounds_to_pence(value): return int(round(float(value) * 100)) def build_matrices(prescriptions, practices, dates): """ Accepts an iterable of prescriptions plus mappings of pratice codes and date strings to their respective row/column offsets. Yields tuples of the form: bnf_code, items_matrix, quantity_matrix, actual_cost_matrix, net_cost_matrix Where the matrices contain the prescribed values for that presentation for every practice and date. """ max_row = max(practices.values()) max_col = max(dates.values()) shape = (max_row + 1, max_col + 1) grouped_by_bnf_code = groupby(prescriptions, lambda row: row[0]) for bnf_code, row_group in grouped_by_bnf_code: items_matrix = sparse_matrix(shape, integer=True) quantity_matrix = sparse_matrix(shape, integer=False) actual_cost_matrix = sparse_matrix(shape, integer=True) net_cost_matrix = sparse_matrix(shape, integer=True) for _, practice, date, items, quantity, actual_cost, net_cost in row_group: practice_offset = practices[practice] date_offset = dates[date] items_matrix[practice_offset, date_offset] = items quantity_matrix[practice_offset, date_offset] = quantity actual_cost_matrix[practice_offset, date_offset] = actual_cost net_cost_matrix[practice_offset, date_offset] = net_cost yield MatrixRow( bnf_code, finalise_matrix(items_matrix), finalise_matrix(quantity_matrix), finalise_matrix(actual_cost_matrix), finalise_matrix(net_cost_matrix), ) def format_as_sql_rows(matrices, connection):
def should_log_message(n): """ To avoid cluttering log output we don't log the insertion of every single presentation """ if n <= 10: return True if n == 100: return True return n % 200 == 0
""" Given an iterable of MatrixRows (which contain a BNF code plus all prescribing data for that presentation) yield tuples of values ready for insertion into SQLite """ cursor = connection.cursor() num_presentations = next(cursor.execute("SELECT COUNT(*) FROM presentation"))[0] count = 0 for row in matrices: count += 1 # We make sure we have a row for every BNF code in the data, even ones # we didn't know about previously. This is a hack that we won't need # once we can use SQLite v3.24.0 which has proper UPSERT support. cursor.execute( "INSERT OR IGNORE INTO presentation (bnf_code) VALUES (?)", [row.bnf_code] ) if should_log_message(count): logger.info( "Writing data for %s (%s/%s)", row.bnf_code, count, num_presentations ) yield ( serialize_compressed(row.items), serialize_compressed(row.quantity), serialize_compressed(row.actual_cost), serialize_compressed(row.net_cost), row.bnf_code, ) logger.info("Finished writing data for %s presentations", count)
identifier_body
import_prescribing.py
""" Import prescribing data from CSV files into SQLite """ from collections import namedtuple import csv from itertools import groupby import logging import os import sqlite3 import gzip import heapq from matrixstore.matrix_ops import sparse_matrix, finalise_matrix from matrixstore.serializer import serialize_compressed from .common import get_prescribing_filename logger = logging.getLogger(__name__) MatrixRow = namedtuple("MatrixRow", "bnf_code items quantity actual_cost net_cost") class MissingHeaderError(Exception): pass def import_prescribing(filename): if not os.path.exists(filename): raise RuntimeError("No SQLite file at: {}".format(filename)) connection = sqlite3.connect(filename) # Trade crash-safety for insert speed connection.execute("PRAGMA synchronous=OFF") dates = [date for (date,) in connection.execute("SELECT date FROM date")] prescriptions = get_prescriptions_for_dates(dates) write_prescribing(connection, prescriptions) connection.commit() connection.close() def write_prescribing(connection, prescriptions): cursor = connection.cursor() # Map practice codes and date strings to their corresponding row/column # offset in the matrix practices = dict(cursor.execute("SELECT code, offset FROM practice")) dates = dict(cursor.execute("SELECT date, offset FROM date")) matrices = build_matrices(prescriptions, practices, dates) rows = format_as_sql_rows(matrices, connection) cursor.executemany( """ UPDATE presentation SET items=?, quantity=?, actual_cost=?, net_cost=? WHERE bnf_code=? """, rows, ) def get_prescriptions_for_dates(dates): """ Yield all prescribing data for the given dates as tuples of the form: bnf_code, practice_code, date, items, quantity, actual_cost, net_cost sorted by bnf_code, practice and date. """ dates = sorted(dates) filenames = [get_prescribing_filename(date) for date in dates] missing_files = [f for f in filenames if not os.path.exists(f)] if missing_files: raise RuntimeError( "Some required CSV files were missing:\n {}".format( "\n ".join(missing_files) ) ) prescribing_streams = [read_gzipped_prescribing_csv(f) for f in filenames] # We assume that the input files are already sorted by (bnf_code, practice, # month) so to ensure that the combined stream is sorted we just need to # merge them correctly, which heapq.merge handles nicely for us return heapq.merge(*prescribing_streams) def read_gzipped_prescribing_csv(filename): with gzip.open(filename, "rt") as f: for row in parse_prescribing_csv(f): yield row def parse_prescribing_csv(input_stream): """ Accepts a stream of CSV and yields prescribing data as tuples of the form: bnf_code, practice_code, date, items, quantity, actual_cost, net_cost """ reader = csv.reader(input_stream) headers = next(reader) try: bnf_code_col = headers.index("bnf_code") practice_col = headers.index("practice") date_col = headers.index("month") items_col = headers.index("items") quantity_col = headers.index("quantity") actual_cost_col = headers.index("actual_cost") net_cost_col = headers.index("net_cost") except ValueError as e: raise MissingHeaderError(str(e)) for row in reader: yield ( # These sometimes have trailing spaces in the CSV row[bnf_code_col].strip(), row[practice_col].strip(), # We only need the YYYY-MM-DD part of the date row[date_col][:10], int(row[items_col]), float(row[quantity_col]), pounds_to_pence(row[actual_cost_col]), pounds_to_pence(row[net_cost_col]), ) def pounds_to_pence(value): return int(round(float(value) * 100)) def build_matrices(prescriptions, practices, dates): """ Accepts an iterable of prescriptions plus mappings of pratice codes and date strings to their respective row/column offsets. Yields tuples of the form: bnf_code, items_matrix, quantity_matrix, actual_cost_matrix, net_cost_matrix Where the matrices contain the prescribed values for that presentation for every practice and date. """ max_row = max(practices.values()) max_col = max(dates.values()) shape = (max_row + 1, max_col + 1) grouped_by_bnf_code = groupby(prescriptions, lambda row: row[0]) for bnf_code, row_group in grouped_by_bnf_code: items_matrix = sparse_matrix(shape, integer=True) quantity_matrix = sparse_matrix(shape, integer=False) actual_cost_matrix = sparse_matrix(shape, integer=True) net_cost_matrix = sparse_matrix(shape, integer=True) for _, practice, date, items, quantity, actual_cost, net_cost in row_group:
yield MatrixRow( bnf_code, finalise_matrix(items_matrix), finalise_matrix(quantity_matrix), finalise_matrix(actual_cost_matrix), finalise_matrix(net_cost_matrix), ) def format_as_sql_rows(matrices, connection): """ Given an iterable of MatrixRows (which contain a BNF code plus all prescribing data for that presentation) yield tuples of values ready for insertion into SQLite """ cursor = connection.cursor() num_presentations = next(cursor.execute("SELECT COUNT(*) FROM presentation"))[0] count = 0 for row in matrices: count += 1 # We make sure we have a row for every BNF code in the data, even ones # we didn't know about previously. This is a hack that we won't need # once we can use SQLite v3.24.0 which has proper UPSERT support. cursor.execute( "INSERT OR IGNORE INTO presentation (bnf_code) VALUES (?)", [row.bnf_code] ) if should_log_message(count): logger.info( "Writing data for %s (%s/%s)", row.bnf_code, count, num_presentations ) yield ( serialize_compressed(row.items), serialize_compressed(row.quantity), serialize_compressed(row.actual_cost), serialize_compressed(row.net_cost), row.bnf_code, ) logger.info("Finished writing data for %s presentations", count) def should_log_message(n): """ To avoid cluttering log output we don't log the insertion of every single presentation """ if n <= 10: return True if n == 100: return True return n % 200 == 0
practice_offset = practices[practice] date_offset = dates[date] items_matrix[practice_offset, date_offset] = items quantity_matrix[practice_offset, date_offset] = quantity actual_cost_matrix[practice_offset, date_offset] = actual_cost net_cost_matrix[practice_offset, date_offset] = net_cost
conditional_block
emailMixin.js
var extend = require('extend'); var _ = require('lodash'); var async = require('async'); var nodemailer = require('nodemailer'); var nunjucks = require('nunjucks'); var urls = require('url'); /** * emailMixin * @augments Augments the apos object with a mixin method for attaching * a simple self.email method to modules, so that they can delivewr email * conveniently using templates rendered in the context of that module. * @see static */ module.exports = function(self) { // This mixin adds a self.email method to the specified module object. // // Your module must also have mixinModuleAssets. // // IF YOU ARE WRITING A SUBCLASS OF AN OBJECT THAT ALREADY HAS THIS MIXIN // // When subclassing you do NOT need to invoke this mixin as the methods // are already present on the base class object. // // HOW TO USE THE MIXIN // // If you are creating a new module from scratch that does not subclass another, // invoke the mixin this way in your constructor: // // `self._apos.mixinModuleEmail(self);` // // Then you may send email like this throughout your module: // // return self.email( // req, // person, // 'Your request to reset your password on {{ host }}', // 'resetRequestEmail', // { // url: self._action + '/reset?reset=' + reset // }, // function(err) { ... } // ); // // REQUEST OBJECT // // "req" is the request object and must be present. // // SENDER ("FROM") // // "from" is the full name and email address of the sender. You may // pass a string formatted like this: // // "Bob Smith <bob@example.com>" // // OR an object with "email" and "fullName" properties. "title" is also // accepted if "fullName" is not present. // // Note that req.user (when logged in) and any "person" object from // apostrophe-people are both acceptable as "from" arguments. // // You may omit the "from" argument and set it via configuration in // app.js instead as described below. // // If you omit it AND don't configure it, you'll get a terrible "from" address! // You have been warned! // // RECIPIENT // // "to" works just like "from". However, it is required and there are no // options for it in app.js. // // SUBJECT LINE // // The fourth argument is the subject line. It is rendered by nunjucks and can see // the data you pass in the sixth argument and other variables as described below. // // It is easy to override the subject in app.js as described below. // // TEMPLATE NAME // // The fifth argument is the template name. If it is "resetRequestEmail", then // self.email will look for the templates resetRequestEmail.txt and resetRequestEmail.html // in your module's views folder, render both of them, and build an email with both // plaintext and HTML parts for maximum compatibility. You can override these templates // at project level in lib/modules/modulename exactly as you would for any other template. // // DATA // // All properties passed as part of the sixth argument are passed to the templates // as nunjucks data. They are also available in the subject line. // // In addition, the following variables are automatically supplied: // // "host" is the hostname of the site, as determined from req. // // "baseUrl" is the base URL of the site, like: http://sitename.com // // ABSOLUTE URLS // // URLs in emails must be absolute, but most of the time in your code you use // relative URLs starting with /. As a convenience, self.email() will automatically // transform properties beginning with "url" or ending in "Url" into // absolute URLs before passing your data on to the templates. This rule is // applied recursively to the data object, so an array of events will all have // their .url properties made absolute. // // SENDING EMAIL IN TASKS // // The req object used in tasks will generate the correct absolute URLs // only if you add a "baseUrl" property to it, which should look like: // // http://mysite.com // // Note there is no slash after the hostname. // // CALLBACK // // The final argument is a standard node callback function and will receive // an error if any takes place. // // CONFIGURATION: EASY OVERRIDES IN APP.JS VIA THE "EMAIL" OPTION // // NOTE: FOR THESE FEATURES TO WORK, your module must set self._options or // self.options to the options object it was configured with. This happens // automatically for everything derived from apostrophe-snippets. // // When you configure your module, pass an object as the "email" option, with // sub-properties as described below. // // OVERRIDING THE SUBJECT // // The subject can be overridden in app.js when configuring your module. // If the template name (fifth argument) is "resetRequestEmail", then the // option "resetRequestEmailSubject" overrides the subject. // // OVERRIDING THE "FROM" ADDRESS // // It is easy to override the "from" address. If the "from" option is // a string or is absent, and the template name is "resetRequestEmail", then the // "resetRequestEmailFrom" option determines who the email comes from if // present. If there is no such option then the "from" option // determines who the email comes from. If this option is not set either // and the "from" argument was omitted, then the email comes from: // // 'Do Not Reply <donotreply@example.com>' // // But this is terrible, so make sure you set the appropriate options. // // In app.js you may set the from address to a string in this format: // "Bob Smith <donotreply@example.com>" // // Or use an object with fullName and email properties. // // PLEASE NOTE: if you pass an object as the "from" argument, configuration options are // always ignored in favor of what you passed. However if you pass a string it is // assumed to be a hard-coded default and options are allowed to override it. self.mixinModuleEmail = function(module) { module.email = function(req, from, to, subject, template, data, callback) { var moduleOptions = module._options || module.options || {}; var options = moduleOptions.email || {}; if (!callback) { // "from" may be omitted entirely, shift down one callback = data; data = template; template = subject; subject = to; to = from; from = undefined; } // Object passed for from always wins, string can be overridden if ((!from) || (typeof(from) === 'string')) { from = options[template + 'From'] || options['from'] || from || { fullName: 'Do Not Reply', email: 'donotreply@example.com' }; } var finalData = {}; // Allow middleware to supply baseUrl; if it's not there // use the sitewide option; if that's not there construct it // from what we do know about the request var baseUrl = req.baseUrl || self.options.baseUrl || (req.protocol + '://' + req.get('Host')); var parsed = urls.parse(baseUrl); var host = parsed.host; var protocol = parsed.protocol; // Easy subject override via app.js configuration subject = options[template + 'Subject'] || subject; // bc with a not-so-great templating syntax for subject lines that was // most likely only used once for %HOST% subject = subject.replace(/%HOST%/, '{{ host }}'); _.extend(finalData, data, true); self._mailMixinAbsoluteUrls(finalData, baseUrl); finalData.host = host; finalData.baseUrl = baseUrl; _.defaults(options, { // transport and transportOptions are ignored if options.mailer // has been passed when constructing the module, as apostrophe-site will // always do transport: 'sendmail', transportOptions: {} }); if (!module._mailer) { if (moduleOptions.mailer) { // This will always work with apostrophe-site module._mailer = moduleOptions.mailer; } else { // An alternative for those not using apostrophe-site module._mailer = nodemailer.createTransport(options.transport, options.transportOptions); } } var message = { from: fixAddress(from), to: fixAddress(to), subject: module.renderString(subject, finalData, req), text: module.render(template + '.txt', finalData, req), html: module.render(template + '.html', finalData, req) }; return module._mailer.sendMail(message, callback); }; function
(to) { if (typeof(to) === 'string') { return to; } return (to.fullName || to.title).replace(/[<\>]/g, '') + ' <' + to.email + '>'; } }; self._mailMixinAbsoluteUrls = function(data, baseUrl) { _.each(data, function(val, key) { if (typeof(val) === 'object') { self._mailMixinAbsoluteUrls(val, baseUrl); return; } if ((typeof(key) === 'string') && ((key === 'url') || (key.match(/Url$/)))) { if ((val.charAt(0) === '/') && baseUrl) { val = baseUrl + val; data[key] = val; } } }); }; };
fixAddress
identifier_name
emailMixin.js
var extend = require('extend'); var _ = require('lodash'); var async = require('async'); var nodemailer = require('nodemailer'); var nunjucks = require('nunjucks'); var urls = require('url'); /** * emailMixin * @augments Augments the apos object with a mixin method for attaching * a simple self.email method to modules, so that they can delivewr email * conveniently using templates rendered in the context of that module. * @see static */ module.exports = function(self) { // This mixin adds a self.email method to the specified module object. // // Your module must also have mixinModuleAssets. // // IF YOU ARE WRITING A SUBCLASS OF AN OBJECT THAT ALREADY HAS THIS MIXIN // // When subclassing you do NOT need to invoke this mixin as the methods // are already present on the base class object. // // HOW TO USE THE MIXIN // // If you are creating a new module from scratch that does not subclass another, // invoke the mixin this way in your constructor: // // `self._apos.mixinModuleEmail(self);` // // Then you may send email like this throughout your module: // // return self.email( // req, // person, // 'Your request to reset your password on {{ host }}', // 'resetRequestEmail', // { // url: self._action + '/reset?reset=' + reset // }, // function(err) { ... } // ); // // REQUEST OBJECT // // "req" is the request object and must be present. // // SENDER ("FROM") // // "from" is the full name and email address of the sender. You may // pass a string formatted like this: // // "Bob Smith <bob@example.com>" // // OR an object with "email" and "fullName" properties. "title" is also // accepted if "fullName" is not present. // // Note that req.user (when logged in) and any "person" object from // apostrophe-people are both acceptable as "from" arguments. // // You may omit the "from" argument and set it via configuration in // app.js instead as described below. // // If you omit it AND don't configure it, you'll get a terrible "from" address! // You have been warned! // // RECIPIENT // // "to" works just like "from". However, it is required and there are no // options for it in app.js. // // SUBJECT LINE // // The fourth argument is the subject line. It is rendered by nunjucks and can see // the data you pass in the sixth argument and other variables as described below. // // It is easy to override the subject in app.js as described below. // // TEMPLATE NAME // // The fifth argument is the template name. If it is "resetRequestEmail", then // self.email will look for the templates resetRequestEmail.txt and resetRequestEmail.html // in your module's views folder, render both of them, and build an email with both // plaintext and HTML parts for maximum compatibility. You can override these templates // at project level in lib/modules/modulename exactly as you would for any other template. // // DATA // // All properties passed as part of the sixth argument are passed to the templates // as nunjucks data. They are also available in the subject line. // // In addition, the following variables are automatically supplied: // // "host" is the hostname of the site, as determined from req. // // "baseUrl" is the base URL of the site, like: http://sitename.com // // ABSOLUTE URLS // // URLs in emails must be absolute, but most of the time in your code you use // relative URLs starting with /. As a convenience, self.email() will automatically // transform properties beginning with "url" or ending in "Url" into // absolute URLs before passing your data on to the templates. This rule is // applied recursively to the data object, so an array of events will all have // their .url properties made absolute. // // SENDING EMAIL IN TASKS // // The req object used in tasks will generate the correct absolute URLs // only if you add a "baseUrl" property to it, which should look like: // // http://mysite.com // // Note there is no slash after the hostname. // // CALLBACK // // The final argument is a standard node callback function and will receive // an error if any takes place. // // CONFIGURATION: EASY OVERRIDES IN APP.JS VIA THE "EMAIL" OPTION // // NOTE: FOR THESE FEATURES TO WORK, your module must set self._options or // self.options to the options object it was configured with. This happens // automatically for everything derived from apostrophe-snippets. // // When you configure your module, pass an object as the "email" option, with // sub-properties as described below. // // OVERRIDING THE SUBJECT // // The subject can be overridden in app.js when configuring your module. // If the template name (fifth argument) is "resetRequestEmail", then the // option "resetRequestEmailSubject" overrides the subject. // // OVERRIDING THE "FROM" ADDRESS // // It is easy to override the "from" address. If the "from" option is // a string or is absent, and the template name is "resetRequestEmail", then the // "resetRequestEmailFrom" option determines who the email comes from if // present. If there is no such option then the "from" option // determines who the email comes from. If this option is not set either // and the "from" argument was omitted, then the email comes from: // // 'Do Not Reply <donotreply@example.com>' // // But this is terrible, so make sure you set the appropriate options. // // In app.js you may set the from address to a string in this format: // "Bob Smith <donotreply@example.com>" //
// PLEASE NOTE: if you pass an object as the "from" argument, configuration options are // always ignored in favor of what you passed. However if you pass a string it is // assumed to be a hard-coded default and options are allowed to override it. self.mixinModuleEmail = function(module) { module.email = function(req, from, to, subject, template, data, callback) { var moduleOptions = module._options || module.options || {}; var options = moduleOptions.email || {}; if (!callback) { // "from" may be omitted entirely, shift down one callback = data; data = template; template = subject; subject = to; to = from; from = undefined; } // Object passed for from always wins, string can be overridden if ((!from) || (typeof(from) === 'string')) { from = options[template + 'From'] || options['from'] || from || { fullName: 'Do Not Reply', email: 'donotreply@example.com' }; } var finalData = {}; // Allow middleware to supply baseUrl; if it's not there // use the sitewide option; if that's not there construct it // from what we do know about the request var baseUrl = req.baseUrl || self.options.baseUrl || (req.protocol + '://' + req.get('Host')); var parsed = urls.parse(baseUrl); var host = parsed.host; var protocol = parsed.protocol; // Easy subject override via app.js configuration subject = options[template + 'Subject'] || subject; // bc with a not-so-great templating syntax for subject lines that was // most likely only used once for %HOST% subject = subject.replace(/%HOST%/, '{{ host }}'); _.extend(finalData, data, true); self._mailMixinAbsoluteUrls(finalData, baseUrl); finalData.host = host; finalData.baseUrl = baseUrl; _.defaults(options, { // transport and transportOptions are ignored if options.mailer // has been passed when constructing the module, as apostrophe-site will // always do transport: 'sendmail', transportOptions: {} }); if (!module._mailer) { if (moduleOptions.mailer) { // This will always work with apostrophe-site module._mailer = moduleOptions.mailer; } else { // An alternative for those not using apostrophe-site module._mailer = nodemailer.createTransport(options.transport, options.transportOptions); } } var message = { from: fixAddress(from), to: fixAddress(to), subject: module.renderString(subject, finalData, req), text: module.render(template + '.txt', finalData, req), html: module.render(template + '.html', finalData, req) }; return module._mailer.sendMail(message, callback); }; function fixAddress(to) { if (typeof(to) === 'string') { return to; } return (to.fullName || to.title).replace(/[<\>]/g, '') + ' <' + to.email + '>'; } }; self._mailMixinAbsoluteUrls = function(data, baseUrl) { _.each(data, function(val, key) { if (typeof(val) === 'object') { self._mailMixinAbsoluteUrls(val, baseUrl); return; } if ((typeof(key) === 'string') && ((key === 'url') || (key.match(/Url$/)))) { if ((val.charAt(0) === '/') && baseUrl) { val = baseUrl + val; data[key] = val; } } }); }; };
// Or use an object with fullName and email properties. //
random_line_split
emailMixin.js
var extend = require('extend'); var _ = require('lodash'); var async = require('async'); var nodemailer = require('nodemailer'); var nunjucks = require('nunjucks'); var urls = require('url'); /** * emailMixin * @augments Augments the apos object with a mixin method for attaching * a simple self.email method to modules, so that they can delivewr email * conveniently using templates rendered in the context of that module. * @see static */ module.exports = function(self) { // This mixin adds a self.email method to the specified module object. // // Your module must also have mixinModuleAssets. // // IF YOU ARE WRITING A SUBCLASS OF AN OBJECT THAT ALREADY HAS THIS MIXIN // // When subclassing you do NOT need to invoke this mixin as the methods // are already present on the base class object. // // HOW TO USE THE MIXIN // // If you are creating a new module from scratch that does not subclass another, // invoke the mixin this way in your constructor: // // `self._apos.mixinModuleEmail(self);` // // Then you may send email like this throughout your module: // // return self.email( // req, // person, // 'Your request to reset your password on {{ host }}', // 'resetRequestEmail', // { // url: self._action + '/reset?reset=' + reset // }, // function(err) { ... } // ); // // REQUEST OBJECT // // "req" is the request object and must be present. // // SENDER ("FROM") // // "from" is the full name and email address of the sender. You may // pass a string formatted like this: // // "Bob Smith <bob@example.com>" // // OR an object with "email" and "fullName" properties. "title" is also // accepted if "fullName" is not present. // // Note that req.user (when logged in) and any "person" object from // apostrophe-people are both acceptable as "from" arguments. // // You may omit the "from" argument and set it via configuration in // app.js instead as described below. // // If you omit it AND don't configure it, you'll get a terrible "from" address! // You have been warned! // // RECIPIENT // // "to" works just like "from". However, it is required and there are no // options for it in app.js. // // SUBJECT LINE // // The fourth argument is the subject line. It is rendered by nunjucks and can see // the data you pass in the sixth argument and other variables as described below. // // It is easy to override the subject in app.js as described below. // // TEMPLATE NAME // // The fifth argument is the template name. If it is "resetRequestEmail", then // self.email will look for the templates resetRequestEmail.txt and resetRequestEmail.html // in your module's views folder, render both of them, and build an email with both // plaintext and HTML parts for maximum compatibility. You can override these templates // at project level in lib/modules/modulename exactly as you would for any other template. // // DATA // // All properties passed as part of the sixth argument are passed to the templates // as nunjucks data. They are also available in the subject line. // // In addition, the following variables are automatically supplied: // // "host" is the hostname of the site, as determined from req. // // "baseUrl" is the base URL of the site, like: http://sitename.com // // ABSOLUTE URLS // // URLs in emails must be absolute, but most of the time in your code you use // relative URLs starting with /. As a convenience, self.email() will automatically // transform properties beginning with "url" or ending in "Url" into // absolute URLs before passing your data on to the templates. This rule is // applied recursively to the data object, so an array of events will all have // their .url properties made absolute. // // SENDING EMAIL IN TASKS // // The req object used in tasks will generate the correct absolute URLs // only if you add a "baseUrl" property to it, which should look like: // // http://mysite.com // // Note there is no slash after the hostname. // // CALLBACK // // The final argument is a standard node callback function and will receive // an error if any takes place. // // CONFIGURATION: EASY OVERRIDES IN APP.JS VIA THE "EMAIL" OPTION // // NOTE: FOR THESE FEATURES TO WORK, your module must set self._options or // self.options to the options object it was configured with. This happens // automatically for everything derived from apostrophe-snippets. // // When you configure your module, pass an object as the "email" option, with // sub-properties as described below. // // OVERRIDING THE SUBJECT // // The subject can be overridden in app.js when configuring your module. // If the template name (fifth argument) is "resetRequestEmail", then the // option "resetRequestEmailSubject" overrides the subject. // // OVERRIDING THE "FROM" ADDRESS // // It is easy to override the "from" address. If the "from" option is // a string or is absent, and the template name is "resetRequestEmail", then the // "resetRequestEmailFrom" option determines who the email comes from if // present. If there is no such option then the "from" option // determines who the email comes from. If this option is not set either // and the "from" argument was omitted, then the email comes from: // // 'Do Not Reply <donotreply@example.com>' // // But this is terrible, so make sure you set the appropriate options. // // In app.js you may set the from address to a string in this format: // "Bob Smith <donotreply@example.com>" // // Or use an object with fullName and email properties. // // PLEASE NOTE: if you pass an object as the "from" argument, configuration options are // always ignored in favor of what you passed. However if you pass a string it is // assumed to be a hard-coded default and options are allowed to override it. self.mixinModuleEmail = function(module) { module.email = function(req, from, to, subject, template, data, callback) { var moduleOptions = module._options || module.options || {}; var options = moduleOptions.email || {}; if (!callback) { // "from" may be omitted entirely, shift down one callback = data; data = template; template = subject; subject = to; to = from; from = undefined; } // Object passed for from always wins, string can be overridden if ((!from) || (typeof(from) === 'string')) { from = options[template + 'From'] || options['from'] || from || { fullName: 'Do Not Reply', email: 'donotreply@example.com' }; } var finalData = {}; // Allow middleware to supply baseUrl; if it's not there // use the sitewide option; if that's not there construct it // from what we do know about the request var baseUrl = req.baseUrl || self.options.baseUrl || (req.protocol + '://' + req.get('Host')); var parsed = urls.parse(baseUrl); var host = parsed.host; var protocol = parsed.protocol; // Easy subject override via app.js configuration subject = options[template + 'Subject'] || subject; // bc with a not-so-great templating syntax for subject lines that was // most likely only used once for %HOST% subject = subject.replace(/%HOST%/, '{{ host }}'); _.extend(finalData, data, true); self._mailMixinAbsoluteUrls(finalData, baseUrl); finalData.host = host; finalData.baseUrl = baseUrl; _.defaults(options, { // transport and transportOptions are ignored if options.mailer // has been passed when constructing the module, as apostrophe-site will // always do transport: 'sendmail', transportOptions: {} }); if (!module._mailer) { if (moduleOptions.mailer) { // This will always work with apostrophe-site module._mailer = moduleOptions.mailer; } else { // An alternative for those not using apostrophe-site module._mailer = nodemailer.createTransport(options.transport, options.transportOptions); } } var message = { from: fixAddress(from), to: fixAddress(to), subject: module.renderString(subject, finalData, req), text: module.render(template + '.txt', finalData, req), html: module.render(template + '.html', finalData, req) }; return module._mailer.sendMail(message, callback); }; function fixAddress(to)
}; self._mailMixinAbsoluteUrls = function(data, baseUrl) { _.each(data, function(val, key) { if (typeof(val) === 'object') { self._mailMixinAbsoluteUrls(val, baseUrl); return; } if ((typeof(key) === 'string') && ((key === 'url') || (key.match(/Url$/)))) { if ((val.charAt(0) === '/') && baseUrl) { val = baseUrl + val; data[key] = val; } } }); }; };
{ if (typeof(to) === 'string') { return to; } return (to.fullName || to.title).replace(/[<\>]/g, '') + ' <' + to.email + '>'; }
identifier_body
emailMixin.js
var extend = require('extend'); var _ = require('lodash'); var async = require('async'); var nodemailer = require('nodemailer'); var nunjucks = require('nunjucks'); var urls = require('url'); /** * emailMixin * @augments Augments the apos object with a mixin method for attaching * a simple self.email method to modules, so that they can delivewr email * conveniently using templates rendered in the context of that module. * @see static */ module.exports = function(self) { // This mixin adds a self.email method to the specified module object. // // Your module must also have mixinModuleAssets. // // IF YOU ARE WRITING A SUBCLASS OF AN OBJECT THAT ALREADY HAS THIS MIXIN // // When subclassing you do NOT need to invoke this mixin as the methods // are already present on the base class object. // // HOW TO USE THE MIXIN // // If you are creating a new module from scratch that does not subclass another, // invoke the mixin this way in your constructor: // // `self._apos.mixinModuleEmail(self);` // // Then you may send email like this throughout your module: // // return self.email( // req, // person, // 'Your request to reset your password on {{ host }}', // 'resetRequestEmail', // { // url: self._action + '/reset?reset=' + reset // }, // function(err) { ... } // ); // // REQUEST OBJECT // // "req" is the request object and must be present. // // SENDER ("FROM") // // "from" is the full name and email address of the sender. You may // pass a string formatted like this: // // "Bob Smith <bob@example.com>" // // OR an object with "email" and "fullName" properties. "title" is also // accepted if "fullName" is not present. // // Note that req.user (when logged in) and any "person" object from // apostrophe-people are both acceptable as "from" arguments. // // You may omit the "from" argument and set it via configuration in // app.js instead as described below. // // If you omit it AND don't configure it, you'll get a terrible "from" address! // You have been warned! // // RECIPIENT // // "to" works just like "from". However, it is required and there are no // options for it in app.js. // // SUBJECT LINE // // The fourth argument is the subject line. It is rendered by nunjucks and can see // the data you pass in the sixth argument and other variables as described below. // // It is easy to override the subject in app.js as described below. // // TEMPLATE NAME // // The fifth argument is the template name. If it is "resetRequestEmail", then // self.email will look for the templates resetRequestEmail.txt and resetRequestEmail.html // in your module's views folder, render both of them, and build an email with both // plaintext and HTML parts for maximum compatibility. You can override these templates // at project level in lib/modules/modulename exactly as you would for any other template. // // DATA // // All properties passed as part of the sixth argument are passed to the templates // as nunjucks data. They are also available in the subject line. // // In addition, the following variables are automatically supplied: // // "host" is the hostname of the site, as determined from req. // // "baseUrl" is the base URL of the site, like: http://sitename.com // // ABSOLUTE URLS // // URLs in emails must be absolute, but most of the time in your code you use // relative URLs starting with /. As a convenience, self.email() will automatically // transform properties beginning with "url" or ending in "Url" into // absolute URLs before passing your data on to the templates. This rule is // applied recursively to the data object, so an array of events will all have // their .url properties made absolute. // // SENDING EMAIL IN TASKS // // The req object used in tasks will generate the correct absolute URLs // only if you add a "baseUrl" property to it, which should look like: // // http://mysite.com // // Note there is no slash after the hostname. // // CALLBACK // // The final argument is a standard node callback function and will receive // an error if any takes place. // // CONFIGURATION: EASY OVERRIDES IN APP.JS VIA THE "EMAIL" OPTION // // NOTE: FOR THESE FEATURES TO WORK, your module must set self._options or // self.options to the options object it was configured with. This happens // automatically for everything derived from apostrophe-snippets. // // When you configure your module, pass an object as the "email" option, with // sub-properties as described below. // // OVERRIDING THE SUBJECT // // The subject can be overridden in app.js when configuring your module. // If the template name (fifth argument) is "resetRequestEmail", then the // option "resetRequestEmailSubject" overrides the subject. // // OVERRIDING THE "FROM" ADDRESS // // It is easy to override the "from" address. If the "from" option is // a string or is absent, and the template name is "resetRequestEmail", then the // "resetRequestEmailFrom" option determines who the email comes from if // present. If there is no such option then the "from" option // determines who the email comes from. If this option is not set either // and the "from" argument was omitted, then the email comes from: // // 'Do Not Reply <donotreply@example.com>' // // But this is terrible, so make sure you set the appropriate options. // // In app.js you may set the from address to a string in this format: // "Bob Smith <donotreply@example.com>" // // Or use an object with fullName and email properties. // // PLEASE NOTE: if you pass an object as the "from" argument, configuration options are // always ignored in favor of what you passed. However if you pass a string it is // assumed to be a hard-coded default and options are allowed to override it. self.mixinModuleEmail = function(module) { module.email = function(req, from, to, subject, template, data, callback) { var moduleOptions = module._options || module.options || {}; var options = moduleOptions.email || {}; if (!callback) { // "from" may be omitted entirely, shift down one callback = data; data = template; template = subject; subject = to; to = from; from = undefined; } // Object passed for from always wins, string can be overridden if ((!from) || (typeof(from) === 'string')) { from = options[template + 'From'] || options['from'] || from || { fullName: 'Do Not Reply', email: 'donotreply@example.com' }; } var finalData = {}; // Allow middleware to supply baseUrl; if it's not there // use the sitewide option; if that's not there construct it // from what we do know about the request var baseUrl = req.baseUrl || self.options.baseUrl || (req.protocol + '://' + req.get('Host')); var parsed = urls.parse(baseUrl); var host = parsed.host; var protocol = parsed.protocol; // Easy subject override via app.js configuration subject = options[template + 'Subject'] || subject; // bc with a not-so-great templating syntax for subject lines that was // most likely only used once for %HOST% subject = subject.replace(/%HOST%/, '{{ host }}'); _.extend(finalData, data, true); self._mailMixinAbsoluteUrls(finalData, baseUrl); finalData.host = host; finalData.baseUrl = baseUrl; _.defaults(options, { // transport and transportOptions are ignored if options.mailer // has been passed when constructing the module, as apostrophe-site will // always do transport: 'sendmail', transportOptions: {} }); if (!module._mailer) { if (moduleOptions.mailer)
else { // An alternative for those not using apostrophe-site module._mailer = nodemailer.createTransport(options.transport, options.transportOptions); } } var message = { from: fixAddress(from), to: fixAddress(to), subject: module.renderString(subject, finalData, req), text: module.render(template + '.txt', finalData, req), html: module.render(template + '.html', finalData, req) }; return module._mailer.sendMail(message, callback); }; function fixAddress(to) { if (typeof(to) === 'string') { return to; } return (to.fullName || to.title).replace(/[<\>]/g, '') + ' <' + to.email + '>'; } }; self._mailMixinAbsoluteUrls = function(data, baseUrl) { _.each(data, function(val, key) { if (typeof(val) === 'object') { self._mailMixinAbsoluteUrls(val, baseUrl); return; } if ((typeof(key) === 'string') && ((key === 'url') || (key.match(/Url$/)))) { if ((val.charAt(0) === '/') && baseUrl) { val = baseUrl + val; data[key] = val; } } }); }; };
{ // This will always work with apostrophe-site module._mailer = moduleOptions.mailer; }
conditional_block
setup_wizard.py
################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor is distributed in the hope that it will be ### useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### ### You should have received a copy of the GNU General Public License ### along with the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ from PyQt4 import QtGui, QtCore, Qt from PyQt4.QtGui import QFileDialog, QProgressDialog from ui_wizard import Ui_SetupWizard import base64 import cStringIO import glob import os import shutil import sys import threading import zipfile from bitstring import ConstBitStream, BitStream import common from dialog_fns import get_save_file, get_open_file, get_existing_dir from eboot_patch import apply_eboot_patches from extract import extract_umdimage, extract_pak from extract.eboot import UMDIMAGES from font_parser import font_bmp_to_alpha from gim_converter import GimConverter from gmo_file import GmoFile UMDIMAGE_DAT = os.path.join("PSP_GAME", "USRDIR", "umdimage.dat") UMDIMAGE2_DAT = os.path.join("PSP_GAME", "USRDIR", "umdimage2.dat") VOICE_PAK = os.path.join("PSP_GAME", "USRDIR", "voice.pak") UMDIMAGE_DIR = "umdimage" UMDIMAGE2_DIR = "umdimage2" VOICE_DIR = "voice" CHANGES_DIR = "!changes" BACKUP_DIR = "!backup" EDITED_ISO_DIR = "!ISO_EDITED" EDITED_ISO_FILE = "[PSP] DRBest [Edited].iso" EDITOR_DATA_DIR = "!editor" DUPES_CSV = "dupes.csv" EBOOT_TEXT = "eboot_text.csv" SIMILARITY_DB = "similarity-db.sql" THREAD_TIMEOUT = 0.1 class SetupWizard(QtGui.QDialog): def __init__(self, parent=None): super(SetupWizard, self).__init__(parent) self.ui = Ui_SetupWizard() self.ui.setupUi(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.iso_dir = None self.workspace_dir = None self.eboot_path = None self.terminology_path = None # Don't really feel like doing all this in Designer. self.connect(self.ui.btnIsoBrowse, QtCore.SIGNAL("clicked()"), self.get_iso) self.connect(self.ui.btnIsoOK, QtCore.SIGNAL("clicked()"), self.check_iso) self.connect(self.ui.btnWorkspaceBrowse, QtCore.SIGNAL("clicked()"), self.get_workspace) self.connect(self.ui.btnWorkspaceOK, QtCore.SIGNAL("clicked()"), self.check_workspace) self.connect(self.ui.btnEbootOK, QtCore.SIGNAL("clicked()"), self.check_eboot) self.connect(self.ui.btnSetupWorkspace, QtCore.SIGNAL("clicked()"), self.setup_workspace) self.connect(self.ui.btnWorkspaceSkip, QtCore.SIGNAL("clicked()"), self.skip_setup) self.connect(self.ui.btnCopyGfx, QtCore.SIGNAL("clicked()"), self.copy_gfx) self.connect(self.ui.btnTerminologyNew, QtCore.SIGNAL("clicked()"), self.create_terminology) self.connect(self.ui.btnTerminologyBrowse, QtCore.SIGNAL("clicked()"), self.get_terminology) self.connect(self.ui.btnTerminologyOK, QtCore.SIGNAL("clicked()"), self.check_terminology) def show_error(self, message): QtGui.QMessageBox.critical(self, "Error", message) def show_info(self, message): QtGui.QMessageBox.information(self, "Info", message) ############################################################################## ### STEP 1 ############################################################################## def get_iso(self): dir = get_existing_dir(self, self.ui.txtIso.text()) if not dir == "": self.ui.txtIso.setText(dir) def check_iso(self): iso_dir = common.qt_to_unicode(self.ui.txtIso.text(), normalize = False) if not os.path.isdir(iso_dir): self.show_error("ISO directory does not exist.") return validated = True with open("data/file_order.txt", "rb") as file_order: # Since we're reappropriating this from the file used by mkisofs, # we need to do a little bit of work on it to be useful here. # Split it up on the tab, take the first entry, and chop the slash # off the beginning so we can use it in os.path.join file_list = [line.split('\t')[0][1:] for line in file_order.readlines() if not line == ""] for filename in file_list: full_name = os.path.join(iso_dir, filename) if not os.path.isfile(full_name): validated = False self.show_error("%s missing from ISO directory." % full_name) break if not validated: return self.iso_dir = iso_dir self.show_info("ISO directory looks good.") self.ui.grpStep1.setEnabled(False) self.ui.grpStep2.setEnabled(True) ############################################################################## ### STEP 2 ############################################################################## def get_workspace(self): dir = get_existing_dir(self, self.ui.txtWorkspace.text()) if not dir == "": self.ui.txtWorkspace.setText(dir) def check_workspace(self): workspace_dir = common.qt_to_unicode(self.ui.txtWorkspace.text(), normalize = False) if not os.path.isdir(workspace_dir): try: os.makedirs(workspace_dir) self.show_info("Workspace directory created.") except: self.show_error("Error creating workspace directory.") return else: self.show_info("Workspace directory already exists.\n\nExisting data will be overwritten.") self.workspace_dir = workspace_dir self.ui.grpStep2.setEnabled(False) self.ui.grpStep3.setEnabled(True) ############################################################################## ### STEP 3 ############################################################################## def check_eboot(self): eboot_path = os.path.join(self.workspace_dir, "EBOOT.BIN") if not os.path.isfile(eboot_path): self.show_error("EBOOT.BIN not found in workspace directory.") return eboot = ConstBitStream(filename = eboot_path) if not eboot[:32] == ConstBitStream(hex = "0x7F454C46"): self.show_error("EBOOT.BIN is encrypted.") return self.eboot_path = eboot_path self.show_info("EBOOT.BIN looks good.") self.ui.grpStep3.setEnabled(False) self.ui.grpStep4.setEnabled(True) ############################################################################## ### STEP 4 ############################################################################## def generate_directories(self): self.umdimage_dir = os.path.join(self.workspace_dir, UMDIMAGE_DIR) self.umdimage2_dir = os.path.join(self.workspace_dir, UMDIMAGE2_DIR) self.voice_dir = os.path.join(self.workspace_dir, VOICE_DIR) self.changes_dir = os.path.join(self.workspace_dir, CHANGES_DIR) self.backup_dir = os.path.join(self.workspace_dir, BACKUP_DIR) self.edited_iso_dir = os.path.join(self.workspace_dir, EDITED_ISO_DIR) self.editor_data_dir = os.path.join(self.workspace_dir, EDITOR_DATA_DIR) def skip_setup(self): answer = QtGui.QMessageBox.warning( self, "Skip Setup", "Are you sure you want to skip setting up your workspace?\n\nYou should only do this if you already have a workspace generated by the setup wizard.", buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, defaultButton = QtGui.QMessageBox.No ) if answer == QtGui.QMessageBox.No: return self.generate_directories() self.ui.grpStep4.setEnabled(False) self.ui.grpStep5.setEnabled(True) def setup_workspace(self): umdimage = os.path.join(self.iso_dir, UMDIMAGE_DAT) umdimage2 = os.path.join(self.iso_dir, UMDIMAGE2_DAT) voice = os.path.join(self.iso_dir, VOICE_PAK) self.generate_directories() progress = QProgressDialog("", QtCore.QString(), 0, 11000, self) progress.setWindowTitle("Setting up workspace...") progress.setWindowModality(Qt.Qt.WindowModal) progress.setMinimumDuration(0) progress.setValue(0) progress.setAutoClose(False) progress.setAutoReset(False) progress.setLabelText("Creating directories...") # Do the easy stuff first. if not os.path.isdir(self.changes_dir): os.makedirs(self.changes_dir) progress.setValue(progress.value() + 1) if not os.path.isdir(self.backup_dir): os.makedirs(self.backup_dir) progress.setValue(progress.value() + 1) if not os.path.isdir(self.editor_data_dir): os.makedirs(self.editor_data_dir) progress.setValue(progress.value() + 1) thread_fns = [ {"target": extract_umdimage, "kwargs": {"filename": umdimage, "out_dir": self.umdimage_dir, "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage}}, {"target": extract_umdimage, "kwargs": {"filename": umdimage2, "out_dir": self.umdimage2_dir, "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage2}}, {"target": extract_pak, "kwargs": {"filename": voice, "out_dir": self.voice_dir}}, ] # Going to capture stdout because I don't feel like # rewriting the extract functions to play nice with GUI. stdout = sys.stdout sys.stdout = cStringIO.StringIO() for thread_fn in thread_fns: thread = threading.Thread(**thread_fn) thread.start() while thread.isAlive(): thread.join(THREAD_TIMEOUT) output = [line for line in sys.stdout.getvalue().split('\n') if len(line) > 0] progress.setValue(progress.value() + len(output)) if len(output) > 0: progress.setLabelText("Extracting %s..." % output[-1]) sys.stdout = cStringIO.StringIO() sys.stdout = stdout # Give us an ISO directory for the editor to place modified files in. progress.setLabelText("Copying ISO files...") # ISO directory needs to not exist for copytree. if os.path.isdir(self.edited_iso_dir): shutil.rmtree(self.edited_iso_dir) # One more thing we want threaded so it doesn't lock up the GUI. thread = threading.Thread(target = shutil.copytree, kwargs = {"src": self.iso_dir, "dst": self.edited_iso_dir}) thread.start() while thread.isAlive(): thread.join(THREAD_TIMEOUT) progress.setLabelText("Copying ISO files...") # It has to increase by some amount or it won't update and the UI will lock up. progress.setValue(progress.value() + 1) # shutil.copytree(self.iso_dir, self.edited_iso_dir) progress.setValue(progress.value() + 1) # Files we want to make blank, because they're unnecessary. blank_files = [ os.path.join(self.edited_iso_dir, "PSP_GAME", "INSDIR", "UMDIMAGE.DAT"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "DATA.BIN"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "EBOOT.BIN"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "PARAM.SFO"), ] for blank in blank_files: with open(blank, "wb") as f: pass # Copy the decrypted EBOOT into the ISO folder and apply our hacks to it. progress.setLabelText("Hacking EBOOT...") progress.setValue(progress.value() + 1) hacked_eboot = BitStream(filename = self.eboot_path) hacked_eboot, offset = apply_eboot_patches(hacked_eboot) with open(os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"), "wb") as f: hacked_eboot.tofile(f) # shutil.copy(self.eboot_path, os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN")) progress.setLabelText("Extracting editor data...") progress.setValue(progress.value() + 1) # Extract the editor data. editor_data = zipfile.ZipFile("data/editor_data.zip", "r") editor_data.extractall(self.editor_data_dir) editor_data.close() progress.setValue(progress.maximum()) progress.close() self.ui.grpStep4.setEnabled(False) self.ui.grpStep5.setEnabled(True) ############################################################################## ### STEP 5 ############################################################################## def copy_gfx(self): gfx_dir = os.path.join(self.editor_data_dir, "gfx") if os.path.isdir(gfx_dir): shutil.rmtree(gfx_dir) os.makedirs(gfx_dir) progress = QProgressDialog("", "Abort", 0, 0, self) progress.setWindowTitle("Copying GFX...") progress.setWindowModality(Qt.Qt.WindowModal) progress.setMinimumDuration(0) progress.setValue(0) progress.setAutoClose(False) progress.setLabelText("Setting up GFX dir.") progress.setMaximum(5) progress.setValue(0) # Extract the images we can't just take directly from the game's data. gfx_bin = zipfile.ZipFile("data/gfx_base.bin", "r") progress.setValue(1) gfx_enc = gfx_bin.open("gfx_base.bin") progress.setValue(2) gfx_dec = cStringIO.StringIO() base64.decode(gfx_enc, gfx_dec) progress.setValue(3) gfx_base = zipfile.ZipFile(gfx_dec, "r") progress.setValue(4) gfx_base.extractall(gfx_dir) progress.setValue(5) gfx_base.close() gfx_dec.close() gfx_enc.close() gfx_bin.close() # We can mostly loop this. gfx_data = [ ("ammo", "kotodama_icn_???.gim"), ("bgd", "bgd_???.gim"), ("cutin", "cutin_icn_???.gim"), ("events", "gallery_icn_???.gim"), ("movies", "bin_movie_gallery_l.pak/0000/000[1789].gim"), ("movies", "bin_movie_gallery_l.pak/0000/00[123]?.gim"), ("nametags", "tex_system.pak/00[12]?.gim"), ("nametags", "tex_system.pak/003[0123456].gim"), ("presents", "present_icn_???.gim"), ("sprites", "bustup_??_??.gim"), ("sprites", "stand_??_??.gmo"), ] for (dir, file_glob) in gfx_data: out_dir = os.path.join(gfx_dir, dir) files = glob.glob(os.path.join(self.umdimage_dir, file_glob)) progress.setLabelText("Copying %s." % dir) progress.setMaximum(len(files)) progress.setValue(0) if not os.path.isdir(out_dir): os.makedirs(out_dir) for i, image in enumerate(files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return src = image dest = os.path.join(out_dir, os.path.basename(src)) shutil.copy(src, dest) progress.setValue(len(files)) progress.setLabelText("Copying font.") progress.setMaximum(4) progress.setValue(0) # The font we have to get from umdimage2. font_dir = os.path.join(gfx_dir, "font") if not os.path.isdir(font_dir): os.makedirs(font_dir) progress.setValue(1) # And convert to PNG with an alpha channel so our editor can use it. font1 = font_bmp_to_alpha(os.path.join(self.umdimage2_dir, "font.pak", "0000.bmp")) progress.setValue(2) font2 = font_bmp_to_alpha(os.path.join(self.umdimage2_dir, "font.pak", "0002.bmp")) progress.setValue(3) font1.save(os.path.join(font_dir, "Font01.png")) font2.save(os.path.join(font_dir, "Font02.png")) shutil.copy(os.path.join(self.umdimage2_dir, "font.pak", "0001.font"), os.path.join(font_dir, "Font01.font")) shutil.copy(os.path.join(self.umdimage2_dir, "font.pak", "0003.font"), os.path.join(font_dir, "Font02.font")) progress.setValue(4) # And then the flash files. This'll be fun. flash_dir = os.path.join(gfx_dir, "flash") if not os.path.isdir(flash_dir): os.makedirs(flash_dir) # Because there's so many in so many different places, I just stored a list # of the flash files we need in the gfx_base archive. So let's load that. with open(os.path.join(gfx_dir, "fla.txt"), "rb") as fla: fla_list = fla.readlines() progress.setLabelText("Copying flash.") progress.setMaximum(len(fla_list)) progress.setValue(0) for i, flash in enumerate(fla_list): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return flash = flash.strip() fla_name = flash[:7] # fla_### src = os.path.join(self.umdimage_dir, flash) dest = os.path.join(flash_dir, "%s.gim" % fla_name) shutil.copy(src, dest) progress.setValue(len(fla_list)) # We have a couple sets of files that aren't named the way we want them to # be, just because of how they're stored in umdimage. progress.setLabelText("Renaming files.") to_rename = [ ("movies", "movie_%03d.gim", range(32)), ("nametags", "%02d.gim", range(23) + [24, 25, 30, 31]), ] for (folder, pattern, nums) in to_rename: folder = os.path.join(gfx_dir, folder) files = glob.glob(os.path.join(folder, "*.gim")) progress.setMaximum(len(files)) progress.setValue(0) for i, image in enumerate(files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return src = image dest = os.path.join(folder, pattern % nums[i]) if os.path.isfile(dest): os.remove(dest) shutil.move(src, dest) sprite_dir = os.path.join(gfx_dir, "sprites") gmo_files = glob.glob(os.path.join(sprite_dir, "*.gmo")) progress.setLabelText("Extracting GMO files.") progress.setValue(0) progress.setMaximum(len(gmo_files)) for i, gmo_file in enumerate(gmo_files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return name, ext = os.path.splitext(os.path.basename(gmo_file)) gim_file = os.path.join(sprite_dir, name + ".gim") gmo = GmoFile(filename = gmo_file) # Once we've loaded it, we're all done with it, so make it go away. os.remove(gmo_file) if gmo.gim_count() == 0: continue gim = gmo.get_gim(0) with open(gim_file, "wb") as f: gim.tofile(f) if self.ui.chkGimToPng.isChecked(): gim_files = glob.glob(os.path.join(gfx_dir, "*", "*.gim")) progress.setLabelText("Converting GIM to PNG.") progress.setValue(0) progress.setMaximum(len(gim_files)) converter = GimConverter() for i, gim_file in enumerate(gim_files): progress.setValue(i) if progress.wasCanceled(): return converter.gim_to_png(gim_file) os.remove(gim_file) progress.close() self.gfx_dir = gfx_dir self.ui.grpStep5.setEnabled(False) self.ui.grpStep6.setEnabled(True) ############################################################################## ### STEP 6 ############################################################################## def create_terminology(self): dir
def get_terminology(self): dir = get_open_file(self, self.ui.txtTerminology.text(), filter = "Terminology.csv (*.csv)") if not dir == "": self.ui.txtTerminology.setText(dir) def check_terminology(self): terms_file = common.qt_to_unicode(self.ui.txtTerminology.text(), normalize = False) if not terms_file: self.show_error("No terminology file provided.") return if not os.path.isfile(terms_file): # Create it. with open(terms_file, "wb") as f: self.show_info("Terminology file created.") self.terminology = terms_file self.ui.grpStep6.setEnabled(False) self.ui.btnFinish.setEnabled(True) ############################################################################## ### @fn accept() ### @desc Overrides the OK button. ############################################################################## def accept(self): # Save typing~ cfg = common.editor_config cfg.backup_dir = self.backup_dir cfg.changes_dir = self.changes_dir cfg.dupes_csv = os.path.join(self.editor_data_dir, DUPES_CSV) cfg.eboot_text = os.path.join(self.editor_data_dir, EBOOT_TEXT) cfg.gfx_dir = self.gfx_dir cfg.iso_dir = self.edited_iso_dir cfg.iso_file = os.path.join(self.workspace_dir, EDITED_ISO_FILE) cfg.similarity_db = os.path.join(self.editor_data_dir, SIMILARITY_DB) cfg.terminology = self.terminology cfg.umdimage_dir = self.umdimage_dir cfg.umdimage2_dir = self.umdimage2_dir cfg.voice_dir = self.voice_dir common.editor_config = cfg common.editor_config.save_config() super(SetupWizard, self).accept() ############################################################################## ### @fn reject() ### @desc Overrides the Cancel button. ############################################################################## def reject(self): super(SetupWizard, self).reject() if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app, QtCore.SLOT("quit()") ) form = SetupWizard() form.show() sys.exit(app.exec_()) ### EOF ###
= get_save_file(self, self.ui.txtTerminology.text(), filter = "Terminology.csv (*.csv)") if not dir == "": self.ui.txtTerminology.setText(dir)
identifier_body
setup_wizard.py
################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor is distributed in the hope that it will be ### useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### ### You should have received a copy of the GNU General Public License ### along with the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ from PyQt4 import QtGui, QtCore, Qt from PyQt4.QtGui import QFileDialog, QProgressDialog from ui_wizard import Ui_SetupWizard import base64 import cStringIO import glob import os import shutil import sys import threading import zipfile from bitstring import ConstBitStream, BitStream import common from dialog_fns import get_save_file, get_open_file, get_existing_dir from eboot_patch import apply_eboot_patches from extract import extract_umdimage, extract_pak from extract.eboot import UMDIMAGES from font_parser import font_bmp_to_alpha from gim_converter import GimConverter from gmo_file import GmoFile UMDIMAGE_DAT = os.path.join("PSP_GAME", "USRDIR", "umdimage.dat") UMDIMAGE2_DAT = os.path.join("PSP_GAME", "USRDIR", "umdimage2.dat") VOICE_PAK = os.path.join("PSP_GAME", "USRDIR", "voice.pak") UMDIMAGE_DIR = "umdimage" UMDIMAGE2_DIR = "umdimage2" VOICE_DIR = "voice" CHANGES_DIR = "!changes" BACKUP_DIR = "!backup" EDITED_ISO_DIR = "!ISO_EDITED" EDITED_ISO_FILE = "[PSP] DRBest [Edited].iso" EDITOR_DATA_DIR = "!editor" DUPES_CSV = "dupes.csv" EBOOT_TEXT = "eboot_text.csv" SIMILARITY_DB = "similarity-db.sql" THREAD_TIMEOUT = 0.1 class SetupWizard(QtGui.QDialog): def __init__(self, parent=None): super(SetupWizard, self).__init__(parent) self.ui = Ui_SetupWizard() self.ui.setupUi(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.iso_dir = None self.workspace_dir = None self.eboot_path = None self.terminology_path = None # Don't really feel like doing all this in Designer. self.connect(self.ui.btnIsoBrowse, QtCore.SIGNAL("clicked()"), self.get_iso) self.connect(self.ui.btnIsoOK, QtCore.SIGNAL("clicked()"), self.check_iso) self.connect(self.ui.btnWorkspaceBrowse, QtCore.SIGNAL("clicked()"), self.get_workspace) self.connect(self.ui.btnWorkspaceOK, QtCore.SIGNAL("clicked()"), self.check_workspace) self.connect(self.ui.btnEbootOK, QtCore.SIGNAL("clicked()"), self.check_eboot) self.connect(self.ui.btnSetupWorkspace, QtCore.SIGNAL("clicked()"), self.setup_workspace) self.connect(self.ui.btnWorkspaceSkip, QtCore.SIGNAL("clicked()"), self.skip_setup) self.connect(self.ui.btnCopyGfx, QtCore.SIGNAL("clicked()"), self.copy_gfx) self.connect(self.ui.btnTerminologyNew, QtCore.SIGNAL("clicked()"), self.create_terminology) self.connect(self.ui.btnTerminologyBrowse, QtCore.SIGNAL("clicked()"), self.get_terminology) self.connect(self.ui.btnTerminologyOK, QtCore.SIGNAL("clicked()"), self.check_terminology) def show_error(self, message): QtGui.QMessageBox.critical(self, "Error", message) def show_info(self, message): QtGui.QMessageBox.information(self, "Info", message) ############################################################################## ### STEP 1 ############################################################################## def get_iso(self): dir = get_existing_dir(self, self.ui.txtIso.text()) if not dir == "": self.ui.txtIso.setText(dir) def check_iso(self): iso_dir = common.qt_to_unicode(self.ui.txtIso.text(), normalize = False) if not os.path.isdir(iso_dir): self.show_error("ISO directory does not exist.") return validated = True with open("data/file_order.txt", "rb") as file_order: # Since we're reappropriating this from the file used by mkisofs, # we need to do a little bit of work on it to be useful here. # Split it up on the tab, take the first entry, and chop the slash # off the beginning so we can use it in os.path.join file_list = [line.split('\t')[0][1:] for line in file_order.readlines() if not line == ""] for filename in file_list: full_name = os.path.join(iso_dir, filename) if not os.path.isfile(full_name): validated = False self.show_error("%s missing from ISO directory." % full_name) break if not validated: return self.iso_dir = iso_dir self.show_info("ISO directory looks good.") self.ui.grpStep1.setEnabled(False) self.ui.grpStep2.setEnabled(True) ############################################################################## ### STEP 2 ############################################################################## def get_workspace(self): dir = get_existing_dir(self, self.ui.txtWorkspace.text()) if not dir == "": self.ui.txtWorkspace.setText(dir) def check_workspace(self): workspace_dir = common.qt_to_unicode(self.ui.txtWorkspace.text(), normalize = False) if not os.path.isdir(workspace_dir): try: os.makedirs(workspace_dir) self.show_info("Workspace directory created.") except: self.show_error("Error creating workspace directory.") return else: sel
self.workspace_dir = workspace_dir self.ui.grpStep2.setEnabled(False) self.ui.grpStep3.setEnabled(True) ############################################################################## ### STEP 3 ############################################################################## def check_eboot(self): eboot_path = os.path.join(self.workspace_dir, "EBOOT.BIN") if not os.path.isfile(eboot_path): self.show_error("EBOOT.BIN not found in workspace directory.") return eboot = ConstBitStream(filename = eboot_path) if not eboot[:32] == ConstBitStream(hex = "0x7F454C46"): self.show_error("EBOOT.BIN is encrypted.") return self.eboot_path = eboot_path self.show_info("EBOOT.BIN looks good.") self.ui.grpStep3.setEnabled(False) self.ui.grpStep4.setEnabled(True) ############################################################################## ### STEP 4 ############################################################################## def generate_directories(self): self.umdimage_dir = os.path.join(self.workspace_dir, UMDIMAGE_DIR) self.umdimage2_dir = os.path.join(self.workspace_dir, UMDIMAGE2_DIR) self.voice_dir = os.path.join(self.workspace_dir, VOICE_DIR) self.changes_dir = os.path.join(self.workspace_dir, CHANGES_DIR) self.backup_dir = os.path.join(self.workspace_dir, BACKUP_DIR) self.edited_iso_dir = os.path.join(self.workspace_dir, EDITED_ISO_DIR) self.editor_data_dir = os.path.join(self.workspace_dir, EDITOR_DATA_DIR) def skip_setup(self): answer = QtGui.QMessageBox.warning( self, "Skip Setup", "Are you sure you want to skip setting up your workspace?\n\nYou should only do this if you already have a workspace generated by the setup wizard.", buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, defaultButton = QtGui.QMessageBox.No ) if answer == QtGui.QMessageBox.No: return self.generate_directories() self.ui.grpStep4.setEnabled(False) self.ui.grpStep5.setEnabled(True) def setup_workspace(self): umdimage = os.path.join(self.iso_dir, UMDIMAGE_DAT) umdimage2 = os.path.join(self.iso_dir, UMDIMAGE2_DAT) voice = os.path.join(self.iso_dir, VOICE_PAK) self.generate_directories() progress = QProgressDialog("", QtCore.QString(), 0, 11000, self) progress.setWindowTitle("Setting up workspace...") progress.setWindowModality(Qt.Qt.WindowModal) progress.setMinimumDuration(0) progress.setValue(0) progress.setAutoClose(False) progress.setAutoReset(False) progress.setLabelText("Creating directories...") # Do the easy stuff first. if not os.path.isdir(self.changes_dir): os.makedirs(self.changes_dir) progress.setValue(progress.value() + 1) if not os.path.isdir(self.backup_dir): os.makedirs(self.backup_dir) progress.setValue(progress.value() + 1) if not os.path.isdir(self.editor_data_dir): os.makedirs(self.editor_data_dir) progress.setValue(progress.value() + 1) thread_fns = [ {"target": extract_umdimage, "kwargs": {"filename": umdimage, "out_dir": self.umdimage_dir, "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage}}, {"target": extract_umdimage, "kwargs": {"filename": umdimage2, "out_dir": self.umdimage2_dir, "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage2}}, {"target": extract_pak, "kwargs": {"filename": voice, "out_dir": self.voice_dir}}, ] # Going to capture stdout because I don't feel like # rewriting the extract functions to play nice with GUI. stdout = sys.stdout sys.stdout = cStringIO.StringIO() for thread_fn in thread_fns: thread = threading.Thread(**thread_fn) thread.start() while thread.isAlive(): thread.join(THREAD_TIMEOUT) output = [line for line in sys.stdout.getvalue().split('\n') if len(line) > 0] progress.setValue(progress.value() + len(output)) if len(output) > 0: progress.setLabelText("Extracting %s..." % output[-1]) sys.stdout = cStringIO.StringIO() sys.stdout = stdout # Give us an ISO directory for the editor to place modified files in. progress.setLabelText("Copying ISO files...") # ISO directory needs to not exist for copytree. if os.path.isdir(self.edited_iso_dir): shutil.rmtree(self.edited_iso_dir) # One more thing we want threaded so it doesn't lock up the GUI. thread = threading.Thread(target = shutil.copytree, kwargs = {"src": self.iso_dir, "dst": self.edited_iso_dir}) thread.start() while thread.isAlive(): thread.join(THREAD_TIMEOUT) progress.setLabelText("Copying ISO files...") # It has to increase by some amount or it won't update and the UI will lock up. progress.setValue(progress.value() + 1) # shutil.copytree(self.iso_dir, self.edited_iso_dir) progress.setValue(progress.value() + 1) # Files we want to make blank, because they're unnecessary. blank_files = [ os.path.join(self.edited_iso_dir, "PSP_GAME", "INSDIR", "UMDIMAGE.DAT"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "DATA.BIN"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "EBOOT.BIN"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "PARAM.SFO"), ] for blank in blank_files: with open(blank, "wb") as f: pass # Copy the decrypted EBOOT into the ISO folder and apply our hacks to it. progress.setLabelText("Hacking EBOOT...") progress.setValue(progress.value() + 1) hacked_eboot = BitStream(filename = self.eboot_path) hacked_eboot, offset = apply_eboot_patches(hacked_eboot) with open(os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"), "wb") as f: hacked_eboot.tofile(f) # shutil.copy(self.eboot_path, os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN")) progress.setLabelText("Extracting editor data...") progress.setValue(progress.value() + 1) # Extract the editor data. editor_data = zipfile.ZipFile("data/editor_data.zip", "r") editor_data.extractall(self.editor_data_dir) editor_data.close() progress.setValue(progress.maximum()) progress.close() self.ui.grpStep4.setEnabled(False) self.ui.grpStep5.setEnabled(True) ############################################################################## ### STEP 5 ############################################################################## def copy_gfx(self): gfx_dir = os.path.join(self.editor_data_dir, "gfx") if os.path.isdir(gfx_dir): shutil.rmtree(gfx_dir) os.makedirs(gfx_dir) progress = QProgressDialog("", "Abort", 0, 0, self) progress.setWindowTitle("Copying GFX...") progress.setWindowModality(Qt.Qt.WindowModal) progress.setMinimumDuration(0) progress.setValue(0) progress.setAutoClose(False) progress.setLabelText("Setting up GFX dir.") progress.setMaximum(5) progress.setValue(0) # Extract the images we can't just take directly from the game's data. gfx_bin = zipfile.ZipFile("data/gfx_base.bin", "r") progress.setValue(1) gfx_enc = gfx_bin.open("gfx_base.bin") progress.setValue(2) gfx_dec = cStringIO.StringIO() base64.decode(gfx_enc, gfx_dec) progress.setValue(3) gfx_base = zipfile.ZipFile(gfx_dec, "r") progress.setValue(4) gfx_base.extractall(gfx_dir) progress.setValue(5) gfx_base.close() gfx_dec.close() gfx_enc.close() gfx_bin.close() # We can mostly loop this. gfx_data = [ ("ammo", "kotodama_icn_???.gim"), ("bgd", "bgd_???.gim"), ("cutin", "cutin_icn_???.gim"), ("events", "gallery_icn_???.gim"), ("movies", "bin_movie_gallery_l.pak/0000/000[1789].gim"), ("movies", "bin_movie_gallery_l.pak/0000/00[123]?.gim"), ("nametags", "tex_system.pak/00[12]?.gim"), ("nametags", "tex_system.pak/003[0123456].gim"), ("presents", "present_icn_???.gim"), ("sprites", "bustup_??_??.gim"), ("sprites", "stand_??_??.gmo"), ] for (dir, file_glob) in gfx_data: out_dir = os.path.join(gfx_dir, dir) files = glob.glob(os.path.join(self.umdimage_dir, file_glob)) progress.setLabelText("Copying %s." % dir) progress.setMaximum(len(files)) progress.setValue(0) if not os.path.isdir(out_dir): os.makedirs(out_dir) for i, image in enumerate(files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return src = image dest = os.path.join(out_dir, os.path.basename(src)) shutil.copy(src, dest) progress.setValue(len(files)) progress.setLabelText("Copying font.") progress.setMaximum(4) progress.setValue(0) # The font we have to get from umdimage2. font_dir = os.path.join(gfx_dir, "font") if not os.path.isdir(font_dir): os.makedirs(font_dir) progress.setValue(1) # And convert to PNG with an alpha channel so our editor can use it. font1 = font_bmp_to_alpha(os.path.join(self.umdimage2_dir, "font.pak", "0000.bmp")) progress.setValue(2) font2 = font_bmp_to_alpha(os.path.join(self.umdimage2_dir, "font.pak", "0002.bmp")) progress.setValue(3) font1.save(os.path.join(font_dir, "Font01.png")) font2.save(os.path.join(font_dir, "Font02.png")) shutil.copy(os.path.join(self.umdimage2_dir, "font.pak", "0001.font"), os.path.join(font_dir, "Font01.font")) shutil.copy(os.path.join(self.umdimage2_dir, "font.pak", "0003.font"), os.path.join(font_dir, "Font02.font")) progress.setValue(4) # And then the flash files. This'll be fun. flash_dir = os.path.join(gfx_dir, "flash") if not os.path.isdir(flash_dir): os.makedirs(flash_dir) # Because there's so many in so many different places, I just stored a list # of the flash files we need in the gfx_base archive. So let's load that. with open(os.path.join(gfx_dir, "fla.txt"), "rb") as fla: fla_list = fla.readlines() progress.setLabelText("Copying flash.") progress.setMaximum(len(fla_list)) progress.setValue(0) for i, flash in enumerate(fla_list): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return flash = flash.strip() fla_name = flash[:7] # fla_### src = os.path.join(self.umdimage_dir, flash) dest = os.path.join(flash_dir, "%s.gim" % fla_name) shutil.copy(src, dest) progress.setValue(len(fla_list)) # We have a couple sets of files that aren't named the way we want them to # be, just because of how they're stored in umdimage. progress.setLabelText("Renaming files.") to_rename = [ ("movies", "movie_%03d.gim", range(32)), ("nametags", "%02d.gim", range(23) + [24, 25, 30, 31]), ] for (folder, pattern, nums) in to_rename: folder = os.path.join(gfx_dir, folder) files = glob.glob(os.path.join(folder, "*.gim")) progress.setMaximum(len(files)) progress.setValue(0) for i, image in enumerate(files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return src = image dest = os.path.join(folder, pattern % nums[i]) if os.path.isfile(dest): os.remove(dest) shutil.move(src, dest) sprite_dir = os.path.join(gfx_dir, "sprites") gmo_files = glob.glob(os.path.join(sprite_dir, "*.gmo")) progress.setLabelText("Extracting GMO files.") progress.setValue(0) progress.setMaximum(len(gmo_files)) for i, gmo_file in enumerate(gmo_files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return name, ext = os.path.splitext(os.path.basename(gmo_file)) gim_file = os.path.join(sprite_dir, name + ".gim") gmo = GmoFile(filename = gmo_file) # Once we've loaded it, we're all done with it, so make it go away. os.remove(gmo_file) if gmo.gim_count() == 0: continue gim = gmo.get_gim(0) with open(gim_file, "wb") as f: gim.tofile(f) if self.ui.chkGimToPng.isChecked(): gim_files = glob.glob(os.path.join(gfx_dir, "*", "*.gim")) progress.setLabelText("Converting GIM to PNG.") progress.setValue(0) progress.setMaximum(len(gim_files)) converter = GimConverter() for i, gim_file in enumerate(gim_files): progress.setValue(i) if progress.wasCanceled(): return converter.gim_to_png(gim_file) os.remove(gim_file) progress.close() self.gfx_dir = gfx_dir self.ui.grpStep5.setEnabled(False) self.ui.grpStep6.setEnabled(True) ############################################################################## ### STEP 6 ############################################################################## def create_terminology(self): dir = get_save_file(self, self.ui.txtTerminology.text(), filter = "Terminology.csv (*.csv)") if not dir == "": self.ui.txtTerminology.setText(dir) def get_terminology(self): dir = get_open_file(self, self.ui.txtTerminology.text(), filter = "Terminology.csv (*.csv)") if not dir == "": self.ui.txtTerminology.setText(dir) def check_terminology(self): terms_file = common.qt_to_unicode(self.ui.txtTerminology.text(), normalize = False) if not terms_file: self.show_error("No terminology file provided.") return if not os.path.isfile(terms_file): # Create it. with open(terms_file, "wb") as f: self.show_info("Terminology file created.") self.terminology = terms_file self.ui.grpStep6.setEnabled(False) self.ui.btnFinish.setEnabled(True) ############################################################################## ### @fn accept() ### @desc Overrides the OK button. ############################################################################## def accept(self): # Save typing~ cfg = common.editor_config cfg.backup_dir = self.backup_dir cfg.changes_dir = self.changes_dir cfg.dupes_csv = os.path.join(self.editor_data_dir, DUPES_CSV) cfg.eboot_text = os.path.join(self.editor_data_dir, EBOOT_TEXT) cfg.gfx_dir = self.gfx_dir cfg.iso_dir = self.edited_iso_dir cfg.iso_file = os.path.join(self.workspace_dir, EDITED_ISO_FILE) cfg.similarity_db = os.path.join(self.editor_data_dir, SIMILARITY_DB) cfg.terminology = self.terminology cfg.umdimage_dir = self.umdimage_dir cfg.umdimage2_dir = self.umdimage2_dir cfg.voice_dir = self.voice_dir common.editor_config = cfg common.editor_config.save_config() super(SetupWizard, self).accept() ############################################################################## ### @fn reject() ### @desc Overrides the Cancel button. ############################################################################## def reject(self): super(SetupWizard, self).reject() if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app, QtCore.SLOT("quit()") ) form = SetupWizard() form.show() sys.exit(app.exec_()) ### EOF ###
f.show_info("Workspace directory already exists.\n\nExisting data will be overwritten.")
conditional_block
setup_wizard.py
################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor is distributed in the hope that it will be ### useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### ### You should have received a copy of the GNU General Public License ### along with the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ from PyQt4 import QtGui, QtCore, Qt from PyQt4.QtGui import QFileDialog, QProgressDialog from ui_wizard import Ui_SetupWizard import base64 import cStringIO import glob import os import shutil import sys import threading import zipfile from bitstring import ConstBitStream, BitStream import common from dialog_fns import get_save_file, get_open_file, get_existing_dir from eboot_patch import apply_eboot_patches from extract import extract_umdimage, extract_pak from extract.eboot import UMDIMAGES from font_parser import font_bmp_to_alpha from gim_converter import GimConverter from gmo_file import GmoFile UMDIMAGE_DAT = os.path.join("PSP_GAME", "USRDIR", "umdimage.dat") UMDIMAGE2_DAT = os.path.join("PSP_GAME", "USRDIR", "umdimage2.dat") VOICE_PAK = os.path.join("PSP_GAME", "USRDIR", "voice.pak") UMDIMAGE_DIR = "umdimage" UMDIMAGE2_DIR = "umdimage2" VOICE_DIR = "voice" CHANGES_DIR = "!changes" BACKUP_DIR = "!backup" EDITED_ISO_DIR = "!ISO_EDITED" EDITED_ISO_FILE = "[PSP] DRBest [Edited].iso" EDITOR_DATA_DIR = "!editor" DUPES_CSV = "dupes.csv" EBOOT_TEXT = "eboot_text.csv" SIMILARITY_DB = "similarity-db.sql" THREAD_TIMEOUT = 0.1 class SetupWizard(QtGui.QDialog): def __init__(self, parent=None): super(SetupWizard, self).__init__(parent) self.ui = Ui_SetupWizard() self.ui.setupUi(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.iso_dir = None self.workspace_dir = None self.eboot_path = None self.terminology_path = None # Don't really feel like doing all this in Designer. self.connect(self.ui.btnIsoBrowse, QtCore.SIGNAL("clicked()"), self.get_iso) self.connect(self.ui.btnIsoOK, QtCore.SIGNAL("clicked()"), self.check_iso) self.connect(self.ui.btnWorkspaceBrowse, QtCore.SIGNAL("clicked()"), self.get_workspace) self.connect(self.ui.btnWorkspaceOK, QtCore.SIGNAL("clicked()"), self.check_workspace) self.connect(self.ui.btnEbootOK, QtCore.SIGNAL("clicked()"), self.check_eboot) self.connect(self.ui.btnSetupWorkspace, QtCore.SIGNAL("clicked()"), self.setup_workspace) self.connect(self.ui.btnWorkspaceSkip, QtCore.SIGNAL("clicked()"), self.skip_setup) self.connect(self.ui.btnCopyGfx, QtCore.SIGNAL("clicked()"), self.copy_gfx) self.connect(self.ui.btnTerminologyNew, QtCore.SIGNAL("clicked()"), self.create_terminology) self.connect(self.ui.btnTerminologyBrowse, QtCore.SIGNAL("clicked()"), self.get_terminology) self.connect(self.ui.btnTerminologyOK, QtCore.SIGNAL("clicked()"), self.check_terminology) def show_error(self, message): QtGui.QMessageBox.critical(self, "Error", message) def show_info(self, message): QtGui.QMessageBox.information(self, "Info", message) ############################################################################## ### STEP 1 ############################################################################## def get_iso(self): dir = get_existing_dir(self, self.ui.txtIso.text()) if not dir == "": self.ui.txtIso.setText(dir) def check_iso(self): iso_dir = common.qt_to_unicode(self.ui.txtIso.text(), normalize = False) if not os.path.isdir(iso_dir): self.show_error("ISO directory does not exist.") return validated = True with open("data/file_order.txt", "rb") as file_order: # Since we're reappropriating this from the file used by mkisofs, # we need to do a little bit of work on it to be useful here. # Split it up on the tab, take the first entry, and chop the slash # off the beginning so we can use it in os.path.join file_list = [line.split('\t')[0][1:] for line in file_order.readlines() if not line == ""] for filename in file_list: full_name = os.path.join(iso_dir, filename) if not os.path.isfile(full_name): validated = False self.show_error("%s missing from ISO directory." % full_name) break if not validated: return self.iso_dir = iso_dir self.show_info("ISO directory looks good.") self.ui.grpStep1.setEnabled(False) self.ui.grpStep2.setEnabled(True) ############################################################################## ### STEP 2 ############################################################################## def get_workspace(self): dir = get_existing_dir(self, self.ui.txtWorkspace.text()) if not dir == "": self.ui.txtWorkspace.setText(dir) def check_workspace(self): workspace_dir = common.qt_to_unicode(self.ui.txtWorkspace.text(), normalize = False) if not os.path.isdir(workspace_dir): try: os.makedirs(workspace_dir) self.show_info("Workspace directory created.") except: self.show_error("Error creating workspace directory.") return else: self.show_info("Workspace directory already exists.\n\nExisting data will be overwritten.") self.workspace_dir = workspace_dir self.ui.grpStep2.setEnabled(False) self.ui.grpStep3.setEnabled(True) ############################################################################## ### STEP 3 ############################################################################## def check_eboot(self): eboot_path = os.path.join(self.workspace_dir, "EBOOT.BIN") if not os.path.isfile(eboot_path): self.show_error("EBOOT.BIN not found in workspace directory.") return eboot = ConstBitStream(filename = eboot_path) if not eboot[:32] == ConstBitStream(hex = "0x7F454C46"): self.show_error("EBOOT.BIN is encrypted.") return self.eboot_path = eboot_path self.show_info("EBOOT.BIN looks good.") self.ui.grpStep3.setEnabled(False) self.ui.grpStep4.setEnabled(True) ############################################################################## ### STEP 4 ############################################################################## def generate_directories(self): self.umdimage_dir = os.path.join(self.workspace_dir, UMDIMAGE_DIR) self.umdimage2_dir = os.path.join(self.workspace_dir, UMDIMAGE2_DIR) self.voice_dir = os.path.join(self.workspace_dir, VOICE_DIR) self.changes_dir = os.path.join(self.workspace_dir, CHANGES_DIR) self.backup_dir = os.path.join(self.workspace_dir, BACKUP_DIR) self.edited_iso_dir = os.path.join(self.workspace_dir, EDITED_ISO_DIR) self.editor_data_dir = os.path.join(self.workspace_dir, EDITOR_DATA_DIR) def skip_setup(self): answer = QtGui.QMessageBox.warning( self, "Skip Setup", "Are you sure you want to skip setting up your workspace?\n\nYou should only do this if you already have a workspace generated by the setup wizard.", buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, defaultButton = QtGui.QMessageBox.No ) if answer == QtGui.QMessageBox.No: return self.generate_directories() self.ui.grpStep4.setEnabled(False) self.ui.grpStep5.setEnabled(True) def setup_workspace(self): umdimage = os.path.join(self.iso_dir, UMDIMAGE_DAT) umdimage2 = os.path.join(self.iso_dir, UMDIMAGE2_DAT) voice = os.path.join(self.iso_dir, VOICE_PAK) self.generate_directories() progress = QProgressDialog("", QtCore.QString(), 0, 11000, self) progress.setWindowTitle("Setting up workspace...") progress.setWindowModality(Qt.Qt.WindowModal) progress.setMinimumDuration(0) progress.setValue(0) progress.setAutoClose(False) progress.setAutoReset(False) progress.setLabelText("Creating directories...") # Do the easy stuff first. if not os.path.isdir(self.changes_dir): os.makedirs(self.changes_dir) progress.setValue(progress.value() + 1) if not os.path.isdir(self.backup_dir): os.makedirs(self.backup_dir) progress.setValue(progress.value() + 1) if not os.path.isdir(self.editor_data_dir): os.makedirs(self.editor_data_dir) progress.setValue(progress.value() + 1) thread_fns = [ {"target": extract_umdimage, "kwargs": {"filename": umdimage, "out_dir": self.umdimage_dir, "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage}}, {"target": extract_umdimage, "kwargs": {"filename": umdimage2, "out_dir": self.umdimage2_dir, "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage2}}, {"target": extract_pak, "kwargs": {"filename": voice, "out_dir": self.voice_dir}}, ] # Going to capture stdout because I don't feel like # rewriting the extract functions to play nice with GUI. stdout = sys.stdout sys.stdout = cStringIO.StringIO() for thread_fn in thread_fns: thread = threading.Thread(**thread_fn) thread.start() while thread.isAlive(): thread.join(THREAD_TIMEOUT) output = [line for line in sys.stdout.getvalue().split('\n') if len(line) > 0] progress.setValue(progress.value() + len(output)) if len(output) > 0: progress.setLabelText("Extracting %s..." % output[-1]) sys.stdout = cStringIO.StringIO() sys.stdout = stdout # Give us an ISO directory for the editor to place modified files in. progress.setLabelText("Copying ISO files...") # ISO directory needs to not exist for copytree. if os.path.isdir(self.edited_iso_dir): shutil.rmtree(self.edited_iso_dir) # One more thing we want threaded so it doesn't lock up the GUI. thread = threading.Thread(target = shutil.copytree, kwargs = {"src": self.iso_dir, "dst": self.edited_iso_dir}) thread.start() while thread.isAlive(): thread.join(THREAD_TIMEOUT) progress.setLabelText("Copying ISO files...") # It has to increase by some amount or it won't update and the UI will lock up. progress.setValue(progress.value() + 1) # shutil.copytree(self.iso_dir, self.edited_iso_dir) progress.setValue(progress.value() + 1) # Files we want to make blank, because they're unnecessary. blank_files = [ os.path.join(self.edited_iso_dir, "PSP_GAME", "INSDIR", "UMDIMAGE.DAT"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "DATA.BIN"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "EBOOT.BIN"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "PARAM.SFO"), ] for blank in blank_files: with open(blank, "wb") as f: pass # Copy the decrypted EBOOT into the ISO folder and apply our hacks to it. progress.setLabelText("Hacking EBOOT...") progress.setValue(progress.value() + 1) hacked_eboot = BitStream(filename = self.eboot_path) hacked_eboot, offset = apply_eboot_patches(hacked_eboot) with open(os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"), "wb") as f: hacked_eboot.tofile(f) # shutil.copy(self.eboot_path, os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN")) progress.setLabelText("Extracting editor data...") progress.setValue(progress.value() + 1) # Extract the editor data. editor_data = zipfile.ZipFile("data/editor_data.zip", "r") editor_data.extractall(self.editor_data_dir) editor_data.close() progress.setValue(progress.maximum()) progress.close() self.ui.grpStep4.setEnabled(False) self.ui.grpStep5.setEnabled(True) ############################################################################## ### STEP 5 ############################################################################## def copy_gfx(self): gfx_dir = os.path.join(self.editor_data_dir, "gfx") if os.path.isdir(gfx_dir): shutil.rmtree(gfx_dir) os.makedirs(gfx_dir) progress = QProgressDialog("", "Abort", 0, 0, self) progress.setWindowTitle("Copying GFX...") progress.setWindowModality(Qt.Qt.WindowModal) progress.setMinimumDuration(0) progress.setValue(0) progress.setAutoClose(False) progress.setLabelText("Setting up GFX dir.") progress.setMaximum(5) progress.setValue(0) # Extract the images we can't just take directly from the game's data. gfx_bin = zipfile.ZipFile("data/gfx_base.bin", "r") progress.setValue(1) gfx_enc = gfx_bin.open("gfx_base.bin") progress.setValue(2) gfx_dec = cStringIO.StringIO() base64.decode(gfx_enc, gfx_dec) progress.setValue(3) gfx_base = zipfile.ZipFile(gfx_dec, "r") progress.setValue(4) gfx_base.extractall(gfx_dir) progress.setValue(5) gfx_base.close() gfx_dec.close() gfx_enc.close() gfx_bin.close() # We can mostly loop this. gfx_data = [ ("ammo", "kotodama_icn_???.gim"), ("bgd", "bgd_???.gim"), ("cutin", "cutin_icn_???.gim"), ("events", "gallery_icn_???.gim"), ("movies", "bin_movie_gallery_l.pak/0000/000[1789].gim"), ("movies", "bin_movie_gallery_l.pak/0000/00[123]?.gim"), ("nametags", "tex_system.pak/00[12]?.gim"), ("nametags", "tex_system.pak/003[0123456].gim"), ("presents", "present_icn_???.gim"), ("sprites", "bustup_??_??.gim"), ("sprites", "stand_??_??.gmo"), ] for (dir, file_glob) in gfx_data: out_dir = os.path.join(gfx_dir, dir) files = glob.glob(os.path.join(self.umdimage_dir, file_glob)) progress.setLabelText("Copying %s." % dir) progress.setMaximum(len(files)) progress.setValue(0) if not os.path.isdir(out_dir): os.makedirs(out_dir) for i, image in enumerate(files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return src = image dest = os.path.join(out_dir, os.path.basename(src)) shutil.copy(src, dest) progress.setValue(len(files)) progress.setLabelText("Copying font.") progress.setMaximum(4) progress.setValue(0) # The font we have to get from umdimage2. font_dir = os.path.join(gfx_dir, "font") if not os.path.isdir(font_dir): os.makedirs(font_dir) progress.setValue(1) # And convert to PNG with an alpha channel so our editor can use it. font1 = font_bmp_to_alpha(os.path.join(self.umdimage2_dir, "font.pak", "0000.bmp")) progress.setValue(2) font2 = font_bmp_to_alpha(os.path.join(self.umdimage2_dir, "font.pak", "0002.bmp")) progress.setValue(3) font1.save(os.path.join(font_dir, "Font01.png")) font2.save(os.path.join(font_dir, "Font02.png")) shutil.copy(os.path.join(self.umdimage2_dir, "font.pak", "0001.font"), os.path.join(font_dir, "Font01.font")) shutil.copy(os.path.join(self.umdimage2_dir, "font.pak", "0003.font"), os.path.join(font_dir, "Font02.font")) progress.setValue(4) # And then the flash files. This'll be fun. flash_dir = os.path.join(gfx_dir, "flash") if not os.path.isdir(flash_dir): os.makedirs(flash_dir) # Because there's so many in so many different places, I just stored a list # of the flash files we need in the gfx_base archive. So let's load that. with open(os.path.join(gfx_dir, "fla.txt"), "rb") as fla: fla_list = fla.readlines() progress.setLabelText("Copying flash.") progress.setMaximum(len(fla_list)) progress.setValue(0) for i, flash in enumerate(fla_list): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return flash = flash.strip() fla_name = flash[:7] # fla_### src = os.path.join(self.umdimage_dir, flash) dest = os.path.join(flash_dir, "%s.gim" % fla_name) shutil.copy(src, dest) progress.setValue(len(fla_list)) # We have a couple sets of files that aren't named the way we want them to # be, just because of how they're stored in umdimage. progress.setLabelText("Renaming files.") to_rename = [ ("movies", "movie_%03d.gim", range(32)), ("nametags", "%02d.gim", range(23) + [24, 25, 30, 31]), ] for (folder, pattern, nums) in to_rename: folder = os.path.join(gfx_dir, folder) files = glob.glob(os.path.join(folder, "*.gim")) progress.setMaximum(len(files)) progress.setValue(0) for i, image in enumerate(files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return src = image dest = os.path.join(folder, pattern % nums[i]) if os.path.isfile(dest): os.remove(dest) shutil.move(src, dest) sprite_dir = os.path.join(gfx_dir, "sprites") gmo_files = glob.glob(os.path.join(sprite_dir, "*.gmo")) progress.setLabelText("Extracting GMO files.") progress.setValue(0) progress.setMaximum(len(gmo_files)) for i, gmo_file in enumerate(gmo_files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return name, ext = os.path.splitext(os.path.basename(gmo_file)) gim_file = os.path.join(sprite_dir, name + ".gim") gmo = GmoFile(filename = gmo_file) # Once we've loaded it, we're all done with it, so make it go away. os.remove(gmo_file) if gmo.gim_count() == 0: continue gim = gmo.get_gim(0) with open(gim_file, "wb") as f: gim.tofile(f) if self.ui.chkGimToPng.isChecked(): gim_files = glob.glob(os.path.join(gfx_dir, "*", "*.gim")) progress.setLabelText("Converting GIM to PNG.") progress.setValue(0) progress.setMaximum(len(gim_files)) converter = GimConverter() for i, gim_file in enumerate(gim_files): progress.setValue(i) if progress.wasCanceled(): return converter.gim_to_png(gim_file) os.remove(gim_file) progress.close() self.gfx_dir = gfx_dir self.ui.grpStep5.setEnabled(False) self.ui.grpStep6.setEnabled(True) ############################################################################## ### STEP 6 ############################################################################## def create_terminology(self): dir = get_save_file(self, self.ui.txtTerminology.text(), filter = "Terminology.csv (*.csv)") if not dir == "": self.ui.txtTerminology.setText(dir) def get_terminology(self): dir = get_open_file(self, self.ui.txtTerminology.text(), filter = "Terminology.csv (*.csv)") if not dir == "": self.ui.txtTerminology.setText(dir) def check_terminology(self): terms_file = common.qt_to_unicode(self.ui.txtTerminology.text(), normalize = False) if not terms_file: self.show_error("No terminology file provided.") return if not os.path.isfile(terms_file): # Create it. with open(terms_file, "wb") as f: self.show_info("Terminology file created.") self.terminology = terms_file self.ui.grpStep6.setEnabled(False) self.ui.btnFinish.setEnabled(True) ############################################################################## ### @fn accept() ### @desc Overrides the OK button. ############################################################################## def accept(self): # Save typing~ cfg = common.editor_config cfg.backup_dir = self.backup_dir cfg.changes_dir = self.changes_dir cfg.dupes_csv = os.path.join(self.editor_data_dir, DUPES_CSV) cfg.eboot_text = os.path.join(self.editor_data_dir, EBOOT_TEXT) cfg.gfx_dir = self.gfx_dir cfg.iso_dir = self.edited_iso_dir cfg.iso_file = os.path.join(self.workspace_dir, EDITED_ISO_FILE) cfg.similarity_db = os.path.join(self.editor_data_dir, SIMILARITY_DB) cfg.terminology = self.terminology cfg.umdimage_dir = self.umdimage_dir cfg.umdimage2_dir = self.umdimage2_dir cfg.voice_dir = self.voice_dir common.editor_config = cfg common.editor_config.save_config() super(SetupWizard, self).accept() ############################################################################## ### @fn reject() ### @desc Overrides the Cancel button. ############################################################################## def rej
lf): super(SetupWizard, self).reject() if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app, QtCore.SLOT("quit()") ) form = SetupWizard() form.show() sys.exit(app.exec_()) ### EOF ###
ect(se
identifier_name
setup_wizard.py
################################################################################ ### Copyright © 2012-2013 BlackDragonHunt ### ### This file is part of the Super Duper Script Editor. ### ### The Super Duper Script Editor is free software: you can redistribute it ### and/or modify it under the terms of the GNU General Public License as ### published by the Free Software Foundation, either version 3 of the License, ### or (at your option) any later version. ### ### The Super Duper Script Editor is distributed in the hope that it will be ### useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ### GNU General Public License for more details. ### ### You should have received a copy of the GNU General Public License ### along with the Super Duper Script Editor. ### If not, see <http://www.gnu.org/licenses/>. ################################################################################ from PyQt4 import QtGui, QtCore, Qt from PyQt4.QtGui import QFileDialog, QProgressDialog from ui_wizard import Ui_SetupWizard import base64 import cStringIO import glob import os import shutil import sys import threading import zipfile from bitstring import ConstBitStream, BitStream import common from dialog_fns import get_save_file, get_open_file, get_existing_dir from eboot_patch import apply_eboot_patches from extract import extract_umdimage, extract_pak from extract.eboot import UMDIMAGES from font_parser import font_bmp_to_alpha from gim_converter import GimConverter from gmo_file import GmoFile UMDIMAGE_DAT = os.path.join("PSP_GAME", "USRDIR", "umdimage.dat") UMDIMAGE2_DAT = os.path.join("PSP_GAME", "USRDIR", "umdimage2.dat") VOICE_PAK = os.path.join("PSP_GAME", "USRDIR", "voice.pak") UMDIMAGE_DIR = "umdimage" UMDIMAGE2_DIR = "umdimage2" VOICE_DIR = "voice" CHANGES_DIR = "!changes" BACKUP_DIR = "!backup" EDITED_ISO_DIR = "!ISO_EDITED" EDITED_ISO_FILE = "[PSP] DRBest [Edited].iso" EDITOR_DATA_DIR = "!editor" DUPES_CSV = "dupes.csv" EBOOT_TEXT = "eboot_text.csv" SIMILARITY_DB = "similarity-db.sql" THREAD_TIMEOUT = 0.1 class SetupWizard(QtGui.QDialog): def __init__(self, parent=None): super(SetupWizard, self).__init__(parent) self.ui = Ui_SetupWizard() self.ui.setupUi(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.iso_dir = None self.workspace_dir = None self.eboot_path = None self.terminology_path = None # Don't really feel like doing all this in Designer. self.connect(self.ui.btnIsoBrowse, QtCore.SIGNAL("clicked()"), self.get_iso) self.connect(self.ui.btnIsoOK, QtCore.SIGNAL("clicked()"), self.check_iso) self.connect(self.ui.btnWorkspaceBrowse, QtCore.SIGNAL("clicked()"), self.get_workspace) self.connect(self.ui.btnWorkspaceOK, QtCore.SIGNAL("clicked()"), self.check_workspace) self.connect(self.ui.btnEbootOK, QtCore.SIGNAL("clicked()"), self.check_eboot) self.connect(self.ui.btnSetupWorkspace, QtCore.SIGNAL("clicked()"), self.setup_workspace) self.connect(self.ui.btnWorkspaceSkip, QtCore.SIGNAL("clicked()"), self.skip_setup) self.connect(self.ui.btnCopyGfx, QtCore.SIGNAL("clicked()"), self.copy_gfx) self.connect(self.ui.btnTerminologyNew, QtCore.SIGNAL("clicked()"), self.create_terminology) self.connect(self.ui.btnTerminologyBrowse, QtCore.SIGNAL("clicked()"), self.get_terminology) self.connect(self.ui.btnTerminologyOK, QtCore.SIGNAL("clicked()"), self.check_terminology) def show_error(self, message): QtGui.QMessageBox.critical(self, "Error", message) def show_info(self, message): QtGui.QMessageBox.information(self, "Info", message) ############################################################################## ### STEP 1 ############################################################################## def get_iso(self): dir = get_existing_dir(self, self.ui.txtIso.text()) if not dir == "": self.ui.txtIso.setText(dir) def check_iso(self): iso_dir = common.qt_to_unicode(self.ui.txtIso.text(), normalize = False) if not os.path.isdir(iso_dir): self.show_error("ISO directory does not exist.") return validated = True with open("data/file_order.txt", "rb") as file_order: # Since we're reappropriating this from the file used by mkisofs, # we need to do a little bit of work on it to be useful here. # Split it up on the tab, take the first entry, and chop the slash # off the beginning so we can use it in os.path.join file_list = [line.split('\t')[0][1:] for line in file_order.readlines() if not line == ""] for filename in file_list: full_name = os.path.join(iso_dir, filename) if not os.path.isfile(full_name): validated = False self.show_error("%s missing from ISO directory." % full_name) break if not validated: return self.iso_dir = iso_dir self.show_info("ISO directory looks good.") self.ui.grpStep1.setEnabled(False) self.ui.grpStep2.setEnabled(True) ############################################################################## ### STEP 2 ############################################################################## def get_workspace(self): dir = get_existing_dir(self, self.ui.txtWorkspace.text()) if not dir == "": self.ui.txtWorkspace.setText(dir) def check_workspace(self): workspace_dir = common.qt_to_unicode(self.ui.txtWorkspace.text(), normalize = False) if not os.path.isdir(workspace_dir): try: os.makedirs(workspace_dir) self.show_info("Workspace directory created.") except: self.show_error("Error creating workspace directory.") return else: self.show_info("Workspace directory already exists.\n\nExisting data will be overwritten.") self.workspace_dir = workspace_dir self.ui.grpStep2.setEnabled(False) self.ui.grpStep3.setEnabled(True) ############################################################################## ### STEP 3 ############################################################################## def check_eboot(self): eboot_path = os.path.join(self.workspace_dir, "EBOOT.BIN") if not os.path.isfile(eboot_path): self.show_error("EBOOT.BIN not found in workspace directory.") return eboot = ConstBitStream(filename = eboot_path) if not eboot[:32] == ConstBitStream(hex = "0x7F454C46"): self.show_error("EBOOT.BIN is encrypted.") return self.eboot_path = eboot_path self.show_info("EBOOT.BIN looks good.") self.ui.grpStep3.setEnabled(False) self.ui.grpStep4.setEnabled(True) ############################################################################## ### STEP 4 ############################################################################## def generate_directories(self): self.umdimage_dir = os.path.join(self.workspace_dir, UMDIMAGE_DIR) self.umdimage2_dir = os.path.join(self.workspace_dir, UMDIMAGE2_DIR) self.voice_dir = os.path.join(self.workspace_dir, VOICE_DIR) self.changes_dir = os.path.join(self.workspace_dir, CHANGES_DIR) self.backup_dir = os.path.join(self.workspace_dir, BACKUP_DIR) self.edited_iso_dir = os.path.join(self.workspace_dir, EDITED_ISO_DIR) self.editor_data_dir = os.path.join(self.workspace_dir, EDITOR_DATA_DIR) def skip_setup(self): answer = QtGui.QMessageBox.warning( self, "Skip Setup", "Are you sure you want to skip setting up your workspace?\n\nYou should only do this if you already have a workspace generated by the setup wizard.", buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, defaultButton = QtGui.QMessageBox.No ) if answer == QtGui.QMessageBox.No: return self.generate_directories() self.ui.grpStep4.setEnabled(False) self.ui.grpStep5.setEnabled(True) def setup_workspace(self): umdimage = os.path.join(self.iso_dir, UMDIMAGE_DAT) umdimage2 = os.path.join(self.iso_dir, UMDIMAGE2_DAT) voice = os.path.join(self.iso_dir, VOICE_PAK) self.generate_directories() progress = QProgressDialog("", QtCore.QString(), 0, 11000, self) progress.setWindowTitle("Setting up workspace...") progress.setWindowModality(Qt.Qt.WindowModal) progress.setMinimumDuration(0) progress.setValue(0) progress.setAutoClose(False) progress.setAutoReset(False) progress.setLabelText("Creating directories...") # Do the easy stuff first. if not os.path.isdir(self.changes_dir): os.makedirs(self.changes_dir) progress.setValue(progress.value() + 1) if not os.path.isdir(self.backup_dir): os.makedirs(self.backup_dir) progress.setValue(progress.value() + 1) if not os.path.isdir(self.editor_data_dir): os.makedirs(self.editor_data_dir) progress.setValue(progress.value() + 1) thread_fns = [ {"target": extract_umdimage, "kwargs": {"filename": umdimage, "out_dir": self.umdimage_dir, "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage}}, {"target": extract_umdimage, "kwargs": {"filename": umdimage2, "out_dir": self.umdimage2_dir, "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage2}}, {"target": extract_pak, "kwargs": {"filename": voice, "out_dir": self.voice_dir}}, ] # Going to capture stdout because I don't feel like # rewriting the extract functions to play nice with GUI. stdout = sys.stdout sys.stdout = cStringIO.StringIO() for thread_fn in thread_fns: thread = threading.Thread(**thread_fn) thread.start() while thread.isAlive(): thread.join(THREAD_TIMEOUT) output = [line for line in sys.stdout.getvalue().split('\n') if len(line) > 0] progress.setValue(progress.value() + len(output)) if len(output) > 0: progress.setLabelText("Extracting %s..." % output[-1]) sys.stdout = cStringIO.StringIO() sys.stdout = stdout # Give us an ISO directory for the editor to place modified files in. progress.setLabelText("Copying ISO files...") # ISO directory needs to not exist for copytree. if os.path.isdir(self.edited_iso_dir): shutil.rmtree(self.edited_iso_dir) # One more thing we want threaded so it doesn't lock up the GUI. thread = threading.Thread(target = shutil.copytree, kwargs = {"src": self.iso_dir, "dst": self.edited_iso_dir}) thread.start() while thread.isAlive(): thread.join(THREAD_TIMEOUT) progress.setLabelText("Copying ISO files...") # It has to increase by some amount or it won't update and the UI will lock up. progress.setValue(progress.value() + 1) # shutil.copytree(self.iso_dir, self.edited_iso_dir) progress.setValue(progress.value() + 1) # Files we want to make blank, because they're unnecessary. blank_files = [ os.path.join(self.edited_iso_dir, "PSP_GAME", "INSDIR", "UMDIMAGE.DAT"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "DATA.BIN"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "EBOOT.BIN"), os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "PARAM.SFO"), ] for blank in blank_files: with open(blank, "wb") as f: pass # Copy the decrypted EBOOT into the ISO folder and apply our hacks to it. progress.setLabelText("Hacking EBOOT...") progress.setValue(progress.value() + 1) hacked_eboot = BitStream(filename = self.eboot_path) hacked_eboot, offset = apply_eboot_patches(hacked_eboot) with open(os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"), "wb") as f: hacked_eboot.tofile(f) # shutil.copy(self.eboot_path, os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN")) progress.setLabelText("Extracting editor data...") progress.setValue(progress.value() + 1) # Extract the editor data. editor_data = zipfile.ZipFile("data/editor_data.zip", "r") editor_data.extractall(self.editor_data_dir) editor_data.close() progress.setValue(progress.maximum()) progress.close() self.ui.grpStep4.setEnabled(False) self.ui.grpStep5.setEnabled(True) ############################################################################## ### STEP 5 ############################################################################## def copy_gfx(self): gfx_dir = os.path.join(self.editor_data_dir, "gfx") if os.path.isdir(gfx_dir): shutil.rmtree(gfx_dir) os.makedirs(gfx_dir) progress = QProgressDialog("", "Abort", 0, 0, self) progress.setWindowTitle("Copying GFX...") progress.setWindowModality(Qt.Qt.WindowModal) progress.setMinimumDuration(0) progress.setValue(0) progress.setAutoClose(False) progress.setLabelText("Setting up GFX dir.") progress.setMaximum(5) progress.setValue(0) # Extract the images we can't just take directly from the game's data. gfx_bin = zipfile.ZipFile("data/gfx_base.bin", "r") progress.setValue(1) gfx_enc = gfx_bin.open("gfx_base.bin") progress.setValue(2) gfx_dec = cStringIO.StringIO() base64.decode(gfx_enc, gfx_dec) progress.setValue(3) gfx_base = zipfile.ZipFile(gfx_dec, "r") progress.setValue(4) gfx_base.extractall(gfx_dir) progress.setValue(5) gfx_base.close() gfx_dec.close() gfx_enc.close() gfx_bin.close() # We can mostly loop this. gfx_data = [ ("ammo", "kotodama_icn_???.gim"), ("bgd", "bgd_???.gim"), ("cutin", "cutin_icn_???.gim"), ("events", "gallery_icn_???.gim"), ("movies", "bin_movie_gallery_l.pak/0000/000[1789].gim"), ("movies", "bin_movie_gallery_l.pak/0000/00[123]?.gim"), ("nametags", "tex_system.pak/00[12]?.gim"), ("nametags", "tex_system.pak/003[0123456].gim"), ("presents", "present_icn_???.gim"), ("sprites", "bustup_??_??.gim"), ("sprites", "stand_??_??.gmo"), ] for (dir, file_glob) in gfx_data: out_dir = os.path.join(gfx_dir, dir) files = glob.glob(os.path.join(self.umdimage_dir, file_glob)) progress.setLabelText("Copying %s." % dir) progress.setMaximum(len(files)) progress.setValue(0) if not os.path.isdir(out_dir): os.makedirs(out_dir) for i, image in enumerate(files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return src = image dest = os.path.join(out_dir, os.path.basename(src)) shutil.copy(src, dest) progress.setValue(len(files)) progress.setLabelText("Copying font.") progress.setMaximum(4) progress.setValue(0) # The font we have to get from umdimage2. font_dir = os.path.join(gfx_dir, "font") if not os.path.isdir(font_dir): os.makedirs(font_dir) progress.setValue(1) # And convert to PNG with an alpha channel so our editor can use it. font1 = font_bmp_to_alpha(os.path.join(self.umdimage2_dir, "font.pak", "0000.bmp")) progress.setValue(2) font2 = font_bmp_to_alpha(os.path.join(self.umdimage2_dir, "font.pak", "0002.bmp")) progress.setValue(3) font1.save(os.path.join(font_dir, "Font01.png")) font2.save(os.path.join(font_dir, "Font02.png")) shutil.copy(os.path.join(self.umdimage2_dir, "font.pak", "0001.font"), os.path.join(font_dir, "Font01.font")) shutil.copy(os.path.join(self.umdimage2_dir, "font.pak", "0003.font"), os.path.join(font_dir, "Font02.font")) progress.setValue(4) # And then the flash files. This'll be fun. flash_dir = os.path.join(gfx_dir, "flash") if not os.path.isdir(flash_dir): os.makedirs(flash_dir) # Because there's so many in so many different places, I just stored a list
progress.setLabelText("Copying flash.") progress.setMaximum(len(fla_list)) progress.setValue(0) for i, flash in enumerate(fla_list): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return flash = flash.strip() fla_name = flash[:7] # fla_### src = os.path.join(self.umdimage_dir, flash) dest = os.path.join(flash_dir, "%s.gim" % fla_name) shutil.copy(src, dest) progress.setValue(len(fla_list)) # We have a couple sets of files that aren't named the way we want them to # be, just because of how they're stored in umdimage. progress.setLabelText("Renaming files.") to_rename = [ ("movies", "movie_%03d.gim", range(32)), ("nametags", "%02d.gim", range(23) + [24, 25, 30, 31]), ] for (folder, pattern, nums) in to_rename: folder = os.path.join(gfx_dir, folder) files = glob.glob(os.path.join(folder, "*.gim")) progress.setMaximum(len(files)) progress.setValue(0) for i, image in enumerate(files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return src = image dest = os.path.join(folder, pattern % nums[i]) if os.path.isfile(dest): os.remove(dest) shutil.move(src, dest) sprite_dir = os.path.join(gfx_dir, "sprites") gmo_files = glob.glob(os.path.join(sprite_dir, "*.gmo")) progress.setLabelText("Extracting GMO files.") progress.setValue(0) progress.setMaximum(len(gmo_files)) for i, gmo_file in enumerate(gmo_files): if i % 10 == 0: progress.setValue(i) if progress.wasCanceled(): return name, ext = os.path.splitext(os.path.basename(gmo_file)) gim_file = os.path.join(sprite_dir, name + ".gim") gmo = GmoFile(filename = gmo_file) # Once we've loaded it, we're all done with it, so make it go away. os.remove(gmo_file) if gmo.gim_count() == 0: continue gim = gmo.get_gim(0) with open(gim_file, "wb") as f: gim.tofile(f) if self.ui.chkGimToPng.isChecked(): gim_files = glob.glob(os.path.join(gfx_dir, "*", "*.gim")) progress.setLabelText("Converting GIM to PNG.") progress.setValue(0) progress.setMaximum(len(gim_files)) converter = GimConverter() for i, gim_file in enumerate(gim_files): progress.setValue(i) if progress.wasCanceled(): return converter.gim_to_png(gim_file) os.remove(gim_file) progress.close() self.gfx_dir = gfx_dir self.ui.grpStep5.setEnabled(False) self.ui.grpStep6.setEnabled(True) ############################################################################## ### STEP 6 ############################################################################## def create_terminology(self): dir = get_save_file(self, self.ui.txtTerminology.text(), filter = "Terminology.csv (*.csv)") if not dir == "": self.ui.txtTerminology.setText(dir) def get_terminology(self): dir = get_open_file(self, self.ui.txtTerminology.text(), filter = "Terminology.csv (*.csv)") if not dir == "": self.ui.txtTerminology.setText(dir) def check_terminology(self): terms_file = common.qt_to_unicode(self.ui.txtTerminology.text(), normalize = False) if not terms_file: self.show_error("No terminology file provided.") return if not os.path.isfile(terms_file): # Create it. with open(terms_file, "wb") as f: self.show_info("Terminology file created.") self.terminology = terms_file self.ui.grpStep6.setEnabled(False) self.ui.btnFinish.setEnabled(True) ############################################################################## ### @fn accept() ### @desc Overrides the OK button. ############################################################################## def accept(self): # Save typing~ cfg = common.editor_config cfg.backup_dir = self.backup_dir cfg.changes_dir = self.changes_dir cfg.dupes_csv = os.path.join(self.editor_data_dir, DUPES_CSV) cfg.eboot_text = os.path.join(self.editor_data_dir, EBOOT_TEXT) cfg.gfx_dir = self.gfx_dir cfg.iso_dir = self.edited_iso_dir cfg.iso_file = os.path.join(self.workspace_dir, EDITED_ISO_FILE) cfg.similarity_db = os.path.join(self.editor_data_dir, SIMILARITY_DB) cfg.terminology = self.terminology cfg.umdimage_dir = self.umdimage_dir cfg.umdimage2_dir = self.umdimage2_dir cfg.voice_dir = self.voice_dir common.editor_config = cfg common.editor_config.save_config() super(SetupWizard, self).accept() ############################################################################## ### @fn reject() ### @desc Overrides the Cancel button. ############################################################################## def reject(self): super(SetupWizard, self).reject() if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app, QtCore.SLOT("quit()") ) form = SetupWizard() form.show() sys.exit(app.exec_()) ### EOF ###
# of the flash files we need in the gfx_base archive. So let's load that. with open(os.path.join(gfx_dir, "fla.txt"), "rb") as fla: fla_list = fla.readlines()
random_line_split
api.py
from .resources import ( AuthorResource, BookPrefixResource, ArticleResource, SomeOtherResource, CustomResource, CSVResource) from adrest.api import Api from adrest.utils.auth import AnonimousAuthenticator, AccessKeyAuthenticator, \ UserAuthenticator from adrest.utils.emitter import XMLTemplateEmitter, JSONEmitter from adrest.utils.throttle import CacheThrottle class
(UserAuthenticator): username_fieldname = 'nickname' API = Api( version=(1, 0, 0), emitters=(XMLTemplateEmitter, JSONEmitter), throttle=CacheThrottle, api_prefix='main') API.register(AuthorResource, authenticators=(CustomUserAuth, AnonimousAuthenticator)) API.register(BookPrefixResource) API.register(CustomResource) API.register(ArticleResource, authenticators=AccessKeyAuthenticator) API.register(SomeOtherResource, url_name='test', url_regex='test/mem/$') API.register(CSVResource) # lint_ignore=C
CustomUserAuth
identifier_name
api.py
from .resources import ( AuthorResource, BookPrefixResource, ArticleResource, SomeOtherResource, CustomResource, CSVResource) from adrest.api import Api from adrest.utils.auth import AnonimousAuthenticator, AccessKeyAuthenticator, \ UserAuthenticator from adrest.utils.emitter import XMLTemplateEmitter, JSONEmitter from adrest.utils.throttle import CacheThrottle class CustomUserAuth(UserAuthenticator):
API = Api( version=(1, 0, 0), emitters=(XMLTemplateEmitter, JSONEmitter), throttle=CacheThrottle, api_prefix='main') API.register(AuthorResource, authenticators=(CustomUserAuth, AnonimousAuthenticator)) API.register(BookPrefixResource) API.register(CustomResource) API.register(ArticleResource, authenticators=AccessKeyAuthenticator) API.register(SomeOtherResource, url_name='test', url_regex='test/mem/$') API.register(CSVResource) # lint_ignore=C
username_fieldname = 'nickname'
identifier_body
api.py
from .resources import ( AuthorResource, BookPrefixResource, ArticleResource, SomeOtherResource, CustomResource, CSVResource) from adrest.api import Api from adrest.utils.auth import AnonimousAuthenticator, AccessKeyAuthenticator, \ UserAuthenticator from adrest.utils.emitter import XMLTemplateEmitter, JSONEmitter from adrest.utils.throttle import CacheThrottle class CustomUserAuth(UserAuthenticator): username_fieldname = 'nickname' API = Api( version=(1, 0, 0), emitters=(XMLTemplateEmitter, JSONEmitter), throttle=CacheThrottle, api_prefix='main')
API.register(ArticleResource, authenticators=AccessKeyAuthenticator) API.register(SomeOtherResource, url_name='test', url_regex='test/mem/$') API.register(CSVResource) # lint_ignore=C
API.register(AuthorResource, authenticators=(CustomUserAuth, AnonimousAuthenticator)) API.register(BookPrefixResource) API.register(CustomResource)
random_line_split
run_trf_2.py
import os import sys import numpy as np import matplotlib.pyplot as plt sys.path.insert(0, os.getcwd() + '/../../tools/') import wb import trf import wer def process_nbest(fread, fwrite): nEmptySentNum = 0 with open(fread, 'rt') as f1, open(fwrite, 'wt') as f2: for a in [line.split() for line in f1]: if len(a) == 1: nEmptySentNum += 1 a.append('<UNK>') f2.write(' '.join(a) + '\n') print('[nbest] empty sentence num = {}'.format(nEmptySentNum)) def
(): if len(sys.argv) == 1: print('\"python run.py -train\" train LSTM\n', '\"python run.py -rescore\" rescore nbest\n', '\"python run.py -wer\" compute WER' ) bindir = '../../tools/trf/bin/' workdir = 'trflm/' fres = wb.FRes('models_ppl.txt') model = trf.model(bindir, workdir) nbest_root = 'data/nbest/' nbest_type_list = ['nbest_mvdr_single_heq_multi'] class_num = 200 train = workdir + 'train.id' valid = workdir + 'valid.id' test = workdir + 'test.id' vocab = workdir + 'vocab_c{}.list'.format(class_num) order = 4 feat = 'g4_w_c_ws_cs_wsh_csh_tied.fs' #feat = 'g4_w_c_ws_cs_wsh_csh.fs' maxlen = 0 tmax = 20000 t0 = 0 minibatch = 100 gamma_lambda = '3000,0' gamma_zeta = '0,0.6' reg = 1e-6 thread = 8 write_model = workdir + 'trf_c{}_{}_2'.format(class_num, feat[0:-3]) if '-train' in sys.argv or '-all' in sys.argv: config = '-vocab {} -train {} -valid {} -test {} '.format(vocab, train, valid, test) config += ' -read {}.model'.format(write_model[0:-2]) config += ' -order {} -feat {} '.format(order, feat) config += ' -len {} '.format(maxlen) config += ' -write {0}.model -log {0}.log '.format(write_model) config += ' -t0 {} -iter {}'.format(t0, tmax) config += ' -gamma-lambda {} -gamma-zeta {}'.format(gamma_lambda, gamma_zeta) config += ' -L2 {} '.format(reg) config += ' -mini-batch {} '.format(minibatch) config += ' -thread {} '.format(thread) config += ' -print-per-iter 10 ' config += ' -write-at-iter [{}:10000:{}]'.format(tmax-30000, tmax) # output the intermediate models model.prepare('data/train', 'data/valid', 'data/valid', class_num) model.train(config) if '-plot' in sys.argv: baseline = fres.Get('KN5') trf.PlotLog([write_model], [baseline]) if '-rescore' in sys.argv or '-all' in sys.argv: for nbest_type in nbest_type_list: nbest_dir = nbest_root + nbest_type + '/' for tsk in ['nbestlist_{}_{}'.format(a, b) for a in ['dt05', 'et05'] for b in ['real', 'simu']]: write_dir = workdir + nbest_type + '/' + tsk + '/' wb.mkdir(write_dir) print('{} : {}'.format(nbest_type, tsk)) print(' write -> {}'.format(write_dir)) write_lmscore = write_dir + os.path.split(write_model)[-1] # fill the empty lines process_nbest(nbest_dir + tsk + '/words_text', write_lmscore + '.nbest') config = ' -vocab {} '.format(vocab) config += ' -read {}.model '.format(write_model) config += ' -nbest {} '.format(write_lmscore + '.nbest') config += ' -lmscore {0}.lmscore -lmscore-test-id {0}.test-id '.format(write_lmscore) model.use(config) if '-wer' in sys.argv or '-all' in sys.argv: for nbest_type in nbest_type_list: nbest_dir = nbest_root + nbest_type + '/' lmpaths = {'KN5': nbest_dir + '<tsk>/lmwt.lmonly', 'RNN': nbest_dir + '<tsk>/lmwt.rnn', 'LSTM': 'lstm/' + nbest_type + '/<tsk>/lmwt.lstm', 'TRF': workdir + nbest_type + '/<tsk>/' + os.path.split(write_model)[-1] + '.lmscore'} # 'TRF': nbestdir + '<tsk>/lmwt.trf'} # lmtypes = ['LSTM', 'KN5', 'RNN', 'TRF', 'RNN+KN5', 'LSTM+KN5', 'RNN+TRF', 'LSTM+TRF'] lmtypes = ['TRF','RNN','KN5', 'RNN+TRF'] wer_workdir = 'wer/' + nbest_type + '/' print('wer_workdir = ' + wer_workdir) wer.wer_all(wer_workdir, nbest_dir, lmpaths, lmtypes) config = wer.wer_tune(wer_workdir) wer.wer_print(wer_workdir, config) if __name__ == '__main__': main()
main
identifier_name
run_trf_2.py
import os import sys import numpy as np import matplotlib.pyplot as plt sys.path.insert(0, os.getcwd() + '/../../tools/') import wb import trf import wer def process_nbest(fread, fwrite): nEmptySentNum = 0 with open(fread, 'rt') as f1, open(fwrite, 'wt') as f2: for a in [line.split() for line in f1]: if len(a) == 1: nEmptySentNum += 1 a.append('<UNK>') f2.write(' '.join(a) + '\n') print('[nbest] empty sentence num = {}'.format(nEmptySentNum)) def main():
if __name__ == '__main__': main()
if len(sys.argv) == 1: print('\"python run.py -train\" train LSTM\n', '\"python run.py -rescore\" rescore nbest\n', '\"python run.py -wer\" compute WER' ) bindir = '../../tools/trf/bin/' workdir = 'trflm/' fres = wb.FRes('models_ppl.txt') model = trf.model(bindir, workdir) nbest_root = 'data/nbest/' nbest_type_list = ['nbest_mvdr_single_heq_multi'] class_num = 200 train = workdir + 'train.id' valid = workdir + 'valid.id' test = workdir + 'test.id' vocab = workdir + 'vocab_c{}.list'.format(class_num) order = 4 feat = 'g4_w_c_ws_cs_wsh_csh_tied.fs' #feat = 'g4_w_c_ws_cs_wsh_csh.fs' maxlen = 0 tmax = 20000 t0 = 0 minibatch = 100 gamma_lambda = '3000,0' gamma_zeta = '0,0.6' reg = 1e-6 thread = 8 write_model = workdir + 'trf_c{}_{}_2'.format(class_num, feat[0:-3]) if '-train' in sys.argv or '-all' in sys.argv: config = '-vocab {} -train {} -valid {} -test {} '.format(vocab, train, valid, test) config += ' -read {}.model'.format(write_model[0:-2]) config += ' -order {} -feat {} '.format(order, feat) config += ' -len {} '.format(maxlen) config += ' -write {0}.model -log {0}.log '.format(write_model) config += ' -t0 {} -iter {}'.format(t0, tmax) config += ' -gamma-lambda {} -gamma-zeta {}'.format(gamma_lambda, gamma_zeta) config += ' -L2 {} '.format(reg) config += ' -mini-batch {} '.format(minibatch) config += ' -thread {} '.format(thread) config += ' -print-per-iter 10 ' config += ' -write-at-iter [{}:10000:{}]'.format(tmax-30000, tmax) # output the intermediate models model.prepare('data/train', 'data/valid', 'data/valid', class_num) model.train(config) if '-plot' in sys.argv: baseline = fres.Get('KN5') trf.PlotLog([write_model], [baseline]) if '-rescore' in sys.argv or '-all' in sys.argv: for nbest_type in nbest_type_list: nbest_dir = nbest_root + nbest_type + '/' for tsk in ['nbestlist_{}_{}'.format(a, b) for a in ['dt05', 'et05'] for b in ['real', 'simu']]: write_dir = workdir + nbest_type + '/' + tsk + '/' wb.mkdir(write_dir) print('{} : {}'.format(nbest_type, tsk)) print(' write -> {}'.format(write_dir)) write_lmscore = write_dir + os.path.split(write_model)[-1] # fill the empty lines process_nbest(nbest_dir + tsk + '/words_text', write_lmscore + '.nbest') config = ' -vocab {} '.format(vocab) config += ' -read {}.model '.format(write_model) config += ' -nbest {} '.format(write_lmscore + '.nbest') config += ' -lmscore {0}.lmscore -lmscore-test-id {0}.test-id '.format(write_lmscore) model.use(config) if '-wer' in sys.argv or '-all' in sys.argv: for nbest_type in nbest_type_list: nbest_dir = nbest_root + nbest_type + '/' lmpaths = {'KN5': nbest_dir + '<tsk>/lmwt.lmonly', 'RNN': nbest_dir + '<tsk>/lmwt.rnn', 'LSTM': 'lstm/' + nbest_type + '/<tsk>/lmwt.lstm', 'TRF': workdir + nbest_type + '/<tsk>/' + os.path.split(write_model)[-1] + '.lmscore'} # 'TRF': nbestdir + '<tsk>/lmwt.trf'} # lmtypes = ['LSTM', 'KN5', 'RNN', 'TRF', 'RNN+KN5', 'LSTM+KN5', 'RNN+TRF', 'LSTM+TRF'] lmtypes = ['TRF','RNN','KN5', 'RNN+TRF'] wer_workdir = 'wer/' + nbest_type + '/' print('wer_workdir = ' + wer_workdir) wer.wer_all(wer_workdir, nbest_dir, lmpaths, lmtypes) config = wer.wer_tune(wer_workdir) wer.wer_print(wer_workdir, config)
identifier_body
run_trf_2.py
import os import sys import numpy as np import matplotlib.pyplot as plt sys.path.insert(0, os.getcwd() + '/../../tools/') import wb import trf import wer def process_nbest(fread, fwrite): nEmptySentNum = 0 with open(fread, 'rt') as f1, open(fwrite, 'wt') as f2: for a in [line.split() for line in f1]: if len(a) == 1:
f2.write(' '.join(a) + '\n') print('[nbest] empty sentence num = {}'.format(nEmptySentNum)) def main(): if len(sys.argv) == 1: print('\"python run.py -train\" train LSTM\n', '\"python run.py -rescore\" rescore nbest\n', '\"python run.py -wer\" compute WER' ) bindir = '../../tools/trf/bin/' workdir = 'trflm/' fres = wb.FRes('models_ppl.txt') model = trf.model(bindir, workdir) nbest_root = 'data/nbest/' nbest_type_list = ['nbest_mvdr_single_heq_multi'] class_num = 200 train = workdir + 'train.id' valid = workdir + 'valid.id' test = workdir + 'test.id' vocab = workdir + 'vocab_c{}.list'.format(class_num) order = 4 feat = 'g4_w_c_ws_cs_wsh_csh_tied.fs' #feat = 'g4_w_c_ws_cs_wsh_csh.fs' maxlen = 0 tmax = 20000 t0 = 0 minibatch = 100 gamma_lambda = '3000,0' gamma_zeta = '0,0.6' reg = 1e-6 thread = 8 write_model = workdir + 'trf_c{}_{}_2'.format(class_num, feat[0:-3]) if '-train' in sys.argv or '-all' in sys.argv: config = '-vocab {} -train {} -valid {} -test {} '.format(vocab, train, valid, test) config += ' -read {}.model'.format(write_model[0:-2]) config += ' -order {} -feat {} '.format(order, feat) config += ' -len {} '.format(maxlen) config += ' -write {0}.model -log {0}.log '.format(write_model) config += ' -t0 {} -iter {}'.format(t0, tmax) config += ' -gamma-lambda {} -gamma-zeta {}'.format(gamma_lambda, gamma_zeta) config += ' -L2 {} '.format(reg) config += ' -mini-batch {} '.format(minibatch) config += ' -thread {} '.format(thread) config += ' -print-per-iter 10 ' config += ' -write-at-iter [{}:10000:{}]'.format(tmax-30000, tmax) # output the intermediate models model.prepare('data/train', 'data/valid', 'data/valid', class_num) model.train(config) if '-plot' in sys.argv: baseline = fres.Get('KN5') trf.PlotLog([write_model], [baseline]) if '-rescore' in sys.argv or '-all' in sys.argv: for nbest_type in nbest_type_list: nbest_dir = nbest_root + nbest_type + '/' for tsk in ['nbestlist_{}_{}'.format(a, b) for a in ['dt05', 'et05'] for b in ['real', 'simu']]: write_dir = workdir + nbest_type + '/' + tsk + '/' wb.mkdir(write_dir) print('{} : {}'.format(nbest_type, tsk)) print(' write -> {}'.format(write_dir)) write_lmscore = write_dir + os.path.split(write_model)[-1] # fill the empty lines process_nbest(nbest_dir + tsk + '/words_text', write_lmscore + '.nbest') config = ' -vocab {} '.format(vocab) config += ' -read {}.model '.format(write_model) config += ' -nbest {} '.format(write_lmscore + '.nbest') config += ' -lmscore {0}.lmscore -lmscore-test-id {0}.test-id '.format(write_lmscore) model.use(config) if '-wer' in sys.argv or '-all' in sys.argv: for nbest_type in nbest_type_list: nbest_dir = nbest_root + nbest_type + '/' lmpaths = {'KN5': nbest_dir + '<tsk>/lmwt.lmonly', 'RNN': nbest_dir + '<tsk>/lmwt.rnn', 'LSTM': 'lstm/' + nbest_type + '/<tsk>/lmwt.lstm', 'TRF': workdir + nbest_type + '/<tsk>/' + os.path.split(write_model)[-1] + '.lmscore'} # 'TRF': nbestdir + '<tsk>/lmwt.trf'} # lmtypes = ['LSTM', 'KN5', 'RNN', 'TRF', 'RNN+KN5', 'LSTM+KN5', 'RNN+TRF', 'LSTM+TRF'] lmtypes = ['TRF','RNN','KN5', 'RNN+TRF'] wer_workdir = 'wer/' + nbest_type + '/' print('wer_workdir = ' + wer_workdir) wer.wer_all(wer_workdir, nbest_dir, lmpaths, lmtypes) config = wer.wer_tune(wer_workdir) wer.wer_print(wer_workdir, config) if __name__ == '__main__': main()
nEmptySentNum += 1 a.append('<UNK>')
conditional_block
run_trf_2.py
import os import sys import numpy as np import matplotlib.pyplot as plt sys.path.insert(0, os.getcwd() + '/../../tools/') import wb import trf import wer def process_nbest(fread, fwrite): nEmptySentNum = 0 with open(fread, 'rt') as f1, open(fwrite, 'wt') as f2: for a in [line.split() for line in f1]: if len(a) == 1: nEmptySentNum += 1 a.append('<UNK>') f2.write(' '.join(a) + '\n') print('[nbest] empty sentence num = {}'.format(nEmptySentNum)) def main(): if len(sys.argv) == 1: print('\"python run.py -train\" train LSTM\n', '\"python run.py -rescore\" rescore nbest\n', '\"python run.py -wer\" compute WER' ) bindir = '../../tools/trf/bin/' workdir = 'trflm/' fres = wb.FRes('models_ppl.txt') model = trf.model(bindir, workdir) nbest_root = 'data/nbest/' nbest_type_list = ['nbest_mvdr_single_heq_multi'] class_num = 200 train = workdir + 'train.id' valid = workdir + 'valid.id' test = workdir + 'test.id' vocab = workdir + 'vocab_c{}.list'.format(class_num) order = 4 feat = 'g4_w_c_ws_cs_wsh_csh_tied.fs' #feat = 'g4_w_c_ws_cs_wsh_csh.fs' maxlen = 0 tmax = 20000 t0 = 0 minibatch = 100 gamma_lambda = '3000,0' gamma_zeta = '0,0.6' reg = 1e-6 thread = 8 write_model = workdir + 'trf_c{}_{}_2'.format(class_num, feat[0:-3]) if '-train' in sys.argv or '-all' in sys.argv: config = '-vocab {} -train {} -valid {} -test {} '.format(vocab, train, valid, test) config += ' -read {}.model'.format(write_model[0:-2]) config += ' -order {} -feat {} '.format(order, feat) config += ' -len {} '.format(maxlen) config += ' -write {0}.model -log {0}.log '.format(write_model) config += ' -t0 {} -iter {}'.format(t0, tmax) config += ' -gamma-lambda {} -gamma-zeta {}'.format(gamma_lambda, gamma_zeta) config += ' -L2 {} '.format(reg) config += ' -mini-batch {} '.format(minibatch) config += ' -thread {} '.format(thread) config += ' -print-per-iter 10 ' config += ' -write-at-iter [{}:10000:{}]'.format(tmax-30000, tmax) # output the intermediate models model.prepare('data/train', 'data/valid', 'data/valid', class_num) model.train(config) if '-plot' in sys.argv: baseline = fres.Get('KN5') trf.PlotLog([write_model], [baseline]) if '-rescore' in sys.argv or '-all' in sys.argv: for nbest_type in nbest_type_list: nbest_dir = nbest_root + nbest_type + '/' for tsk in ['nbestlist_{}_{}'.format(a, b) for a in ['dt05', 'et05'] for b in ['real', 'simu']]: write_dir = workdir + nbest_type + '/' + tsk + '/' wb.mkdir(write_dir) print('{} : {}'.format(nbest_type, tsk)) print(' write -> {}'.format(write_dir)) write_lmscore = write_dir + os.path.split(write_model)[-1] # fill the empty lines process_nbest(nbest_dir + tsk + '/words_text', write_lmscore + '.nbest') config = ' -vocab {} '.format(vocab) config += ' -read {}.model '.format(write_model) config += ' -nbest {} '.format(write_lmscore + '.nbest') config += ' -lmscore {0}.lmscore -lmscore-test-id {0}.test-id '.format(write_lmscore) model.use(config) if '-wer' in sys.argv or '-all' in sys.argv: for nbest_type in nbest_type_list: nbest_dir = nbest_root + nbest_type + '/' lmpaths = {'KN5': nbest_dir + '<tsk>/lmwt.lmonly', 'RNN': nbest_dir + '<tsk>/lmwt.rnn', 'LSTM': 'lstm/' + nbest_type + '/<tsk>/lmwt.lstm', 'TRF': workdir + nbest_type + '/<tsk>/' + os.path.split(write_model)[-1] + '.lmscore'} # 'TRF': nbestdir + '<tsk>/lmwt.trf'} # lmtypes = ['LSTM', 'KN5', 'RNN', 'TRF', 'RNN+KN5', 'LSTM+KN5', 'RNN+TRF', 'LSTM+TRF'] lmtypes = ['TRF','RNN','KN5', 'RNN+TRF'] wer_workdir = 'wer/' + nbest_type + '/' print('wer_workdir = ' + wer_workdir) wer.wer_all(wer_workdir, nbest_dir, lmpaths, lmtypes) config = wer.wer_tune(wer_workdir) wer.wer_print(wer_workdir, config)
if __name__ == '__main__': main()
random_line_split
termactions.py
import lxml from lxml.etree import ( XPath, ) from lxml.cssselect import CSSSelector import re from .utils import ( raise_again, generic_translator, preprocess_selector, ) class BaseTermAction(object): in_type = None out_type = None @staticmethod def _check_types_match(t1, t2): return (t1 is None) or (t2 is None) or (t1 == t2) def can_precede(self, other): return BaseTermAction._check_types_match(self.out_type, other.in_type) def can_follow(self, other): return BaseTermAction._check_types_match(self.in_type, other.out_type) def execute(self, value): pass class GenericTermAction(BaseTermAction): def __init__(self, f, in_type=None, out_type=None, args=None, identification=None): self._f = f self._id = identification self.in_type = in_type self.out_type = out_type if args is None: args = [] self._args = list(args) def sub_execute(self, value): return self._f(value, *self._args) def execute(self, value): try: return self.sub_execute(value) except Exception as e: raise_again('%s: %s' % (self._id, e)) class GenericSelectorTermAction(GenericTermAction): def __init__(self, f, selector, in_type=None, out_type=None, identification=None, args=None): super(GenericSelectorTermAction, self).__init__(f, in_type=in_type, out_type=out_type, identification=identification, args=args) self._selector = selector def sub_execute(self, value): return self._f(value, self._selector, *self._args) class AnchorTermAction(BaseTermAction): in_type = 'context' # out_type is set at instantiation, since it can vary def __init__(self, anchor, out_type, identification=None): self._anchor = anchor self._id = identification self.out_type = out_type def execute(self, context): # value must be a context return context.get_anchor(self._anchor) class RegexTermAction(BaseTermAction): in_type = 'string' out_type = 'string' char_to_flag = { 'i': re.IGNORECASE, 'l': re.LOCALE, 'm': re.MULTILINE, 's': re.DOTALL, 'u': re.UNICODE, } allowed_flags = frozenset(char_to_flag.keys() + ['g', 'f']) def __init__(self, args, identification=None): self._id = identification if len(args) < 2 or len(args) > 3: raise ValueError("Invalid number of arguments for 'resub'!") self._replace = args[1] if len(args) == 3:
else: sflags = '' (self._count, flags) = self._handle_flags(sflags) self._re = re.compile(args[0], flags=flags) def _handle_flags(self, flags): flags = set(flags) bflags = 0 if not flags <= self.allowed_flags: raise ValueError("Unknown flags: '%s'!" % (''.join(list(flags - self.allowed_flags)),)) for (k, f) in self.char_to_flag.items(): if k in flags: bflags |= f if 'g' in flags and 'f' in flags: raise ValueError("Only one of 'g' and 'f' is allowed!") count = 0 if 'f' in flags: count = 1 return (count, bflags) def execute(self, value): return self._re.sub(self._replace, value, count=self._count) def make_action_of_class(cls, f, in_type, out_type): def builder(identification, args): return cls(f, in_type=in_type, out_type=out_type, identification=identification, args=args) return builder def make_generic_action(f, in_type, out_type): return make_action_of_class(GenericTermAction, f, in_type, out_type) def make_custom_selector_action(f, selector_ctor, in_type, out_type): def builder(identification, args): selector = selector_ctor(preprocess_selector(args[0])) args = args[1:] return GenericSelectorTermAction(f, selector, in_type=in_type, out_type=out_type, identification=identification, args=args) return builder def make_selector_action(f, in_type, out_type): return make_custom_selector_action(f, CSSSelector, in_type, out_type) def make_axis_selector_action(f, axis, in_type, out_type): return make_custom_selector_action(f, lambda spec: XPath(generic_translator.css_to_xpath(spec, prefix=axis)), in_type, out_type)
sflags = args[2]
conditional_block
termactions.py
import lxml from lxml.etree import ( XPath, ) from lxml.cssselect import CSSSelector import re from .utils import ( raise_again, generic_translator, preprocess_selector, ) class BaseTermAction(object): in_type = None out_type = None @staticmethod def _check_types_match(t1, t2): return (t1 is None) or (t2 is None) or (t1 == t2) def can_precede(self, other): return BaseTermAction._check_types_match(self.out_type, other.in_type) def can_follow(self, other): return BaseTermAction._check_types_match(self.in_type, other.out_type) def execute(self, value): pass class GenericTermAction(BaseTermAction):
class GenericSelectorTermAction(GenericTermAction): def __init__(self, f, selector, in_type=None, out_type=None, identification=None, args=None): super(GenericSelectorTermAction, self).__init__(f, in_type=in_type, out_type=out_type, identification=identification, args=args) self._selector = selector def sub_execute(self, value): return self._f(value, self._selector, *self._args) class AnchorTermAction(BaseTermAction): in_type = 'context' # out_type is set at instantiation, since it can vary def __init__(self, anchor, out_type, identification=None): self._anchor = anchor self._id = identification self.out_type = out_type def execute(self, context): # value must be a context return context.get_anchor(self._anchor) class RegexTermAction(BaseTermAction): in_type = 'string' out_type = 'string' char_to_flag = { 'i': re.IGNORECASE, 'l': re.LOCALE, 'm': re.MULTILINE, 's': re.DOTALL, 'u': re.UNICODE, } allowed_flags = frozenset(char_to_flag.keys() + ['g', 'f']) def __init__(self, args, identification=None): self._id = identification if len(args) < 2 or len(args) > 3: raise ValueError("Invalid number of arguments for 'resub'!") self._replace = args[1] if len(args) == 3: sflags = args[2] else: sflags = '' (self._count, flags) = self._handle_flags(sflags) self._re = re.compile(args[0], flags=flags) def _handle_flags(self, flags): flags = set(flags) bflags = 0 if not flags <= self.allowed_flags: raise ValueError("Unknown flags: '%s'!" % (''.join(list(flags - self.allowed_flags)),)) for (k, f) in self.char_to_flag.items(): if k in flags: bflags |= f if 'g' in flags and 'f' in flags: raise ValueError("Only one of 'g' and 'f' is allowed!") count = 0 if 'f' in flags: count = 1 return (count, bflags) def execute(self, value): return self._re.sub(self._replace, value, count=self._count) def make_action_of_class(cls, f, in_type, out_type): def builder(identification, args): return cls(f, in_type=in_type, out_type=out_type, identification=identification, args=args) return builder def make_generic_action(f, in_type, out_type): return make_action_of_class(GenericTermAction, f, in_type, out_type) def make_custom_selector_action(f, selector_ctor, in_type, out_type): def builder(identification, args): selector = selector_ctor(preprocess_selector(args[0])) args = args[1:] return GenericSelectorTermAction(f, selector, in_type=in_type, out_type=out_type, identification=identification, args=args) return builder def make_selector_action(f, in_type, out_type): return make_custom_selector_action(f, CSSSelector, in_type, out_type) def make_axis_selector_action(f, axis, in_type, out_type): return make_custom_selector_action(f, lambda spec: XPath(generic_translator.css_to_xpath(spec, prefix=axis)), in_type, out_type)
def __init__(self, f, in_type=None, out_type=None, args=None, identification=None): self._f = f self._id = identification self.in_type = in_type self.out_type = out_type if args is None: args = [] self._args = list(args) def sub_execute(self, value): return self._f(value, *self._args) def execute(self, value): try: return self.sub_execute(value) except Exception as e: raise_again('%s: %s' % (self._id, e))
identifier_body
termactions.py
import lxml from lxml.etree import ( XPath, ) from lxml.cssselect import CSSSelector import re from .utils import (
class BaseTermAction(object): in_type = None out_type = None @staticmethod def _check_types_match(t1, t2): return (t1 is None) or (t2 is None) or (t1 == t2) def can_precede(self, other): return BaseTermAction._check_types_match(self.out_type, other.in_type) def can_follow(self, other): return BaseTermAction._check_types_match(self.in_type, other.out_type) def execute(self, value): pass class GenericTermAction(BaseTermAction): def __init__(self, f, in_type=None, out_type=None, args=None, identification=None): self._f = f self._id = identification self.in_type = in_type self.out_type = out_type if args is None: args = [] self._args = list(args) def sub_execute(self, value): return self._f(value, *self._args) def execute(self, value): try: return self.sub_execute(value) except Exception as e: raise_again('%s: %s' % (self._id, e)) class GenericSelectorTermAction(GenericTermAction): def __init__(self, f, selector, in_type=None, out_type=None, identification=None, args=None): super(GenericSelectorTermAction, self).__init__(f, in_type=in_type, out_type=out_type, identification=identification, args=args) self._selector = selector def sub_execute(self, value): return self._f(value, self._selector, *self._args) class AnchorTermAction(BaseTermAction): in_type = 'context' # out_type is set at instantiation, since it can vary def __init__(self, anchor, out_type, identification=None): self._anchor = anchor self._id = identification self.out_type = out_type def execute(self, context): # value must be a context return context.get_anchor(self._anchor) class RegexTermAction(BaseTermAction): in_type = 'string' out_type = 'string' char_to_flag = { 'i': re.IGNORECASE, 'l': re.LOCALE, 'm': re.MULTILINE, 's': re.DOTALL, 'u': re.UNICODE, } allowed_flags = frozenset(char_to_flag.keys() + ['g', 'f']) def __init__(self, args, identification=None): self._id = identification if len(args) < 2 or len(args) > 3: raise ValueError("Invalid number of arguments for 'resub'!") self._replace = args[1] if len(args) == 3: sflags = args[2] else: sflags = '' (self._count, flags) = self._handle_flags(sflags) self._re = re.compile(args[0], flags=flags) def _handle_flags(self, flags): flags = set(flags) bflags = 0 if not flags <= self.allowed_flags: raise ValueError("Unknown flags: '%s'!" % (''.join(list(flags - self.allowed_flags)),)) for (k, f) in self.char_to_flag.items(): if k in flags: bflags |= f if 'g' in flags and 'f' in flags: raise ValueError("Only one of 'g' and 'f' is allowed!") count = 0 if 'f' in flags: count = 1 return (count, bflags) def execute(self, value): return self._re.sub(self._replace, value, count=self._count) def make_action_of_class(cls, f, in_type, out_type): def builder(identification, args): return cls(f, in_type=in_type, out_type=out_type, identification=identification, args=args) return builder def make_generic_action(f, in_type, out_type): return make_action_of_class(GenericTermAction, f, in_type, out_type) def make_custom_selector_action(f, selector_ctor, in_type, out_type): def builder(identification, args): selector = selector_ctor(preprocess_selector(args[0])) args = args[1:] return GenericSelectorTermAction(f, selector, in_type=in_type, out_type=out_type, identification=identification, args=args) return builder def make_selector_action(f, in_type, out_type): return make_custom_selector_action(f, CSSSelector, in_type, out_type) def make_axis_selector_action(f, axis, in_type, out_type): return make_custom_selector_action(f, lambda spec: XPath(generic_translator.css_to_xpath(spec, prefix=axis)), in_type, out_type)
raise_again, generic_translator, preprocess_selector, )
random_line_split
termactions.py
import lxml from lxml.etree import ( XPath, ) from lxml.cssselect import CSSSelector import re from .utils import ( raise_again, generic_translator, preprocess_selector, ) class BaseTermAction(object): in_type = None out_type = None @staticmethod def _check_types_match(t1, t2): return (t1 is None) or (t2 is None) or (t1 == t2) def can_precede(self, other): return BaseTermAction._check_types_match(self.out_type, other.in_type) def can_follow(self, other): return BaseTermAction._check_types_match(self.in_type, other.out_type) def execute(self, value): pass class GenericTermAction(BaseTermAction): def __init__(self, f, in_type=None, out_type=None, args=None, identification=None): self._f = f self._id = identification self.in_type = in_type self.out_type = out_type if args is None: args = [] self._args = list(args) def sub_execute(self, value): return self._f(value, *self._args) def execute(self, value): try: return self.sub_execute(value) except Exception as e: raise_again('%s: %s' % (self._id, e)) class GenericSelectorTermAction(GenericTermAction): def __init__(self, f, selector, in_type=None, out_type=None, identification=None, args=None): super(GenericSelectorTermAction, self).__init__(f, in_type=in_type, out_type=out_type, identification=identification, args=args) self._selector = selector def sub_execute(self, value): return self._f(value, self._selector, *self._args) class AnchorTermAction(BaseTermAction): in_type = 'context' # out_type is set at instantiation, since it can vary def
(self, anchor, out_type, identification=None): self._anchor = anchor self._id = identification self.out_type = out_type def execute(self, context): # value must be a context return context.get_anchor(self._anchor) class RegexTermAction(BaseTermAction): in_type = 'string' out_type = 'string' char_to_flag = { 'i': re.IGNORECASE, 'l': re.LOCALE, 'm': re.MULTILINE, 's': re.DOTALL, 'u': re.UNICODE, } allowed_flags = frozenset(char_to_flag.keys() + ['g', 'f']) def __init__(self, args, identification=None): self._id = identification if len(args) < 2 or len(args) > 3: raise ValueError("Invalid number of arguments for 'resub'!") self._replace = args[1] if len(args) == 3: sflags = args[2] else: sflags = '' (self._count, flags) = self._handle_flags(sflags) self._re = re.compile(args[0], flags=flags) def _handle_flags(self, flags): flags = set(flags) bflags = 0 if not flags <= self.allowed_flags: raise ValueError("Unknown flags: '%s'!" % (''.join(list(flags - self.allowed_flags)),)) for (k, f) in self.char_to_flag.items(): if k in flags: bflags |= f if 'g' in flags and 'f' in flags: raise ValueError("Only one of 'g' and 'f' is allowed!") count = 0 if 'f' in flags: count = 1 return (count, bflags) def execute(self, value): return self._re.sub(self._replace, value, count=self._count) def make_action_of_class(cls, f, in_type, out_type): def builder(identification, args): return cls(f, in_type=in_type, out_type=out_type, identification=identification, args=args) return builder def make_generic_action(f, in_type, out_type): return make_action_of_class(GenericTermAction, f, in_type, out_type) def make_custom_selector_action(f, selector_ctor, in_type, out_type): def builder(identification, args): selector = selector_ctor(preprocess_selector(args[0])) args = args[1:] return GenericSelectorTermAction(f, selector, in_type=in_type, out_type=out_type, identification=identification, args=args) return builder def make_selector_action(f, in_type, out_type): return make_custom_selector_action(f, CSSSelector, in_type, out_type) def make_axis_selector_action(f, axis, in_type, out_type): return make_custom_selector_action(f, lambda spec: XPath(generic_translator.css_to_xpath(spec, prefix=axis)), in_type, out_type)
__init__
identifier_name
execute-1.py
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2014-2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import os, sys, traceback import IECore import Gaffer class execute( Gaffer.Application ) : def
( self ) : Gaffer.Application.__init__( self, """ Executes task nodes such as ImageWriters, SystemCommands and Render nodes from within a .gfr file. This is used by Gaffer's dispatchers when executing nodes in a background process or on a render farm, but can also be used to perform a manual execution from the command line. Example usage : ``` gaffer execute -script comp.gfr -nodes ImageWriter -frames 1-10 ``` """ ) self.parameters().addParameters( [ IECore.FileNameParameter( name = "script", description = "The script to execute.", defaultValue = "", allowEmptyString = False, extensions = "gfr", check = IECore.FileNameParameter.CheckType.MustExist, ), IECore.BoolParameter( name = "ignoreScriptLoadErrors", description = "Causes errors which occur while loading the script " "to be ignored. Not recommended.", defaultValue = False, ), IECore.StringVectorParameter( name = "nodes", description = "The names of the nodes to execute. If not specified " "then all executable nodes will be found automatically.", defaultValue = IECore.StringVectorData( [] ), ), IECore.FrameListParameter( name = "frames", description = "The frames to execute.", defaultValue = "1", allowEmptyList = False, ), IECore.StringVectorParameter( name = "context", description = "The context used during execution. Note that the frames " "parameter will be used to vary the context frame entry.", defaultValue = IECore.StringVectorData( [] ), userData = { "parser" : { "acceptFlags" : IECore.BoolData( True ), }, }, ), ] ) self.parameters().userData()["parser"] = IECore.CompoundObject( { "flagless" : IECore.StringVectorData( [ "script" ] ) } ) def _run( self, args ) : scriptNode = Gaffer.ScriptNode() scriptNode["fileName"].setValue( os.path.abspath( args["script"].value ) ) try : scriptNode.load( continueOnError = args["ignoreScriptLoadErrors"].value ) except Exception as exception : IECore.msg( IECore.Msg.Level.Error, "gaffer execute : loading \"%s\"" % scriptNode["fileName"].getValue(), str( exception ) ) return 1 self.root()["scripts"].addChild( scriptNode ) nodes = [] if len( args["nodes"] ) : for nodeName in args["nodes"] : node = scriptNode.descendant( nodeName ) if node is None : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Node \"%s\" does not exist" % nodeName ) return 1 if not hasattr( node, "execute" ) : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Node \"%s\" is not executable" % nodeName ) return 1 nodes.append( node ) else : for node in scriptNode.children() : if hasattr( node, "execute" ) : nodes.append( node ) if not nodes : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Script has no executable nodes" ) return 1 if len(args["context"]) % 2 : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Context parameter must have matching entry/value pairs" ) return 1 context = Gaffer.Context( scriptNode.context() ) for i in range( 0, len(args["context"]), 2 ) : entry = args["context"][i].lstrip( "-" ) context[entry] = eval( args["context"][i+1] ) frames = self.parameters()["frames"].getFrameListValue().asList() with context : for node in nodes : try : node["task"].executeSequence( frames ) except Exception as exception : IECore.msg( IECore.Msg.Level.Debug, "gaffer execute : executing %s" % node.relativeName( scriptNode ), "".join( traceback.format_exception( *sys.exc_info() ) ), ) IECore.msg( IECore.Msg.Level.Error, "gaffer execute : executing %s" % node.relativeName( scriptNode ), "".join( traceback.format_exception_only( *sys.exc_info()[:2] ) ), ) return 1 return 0 IECore.registerRunTimeTyped( execute )
__init__
identifier_name
execute-1.py
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2014-2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import os, sys, traceback import IECore import Gaffer class execute( Gaffer.Application ) : def __init__( self ) : Gaffer.Application.__init__( self, """ Executes task nodes such as ImageWriters, SystemCommands and Render nodes from within a .gfr file. This is used by Gaffer's dispatchers when executing nodes in a background process or on a render farm, but can also be used to perform a manual execution from the command line. Example usage : ``` gaffer execute -script comp.gfr -nodes ImageWriter -frames 1-10 ``` """ ) self.parameters().addParameters( [ IECore.FileNameParameter( name = "script", description = "The script to execute.", defaultValue = "", allowEmptyString = False, extensions = "gfr", check = IECore.FileNameParameter.CheckType.MustExist, ), IECore.BoolParameter( name = "ignoreScriptLoadErrors", description = "Causes errors which occur while loading the script " "to be ignored. Not recommended.", defaultValue = False, ), IECore.StringVectorParameter( name = "nodes", description = "The names of the nodes to execute. If not specified " "then all executable nodes will be found automatically.", defaultValue = IECore.StringVectorData( [] ), ), IECore.FrameListParameter( name = "frames", description = "The frames to execute.", defaultValue = "1", allowEmptyList = False, ), IECore.StringVectorParameter( name = "context", description = "The context used during execution. Note that the frames " "parameter will be used to vary the context frame entry.", defaultValue = IECore.StringVectorData( [] ), userData = { "parser" : { "acceptFlags" : IECore.BoolData( True ), }, }, ), ] ) self.parameters().userData()["parser"] = IECore.CompoundObject( { "flagless" : IECore.StringVectorData( [ "script" ] ) } ) def _run( self, args ) :
IECore.registerRunTimeTyped( execute )
scriptNode = Gaffer.ScriptNode() scriptNode["fileName"].setValue( os.path.abspath( args["script"].value ) ) try : scriptNode.load( continueOnError = args["ignoreScriptLoadErrors"].value ) except Exception as exception : IECore.msg( IECore.Msg.Level.Error, "gaffer execute : loading \"%s\"" % scriptNode["fileName"].getValue(), str( exception ) ) return 1 self.root()["scripts"].addChild( scriptNode ) nodes = [] if len( args["nodes"] ) : for nodeName in args["nodes"] : node = scriptNode.descendant( nodeName ) if node is None : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Node \"%s\" does not exist" % nodeName ) return 1 if not hasattr( node, "execute" ) : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Node \"%s\" is not executable" % nodeName ) return 1 nodes.append( node ) else : for node in scriptNode.children() : if hasattr( node, "execute" ) : nodes.append( node ) if not nodes : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Script has no executable nodes" ) return 1 if len(args["context"]) % 2 : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Context parameter must have matching entry/value pairs" ) return 1 context = Gaffer.Context( scriptNode.context() ) for i in range( 0, len(args["context"]), 2 ) : entry = args["context"][i].lstrip( "-" ) context[entry] = eval( args["context"][i+1] ) frames = self.parameters()["frames"].getFrameListValue().asList() with context : for node in nodes : try : node["task"].executeSequence( frames ) except Exception as exception : IECore.msg( IECore.Msg.Level.Debug, "gaffer execute : executing %s" % node.relativeName( scriptNode ), "".join( traceback.format_exception( *sys.exc_info() ) ), ) IECore.msg( IECore.Msg.Level.Error, "gaffer execute : executing %s" % node.relativeName( scriptNode ), "".join( traceback.format_exception_only( *sys.exc_info()[:2] ) ), ) return 1 return 0
identifier_body
execute-1.py
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2014-2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import os, sys, traceback import IECore import Gaffer class execute( Gaffer.Application ) : def __init__( self ) : Gaffer.Application.__init__( self, """ Executes task nodes such as ImageWriters, SystemCommands and Render nodes from within a .gfr file. This is used by Gaffer's dispatchers when executing nodes in a background process or on a render farm, but can also be used to perform a manual execution from the command line. Example usage : ``` gaffer execute -script comp.gfr -nodes ImageWriter -frames 1-10 ``` """ ) self.parameters().addParameters( [ IECore.FileNameParameter( name = "script", description = "The script to execute.", defaultValue = "", allowEmptyString = False, extensions = "gfr", check = IECore.FileNameParameter.CheckType.MustExist, ), IECore.BoolParameter( name = "ignoreScriptLoadErrors", description = "Causes errors which occur while loading the script " "to be ignored. Not recommended.", defaultValue = False, ), IECore.StringVectorParameter( name = "nodes", description = "The names of the nodes to execute. If not specified " "then all executable nodes will be found automatically.", defaultValue = IECore.StringVectorData( [] ), ), IECore.FrameListParameter( name = "frames", description = "The frames to execute.", defaultValue = "1", allowEmptyList = False, ), IECore.StringVectorParameter( name = "context", description = "The context used during execution. Note that the frames " "parameter will be used to vary the context frame entry.", defaultValue = IECore.StringVectorData( [] ), userData = { "parser" : { "acceptFlags" : IECore.BoolData( True ), }, }, ), ] ) self.parameters().userData()["parser"] = IECore.CompoundObject( { "flagless" : IECore.StringVectorData( [ "script" ] ) } ) def _run( self, args ) : scriptNode = Gaffer.ScriptNode() scriptNode["fileName"].setValue( os.path.abspath( args["script"].value ) ) try : scriptNode.load( continueOnError = args["ignoreScriptLoadErrors"].value ) except Exception as exception : IECore.msg( IECore.Msg.Level.Error, "gaffer execute : loading \"%s\"" % scriptNode["fileName"].getValue(), str( exception ) ) return 1 self.root()["scripts"].addChild( scriptNode ) nodes = [] if len( args["nodes"] ) : for nodeName in args["nodes"] : node = scriptNode.descendant( nodeName ) if node is None : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Node \"%s\" does not exist" % nodeName ) return 1 if not hasattr( node, "execute" ) : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Node \"%s\" is not executable" % nodeName ) return 1 nodes.append( node ) else : for node in scriptNode.children() : if hasattr( node, "execute" ) : nodes.append( node ) if not nodes :
if len(args["context"]) % 2 : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Context parameter must have matching entry/value pairs" ) return 1 context = Gaffer.Context( scriptNode.context() ) for i in range( 0, len(args["context"]), 2 ) : entry = args["context"][i].lstrip( "-" ) context[entry] = eval( args["context"][i+1] ) frames = self.parameters()["frames"].getFrameListValue().asList() with context : for node in nodes : try : node["task"].executeSequence( frames ) except Exception as exception : IECore.msg( IECore.Msg.Level.Debug, "gaffer execute : executing %s" % node.relativeName( scriptNode ), "".join( traceback.format_exception( *sys.exc_info() ) ), ) IECore.msg( IECore.Msg.Level.Error, "gaffer execute : executing %s" % node.relativeName( scriptNode ), "".join( traceback.format_exception_only( *sys.exc_info()[:2] ) ), ) return 1 return 0 IECore.registerRunTimeTyped( execute )
IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Script has no executable nodes" ) return 1
conditional_block
execute-1.py
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2014-2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import os, sys, traceback import IECore import Gaffer class execute( Gaffer.Application ) : def __init__( self ) : Gaffer.Application.__init__( self, """ Executes task nodes such as ImageWriters, SystemCommands and Render nodes from within a .gfr file. This is used by Gaffer's dispatchers when executing nodes in a background process or on a render farm, but can also be used to perform a manual execution from the command line. Example usage : ``` gaffer execute -script comp.gfr -nodes ImageWriter -frames 1-10 ``` """ ) self.parameters().addParameters( [ IECore.FileNameParameter( name = "script", description = "The script to execute.", defaultValue = "", allowEmptyString = False, extensions = "gfr", check = IECore.FileNameParameter.CheckType.MustExist, ), IECore.BoolParameter( name = "ignoreScriptLoadErrors", description = "Causes errors which occur while loading the script " "to be ignored. Not recommended.", defaultValue = False, ), IECore.StringVectorParameter( name = "nodes", description = "The names of the nodes to execute. If not specified " "then all executable nodes will be found automatically.", defaultValue = IECore.StringVectorData( [] ), ), IECore.FrameListParameter( name = "frames", description = "The frames to execute.", defaultValue = "1", allowEmptyList = False, ), IECore.StringVectorParameter( name = "context", description = "The context used during execution. Note that the frames " "parameter will be used to vary the context frame entry.", defaultValue = IECore.StringVectorData( [] ), userData = { "parser" : { "acceptFlags" : IECore.BoolData( True ), }, }, ), ] ) self.parameters().userData()["parser"] = IECore.CompoundObject( {
"flagless" : IECore.StringVectorData( [ "script" ] ) } ) def _run( self, args ) : scriptNode = Gaffer.ScriptNode() scriptNode["fileName"].setValue( os.path.abspath( args["script"].value ) ) try : scriptNode.load( continueOnError = args["ignoreScriptLoadErrors"].value ) except Exception as exception : IECore.msg( IECore.Msg.Level.Error, "gaffer execute : loading \"%s\"" % scriptNode["fileName"].getValue(), str( exception ) ) return 1 self.root()["scripts"].addChild( scriptNode ) nodes = [] if len( args["nodes"] ) : for nodeName in args["nodes"] : node = scriptNode.descendant( nodeName ) if node is None : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Node \"%s\" does not exist" % nodeName ) return 1 if not hasattr( node, "execute" ) : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Node \"%s\" is not executable" % nodeName ) return 1 nodes.append( node ) else : for node in scriptNode.children() : if hasattr( node, "execute" ) : nodes.append( node ) if not nodes : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Script has no executable nodes" ) return 1 if len(args["context"]) % 2 : IECore.msg( IECore.Msg.Level.Error, "gaffer execute", "Context parameter must have matching entry/value pairs" ) return 1 context = Gaffer.Context( scriptNode.context() ) for i in range( 0, len(args["context"]), 2 ) : entry = args["context"][i].lstrip( "-" ) context[entry] = eval( args["context"][i+1] ) frames = self.parameters()["frames"].getFrameListValue().asList() with context : for node in nodes : try : node["task"].executeSequence( frames ) except Exception as exception : IECore.msg( IECore.Msg.Level.Debug, "gaffer execute : executing %s" % node.relativeName( scriptNode ), "".join( traceback.format_exception( *sys.exc_info() ) ), ) IECore.msg( IECore.Msg.Level.Error, "gaffer execute : executing %s" % node.relativeName( scriptNode ), "".join( traceback.format_exception_only( *sys.exc_info()[:2] ) ), ) return 1 return 0 IECore.registerRunTimeTyped( execute )
random_line_split
telegram.service.js
var PostService = require('./post.service'); var ZiviService = require('./zivi.service'); var ConfigService = require('./config.service'); var STATES = require('../models/states'); const apiKey = ConfigService.getTelegramApiKey(); var TelegramService = require('./telegram-dummy.service'); if (!apiKey || process.env.zimonTest) { console.warn('Using dummy Telegram service, i.e. ignoring all calls.'); console.warn('Set an API key in ./config/local-config.json to change this.'); module.exports = TelegramService; return; } var TelegramBot = require('node-telegram-bot-api'); var bot = new TelegramBot(apiKey, { polling: true, filepath: false }); var errorCounter = 0; bot.on('polling_error', function(err) { if(errorCounter < 5) { console.error('Telegram polling failure', err.code, err.response && err.response.body); } else if((errorCounter % 40) === 0) { console.error('Telegram polling failure (... 9 more) - trace:', err.code, err.response && err.response.body); } else if((errorCounter % 10) === 0) { console.error('Telegram polling failure (... 9 more) - trace every 40 errors'); } errorCounter++; }); bot.onText(/\/start/, function (msg) { return bot.sendMessage(msg.chat.id, 'Hello, it me, El Señor Chefzimon.\n' + 'First and foremost, if you have no idea what this is, please kindly leave. I dislike strangers.\n' + 'If you are authorised by the authorities to communicate with me, kindly tell me your registered ' + 'first name using /init <Your first name>. Note that the first name is case-sensitive.\n\n' + 'If you require assistance, type /help and I will silently ignore your request but print a standardised message.'); }); bot.onText(/\/help/, function (msg) { return bot.sendMessage(msg.chat.id, 'My name is El Señor Chefzimon.\n' + 'I can (but would prefer not to) do these amazing things:\n' + '/init <first name> - Registers your account with me\n' + '/postler - Asks me for the current Postler\n' + '/accept - Accepts your post offer and increments your counter\n' + '/next - Refuses the post offer, choosing somebody else using my entirely fair algorithm\n\n' + 'If you encounter any issues, feel free to open an issue on GitHub: https://github.com/realzimon/backzimon-node'); }); bot.onText(/\/init (.+)/, function (msg, match) { ZiviService.findOneByName(match[1], function (err, zivi) { if (err || !zivi) { return bot.sendMessage(msg.chat.id, 'Sorry, El Señor Chefzimon is not aware of anyone with this name. Note that ' + 'the name is case-sensitive. Do not hack El Señor Chefzimon because he possesses great power beyond human imagination.'); } zivi.chat = msg.chat.id; ZiviService.saveZivi(zivi, function (err) { if (err) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not sorry, but an error occurred either way.'); } bot.sendMessage(msg.chat.id, 'You have connected your Telegram account to El Señor Chefzimon. He will now read ' + 'all the messages you send to him. Do not send nudes.'); }); }); }); bot.onText(/\/postler/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state === STATES.IDLE || !post.zivi) { return bot.sendMessage(msg.chat.id, 'Nobody has been selected yet. Stay alert.'); } return bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); }); }); }); bot.onText(/\/accept/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.acceptPost(function (err, post) { if (err) { bot.sendMessage(msg.chat.id, 'Internal error accepting. Try again later.'); console.error('Failed to accept post', err); } else { bot.sendMessage(msg.chat.id, 'You have agreed to carry out the Honourable Task. Please note that this is ' + 'a legally binding agreement. Should you not carry out the Honourable Task, your second-born child belongs ' + 'to El Señor Chefzimon. Take care.'); PostService.pushPostState(post); } }); } }); }); }); bot.onText(/\/next/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.nextZivi(function (err, post) { bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); PostService.pushPostState(post); TelegramService.sendPostlerPromptTo(post.zivi); }); } }); }); }); bot.onText(/\/cancel/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err, post) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.justSetState(STATES.IDLE, function (err) { if (err) { console.error(' ## error cancelling Telegram post', err); bot.sendMessage(msg.chat.id, 'Error cancelling the Honourable Task. Try again later.') } else { bot.sendMessage(msg.chat.id, 'You have declined the Honourable Task and therefore ruined the fun for everyone. ' + 'EL Señor Chefzimon is not amused. He will strike upon thee with great vengeance next time.'); } }); } }); }); }); bot.onText(/\/dismiss/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state !== STATES.REMINDER) { return bot.sendMessage(msg.chat.id, 'It\'s not time yet. Have a little patience.'); } if (post.zivi.chat !== msg.chat.id) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon has *not* asked you to return the yellow card. Please do not annoy him again.'); } PostService.dismissReminder(function () { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not convinced yet. He is watching you.'); }); }); }); }); bot.onText(/\/volunteer/, function (msg) { checkAccountInitialisedOrFail(msg, function (senderZivi) { PostService.findCurrentState(function (post) { if (post.state === STATES.ACTION) { return bot.sendMessage(msg.chat.id, 'Somebody else is currently doing the post, so idk what you\'re doing'); } if (post.zivi.chat === msg.chat.id && post.state !== STATES.IDLE) { return bot.sendMessage(msg.chat.id, 'You are already the assigned Postler. El Señor will not repeat himself again.'); } PostService.forcePostler(senderZivi, function (err, post) { bot.sendMessage(msg.chat.id, 'This is your life now'); TelegramService.sendPostlerPromptTo(post.zivi); }); }); }); }); TelegramService.sendZiviUpdateToUser = function (zivi, message) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, message); }; TelegramService.sendPostlerPromptTo = function (zivi) { if (!zivi || !zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'Congratulations, you have been selected for the Honourable Task!\n' + 'You may */accept* the offer later, when you\'re leaving,\n' + 'request the */next* Zivi now if you absolutely cannot do it,\n' + 'or */cancel* if there is no need.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/accept'], ['/next', '/cancel'] ] } }); }; TelegramService.sendYellowCardReminder = function (zivi) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'El Señor Chefzimon assumes that you have already returned ' + 'the yellow card like a responsible adult. Type /dismiss to swear to ' + 'the sacred GNU General Public License.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/dismiss'] ] } }); }; function checkAccountInitialisedOrFail(msg, callback) { var chatId = msg.chat.id; ZiviService.findBy({chart: chatId}, function (err, zivi) { if (!err && zivi) { callback(zivi); } else { return bot.sendMessage(msg.chat.id, 'You have not yet registered with the El Señor Chefzimon Telegram Integration. ' + 'Type /help for more information.'); } }); } function findPostAndCh
k) { PostService.findCurrentState(function (post) { if (post.state !== STATES.PREPARATION) { return callback('It\'s not time yet. Have a little patience.'); } else if (!post.zivi || post.zivi.chat !== msg.chat.id) { return callback('I\'m sorry, Dave, I cannot do this. You have not been selected for the Honourable Task.'); } callback(null, post); }); } module.exports = TelegramService;
eckPreconditions(msg, callbac
identifier_name
telegram.service.js
var PostService = require('./post.service'); var ZiviService = require('./zivi.service'); var ConfigService = require('./config.service'); var STATES = require('../models/states'); const apiKey = ConfigService.getTelegramApiKey(); var TelegramService = require('./telegram-dummy.service'); if (!apiKey || process.env.zimonTest) { console.warn('Using dummy Telegram service, i.e. ignoring all calls.'); console.warn('Set an API key in ./config/local-config.json to change this.'); module.exports = TelegramService; return; } var TelegramBot = require('node-telegram-bot-api'); var bot = new TelegramBot(apiKey, { polling: true, filepath: false }); var errorCounter = 0; bot.on('polling_error', function(err) { if(errorCounter < 5) { console.error('Telegram polling failure', err.code, err.response && err.response.body); } else if((errorCounter % 40) === 0) { console.error('Telegram polling failure (... 9 more) - trace:', err.code, err.response && err.response.body); } else if((errorCounter % 10) === 0) { console.error('Telegram polling failure (... 9 more) - trace every 40 errors'); } errorCounter++; }); bot.onText(/\/start/, function (msg) { return bot.sendMessage(msg.chat.id, 'Hello, it me, El Señor Chefzimon.\n' + 'First and foremost, if you have no idea what this is, please kindly leave. I dislike strangers.\n' + 'If you are authorised by the authorities to communicate with me, kindly tell me your registered ' + 'first name using /init <Your first name>. Note that the first name is case-sensitive.\n\n' + 'If you require assistance, type /help and I will silently ignore your request but print a standardised message.'); }); bot.onText(/\/help/, function (msg) { return bot.sendMessage(msg.chat.id, 'My name is El Señor Chefzimon.\n' + 'I can (but would prefer not to) do these amazing things:\n' + '/init <first name> - Registers your account with me\n' + '/postler - Asks me for the current Postler\n' + '/accept - Accepts your post offer and increments your counter\n' + '/next - Refuses the post offer, choosing somebody else using my entirely fair algorithm\n\n' + 'If you encounter any issues, feel free to open an issue on GitHub: https://github.com/realzimon/backzimon-node'); }); bot.onText(/\/init (.+)/, function (msg, match) { ZiviService.findOneByName(match[1], function (err, zivi) { if (err || !zivi) { return bot.sendMessage(msg.chat.id, 'Sorry, El Señor Chefzimon is not aware of anyone with this name. Note that ' + 'the name is case-sensitive. Do not hack El Señor Chefzimon because he possesses great power beyond human imagination.'); } zivi.chat = msg.chat.id; ZiviService.saveZivi(zivi, function (err) { if (err) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not sorry, but an error occurred either way.'); } bot.sendMessage(msg.chat.id, 'You have connected your Telegram account to El Señor Chefzimon. He will now read ' + 'all the messages you send to him. Do not send nudes.'); }); }); }); bot.onText(/\/postler/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state === STATES.IDLE || !post.zivi) { return bot.sendMessage(msg.chat.id, 'Nobody has been selected yet. Stay alert.'); } return bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); }); }); }); bot.onText(/\/accept/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.acceptPost(function (err, post) { if (err) { bot.sendMessage(msg.chat.id, 'Internal error accepting. Try again later.'); console.error('Failed to accept post', err); } else { bot.sendMessage(msg.chat.id, 'You have agreed to carry out the Honourable Task. Please note that this is ' + 'a legally binding agreement. Should you not carry out the Honourable Task, your second-born child belongs ' + 'to El Señor Chefzimon. Take care.'); PostService.pushPostState(post); } }); } }); }); }); bot.onText(/\/next/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.nextZivi(function (err, post) { bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); PostService.pushPostState(post); TelegramService.sendPostlerPromptTo(post.zivi); }); } }); }); }); bot.onText(/\/cancel/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err, post) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.justSetState(STATES.IDLE, function (err) { if (err) { console.error(' ## error cancelling Telegram post', err); bot.sendMessage(msg.chat.id, 'Error cancelling the Honourable Task. Try again later.') } else { bot.sendMessage(msg.chat.id, 'You have declined the Honourable Task and therefore ruined the fun for everyone. ' + 'EL Señor Chefzimon is not amused. He will strike upon thee with great vengeance next time.'); } }); } }); }); }); bot.onText(/\/dismiss/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state !== STATES.REMINDER) { return bot.sendMessage(msg.chat.id, 'It\'s not time yet. Have a little patience.'); } if (post.zivi.chat !== msg.chat.id) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon has *not* asked you to return the yellow card. Please do not annoy him again.'); } PostService.dismissReminder(function () { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not convinced yet. He is watching you.'); }); }); }); }); bot.onText(/\/volunteer/, function (msg) { checkAccountInitialisedOrFail(msg, function (senderZivi) { PostService.findCurrentState(function (post) { if (post.state === STATES.ACTION) { return bot.sendMessage(msg.chat.id, 'Somebody else is currently doing the post, so idk what you\'re doing'); } if (post.zivi.chat === msg.chat.id && post.state !== STATES.IDLE) { return bot.sendMessage(msg.chat.id, 'You are already the assigned Postler. El Señor will not repeat himself again.'); } PostService.forcePostler(senderZivi, function (err, post) { bot.sendMessage(msg.chat.id, 'This is your life now'); TelegramService.sendPostlerPromptTo(post.zivi); }); }); }); }); TelegramService.sendZiviUpdateToUser = function (zivi, message) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, message); }; TelegramService.sendPostlerPromptTo = function (zivi) { if (!zivi || !zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'Congratulations, you have been selected for the Honourable Task!\n' + 'You may */accept* the offer later, when you\'re leaving,\n' + 'request the */next* Zivi now if you absolutely cannot do it,\n' + 'or */cancel* if there is no need.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/accept'], ['/next', '/cancel'] ] } }); }; TelegramService.sendYellowCardReminder = function (zivi) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'El Señor Chefzimon assumes that you have already returned ' + 'the yellow card like a responsible adult. Type /dismiss to swear to ' + 'the sacred GNU General Public License.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/dismiss'] ] } }); }; function checkAccountInitialisedOrFail(msg, callback) { var chat
ndPostAndCheckPreconditions(msg, callback) { PostService.findCurrentState(function (post) { if (post.state !== STATES.PREPARATION) { return callback('It\'s not time yet. Have a little patience.'); } else if (!post.zivi || post.zivi.chat !== msg.chat.id) { return callback('I\'m sorry, Dave, I cannot do this. You have not been selected for the Honourable Task.'); } callback(null, post); }); } module.exports = TelegramService;
Id = msg.chat.id; ZiviService.findBy({chart: chatId}, function (err, zivi) { if (!err && zivi) { callback(zivi); } else { return bot.sendMessage(msg.chat.id, 'You have not yet registered with the El Señor Chefzimon Telegram Integration. ' + 'Type /help for more information.'); } }); } function fi
identifier_body
telegram.service.js
var PostService = require('./post.service'); var ZiviService = require('./zivi.service'); var ConfigService = require('./config.service'); var STATES = require('../models/states'); const apiKey = ConfigService.getTelegramApiKey();
module.exports = TelegramService; return; } var TelegramBot = require('node-telegram-bot-api'); var bot = new TelegramBot(apiKey, { polling: true, filepath: false }); var errorCounter = 0; bot.on('polling_error', function(err) { if(errorCounter < 5) { console.error('Telegram polling failure', err.code, err.response && err.response.body); } else if((errorCounter % 40) === 0) { console.error('Telegram polling failure (... 9 more) - trace:', err.code, err.response && err.response.body); } else if((errorCounter % 10) === 0) { console.error('Telegram polling failure (... 9 more) - trace every 40 errors'); } errorCounter++; }); bot.onText(/\/start/, function (msg) { return bot.sendMessage(msg.chat.id, 'Hello, it me, El Señor Chefzimon.\n' + 'First and foremost, if you have no idea what this is, please kindly leave. I dislike strangers.\n' + 'If you are authorised by the authorities to communicate with me, kindly tell me your registered ' + 'first name using /init <Your first name>. Note that the first name is case-sensitive.\n\n' + 'If you require assistance, type /help and I will silently ignore your request but print a standardised message.'); }); bot.onText(/\/help/, function (msg) { return bot.sendMessage(msg.chat.id, 'My name is El Señor Chefzimon.\n' + 'I can (but would prefer not to) do these amazing things:\n' + '/init <first name> - Registers your account with me\n' + '/postler - Asks me for the current Postler\n' + '/accept - Accepts your post offer and increments your counter\n' + '/next - Refuses the post offer, choosing somebody else using my entirely fair algorithm\n\n' + 'If you encounter any issues, feel free to open an issue on GitHub: https://github.com/realzimon/backzimon-node'); }); bot.onText(/\/init (.+)/, function (msg, match) { ZiviService.findOneByName(match[1], function (err, zivi) { if (err || !zivi) { return bot.sendMessage(msg.chat.id, 'Sorry, El Señor Chefzimon is not aware of anyone with this name. Note that ' + 'the name is case-sensitive. Do not hack El Señor Chefzimon because he possesses great power beyond human imagination.'); } zivi.chat = msg.chat.id; ZiviService.saveZivi(zivi, function (err) { if (err) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not sorry, but an error occurred either way.'); } bot.sendMessage(msg.chat.id, 'You have connected your Telegram account to El Señor Chefzimon. He will now read ' + 'all the messages you send to him. Do not send nudes.'); }); }); }); bot.onText(/\/postler/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state === STATES.IDLE || !post.zivi) { return bot.sendMessage(msg.chat.id, 'Nobody has been selected yet. Stay alert.'); } return bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); }); }); }); bot.onText(/\/accept/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.acceptPost(function (err, post) { if (err) { bot.sendMessage(msg.chat.id, 'Internal error accepting. Try again later.'); console.error('Failed to accept post', err); } else { bot.sendMessage(msg.chat.id, 'You have agreed to carry out the Honourable Task. Please note that this is ' + 'a legally binding agreement. Should you not carry out the Honourable Task, your second-born child belongs ' + 'to El Señor Chefzimon. Take care.'); PostService.pushPostState(post); } }); } }); }); }); bot.onText(/\/next/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.nextZivi(function (err, post) { bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); PostService.pushPostState(post); TelegramService.sendPostlerPromptTo(post.zivi); }); } }); }); }); bot.onText(/\/cancel/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err, post) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.justSetState(STATES.IDLE, function (err) { if (err) { console.error(' ## error cancelling Telegram post', err); bot.sendMessage(msg.chat.id, 'Error cancelling the Honourable Task. Try again later.') } else { bot.sendMessage(msg.chat.id, 'You have declined the Honourable Task and therefore ruined the fun for everyone. ' + 'EL Señor Chefzimon is not amused. He will strike upon thee with great vengeance next time.'); } }); } }); }); }); bot.onText(/\/dismiss/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state !== STATES.REMINDER) { return bot.sendMessage(msg.chat.id, 'It\'s not time yet. Have a little patience.'); } if (post.zivi.chat !== msg.chat.id) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon has *not* asked you to return the yellow card. Please do not annoy him again.'); } PostService.dismissReminder(function () { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not convinced yet. He is watching you.'); }); }); }); }); bot.onText(/\/volunteer/, function (msg) { checkAccountInitialisedOrFail(msg, function (senderZivi) { PostService.findCurrentState(function (post) { if (post.state === STATES.ACTION) { return bot.sendMessage(msg.chat.id, 'Somebody else is currently doing the post, so idk what you\'re doing'); } if (post.zivi.chat === msg.chat.id && post.state !== STATES.IDLE) { return bot.sendMessage(msg.chat.id, 'You are already the assigned Postler. El Señor will not repeat himself again.'); } PostService.forcePostler(senderZivi, function (err, post) { bot.sendMessage(msg.chat.id, 'This is your life now'); TelegramService.sendPostlerPromptTo(post.zivi); }); }); }); }); TelegramService.sendZiviUpdateToUser = function (zivi, message) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, message); }; TelegramService.sendPostlerPromptTo = function (zivi) { if (!zivi || !zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'Congratulations, you have been selected for the Honourable Task!\n' + 'You may */accept* the offer later, when you\'re leaving,\n' + 'request the */next* Zivi now if you absolutely cannot do it,\n' + 'or */cancel* if there is no need.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/accept'], ['/next', '/cancel'] ] } }); }; TelegramService.sendYellowCardReminder = function (zivi) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'El Señor Chefzimon assumes that you have already returned ' + 'the yellow card like a responsible adult. Type /dismiss to swear to ' + 'the sacred GNU General Public License.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/dismiss'] ] } }); }; function checkAccountInitialisedOrFail(msg, callback) { var chatId = msg.chat.id; ZiviService.findBy({chart: chatId}, function (err, zivi) { if (!err && zivi) { callback(zivi); } else { return bot.sendMessage(msg.chat.id, 'You have not yet registered with the El Señor Chefzimon Telegram Integration. ' + 'Type /help for more information.'); } }); } function findPostAndCheckPreconditions(msg, callback) { PostService.findCurrentState(function (post) { if (post.state !== STATES.PREPARATION) { return callback('It\'s not time yet. Have a little patience.'); } else if (!post.zivi || post.zivi.chat !== msg.chat.id) { return callback('I\'m sorry, Dave, I cannot do this. You have not been selected for the Honourable Task.'); } callback(null, post); }); } module.exports = TelegramService;
var TelegramService = require('./telegram-dummy.service'); if (!apiKey || process.env.zimonTest) { console.warn('Using dummy Telegram service, i.e. ignoring all calls.'); console.warn('Set an API key in ./config/local-config.json to change this.');
random_line_split
telegram.service.js
var PostService = require('./post.service'); var ZiviService = require('./zivi.service'); var ConfigService = require('./config.service'); var STATES = require('../models/states'); const apiKey = ConfigService.getTelegramApiKey(); var TelegramService = require('./telegram-dummy.service'); if (!apiKey || process.env.zimonTest) { console.warn('Using dummy Telegram service, i.e. ignoring all calls.'); console.warn('Set an API key in ./config/local-config.json to change this.'); module.exports = TelegramService; return; } var TelegramBot = require('node-telegram-bot-api'); var bot = new TelegramBot(apiKey, { polling: true, filepath: false }); var errorCounter = 0; bot.on('polling_error', function(err) { if(errorCounter < 5) { console.error('Telegram polling failure', err.code, err.response && err.response.body); } else if((errorCounter % 40) === 0) { console.error('Telegram polling failure (... 9 more) - trace:', err.code, err.response && err.response.body); } else if((errorCounter % 10) === 0) { console.error('Telegram polling failure (... 9 more) - trace every 40 errors'); } errorCounter++; }); bot.onText(/\/start/, function (msg) { return bot.sendMessage(msg.chat.id, 'Hello, it me, El Señor Chefzimon.\n' + 'First and foremost, if you have no idea what this is, please kindly leave. I dislike strangers.\n' + 'If you are authorised by the authorities to communicate with me, kindly tell me your registered ' + 'first name using /init <Your first name>. Note that the first name is case-sensitive.\n\n' + 'If you require assistance, type /help and I will silently ignore your request but print a standardised message.'); }); bot.onText(/\/help/, function (msg) { return bot.sendMessage(msg.chat.id, 'My name is El Señor Chefzimon.\n' + 'I can (but would prefer not to) do these amazing things:\n' + '/init <first name> - Registers your account with me\n' + '/postler - Asks me for the current Postler\n' + '/accept - Accepts your post offer and increments your counter\n' + '/next - Refuses the post offer, choosing somebody else using my entirely fair algorithm\n\n' + 'If you encounter any issues, feel free to open an issue on GitHub: https://github.com/realzimon/backzimon-node'); }); bot.onText(/\/init (.+)/, function (msg, match) { ZiviService.findOneByName(match[1], function (err, zivi) { if (err || !zivi) { return bot.sendMessage(msg.chat.id, 'Sorry, El Señor Chefzimon is not aware of anyone with this name. Note that ' + 'the name is case-sensitive. Do not hack El Señor Chefzimon because he possesses great power beyond human imagination.'); } zivi.chat = msg.chat.id; ZiviService.saveZivi(zivi, function (err) { if (err) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not sorry, but an error occurred either way.'); } bot.sendMessage(msg.chat.id, 'You have connected your Telegram account to El Señor Chefzimon. He will now read ' + 'all the messages you send to him. Do not send nudes.'); }); }); }); bot.onText(/\/postler/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state === STATES.IDLE || !post.zivi) { return bot.sendMessage(msg.chat.id, 'Nobody has been selected yet. Stay alert.'); } return bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); }); }); }); bot.onText(/\/accept/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else {
; }); }); bot.onText(/\/next/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.nextZivi(function (err, post) { bot.sendMessage(msg.chat.id, post.zivi.name + ' will carry out the Honourable Task.'); PostService.pushPostState(post); TelegramService.sendPostlerPromptTo(post.zivi); }); } }); }); }); bot.onText(/\/cancel/, function (msg) { checkAccountInitialisedOrFail(msg, function () { findPostAndCheckPreconditions(msg, function (err, post) { if (err) { return bot.sendMessage(msg.chat.id, err); } else { PostService.justSetState(STATES.IDLE, function (err) { if (err) { console.error(' ## error cancelling Telegram post', err); bot.sendMessage(msg.chat.id, 'Error cancelling the Honourable Task. Try again later.') } else { bot.sendMessage(msg.chat.id, 'You have declined the Honourable Task and therefore ruined the fun for everyone. ' + 'EL Señor Chefzimon is not amused. He will strike upon thee with great vengeance next time.'); } }); } }); }); }); bot.onText(/\/dismiss/, function (msg) { checkAccountInitialisedOrFail(msg, function () { PostService.findCurrentState(function (post) { if (post.state !== STATES.REMINDER) { return bot.sendMessage(msg.chat.id, 'It\'s not time yet. Have a little patience.'); } if (post.zivi.chat !== msg.chat.id) { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon has *not* asked you to return the yellow card. Please do not annoy him again.'); } PostService.dismissReminder(function () { return bot.sendMessage(msg.chat.id, 'El Señor Chefzimon is not convinced yet. He is watching you.'); }); }); }); }); bot.onText(/\/volunteer/, function (msg) { checkAccountInitialisedOrFail(msg, function (senderZivi) { PostService.findCurrentState(function (post) { if (post.state === STATES.ACTION) { return bot.sendMessage(msg.chat.id, 'Somebody else is currently doing the post, so idk what you\'re doing'); } if (post.zivi.chat === msg.chat.id && post.state !== STATES.IDLE) { return bot.sendMessage(msg.chat.id, 'You are already the assigned Postler. El Señor will not repeat himself again.'); } PostService.forcePostler(senderZivi, function (err, post) { bot.sendMessage(msg.chat.id, 'This is your life now'); TelegramService.sendPostlerPromptTo(post.zivi); }); }); }); }); TelegramService.sendZiviUpdateToUser = function (zivi, message) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, message); }; TelegramService.sendPostlerPromptTo = function (zivi) { if (!zivi || !zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'Congratulations, you have been selected for the Honourable Task!\n' + 'You may */accept* the offer later, when you\'re leaving,\n' + 'request the */next* Zivi now if you absolutely cannot do it,\n' + 'or */cancel* if there is no need.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/accept'], ['/next', '/cancel'] ] } }); }; TelegramService.sendYellowCardReminder = function (zivi) { if (!zivi.chat || zivi.chat === -1) { return console.log(' ## No Telegram chat for', zivi.name); } bot.sendMessage(zivi.chat, 'El Señor Chefzimon assumes that you have already returned ' + 'the yellow card like a responsible adult. Type /dismiss to swear to ' + 'the sacred GNU General Public License.', { parse_mode: 'Markdown', reply_markup: { one_time_keyboard: true, resize_keyboard: true, keyboard: [ ['/dismiss'] ] } }); }; function checkAccountInitialisedOrFail(msg, callback) { var chatId = msg.chat.id; ZiviService.findBy({chart: chatId}, function (err, zivi) { if (!err && zivi) { callback(zivi); } else { return bot.sendMessage(msg.chat.id, 'You have not yet registered with the El Señor Chefzimon Telegram Integration. ' + 'Type /help for more information.'); } }); } function findPostAndCheckPreconditions(msg, callback) { PostService.findCurrentState(function (post) { if (post.state !== STATES.PREPARATION) { return callback('It\'s not time yet. Have a little patience.'); } else if (!post.zivi || post.zivi.chat !== msg.chat.id) { return callback('I\'m sorry, Dave, I cannot do this. You have not been selected for the Honourable Task.'); } callback(null, post); }); } module.exports = TelegramService;
PostService.acceptPost(function (err, post) { if (err) { bot.sendMessage(msg.chat.id, 'Internal error accepting. Try again later.'); console.error('Failed to accept post', err); } else { bot.sendMessage(msg.chat.id, 'You have agreed to carry out the Honourable Task. Please note that this is ' + 'a legally binding agreement. Should you not carry out the Honourable Task, your second-born child belongs ' + 'to El Señor Chefzimon. Take care.'); PostService.pushPostState(post); } }); } })
conditional_block
regress-96526-noargsub.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Netscape Communications Corp. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * brendan@mozilla.org, pschwartau@netscape.com * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * * Date: 29 Oct 2002 * SUMMARY: Testing "use" and "set" operations on expressions like a[i][j][k] * See http://bugzilla.mozilla.org/show_bug.cgi?id=96526#c52 * * Brendan: "The idea is to cover all the 'use' and 'set' (as in modify) * operations you can do on an expression like a[i][j][k], including variations * where you replace |a| with arguments (literally) and |i| with 0, 1, 2, etc. * (to hit the optimization for arguments[0]... that uses JSOP_ARGSUB)." */ //----------------------------------------------------------------------------- var gTestfile = 'regress-96526-noargsub.js'; var UBound = 0; var BUGNUMBER = 96526; var summary = 'Testing "use" and "set" ops on expressions like a[i][j][k]'; var status = ''; var statusitems = []; var actual = ''; var actualvalues = []; var expect= ''; var expectedvalues = []; var z='magic'; Number.prototype.magic=42; status = inSection(1); actual = f(2,1,[-1,0,[1,2,[3,4]]]); expect = 42; addThis(); function f(j,k,a) { status = inSection(2); actual = formatArray(a[2]); expect = formatArray([1,2,[3,4]]); addThis(); status = inSection(3); actual = formatArray(a[2][j]); expect = formatArray([3,4]); addThis(); status = inSection(4); actual = a[2][j][k]; expect = 4; addThis(); status = inSection(5); actual = a[2][j][k][z]; expect = 42; addThis(); return a[2][j][k][z]; } //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function addThis() { statusitems[UBound] = status; actualvalues[UBound] = actual; expectedvalues[UBound] = expect; UBound++; } function test() { enterFunc('test'); printBugNumber(BUGNUMBER); printStatus(summary); for (var i=0; i<UBound; i++)
exitFunc ('test'); }
{ reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]); }
conditional_block
regress-96526-noargsub.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Netscape Communications Corp. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * brendan@mozilla.org, pschwartau@netscape.com * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * * Date: 29 Oct 2002 * SUMMARY: Testing "use" and "set" operations on expressions like a[i][j][k] * See http://bugzilla.mozilla.org/show_bug.cgi?id=96526#c52 * * Brendan: "The idea is to cover all the 'use' and 'set' (as in modify) * operations you can do on an expression like a[i][j][k], including variations * where you replace |a| with arguments (literally) and |i| with 0, 1, 2, etc. * (to hit the optimization for arguments[0]... that uses JSOP_ARGSUB)." */ //----------------------------------------------------------------------------- var gTestfile = 'regress-96526-noargsub.js'; var UBound = 0; var BUGNUMBER = 96526; var summary = 'Testing "use" and "set" ops on expressions like a[i][j][k]'; var status = ''; var statusitems = []; var actual = ''; var actualvalues = []; var expect= ''; var expectedvalues = []; var z='magic'; Number.prototype.magic=42; status = inSection(1); actual = f(2,1,[-1,0,[1,2,[3,4]]]); expect = 42; addThis(); function f(j,k,a)
//----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function addThis() { statusitems[UBound] = status; actualvalues[UBound] = actual; expectedvalues[UBound] = expect; UBound++; } function test() { enterFunc('test'); printBugNumber(BUGNUMBER); printStatus(summary); for (var i=0; i<UBound; i++) { reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]); } exitFunc ('test'); }
{ status = inSection(2); actual = formatArray(a[2]); expect = formatArray([1,2,[3,4]]); addThis(); status = inSection(3); actual = formatArray(a[2][j]); expect = formatArray([3,4]); addThis(); status = inSection(4); actual = a[2][j][k]; expect = 4; addThis(); status = inSection(5); actual = a[2][j][k][z]; expect = 42; addThis(); return a[2][j][k][z]; }
identifier_body
regress-96526-noargsub.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Netscape Communications Corp. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * brendan@mozilla.org, pschwartau@netscape.com * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * * Date: 29 Oct 2002 * SUMMARY: Testing "use" and "set" operations on expressions like a[i][j][k] * See http://bugzilla.mozilla.org/show_bug.cgi?id=96526#c52 * * Brendan: "The idea is to cover all the 'use' and 'set' (as in modify) * operations you can do on an expression like a[i][j][k], including variations * where you replace |a| with arguments (literally) and |i| with 0, 1, 2, etc. * (to hit the optimization for arguments[0]... that uses JSOP_ARGSUB)." */ //----------------------------------------------------------------------------- var gTestfile = 'regress-96526-noargsub.js'; var UBound = 0; var BUGNUMBER = 96526; var summary = 'Testing "use" and "set" ops on expressions like a[i][j][k]'; var status = ''; var statusitems = []; var actual = ''; var actualvalues = []; var expect= ''; var expectedvalues = []; var z='magic'; Number.prototype.magic=42; status = inSection(1); actual = f(2,1,[-1,0,[1,2,[3,4]]]); expect = 42; addThis(); function f(j,k,a) { status = inSection(2); actual = formatArray(a[2]); expect = formatArray([1,2,[3,4]]); addThis(); status = inSection(3); actual = formatArray(a[2][j]); expect = formatArray([3,4]); addThis(); status = inSection(4); actual = a[2][j][k]; expect = 4; addThis(); status = inSection(5); actual = a[2][j][k][z]; expect = 42; addThis(); return a[2][j][k][z]; } //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function addThis() { statusitems[UBound] = status; actualvalues[UBound] = actual; expectedvalues[UBound] = expect; UBound++; } function
() { enterFunc('test'); printBugNumber(BUGNUMBER); printStatus(summary); for (var i=0; i<UBound; i++) { reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]); } exitFunc ('test'); }
test
identifier_name
regress-96526-noargsub.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Netscape Communications Corp. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * brendan@mozilla.org, pschwartau@netscape.com * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete
* ***** END LICENSE BLOCK ***** */ /* * * Date: 29 Oct 2002 * SUMMARY: Testing "use" and "set" operations on expressions like a[i][j][k] * See http://bugzilla.mozilla.org/show_bug.cgi?id=96526#c52 * * Brendan: "The idea is to cover all the 'use' and 'set' (as in modify) * operations you can do on an expression like a[i][j][k], including variations * where you replace |a| with arguments (literally) and |i| with 0, 1, 2, etc. * (to hit the optimization for arguments[0]... that uses JSOP_ARGSUB)." */ //----------------------------------------------------------------------------- var gTestfile = 'regress-96526-noargsub.js'; var UBound = 0; var BUGNUMBER = 96526; var summary = 'Testing "use" and "set" ops on expressions like a[i][j][k]'; var status = ''; var statusitems = []; var actual = ''; var actualvalues = []; var expect= ''; var expectedvalues = []; var z='magic'; Number.prototype.magic=42; status = inSection(1); actual = f(2,1,[-1,0,[1,2,[3,4]]]); expect = 42; addThis(); function f(j,k,a) { status = inSection(2); actual = formatArray(a[2]); expect = formatArray([1,2,[3,4]]); addThis(); status = inSection(3); actual = formatArray(a[2][j]); expect = formatArray([3,4]); addThis(); status = inSection(4); actual = a[2][j][k]; expect = 4; addThis(); status = inSection(5); actual = a[2][j][k][z]; expect = 42; addThis(); return a[2][j][k][z]; } //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function addThis() { statusitems[UBound] = status; actualvalues[UBound] = actual; expectedvalues[UBound] = expect; UBound++; } function test() { enterFunc('test'); printBugNumber(BUGNUMBER); printStatus(summary); for (var i=0; i<UBound; i++) { reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]); } exitFunc ('test'); }
* the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. *
random_line_split
connectivity_source_py3.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class ConnectivitySource(Model): """Parameters that define the source of the connection. All required parameters must be populated in order to send to Azure. :param resource_id: Required. The ID of the resource from which a connectivity check will be initiated. :type resource_id: str :param port: The source port from which a connectivity check will be performed. :type port: int """ _validation = { 'resource_id': {'required': True}, }
'resource_id': {'key': 'resourceId', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, *, resource_id: str, port: int=None, **kwargs) -> None: super(ConnectivitySource, self).__init__(**kwargs) self.resource_id = resource_id self.port = port
_attribute_map = {
random_line_split
connectivity_source_py3.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class
(Model): """Parameters that define the source of the connection. All required parameters must be populated in order to send to Azure. :param resource_id: Required. The ID of the resource from which a connectivity check will be initiated. :type resource_id: str :param port: The source port from which a connectivity check will be performed. :type port: int """ _validation = { 'resource_id': {'required': True}, } _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, *, resource_id: str, port: int=None, **kwargs) -> None: super(ConnectivitySource, self).__init__(**kwargs) self.resource_id = resource_id self.port = port
ConnectivitySource
identifier_name
connectivity_source_py3.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class ConnectivitySource(Model): """Parameters that define the source of the connection. All required parameters must be populated in order to send to Azure. :param resource_id: Required. The ID of the resource from which a connectivity check will be initiated. :type resource_id: str :param port: The source port from which a connectivity check will be performed. :type port: int """ _validation = { 'resource_id': {'required': True}, } _attribute_map = { 'resource_id': {'key': 'resourceId', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, } def __init__(self, *, resource_id: str, port: int=None, **kwargs) -> None:
super(ConnectivitySource, self).__init__(**kwargs) self.resource_id = resource_id self.port = port
identifier_body
GroupAlert.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import * as React from 'react'; import { webAPI } from '@csegames/library/lib/camelotunchained'; import { Container, InputContainer, Button, ButtonOverlay } from './lib/styles'; import { GroupAlert, IInteractiveAlert } from 'gql/interfaces'; // Utility Functions export function groupInviteID(alert: GroupAlert) { return `${alert.kind}:${alert.forGroup}`; } export function handleNewGroupAlert(alertsList: IInteractiveAlert[], alert: GroupAlert)
export interface GroupAlertProps { alert: GroupAlert; remove: (alert: IInteractiveAlert) => void; } export class GroupAlertView extends React.Component<GroupAlertProps> { public render() { const { alert } = this.props; return ( <Container> <h4> {alert.fromName || 'Unknown'} has invited you to the {alert.kind.replace('Invite', '')}{alert.forGroupName}. </h4> <InputContainer style={{zIndex: 9999}}> <Button onClick={this.joinGroup}><ButtonOverlay>Join {alert.kind.replace('Invite', '')}</ButtonOverlay></Button> <Button onClick={this.onDecline}><ButtonOverlay>Decline</ButtonOverlay></Button> </InputContainer> </Container> ); } private joinGroup = () => { const { alert } = this.props; this.props.remove(alert); setTimeout(async () => { try { const res = await webAPI.GroupsAPI.JoinV1( webAPI.defaultConfig, alert.forGroup, alert.code); if (res.ok) { return } const data = JSON.parse(res.data); if (data.FieldCodes && data.FieldCodes.length > 0) { console.error(data.FieldCodes[0].Message); } else { // This means api server failed AcceptInvite request but did not provide a message about what happened console.error('An error occured'); } } catch (e) { console.error('There was an unhandled error'); } }); } private onDecline = async () => { // remove this alert from our ui const { alert } = this.props; this.props.remove(alert); } }
{ const alerts = [...alertsList]; if (alerts.findIndex(a => groupInviteID(a as GroupAlert) === groupInviteID(alert)) !== -1) { return { alerts, }; } alerts.push(alert); return { alerts, }; }
identifier_body
GroupAlert.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import * as React from 'react'; import { webAPI } from '@csegames/library/lib/camelotunchained'; import { Container, InputContainer, Button, ButtonOverlay } from './lib/styles'; import { GroupAlert, IInteractiveAlert } from 'gql/interfaces'; // Utility Functions export function groupInviteID(alert: GroupAlert) { return `${alert.kind}:${alert.forGroup}`; } export function handleNewGroupAlert(alertsList: IInteractiveAlert[], alert: GroupAlert) { const alerts = [...alertsList]; if (alerts.findIndex(a => groupInviteID(a as GroupAlert) === groupInviteID(alert)) !== -1) { return { alerts, }; } alerts.push(alert); return { alerts, }; } export interface GroupAlertProps { alert: GroupAlert; remove: (alert: IInteractiveAlert) => void; } export class GroupAlertView extends React.Component<GroupAlertProps> { public render() { const { alert } = this.props; return ( <Container> <h4> {alert.fromName || 'Unknown'} has invited you to the {alert.kind.replace('Invite', '')}{alert.forGroupName}. </h4> <InputContainer style={{zIndex: 9999}}> <Button onClick={this.joinGroup}><ButtonOverlay>Join {alert.kind.replace('Invite', '')}</ButtonOverlay></Button> <Button onClick={this.onDecline}><ButtonOverlay>Decline</ButtonOverlay></Button> </InputContainer> </Container> ); } private joinGroup = () => { const { alert } = this.props; this.props.remove(alert); setTimeout(async () => { try { const res = await webAPI.GroupsAPI.JoinV1( webAPI.defaultConfig, alert.forGroup, alert.code); if (res.ok)
const data = JSON.parse(res.data); if (data.FieldCodes && data.FieldCodes.length > 0) { console.error(data.FieldCodes[0].Message); } else { // This means api server failed AcceptInvite request but did not provide a message about what happened console.error('An error occured'); } } catch (e) { console.error('There was an unhandled error'); } }); } private onDecline = async () => { // remove this alert from our ui const { alert } = this.props; this.props.remove(alert); } }
{ return }
conditional_block
GroupAlert.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import * as React from 'react'; import { webAPI } from '@csegames/library/lib/camelotunchained'; import { Container, InputContainer, Button, ButtonOverlay } from './lib/styles'; import { GroupAlert, IInteractiveAlert } from 'gql/interfaces'; // Utility Functions export function
(alert: GroupAlert) { return `${alert.kind}:${alert.forGroup}`; } export function handleNewGroupAlert(alertsList: IInteractiveAlert[], alert: GroupAlert) { const alerts = [...alertsList]; if (alerts.findIndex(a => groupInviteID(a as GroupAlert) === groupInviteID(alert)) !== -1) { return { alerts, }; } alerts.push(alert); return { alerts, }; } export interface GroupAlertProps { alert: GroupAlert; remove: (alert: IInteractiveAlert) => void; } export class GroupAlertView extends React.Component<GroupAlertProps> { public render() { const { alert } = this.props; return ( <Container> <h4> {alert.fromName || 'Unknown'} has invited you to the {alert.kind.replace('Invite', '')}{alert.forGroupName}. </h4> <InputContainer style={{zIndex: 9999}}> <Button onClick={this.joinGroup}><ButtonOverlay>Join {alert.kind.replace('Invite', '')}</ButtonOverlay></Button> <Button onClick={this.onDecline}><ButtonOverlay>Decline</ButtonOverlay></Button> </InputContainer> </Container> ); } private joinGroup = () => { const { alert } = this.props; this.props.remove(alert); setTimeout(async () => { try { const res = await webAPI.GroupsAPI.JoinV1( webAPI.defaultConfig, alert.forGroup, alert.code); if (res.ok) { return } const data = JSON.parse(res.data); if (data.FieldCodes && data.FieldCodes.length > 0) { console.error(data.FieldCodes[0].Message); } else { // This means api server failed AcceptInvite request but did not provide a message about what happened console.error('An error occured'); } } catch (e) { console.error('There was an unhandled error'); } }); } private onDecline = async () => { // remove this alert from our ui const { alert } = this.props; this.props.remove(alert); } }
groupInviteID
identifier_name
GroupAlert.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ import * as React from 'react'; import { webAPI } from '@csegames/library/lib/camelotunchained'; import { Container, InputContainer, Button, ButtonOverlay } from './lib/styles'; import { GroupAlert, IInteractiveAlert } from 'gql/interfaces'; // Utility Functions export function groupInviteID(alert: GroupAlert) { return `${alert.kind}:${alert.forGroup}`; } export function handleNewGroupAlert(alertsList: IInteractiveAlert[], alert: GroupAlert) { const alerts = [...alertsList]; if (alerts.findIndex(a => groupInviteID(a as GroupAlert) === groupInviteID(alert)) !== -1) { return { alerts, }; } alerts.push(alert); return { alerts, }; } export interface GroupAlertProps { alert: GroupAlert; remove: (alert: IInteractiveAlert) => void; } export class GroupAlertView extends React.Component<GroupAlertProps> { public render() { const { alert } = this.props; return ( <Container> <h4> {alert.fromName || 'Unknown'} has invited you to the {alert.kind.replace('Invite', '')}{alert.forGroupName}. </h4> <InputContainer style={{zIndex: 9999}}> <Button onClick={this.joinGroup}><ButtonOverlay>Join {alert.kind.replace('Invite', '')}</ButtonOverlay></Button> <Button onClick={this.onDecline}><ButtonOverlay>Decline</ButtonOverlay></Button> </InputContainer> </Container>
const { alert } = this.props; this.props.remove(alert); setTimeout(async () => { try { const res = await webAPI.GroupsAPI.JoinV1( webAPI.defaultConfig, alert.forGroup, alert.code); if (res.ok) { return } const data = JSON.parse(res.data); if (data.FieldCodes && data.FieldCodes.length > 0) { console.error(data.FieldCodes[0].Message); } else { // This means api server failed AcceptInvite request but did not provide a message about what happened console.error('An error occured'); } } catch (e) { console.error('There was an unhandled error'); } }); } private onDecline = async () => { // remove this alert from our ui const { alert } = this.props; this.props.remove(alert); } }
); } private joinGroup = () => {
random_line_split
mut-ptr-cant-outlive-ref.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::RefCell; fn main()
trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } } impl<T> Fake for T { }
{ let m = RefCell::new(0); let p; { let b = m.borrow(); p = &*b; } //~^^ ERROR `b` does not live long enough p.use_ref(); }
identifier_body
mut-ptr-cant-outlive-ref.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::RefCell; fn main() { let m = RefCell::new(0); let p; { let b = m.borrow(); p = &*b; } //~^^ ERROR `b` does not live long enough p.use_ref(); } trait Fake { fn
(&mut self) { } fn use_ref(&self) { } } impl<T> Fake for T { }
use_mut
identifier_name
mut-ptr-cant-outlive-ref.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// option. This file may not be copied, modified, or distributed // except according to those terms. use std::cell::RefCell; fn main() { let m = RefCell::new(0); let p; { let b = m.borrow(); p = &*b; } //~^^ ERROR `b` does not live long enough p.use_ref(); } trait Fake { fn use_mut(&mut self) { } fn use_ref(&self) { } } impl<T> Fake for T { }
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
serializers.py
from django.contrib.auth import get_user_model User = get_user_model() from rest_framework import serializers from nodeshot.core.base.serializers import ModelValidationSerializer from nodeshot.community.profiles.serializers import ProfileRelationSerializer from .models import Comment, Vote, Rating, NodeRatingCount __all__ = ['CommentSerializer', 'RatingSerializer', 'CommentRelationSerializer', 'VoteSerializer', 'ParticipationSerializer'] class AutoNodeMixin(object): """ automatically adds node to validated_data the node info is taken from views that extend NodeRelationViewMixin """ def validate(self, data): data['node'] = self.context['view'].node return super(AutoNodeMixin, self).validate(data) class CommentSerializer(AutoNodeMixin, ModelValidationSerializer): """ Comment serializer """ node = serializers.ReadOnlyField(source='node.name') username = serializers.ReadOnlyField(source='user.username') class Meta: model = Comment fields = ('node', 'username', 'text', 'added') read_only_fields = ('added',) class CommentRelationSerializer(serializers.ModelSerializer): """ display user info """ user = ProfileRelationSerializer() class Meta: model = Comment fields = ('user', 'text', 'added',) class RatingSerializer(AutoNodeMixin, ModelValidationSerializer): """ Rating serializer """ node = serializers.ReadOnlyField(source='node.name') username = serializers.ReadOnlyField(source='user.username') class Meta: model = Rating fields = ('node', 'username', 'value',) read_only_fields = ('added',) class VoteSerializer(AutoNodeMixin, ModelValidationSerializer): node = serializers.ReadOnlyField(source='node.name') username = serializers.ReadOnlyField(source='user.username') class Meta: model = Vote fields = ('node', 'username', 'vote',) read_only_fields = ('added',) class ParticipationSerializer(serializers.ModelSerializer): class
: model = NodeRatingCount fields = ('likes', 'dislikes', 'rating_count', 'rating_avg', 'comment_count')
Meta
identifier_name
serializers.py
from django.contrib.auth import get_user_model User = get_user_model() from rest_framework import serializers from nodeshot.core.base.serializers import ModelValidationSerializer from nodeshot.community.profiles.serializers import ProfileRelationSerializer from .models import Comment, Vote, Rating, NodeRatingCount __all__ = ['CommentSerializer', 'RatingSerializer', 'CommentRelationSerializer', 'VoteSerializer', 'ParticipationSerializer'] class AutoNodeMixin(object): """ automatically adds node to validated_data the node info is taken from views that extend NodeRelationViewMixin """ def validate(self, data): data['node'] = self.context['view'].node return super(AutoNodeMixin, self).validate(data) class CommentSerializer(AutoNodeMixin, ModelValidationSerializer): """ Comment serializer """ node = serializers.ReadOnlyField(source='node.name') username = serializers.ReadOnlyField(source='user.username') class Meta: model = Comment fields = ('node', 'username', 'text', 'added') read_only_fields = ('added',) class CommentRelationSerializer(serializers.ModelSerializer):
class RatingSerializer(AutoNodeMixin, ModelValidationSerializer): """ Rating serializer """ node = serializers.ReadOnlyField(source='node.name') username = serializers.ReadOnlyField(source='user.username') class Meta: model = Rating fields = ('node', 'username', 'value',) read_only_fields = ('added',) class VoteSerializer(AutoNodeMixin, ModelValidationSerializer): node = serializers.ReadOnlyField(source='node.name') username = serializers.ReadOnlyField(source='user.username') class Meta: model = Vote fields = ('node', 'username', 'vote',) read_only_fields = ('added',) class ParticipationSerializer(serializers.ModelSerializer): class Meta: model = NodeRatingCount fields = ('likes', 'dislikes', 'rating_count', 'rating_avg', 'comment_count')
""" display user info """ user = ProfileRelationSerializer() class Meta: model = Comment fields = ('user', 'text', 'added',)
identifier_body
serializers.py
from django.contrib.auth import get_user_model User = get_user_model() from rest_framework import serializers from nodeshot.core.base.serializers import ModelValidationSerializer from nodeshot.community.profiles.serializers import ProfileRelationSerializer from .models import Comment, Vote, Rating, NodeRatingCount __all__ = ['CommentSerializer', 'RatingSerializer', 'CommentRelationSerializer', 'VoteSerializer', 'ParticipationSerializer'] class AutoNodeMixin(object): """ automatically adds node to validated_data the node info is taken from views that extend NodeRelationViewMixin """ def validate(self, data): data['node'] = self.context['view'].node return super(AutoNodeMixin, self).validate(data) class CommentSerializer(AutoNodeMixin, ModelValidationSerializer): """ Comment serializer """ node = serializers.ReadOnlyField(source='node.name') username = serializers.ReadOnlyField(source='user.username') class Meta: model = Comment fields = ('node', 'username', 'text', 'added') read_only_fields = ('added',) class CommentRelationSerializer(serializers.ModelSerializer): """ display user info """ user = ProfileRelationSerializer() class Meta: model = Comment fields = ('user', 'text', 'added',) class RatingSerializer(AutoNodeMixin, ModelValidationSerializer): """ Rating serializer """ node = serializers.ReadOnlyField(source='node.name')
class Meta: model = Rating fields = ('node', 'username', 'value',) read_only_fields = ('added',) class VoteSerializer(AutoNodeMixin, ModelValidationSerializer): node = serializers.ReadOnlyField(source='node.name') username = serializers.ReadOnlyField(source='user.username') class Meta: model = Vote fields = ('node', 'username', 'vote',) read_only_fields = ('added',) class ParticipationSerializer(serializers.ModelSerializer): class Meta: model = NodeRatingCount fields = ('likes', 'dislikes', 'rating_count', 'rating_avg', 'comment_count')
username = serializers.ReadOnlyField(source='user.username')
random_line_split
symbollist.py
#!/usr/bin/python # # Request for symbolList. Currently RFA only support refresh messages # for symbolList. Hence, polling is required and symbolListRequest is called # internally by getSymbolList. # # IMAGE/REFRESH:
# {'ACTION':'ADD','MTYPE':'IMAGE','SERVICE':'NIP','RIC':'0#BMD','KEY':'FKLI'}, # {'ACTION':'ADD','MTYPE':'IMAGE','SERVICE':'NIP','RIC':'0#BMD','KEY':'FKLL'}, # {'ACTION':'ADD','MTYPE':'IMAGE','SERVICE':'NIP','RIC':'0#BMD','KEY':'FKLM'}) # import pyrfa p = pyrfa.Pyrfa() p.createConfigDb("./pyrfa.cfg") p.acquireSession("Session3") p.createOMMConsumer() p.login() p.directoryRequest() p.dictionaryRequest() RIC = "0#BMD" symbolList = p.getSymbolList(RIC) print("\n=======\n" + RIC + "\n=======") print(symbolList.replace(" ","\n"))
# ({'MTYPE':'REFRESH','RIC':'0#BMD','SERVICE':'NIP'},
random_line_split
index.js
import axios from 'axios' const basePath = '/api' axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = 'X-CSRFToken' export default { Utils: { getYearsChoiceList: (app, model) => axios({ url: `${basePath}/${app}/${model}/years/`, method: 'GET' }), getModelOrderedList: (app, model, ordering = '', page = 1, query_string = '') => axios({ url: `${basePath}/${app}/${model}/?o=${ordering}&page=${page}${query_string}`, method: 'GET' }), getModelList: (app, model, page = 1, query_string = '') => axios({ url: `${basePath}/${app}/${model}/?page=${page}${query_string}`, method: 'GET' }), getModel: (app, model, id) => axios({ url: `${basePath}/${app}/${model}/${id}/`, method: 'GET' }), getModelAction: (app, model, id, action) => axios({ url: `${basePath}/${app}/${model}/${id}/${action}/`,
url: `${basePath}/${app}/${model}/${action}/?page=${page}`, method: 'GET' }), getByMetadata: (m, query_string = '') => axios({ url: `${basePath}/${m.app}/${m.model}/${m.id}${m.id !== '' ? '/' : ''}${m.action}${m.action !== '' ? '/' : ''}${query_string !== '' ? '?' : ''}${query_string}`, method: 'GET' }) } }
method: 'GET' }), getModelListAction: (app, model, action, page = 1) => axios({
random_line_split
gen_split.py
#!/opt/local/bin/python import string import os def
(n) : return "//\n\ // BAGEL - Brilliantly Advanced General Electronic Structure Library\n\ // Filename: SPCASPT2_gen" + str(n) + ".cc\n\ // Copyright (C) 2014 Toru Shiozaki\n\ //\n\ // Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\ // Maintainer: Shiozaki group\n\ //\n\ // This file is part of the BAGEL package.\n\ //\n\ // This program is free software: you can redistribute it and/or modify\n\ // it under the terms of the GNU General Public License as published by\n\ // the Free Software Foundation, either version 3 of the License, or\n\ // (at your option) any later version.\n\ //\n\ // This program is distributed in the hope that it will be useful,\n\ // but WITHOUT ANY WARRANTY; without even the implied warranty of\n\ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\ // GNU General Public License for more details.\n\ //\n\ // You should have received a copy of the GNU General Public License\n\ // along with this program. If not, see <http://www.gnu.org/licenses/>.\n\ //\n\ \n\ #include <bagel_config.h>\n\ #ifdef COMPILE_SMITH\n\ \n\ #include <src/smith/caspt2/SPCASPT2_tasks" + str(n) + ".h>\n\ \n\ using namespace std;\n\ using namespace bagel;\n\ using namespace bagel::SMITH;\n\ using namespace bagel::SMITH::SPCASPT2;\n\ \n\ " footer = "#endif\n" f = open('SPCASPT2_gen.cc', 'r') lines = f.read().split("\n")[32:] tasks = [] tmp = "" for line in lines: if (line[0:4] == "Task"): if (tmp != ""): tasks.append(tmp) tmp = "" if (line != ""): tmp += line + "\n" if (line == "}"): tmp += "\n" tasks.append(tmp) tmp = "" num = 0 chunk = 50 for i in range(len(tasks)): if (num != 0 and num % chunk == 0): n = num / chunk fout = open("SPCASPT2_gen" + str(n) + ".cc", "w") out = header(n) + tmp + footer fout.write(out) fout.close() tmp = "" num = num+1 tmp = tmp + tasks[i]; n = (num-1) / chunk + 1 fout = open("SPCASPT2_gen" + str(n) + ".cc", "w") out = header(n) + tmp + footer fout.write(out) fout.close() os.remove("SPCASPT2_gen.cc")
header
identifier_name
gen_split.py
#!/opt/local/bin/python import string import os def header(n) : return "//\n\ // BAGEL - Brilliantly Advanced General Electronic Structure Library\n\ // Filename: SPCASPT2_gen" + str(n) + ".cc\n\ // Copyright (C) 2014 Toru Shiozaki\n\ //\n\ // Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\ // Maintainer: Shiozaki group\n\ //\n\ // This file is part of the BAGEL package.\n\ //\n\ // This program is free software: you can redistribute it and/or modify\n\ // it under the terms of the GNU General Public License as published by\n\ // the Free Software Foundation, either version 3 of the License, or\n\ // (at your option) any later version.\n\ //\n\ // This program is distributed in the hope that it will be useful,\n\ // but WITHOUT ANY WARRANTY; without even the implied warranty of\n\ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\ // GNU General Public License for more details.\n\ //\n\ // You should have received a copy of the GNU General Public License\n\ // along with this program. If not, see <http://www.gnu.org/licenses/>.\n\ //\n\ \n\ #include <bagel_config.h>\n\ #ifdef COMPILE_SMITH\n\ \n\ #include <src/smith/caspt2/SPCASPT2_tasks" + str(n) + ".h>\n\ \n\ using namespace std;\n\ using namespace bagel;\n\ using namespace bagel::SMITH;\n\ using namespace bagel::SMITH::SPCASPT2;\n\ \n\ " footer = "#endif\n" f = open('SPCASPT2_gen.cc', 'r') lines = f.read().split("\n")[32:] tasks = [] tmp = "" for line in lines: if (line[0:4] == "Task"): if (tmp != ""):
if (line != ""): tmp += line + "\n" if (line == "}"): tmp += "\n" tasks.append(tmp) tmp = "" num = 0 chunk = 50 for i in range(len(tasks)): if (num != 0 and num % chunk == 0): n = num / chunk fout = open("SPCASPT2_gen" + str(n) + ".cc", "w") out = header(n) + tmp + footer fout.write(out) fout.close() tmp = "" num = num+1 tmp = tmp + tasks[i]; n = (num-1) / chunk + 1 fout = open("SPCASPT2_gen" + str(n) + ".cc", "w") out = header(n) + tmp + footer fout.write(out) fout.close() os.remove("SPCASPT2_gen.cc")
tasks.append(tmp) tmp = ""
conditional_block
gen_split.py
import string import os def header(n) : return "//\n\ // BAGEL - Brilliantly Advanced General Electronic Structure Library\n\ // Filename: SPCASPT2_gen" + str(n) + ".cc\n\ // Copyright (C) 2014 Toru Shiozaki\n\ //\n\ // Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\ // Maintainer: Shiozaki group\n\ //\n\ // This file is part of the BAGEL package.\n\ //\n\ // This program is free software: you can redistribute it and/or modify\n\ // it under the terms of the GNU General Public License as published by\n\ // the Free Software Foundation, either version 3 of the License, or\n\ // (at your option) any later version.\n\ //\n\ // This program is distributed in the hope that it will be useful,\n\ // but WITHOUT ANY WARRANTY; without even the implied warranty of\n\ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\ // GNU General Public License for more details.\n\ //\n\ // You should have received a copy of the GNU General Public License\n\ // along with this program. If not, see <http://www.gnu.org/licenses/>.\n\ //\n\ \n\ #include <bagel_config.h>\n\ #ifdef COMPILE_SMITH\n\ \n\ #include <src/smith/caspt2/SPCASPT2_tasks" + str(n) + ".h>\n\ \n\ using namespace std;\n\ using namespace bagel;\n\ using namespace bagel::SMITH;\n\ using namespace bagel::SMITH::SPCASPT2;\n\ \n\ " footer = "#endif\n" f = open('SPCASPT2_gen.cc', 'r') lines = f.read().split("\n")[32:] tasks = [] tmp = "" for line in lines: if (line[0:4] == "Task"): if (tmp != ""): tasks.append(tmp) tmp = "" if (line != ""): tmp += line + "\n" if (line == "}"): tmp += "\n" tasks.append(tmp) tmp = "" num = 0 chunk = 50 for i in range(len(tasks)): if (num != 0 and num % chunk == 0): n = num / chunk fout = open("SPCASPT2_gen" + str(n) + ".cc", "w") out = header(n) + tmp + footer fout.write(out) fout.close() tmp = "" num = num+1 tmp = tmp + tasks[i]; n = (num-1) / chunk + 1 fout = open("SPCASPT2_gen" + str(n) + ".cc", "w") out = header(n) + tmp + footer fout.write(out) fout.close() os.remove("SPCASPT2_gen.cc")
#!/opt/local/bin/python
random_line_split
gen_split.py
#!/opt/local/bin/python import string import os def header(n) :
footer = "#endif\n" f = open('SPCASPT2_gen.cc', 'r') lines = f.read().split("\n")[32:] tasks = [] tmp = "" for line in lines: if (line[0:4] == "Task"): if (tmp != ""): tasks.append(tmp) tmp = "" if (line != ""): tmp += line + "\n" if (line == "}"): tmp += "\n" tasks.append(tmp) tmp = "" num = 0 chunk = 50 for i in range(len(tasks)): if (num != 0 and num % chunk == 0): n = num / chunk fout = open("SPCASPT2_gen" + str(n) + ".cc", "w") out = header(n) + tmp + footer fout.write(out) fout.close() tmp = "" num = num+1 tmp = tmp + tasks[i]; n = (num-1) / chunk + 1 fout = open("SPCASPT2_gen" + str(n) + ".cc", "w") out = header(n) + tmp + footer fout.write(out) fout.close() os.remove("SPCASPT2_gen.cc")
return "//\n\ // BAGEL - Brilliantly Advanced General Electronic Structure Library\n\ // Filename: SPCASPT2_gen" + str(n) + ".cc\n\ // Copyright (C) 2014 Toru Shiozaki\n\ //\n\ // Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\ // Maintainer: Shiozaki group\n\ //\n\ // This file is part of the BAGEL package.\n\ //\n\ // This program is free software: you can redistribute it and/or modify\n\ // it under the terms of the GNU General Public License as published by\n\ // the Free Software Foundation, either version 3 of the License, or\n\ // (at your option) any later version.\n\ //\n\ // This program is distributed in the hope that it will be useful,\n\ // but WITHOUT ANY WARRANTY; without even the implied warranty of\n\ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\ // GNU General Public License for more details.\n\ //\n\ // You should have received a copy of the GNU General Public License\n\ // along with this program. If not, see <http://www.gnu.org/licenses/>.\n\ //\n\ \n\ #include <bagel_config.h>\n\ #ifdef COMPILE_SMITH\n\ \n\ #include <src/smith/caspt2/SPCASPT2_tasks" + str(n) + ".h>\n\ \n\ using namespace std;\n\ using namespace bagel;\n\ using namespace bagel::SMITH;\n\ using namespace bagel::SMITH::SPCASPT2;\n\ \n\ "
identifier_body
ChunkTask.d.ts
import BaseTask from "./BaseTask"; /** * 分块任务 */ declare class ChunkTask extends BaseTask { private _blocks; private _blockSize; private _chunkSize; /** * 构造函数 * @param file * @param blockSize 块大小 * @param chunkSize 片大小 */ constructor(file: File, blockSize: number, chunkSize: number); /** * 将文件分块 */ spliceFile2Block(): void; /** * 获取所有的block * @returns {Block[]} */ readonly blocks: Block[]; /** * 获取正在处理的block * @returns {Block}
readonly chunks: Chunk[]; /** * 获取正在处理的chunk * @returns {Block} */ readonly processingChunk: Chunk; /** * 总共分片数量(所有分块的分片数量总和) * @returns {number} */ readonly totalChunkCount: number; } /** * 分块,分块大小七牛固定是4M */ declare class Block { private _data; private _start; private _end; private _chunks; private _isFinish; private _processing; private _file; /** * * @param start 起始位置 * @param end 结束位置 * @param data 块数据 * @param chunkSize 分片数据的最大大小 * @param file 分块所属文件 */ constructor(start: number, end: number, data: Blob, chunkSize: number, file: File); /** * 将块分片 */ private spliceBlock2Chunk(chunkSize); /** * 是否上传中 * @returns {boolean} */ processing: boolean; /** * 分块所属的文件 * @returns {File} */ readonly file: File; /** * 是否已经结束 * @returns {boolean} */ isFinish: boolean; /** * 返回分块数据 * @returns {Blob} */ readonly data: Blob; /** * 返回字节起始位置 * @returns {number} */ readonly start: number; /** * 返回字节结束位置 * @returns {number} */ readonly end: number; readonly chunks: Chunk[]; } /** * 分片,分片大小可以自定义,至少1字节 */ declare class Chunk { private _start; private _end; private _data; private _processing; private _isFinish; private _ctx; private _block; private _host; /** * * @param start 字节起始位置 * @param end 字节结束位置 * @param data 分片数据 * @param block 分块对象 */ constructor(start: number, end: number, data: Blob, block: Block); /** * 返回chunk所属的Block对象 * @returns {Block} */ readonly block: Block; /** * 返回字节起始位置 * @returns {number} */ readonly start: number; /** * 返回字节结束位置 * @returns {number} */ readonly end: number; /** * 返回分片数据 * @returns {Blob} */ readonly data: Blob; /** * 是否已经结束 * @returns {boolean} */ isFinish: boolean; host: string; /** * 是否上传中 * @returns {boolean} */ processing: boolean; /** * 返回上传控制信息(七牛服务器返回前一次上传返回的分片上传控制信息,用于下一次上传,第一个chunk此值为空) * @returns {string} */ ctx: string; } export { ChunkTask, Block, Chunk };
*/ readonly processingBlock: Block; readonly finishedBlocksSize: number;
random_line_split
ChunkTask.d.ts
import BaseTask from "./BaseTask"; /** * 分块任务 */ declare class ChunkTask extends BaseTask { private _blocks; private _blockSize; private _chunkSize; /** * 构造函数 * @param file * @param blockSize 块大小 * @param chunkSize 片大小 */ constructor(file: File, blockSize: number, chunkSize: number); /** * 将文件分块 */ spliceFile2Block(): void; /** * 获取所有的block * @returns {Block[]} */ readonly blocks: Block[]; /** * 获取正在处理的block * @returns {Block} */ readonly processingBlock: Block; readonly finishedBlocksSize: number; readonly chunks: Chunk[]; /** * 获取正在处理的chunk * @returns {Block} */ readonly processingChunk: Chunk; /** * 总共分片数量(所有分块的分片数量总和) * @returns {number} */ readonly totalChunkCount: number; } /** * 分块,分块大小七牛固定是4M */ declare class Block { private _data; private _start; private _end; private _chunks; private _isFinish; private _processing; private _file; /** * * @param start 起始位置 * @param end 结束位置 * @param data 块数据 * @param chunkSize 分片数据的最大大小 * @param file 分块所属文件 */ constructor(start: number, end: number, data: Blob, chunkSize: number, file: File); /** * 将块分片 */ private spliceBlock2Chunk(chunkSize); /** * 是否上传中 * @returns {boolean} */ processing: boolean; /** * 分块所属的文件 * @returns {File} */ readonly file: File; /** * 是否已经结束 * @returns {boolean} */ isFinish: boolean; /** * 返回分块数据 * @returns {Blob} */ readonly data: Blob; /** * 返回字节起始位置 * @returns {number} */ readonly start: number; /** * 返回字节结束位置 * @returns {number} */ readonly end: number; readonly chunks: Chunk[]; } /** * 分片,分片大小可以自定义,至少1字节 */ declare class Chunk { private _start; private _end; private _data; private _processing; private _isFinish; private _ctx; private _block; private _host; /** * * @param start 字节起始位置 * @param end 字节结束位置 * @param data 分片数据 * @param block 分块对象 */ constructo
rt: number, end: number, data: Blob, block: Block); /** * 返回chunk所属的Block对象 * @returns {Block} */ readonly block: Block; /** * 返回字节起始位置 * @returns {number} */ readonly start: number; /** * 返回字节结束位置 * @returns {number} */ readonly end: number; /** * 返回分片数据 * @returns {Blob} */ readonly data: Blob; /** * 是否已经结束 * @returns {boolean} */ isFinish: boolean; host: string; /** * 是否上传中 * @returns {boolean} */ processing: boolean; /** * 返回上传控制信息(七牛服务器返回前一次上传返回的分片上传控制信息,用于下一次上传,第一个chunk此值为空) * @returns {string} */ ctx: string; } export { ChunkTask, Block, Chunk };
r(sta
identifier_name
neuroml_via_neurounits_neuron.py
#!/usr/bin/python # -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Copyright (c) 2012 Michael Hull. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------- from morphforge.simulation.neuron.core.neuronsimulationenvironment import NEURONEnvironment from morphforgecontrib.simulation.channels.neuroml_via_neurounits.neuroml_via_neurounits_core import NeuroML_Via_NeuroUnits_Channel from neurounits.importers.neuroml import ChannelMLReader from morphforgecontrib.simulation.channels.neurounits.neuro_units_bridge import Neuron_NeuroUnitEqnsetMechanism class NeuroML_Via_NeuroUnits_ChannelNEURON(Neuron_NeuroUnitEqnsetMechanism, NeuroML_Via_NeuroUnits_Channel):
NEURONEnvironment.channels.register_plugin(NeuroML_Via_NeuroUnits_Channel, NeuroML_Via_NeuroUnits_ChannelNEURON)
def __init__(self, xml_filename, chlname=None,**kwargs): (eqnset, chlinfo, default_params) = ChannelMLReader.BuildEqnset(xml_filename) default_params = dict([(k, v.as_quantities_quantity()) for (k, v) in default_params.iteritems()]) super(NeuroML_Via_NeuroUnits_ChannelNEURON,self).__init__(eqnset=eqnset, default_parameters=default_params, recordables_map=None, recordables_data=None, xml_filename=xml_filename, chlname=chlname, **kwargs)
identifier_body
neuroml_via_neurounits_neuron.py
#!/usr/bin/python # -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Copyright (c) 2012 Michael Hull. # All rights reserved.
# modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------- from morphforge.simulation.neuron.core.neuronsimulationenvironment import NEURONEnvironment from morphforgecontrib.simulation.channels.neuroml_via_neurounits.neuroml_via_neurounits_core import NeuroML_Via_NeuroUnits_Channel from neurounits.importers.neuroml import ChannelMLReader from morphforgecontrib.simulation.channels.neurounits.neuro_units_bridge import Neuron_NeuroUnitEqnsetMechanism class NeuroML_Via_NeuroUnits_ChannelNEURON(Neuron_NeuroUnitEqnsetMechanism, NeuroML_Via_NeuroUnits_Channel): def __init__(self, xml_filename, chlname=None,**kwargs): (eqnset, chlinfo, default_params) = ChannelMLReader.BuildEqnset(xml_filename) default_params = dict([(k, v.as_quantities_quantity()) for (k, v) in default_params.iteritems()]) super(NeuroML_Via_NeuroUnits_ChannelNEURON,self).__init__(eqnset=eqnset, default_parameters=default_params, recordables_map=None, recordables_data=None, xml_filename=xml_filename, chlname=chlname, **kwargs) NEURONEnvironment.channels.register_plugin(NeuroML_Via_NeuroUnits_Channel, NeuroML_Via_NeuroUnits_ChannelNEURON)
# # Redistribution and use in source and binary forms, with or without
random_line_split
neuroml_via_neurounits_neuron.py
#!/usr/bin/python # -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Copyright (c) 2012 Michael Hull. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # - Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------- from morphforge.simulation.neuron.core.neuronsimulationenvironment import NEURONEnvironment from morphforgecontrib.simulation.channels.neuroml_via_neurounits.neuroml_via_neurounits_core import NeuroML_Via_NeuroUnits_Channel from neurounits.importers.neuroml import ChannelMLReader from morphforgecontrib.simulation.channels.neurounits.neuro_units_bridge import Neuron_NeuroUnitEqnsetMechanism class
(Neuron_NeuroUnitEqnsetMechanism, NeuroML_Via_NeuroUnits_Channel): def __init__(self, xml_filename, chlname=None,**kwargs): (eqnset, chlinfo, default_params) = ChannelMLReader.BuildEqnset(xml_filename) default_params = dict([(k, v.as_quantities_quantity()) for (k, v) in default_params.iteritems()]) super(NeuroML_Via_NeuroUnits_ChannelNEURON,self).__init__(eqnset=eqnset, default_parameters=default_params, recordables_map=None, recordables_data=None, xml_filename=xml_filename, chlname=chlname, **kwargs) NEURONEnvironment.channels.register_plugin(NeuroML_Via_NeuroUnits_Channel, NeuroML_Via_NeuroUnits_ChannelNEURON)
NeuroML_Via_NeuroUnits_ChannelNEURON
identifier_name
process_warnings.py
""" Script to process pytest warnings output by pytest-json-report plugin and output it as a html """ from __future__ import absolute_import from __future__ import print_function import json import os import io import re import argparse from collections import Counter import pandas as pd from write_to_html import ( HtmlOutlineWriter, ) # noqa pylint: disable=import-error,useless-suppression columns = [ "message", "category", "filename", "lineno", "high_location", "label", "num", "deprecated", ] columns_index_dict = {key: index for index, key in enumerate(columns)} def seperate_warnings_by_location(warnings_data): """ Warnings originate from multiple locations, this function takes in list of warning objects and separates them based on their filename location """ # first create regex for each n file location warnings_locations = { ".*/python\d\.\d/site-packages/.*\.py": "python", # noqa pylint: disable=W1401 ".*/edx-platform/lms/.*\.py": "lms", # noqa pylint: disable=W1401 ".*/edx-platform/openedx/.*\.py": "openedx", # noqa pylint: disable=W1401 ".*/edx-platform/cms/.*\.py": "cms", # noqa pylint: disable=W1401 ".*/edx-platform/common/.*\.py": "common", # noqa pylint: disable=W1401 } # separate into locations flow: # - iterate through each wanring_object, see if its filename matches any regex in warning locations. # - If so, change high_location index on warnings_object to location name for warnings_object in warnings_data: warning_origin_located = False for key in warnings_locations: if ( re.search(key, warnings_object[columns_index_dict["filename"]]) is not None ): warnings_object[ columns_index_dict["high_location"] ] = warnings_locations[key] warning_origin_located = True break if not warning_origin_located: warnings_object[columns_index_dict["high_location"]] = "other" return warnings_data def convert_warning_dict_to_list(warning_dict): """ converts our data dict into our defined list based on columns defined at top of this file """ output = [] for column in columns: if column in warning_dict: output.append(warning_dict[column]) else: output.append(None) output[columns_index_dict["num"]] = 1 return output def read_warning_data(dir_path): """ During test runs in jenkins, multiple warning json files are output. This function finds all files and aggregates the warnings in to one large list """ # pdb.set_trace() dir_path = os.path.expanduser(dir_path) # find all files that exist in given directory files_in_dir = [ f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) ] warnings_files = [] # TODO(jinder): currently this is hard-coded in, maybe create a constants file with info # THINK(jinder): but creating file for one constant seems overkill warnings_file_name_regex = ( "pytest_warnings_?\d*\.json" # noqa pylint: disable=W1401 ) # iterate through files_in_dir and see if they match our know file name pattern for temp_file in files_in_dir: if re.search(warnings_file_name_regex, temp_file) is not None: warnings_files.append(temp_file) # go through each warning file and aggregate warnings into warnings_data warnings_data = [] for temp_file in warnings_files: with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file: json_input = json.load(read_file) if "warnings" in json_input: data = [ convert_warning_dict_to_list(warning_dict) for warning_dict in json_input["warnings"] ] warnings_data.extend(data) else: print(temp_file) return warnings_data def compress_similar_warnings(warnings_data): """ find all warnings that are exactly the same, count them, and return set with count added to each warning """ tupled_data = [tuple(data) for data in warnings_data] test_counter = Counter(tupled_data) output = [list(value) for value in test_counter.keys()] for data_object in output: data_object[columns_index_dict["num"]] = test_counter[tuple(data_object)] return output def process_warnings_json(dir_path): """ Master function to process through all warnings and output a dict dict structure: { location: [{warning text: {file_name: warning object}}] } flow: - Aggregate data from all warning files - Separate warnings by deprecated vs non deprecated(has word deprecate in it) - Further categorize warnings - Return output Possible Error/enhancement: there might be better ways to separate deprecates vs non-deprecated warnings """ warnings_data = read_warning_data(dir_path) for warnings_object in warnings_data: warnings_object[columns_index_dict["deprecated"]] = bool( "deprecated" in warnings_object[columns_index_dict["message"]] ) warnings_data = seperate_warnings_by_location(warnings_data) compressed_warnings_data = compress_similar_warnings(warnings_data) return compressed_warnings_data def group_and_sort_by_sumof(dataframe, group, sort_by): groups_by = dataframe.groupby(group) temp_list_to_sort = [(key, value, value[sort_by].sum()) for key, value in groups_by] # sort by count return sorted(temp_list_to_sort, key=lambda x: -x[2]) def write_html_report(warnings_dataframe, html_path):
if __name__ == "__main__": parser = argparse.ArgumentParser( description="Process and categorize pytest warnings and output html report." ) parser.add_argument("--dir-path", default="test_root/log") parser.add_argument("--html-path", default="test_html.html") args = parser.parse_args() data_output = process_warnings_json(args.dir_path) data_dataframe = pd.DataFrame(data=data_output, columns=columns) write_html_report(data_dataframe, args.html_path)
""" converts from panda dataframe to our html """ html_path = os.path.expanduser(html_path) if "/" in html_path: location_of_last_dir = html_path.rfind("/") dir_path = html_path[:location_of_last_dir] os.makedirs(dir_path, exist_ok=True) with io.open(html_path, "w") as fout: html_writer = HtmlOutlineWriter(fout) category_sorted_by_count = group_and_sort_by_sumof( warnings_dataframe, "category", "num" ) for category, group_in_category, category_count in category_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{category}, count: {count}</span> '.format( category=category, count=category_count ) html_writer.start_section(html, klass=u"category") locations_sorted_by_count = group_and_sort_by_sumof( group_in_category, "high_location", "num" ) for ( location, group_in_location, location_count, ) in locations_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{location}, count: {count}</span> '.format( location=location, count=location_count ) html_writer.start_section(html, klass=u"location") message_group_sorted_by_count = group_and_sort_by_sumof( group_in_location, "message", "num" ) for ( message, message_group, message_count, ) in message_group_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_text}, count: {count}</span> '.format( warning_text=message, count=message_count ) html_writer.start_section(html, klass=u"warning_text") # warnings_object[location][warning_text] is a list for _, warning in message_group.iterrows(): # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_file_path}</span> '.format( warning_file_path=warning["filename"] ) html_writer.start_section(html, klass=u"warning") # xss-lint: disable=python-wrap-html html = u'<p class="lineno">lineno: {lineno}</p> '.format( lineno=warning["lineno"] ) html_writer.write(html) # xss-lint: disable=python-wrap-html html = u'<p class="num">num_occur: {num}</p> '.format( num=warning["num"] ) html_writer.write(html) html_writer.end_section() html_writer.end_section() html_writer.end_section() html_writer.end_section()
identifier_body
process_warnings.py
""" Script to process pytest warnings output by pytest-json-report plugin and output it as a html """ from __future__ import absolute_import from __future__ import print_function import json import os import io import re import argparse from collections import Counter import pandas as pd from write_to_html import ( HtmlOutlineWriter, ) # noqa pylint: disable=import-error,useless-suppression columns = [ "message", "category", "filename", "lineno", "high_location", "label", "num", "deprecated", ] columns_index_dict = {key: index for index, key in enumerate(columns)} def seperate_warnings_by_location(warnings_data): """ Warnings originate from multiple locations, this function takes in list of warning objects and separates them based on their filename location """ # first create regex for each n file location warnings_locations = { ".*/python\d\.\d/site-packages/.*\.py": "python", # noqa pylint: disable=W1401 ".*/edx-platform/lms/.*\.py": "lms", # noqa pylint: disable=W1401 ".*/edx-platform/openedx/.*\.py": "openedx", # noqa pylint: disable=W1401 ".*/edx-platform/cms/.*\.py": "cms", # noqa pylint: disable=W1401 ".*/edx-platform/common/.*\.py": "common", # noqa pylint: disable=W1401 } # separate into locations flow: # - iterate through each wanring_object, see if its filename matches any regex in warning locations. # - If so, change high_location index on warnings_object to location name for warnings_object in warnings_data: warning_origin_located = False for key in warnings_locations: if ( re.search(key, warnings_object[columns_index_dict["filename"]]) is not None ): warnings_object[ columns_index_dict["high_location"] ] = warnings_locations[key] warning_origin_located = True break if not warning_origin_located: warnings_object[columns_index_dict["high_location"]] = "other" return warnings_data def convert_warning_dict_to_list(warning_dict): """ converts our data dict into our defined list based on columns defined at top of this file """ output = [] for column in columns: if column in warning_dict: output.append(warning_dict[column]) else: output.append(None) output[columns_index_dict["num"]] = 1 return output def read_warning_data(dir_path): """ During test runs in jenkins, multiple warning json files are output. This function finds all files and aggregates the warnings in to one large list """ # pdb.set_trace() dir_path = os.path.expanduser(dir_path) # find all files that exist in given directory files_in_dir = [ f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) ] warnings_files = [] # TODO(jinder): currently this is hard-coded in, maybe create a constants file with info # THINK(jinder): but creating file for one constant seems overkill warnings_file_name_regex = ( "pytest_warnings_?\d*\.json" # noqa pylint: disable=W1401 ) # iterate through files_in_dir and see if they match our know file name pattern for temp_file in files_in_dir:
# go through each warning file and aggregate warnings into warnings_data warnings_data = [] for temp_file in warnings_files: with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file: json_input = json.load(read_file) if "warnings" in json_input: data = [ convert_warning_dict_to_list(warning_dict) for warning_dict in json_input["warnings"] ] warnings_data.extend(data) else: print(temp_file) return warnings_data def compress_similar_warnings(warnings_data): """ find all warnings that are exactly the same, count them, and return set with count added to each warning """ tupled_data = [tuple(data) for data in warnings_data] test_counter = Counter(tupled_data) output = [list(value) for value in test_counter.keys()] for data_object in output: data_object[columns_index_dict["num"]] = test_counter[tuple(data_object)] return output def process_warnings_json(dir_path): """ Master function to process through all warnings and output a dict dict structure: { location: [{warning text: {file_name: warning object}}] } flow: - Aggregate data from all warning files - Separate warnings by deprecated vs non deprecated(has word deprecate in it) - Further categorize warnings - Return output Possible Error/enhancement: there might be better ways to separate deprecates vs non-deprecated warnings """ warnings_data = read_warning_data(dir_path) for warnings_object in warnings_data: warnings_object[columns_index_dict["deprecated"]] = bool( "deprecated" in warnings_object[columns_index_dict["message"]] ) warnings_data = seperate_warnings_by_location(warnings_data) compressed_warnings_data = compress_similar_warnings(warnings_data) return compressed_warnings_data def group_and_sort_by_sumof(dataframe, group, sort_by): groups_by = dataframe.groupby(group) temp_list_to_sort = [(key, value, value[sort_by].sum()) for key, value in groups_by] # sort by count return sorted(temp_list_to_sort, key=lambda x: -x[2]) def write_html_report(warnings_dataframe, html_path): """ converts from panda dataframe to our html """ html_path = os.path.expanduser(html_path) if "/" in html_path: location_of_last_dir = html_path.rfind("/") dir_path = html_path[:location_of_last_dir] os.makedirs(dir_path, exist_ok=True) with io.open(html_path, "w") as fout: html_writer = HtmlOutlineWriter(fout) category_sorted_by_count = group_and_sort_by_sumof( warnings_dataframe, "category", "num" ) for category, group_in_category, category_count in category_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{category}, count: {count}</span> '.format( category=category, count=category_count ) html_writer.start_section(html, klass=u"category") locations_sorted_by_count = group_and_sort_by_sumof( group_in_category, "high_location", "num" ) for ( location, group_in_location, location_count, ) in locations_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{location}, count: {count}</span> '.format( location=location, count=location_count ) html_writer.start_section(html, klass=u"location") message_group_sorted_by_count = group_and_sort_by_sumof( group_in_location, "message", "num" ) for ( message, message_group, message_count, ) in message_group_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_text}, count: {count}</span> '.format( warning_text=message, count=message_count ) html_writer.start_section(html, klass=u"warning_text") # warnings_object[location][warning_text] is a list for _, warning in message_group.iterrows(): # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_file_path}</span> '.format( warning_file_path=warning["filename"] ) html_writer.start_section(html, klass=u"warning") # xss-lint: disable=python-wrap-html html = u'<p class="lineno">lineno: {lineno}</p> '.format( lineno=warning["lineno"] ) html_writer.write(html) # xss-lint: disable=python-wrap-html html = u'<p class="num">num_occur: {num}</p> '.format( num=warning["num"] ) html_writer.write(html) html_writer.end_section() html_writer.end_section() html_writer.end_section() html_writer.end_section() if __name__ == "__main__": parser = argparse.ArgumentParser( description="Process and categorize pytest warnings and output html report." ) parser.add_argument("--dir-path", default="test_root/log") parser.add_argument("--html-path", default="test_html.html") args = parser.parse_args() data_output = process_warnings_json(args.dir_path) data_dataframe = pd.DataFrame(data=data_output, columns=columns) write_html_report(data_dataframe, args.html_path)
if re.search(warnings_file_name_regex, temp_file) is not None: warnings_files.append(temp_file)
conditional_block
process_warnings.py
""" Script to process pytest warnings output by pytest-json-report plugin and output it as a html """ from __future__ import absolute_import from __future__ import print_function import json import os import io import re import argparse from collections import Counter import pandas as pd from write_to_html import ( HtmlOutlineWriter, ) # noqa pylint: disable=import-error,useless-suppression columns = [ "message", "category", "filename", "lineno", "high_location", "label", "num", "deprecated", ] columns_index_dict = {key: index for index, key in enumerate(columns)} def seperate_warnings_by_location(warnings_data): """ Warnings originate from multiple locations, this function takes in list of warning objects and separates them based on their filename location """ # first create regex for each n file location warnings_locations = { ".*/python\d\.\d/site-packages/.*\.py": "python", # noqa pylint: disable=W1401 ".*/edx-platform/lms/.*\.py": "lms", # noqa pylint: disable=W1401 ".*/edx-platform/openedx/.*\.py": "openedx", # noqa pylint: disable=W1401 ".*/edx-platform/cms/.*\.py": "cms", # noqa pylint: disable=W1401 ".*/edx-platform/common/.*\.py": "common", # noqa pylint: disable=W1401 } # separate into locations flow: # - iterate through each wanring_object, see if its filename matches any regex in warning locations. # - If so, change high_location index on warnings_object to location name for warnings_object in warnings_data: warning_origin_located = False for key in warnings_locations: if ( re.search(key, warnings_object[columns_index_dict["filename"]]) is not None ): warnings_object[ columns_index_dict["high_location"] ] = warnings_locations[key] warning_origin_located = True break if not warning_origin_located: warnings_object[columns_index_dict["high_location"]] = "other" return warnings_data def convert_warning_dict_to_list(warning_dict): """ converts our data dict into our defined list based on columns defined at top of this file """ output = [] for column in columns: if column in warning_dict: output.append(warning_dict[column]) else: output.append(None) output[columns_index_dict["num"]] = 1 return output def read_warning_data(dir_path): """ During test runs in jenkins, multiple warning json files are output. This function finds all files and aggregates the warnings in to one large list """ # pdb.set_trace() dir_path = os.path.expanduser(dir_path) # find all files that exist in given directory files_in_dir = [ f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) ] warnings_files = [] # TODO(jinder): currently this is hard-coded in, maybe create a constants file with info # THINK(jinder): but creating file for one constant seems overkill warnings_file_name_regex = ( "pytest_warnings_?\d*\.json" # noqa pylint: disable=W1401 ) # iterate through files_in_dir and see if they match our know file name pattern for temp_file in files_in_dir: if re.search(warnings_file_name_regex, temp_file) is not None: warnings_files.append(temp_file) # go through each warning file and aggregate warnings into warnings_data warnings_data = [] for temp_file in warnings_files: with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file: json_input = json.load(read_file) if "warnings" in json_input: data = [ convert_warning_dict_to_list(warning_dict) for warning_dict in json_input["warnings"] ] warnings_data.extend(data) else: print(temp_file) return warnings_data def compress_similar_warnings(warnings_data): """ find all warnings that are exactly the same, count them, and return set with count added to each warning """ tupled_data = [tuple(data) for data in warnings_data] test_counter = Counter(tupled_data) output = [list(value) for value in test_counter.keys()] for data_object in output: data_object[columns_index_dict["num"]] = test_counter[tuple(data_object)] return output def process_warnings_json(dir_path): """ Master function to process through all warnings and output a dict dict structure: { location: [{warning text: {file_name: warning object}}] } flow: - Aggregate data from all warning files - Separate warnings by deprecated vs non deprecated(has word deprecate in it) - Further categorize warnings - Return output Possible Error/enhancement: there might be better ways to separate deprecates vs non-deprecated warnings """ warnings_data = read_warning_data(dir_path) for warnings_object in warnings_data: warnings_object[columns_index_dict["deprecated"]] = bool( "deprecated" in warnings_object[columns_index_dict["message"]] ) warnings_data = seperate_warnings_by_location(warnings_data) compressed_warnings_data = compress_similar_warnings(warnings_data) return compressed_warnings_data def group_and_sort_by_sumof(dataframe, group, sort_by): groups_by = dataframe.groupby(group) temp_list_to_sort = [(key, value, value[sort_by].sum()) for key, value in groups_by] # sort by count return sorted(temp_list_to_sort, key=lambda x: -x[2]) def
(warnings_dataframe, html_path): """ converts from panda dataframe to our html """ html_path = os.path.expanduser(html_path) if "/" in html_path: location_of_last_dir = html_path.rfind("/") dir_path = html_path[:location_of_last_dir] os.makedirs(dir_path, exist_ok=True) with io.open(html_path, "w") as fout: html_writer = HtmlOutlineWriter(fout) category_sorted_by_count = group_and_sort_by_sumof( warnings_dataframe, "category", "num" ) for category, group_in_category, category_count in category_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{category}, count: {count}</span> '.format( category=category, count=category_count ) html_writer.start_section(html, klass=u"category") locations_sorted_by_count = group_and_sort_by_sumof( group_in_category, "high_location", "num" ) for ( location, group_in_location, location_count, ) in locations_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{location}, count: {count}</span> '.format( location=location, count=location_count ) html_writer.start_section(html, klass=u"location") message_group_sorted_by_count = group_and_sort_by_sumof( group_in_location, "message", "num" ) for ( message, message_group, message_count, ) in message_group_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_text}, count: {count}</span> '.format( warning_text=message, count=message_count ) html_writer.start_section(html, klass=u"warning_text") # warnings_object[location][warning_text] is a list for _, warning in message_group.iterrows(): # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_file_path}</span> '.format( warning_file_path=warning["filename"] ) html_writer.start_section(html, klass=u"warning") # xss-lint: disable=python-wrap-html html = u'<p class="lineno">lineno: {lineno}</p> '.format( lineno=warning["lineno"] ) html_writer.write(html) # xss-lint: disable=python-wrap-html html = u'<p class="num">num_occur: {num}</p> '.format( num=warning["num"] ) html_writer.write(html) html_writer.end_section() html_writer.end_section() html_writer.end_section() html_writer.end_section() if __name__ == "__main__": parser = argparse.ArgumentParser( description="Process and categorize pytest warnings and output html report." ) parser.add_argument("--dir-path", default="test_root/log") parser.add_argument("--html-path", default="test_html.html") args = parser.parse_args() data_output = process_warnings_json(args.dir_path) data_dataframe = pd.DataFrame(data=data_output, columns=columns) write_html_report(data_dataframe, args.html_path)
write_html_report
identifier_name
process_warnings.py
""" Script to process pytest warnings output by pytest-json-report plugin and output it as a html """ from __future__ import absolute_import from __future__ import print_function import json import os import io import re import argparse from collections import Counter import pandas as pd from write_to_html import ( HtmlOutlineWriter, ) # noqa pylint: disable=import-error,useless-suppression columns = [ "message", "category", "filename", "lineno", "high_location", "label", "num", "deprecated", ] columns_index_dict = {key: index for index, key in enumerate(columns)} def seperate_warnings_by_location(warnings_data): """ Warnings originate from multiple locations, this function takes in list of warning objects and separates them based on their filename location """ # first create regex for each n file location warnings_locations = { ".*/python\d\.\d/site-packages/.*\.py": "python", # noqa pylint: disable=W1401 ".*/edx-platform/lms/.*\.py": "lms", # noqa pylint: disable=W1401 ".*/edx-platform/openedx/.*\.py": "openedx", # noqa pylint: disable=W1401 ".*/edx-platform/cms/.*\.py": "cms", # noqa pylint: disable=W1401 ".*/edx-platform/common/.*\.py": "common", # noqa pylint: disable=W1401 } # separate into locations flow: # - iterate through each wanring_object, see if its filename matches any regex in warning locations. # - If so, change high_location index on warnings_object to location name for warnings_object in warnings_data: warning_origin_located = False for key in warnings_locations: if ( re.search(key, warnings_object[columns_index_dict["filename"]]) is not None ): warnings_object[ columns_index_dict["high_location"] ] = warnings_locations[key] warning_origin_located = True break if not warning_origin_located: warnings_object[columns_index_dict["high_location"]] = "other" return warnings_data def convert_warning_dict_to_list(warning_dict): """ converts our data dict into our defined list based on columns defined at top of this file """ output = [] for column in columns: if column in warning_dict: output.append(warning_dict[column]) else: output.append(None) output[columns_index_dict["num"]] = 1 return output
def read_warning_data(dir_path): """ During test runs in jenkins, multiple warning json files are output. This function finds all files and aggregates the warnings in to one large list """ # pdb.set_trace() dir_path = os.path.expanduser(dir_path) # find all files that exist in given directory files_in_dir = [ f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) ] warnings_files = [] # TODO(jinder): currently this is hard-coded in, maybe create a constants file with info # THINK(jinder): but creating file for one constant seems overkill warnings_file_name_regex = ( "pytest_warnings_?\d*\.json" # noqa pylint: disable=W1401 ) # iterate through files_in_dir and see if they match our know file name pattern for temp_file in files_in_dir: if re.search(warnings_file_name_regex, temp_file) is not None: warnings_files.append(temp_file) # go through each warning file and aggregate warnings into warnings_data warnings_data = [] for temp_file in warnings_files: with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file: json_input = json.load(read_file) if "warnings" in json_input: data = [ convert_warning_dict_to_list(warning_dict) for warning_dict in json_input["warnings"] ] warnings_data.extend(data) else: print(temp_file) return warnings_data def compress_similar_warnings(warnings_data): """ find all warnings that are exactly the same, count them, and return set with count added to each warning """ tupled_data = [tuple(data) for data in warnings_data] test_counter = Counter(tupled_data) output = [list(value) for value in test_counter.keys()] for data_object in output: data_object[columns_index_dict["num"]] = test_counter[tuple(data_object)] return output def process_warnings_json(dir_path): """ Master function to process through all warnings and output a dict dict structure: { location: [{warning text: {file_name: warning object}}] } flow: - Aggregate data from all warning files - Separate warnings by deprecated vs non deprecated(has word deprecate in it) - Further categorize warnings - Return output Possible Error/enhancement: there might be better ways to separate deprecates vs non-deprecated warnings """ warnings_data = read_warning_data(dir_path) for warnings_object in warnings_data: warnings_object[columns_index_dict["deprecated"]] = bool( "deprecated" in warnings_object[columns_index_dict["message"]] ) warnings_data = seperate_warnings_by_location(warnings_data) compressed_warnings_data = compress_similar_warnings(warnings_data) return compressed_warnings_data def group_and_sort_by_sumof(dataframe, group, sort_by): groups_by = dataframe.groupby(group) temp_list_to_sort = [(key, value, value[sort_by].sum()) for key, value in groups_by] # sort by count return sorted(temp_list_to_sort, key=lambda x: -x[2]) def write_html_report(warnings_dataframe, html_path): """ converts from panda dataframe to our html """ html_path = os.path.expanduser(html_path) if "/" in html_path: location_of_last_dir = html_path.rfind("/") dir_path = html_path[:location_of_last_dir] os.makedirs(dir_path, exist_ok=True) with io.open(html_path, "w") as fout: html_writer = HtmlOutlineWriter(fout) category_sorted_by_count = group_and_sort_by_sumof( warnings_dataframe, "category", "num" ) for category, group_in_category, category_count in category_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{category}, count: {count}</span> '.format( category=category, count=category_count ) html_writer.start_section(html, klass=u"category") locations_sorted_by_count = group_and_sort_by_sumof( group_in_category, "high_location", "num" ) for ( location, group_in_location, location_count, ) in locations_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{location}, count: {count}</span> '.format( location=location, count=location_count ) html_writer.start_section(html, klass=u"location") message_group_sorted_by_count = group_and_sort_by_sumof( group_in_location, "message", "num" ) for ( message, message_group, message_count, ) in message_group_sorted_by_count: # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_text}, count: {count}</span> '.format( warning_text=message, count=message_count ) html_writer.start_section(html, klass=u"warning_text") # warnings_object[location][warning_text] is a list for _, warning in message_group.iterrows(): # xss-lint: disable=python-wrap-html html = u'<span class="count">{warning_file_path}</span> '.format( warning_file_path=warning["filename"] ) html_writer.start_section(html, klass=u"warning") # xss-lint: disable=python-wrap-html html = u'<p class="lineno">lineno: {lineno}</p> '.format( lineno=warning["lineno"] ) html_writer.write(html) # xss-lint: disable=python-wrap-html html = u'<p class="num">num_occur: {num}</p> '.format( num=warning["num"] ) html_writer.write(html) html_writer.end_section() html_writer.end_section() html_writer.end_section() html_writer.end_section() if __name__ == "__main__": parser = argparse.ArgumentParser( description="Process and categorize pytest warnings and output html report." ) parser.add_argument("--dir-path", default="test_root/log") parser.add_argument("--html-path", default="test_html.html") args = parser.parse_args() data_output = process_warnings_json(args.dir_path) data_dataframe = pd.DataFrame(data=data_output, columns=columns) write_html_report(data_dataframe, args.html_path)
random_line_split
dict.js
var oper = { width : 400, height : 500, form : document.form1, jqgrid : function() { var fields = $("form").serializeArray(); var jsonData = {}; jQuery.each( fields, function(i, field){ jsonData[field.name]=field.value; }); $('#jqGrid').jqGrid('setGridParam', { postData : jsonData }).trigger('reloadGrid'); return false; }, list : function() { oper.jqgrid(); }, view : function(id) { var url = 'system/dict/view/'+id; var title = '查看数据字典类型'; Iframe(url, this.width, this.height, title, false, false, false, EmptyFunc); }, add : function() { var url = 'system/dict/add'; var title = '添加数据字典类型'; Iframe(url, this.width, this.height, title); }, edit : function(id) { var url = 'system/dict/edit/'+id; var title = '修改数据字典类型'; Iframe(url, this.width, this.height, title); }, del : function(id) { var title = '确认要删除该数据字典类型信息?'; var url = 'system/dict/delete/'+id; Confirm(title, function() { ajax_post(url,null, function (data) { if(data.code==0){ oper.list(); } else { ErrorInfo('操作失败:'+data.msg); } }); }); } }; // 初始化 jQuery(function($) { // 加载jqgrid var editStr = $('#jqGridEdit').html(); $('#jqGrid').jqGrid({ url:"system/dict/jqgrid", mtype: "POST", styleUI : 'Bootstrap',
{label: "类型",name: 'type',width: 120,sortable:true}, {label: "备注",name: 'remark',width: 120,sortable:true}, {label: "是否启用",name: 'enable',width: 120,sortable:true,hidden:true}, {label : "更新时间",name: 'updateTime',width: 240}, {label : "更新人",name: 'updateName',width: 160,sortable:false}, {label : "创建时间",name: 'createTime',width: 240}, {label : "创建人",name: 'createName',width: 160,sortable:false}, { name: '操作', index: '', width: 200, fixed: true, sortable: false, resize: false, formatter: function(cellvalue, options, rowObject) { var replaceStr = "\\[id\\]"; var buttonStr = editStr; try{ buttonStr = buttonStr.replace(/\r\n/g,""); buttonStr = buttonStr.replace(/\n/g,""); buttonStr = buttonStr.replace(new RegExp(replaceStr,'gm'),rowObject.id ); }catch(e) { alert(e.message); } return buttonStr ; } } ], rownumbers: true, sortname: 'id', viewrecords: true, autowidth: true, width: 1050, height: 630, rowNum: 20, caption: "数据字典类型列表", pager: "#jqGridPager" }); // 宽高自适应 $("#jqGrid").setGridHeight($(window).height() - 250); $("#tree").height($(window).height() - 150); $(window).resize(function(){ $(window).unbind("onresize"); $("#jqGrid").setGridHeight($(window).height() - 250).jqGrid('setGridWidth', $('#data_content').width() - 5); $("#tree").height($(window).height() - 150); $(window).bind("onresize", this); }); $('#jqGrid').jqGrid('navGrid',"#jqGridPager", { search: false, // show search button on the toolbar add: false, edit: false, del: false, refresh: true, view: false }); $('#jqGrid').navButtonAdd('#jqGridPager', { buttonicon: "glyphicon-plus", title: "新增", caption: "新增", position: "first", onClickButton: function(){ oper.add(); } }); });
datatype: "json", colModel: [ {label: "id",name: 'id',width: 75,hidden:true,key:true}, {label: "名称",name: 'name',width: 120,sortable:true},
random_line_split
dict.js
var oper = { width : 400, height : 500, form : document.form1, jqgrid : function() { var fields = $("form").serializeArray(); var jsonData = {}; jQuery.each( fields, function(i, field){ jsonData[field.name]=field.value; }); $('#jqGrid').jqGrid('setGridParam', { postData : jsonData }).trigger('reloadGrid'); return false; }, list : function() { oper.jqgrid(); }, view : function(id) { var url = 'system/dict/view/'+id; var title = '查看数据字典类型'; Iframe(url, this.width, this.height, title, false, false, false, EmptyFunc); }, add : function() { var url = 'system/dict/add'; var title = '添加数据字典类型'; Iframe(url, this.width, this.height, title); }, edit : function(id) { var url = 'system/dict/edit/'+id; var title = '修改数据字典类型'; Iframe(url, this.width, this.height, title); }, del : function(id) { var title = '确认要删除该数据字典类型信息?'; var url = 'system/dict/delete/'+id; Confirm(title, function() { ajax_post(url,null, function (data) { if(data.code==0){ oper.list(); } else { ErrorInfo('操作失败:'+data.msg); }
ar editStr = $('#jqGridEdit').html(); $('#jqGrid').jqGrid({ url:"system/dict/jqgrid", mtype: "POST", styleUI : 'Bootstrap', datatype: "json", colModel: [ {label: "id",name: 'id',width: 75,hidden:true,key:true}, {label: "名称",name: 'name',width: 120,sortable:true}, {label: "类型",name: 'type',width: 120,sortable:true}, {label: "备注",name: 'remark',width: 120,sortable:true}, {label: "是否启用",name: 'enable',width: 120,sortable:true,hidden:true}, {label : "更新时间",name: 'updateTime',width: 240}, {label : "更新人",name: 'updateName',width: 160,sortable:false}, {label : "创建时间",name: 'createTime',width: 240}, {label : "创建人",name: 'createName',width: 160,sortable:false}, { name: '操作', index: '', width: 200, fixed: true, sortable: false, resize: false, formatter: function(cellvalue, options, rowObject) { var replaceStr = "\\[id\\]"; var buttonStr = editStr; try{ buttonStr = buttonStr.replace(/\r\n/g,""); buttonStr = buttonStr.replace(/\n/g,""); buttonStr = buttonStr.replace(new RegExp(replaceStr,'gm'),rowObject.id ); }catch(e) { alert(e.message); } return buttonStr ; } } ], rownumbers: true, sortname: 'id', viewrecords: true, autowidth: true, width: 1050, height: 630, rowNum: 20, caption: "数据字典类型列表", pager: "#jqGridPager" }); // 宽高自适应 $("#jqGrid").setGridHeight($(window).height() - 250); $("#tree").height($(window).height() - 150); $(window).resize(function(){ $(window).unbind("onresize"); $("#jqGrid").setGridHeight($(window).height() - 250).jqGrid('setGridWidth', $('#data_content').width() - 5); $("#tree").height($(window).height() - 150); $(window).bind("onresize", this); }); $('#jqGrid').jqGrid('navGrid',"#jqGridPager", { search: false, // show search button on the toolbar add: false, edit: false, del: false, refresh: true, view: false }); $('#jqGrid').navButtonAdd('#jqGridPager', { buttonicon: "glyphicon-plus", title: "新增", caption: "新增", position: "first", onClickButton: function(){ oper.add(); } }); });
}); }); } }; // 初始化 jQuery(function($) { // 加载jqgrid v
conditional_block
crdb_mobile.js
var CRDB_mobile = { // Message displayed above group record buttons group_record_message: 'This resource is available from multiple vendors. Please select a link button below.', // Sets up a mapping of resource field internal names to display names. Customizable by sites. field_map: { access: 'Access', alert: 'Alert', allows_coursepacks: 'Allows Coursepacks', allows_ereserves: 'Allows Electronic Reserves', allows_ill: 'Allows Interlibrary Loans', coverage: 'Coverage', description_full: 'Description', ill_notes: 'Interlibrary Loan Notes', name: 'Name', open_access: 'Open Access', print_equivalents: 'Print Equivalents', refworks_compatible: 'Refworks Compatible', resolver_enabled: 'Resolver Enabled', resource_type: 'Resource Type', simultaneous_users: 'Simultaneous Users', subjects: 'Subjects', title_list_url: 'Title List URL', update_frequency: 'Update Frequency', url: 'Connect', user_documentation: 'User Documentation', vendor: 'Vendor' }, // Override display fields - if you want to show different fields in your mobile site than in your // main site, you can override the list of fields for display here. display_fields_override: null, /* --- jQuery Mobile page setups. These can be overridden if necessary, but I'm trying to add hooks to avoid that where I can --- */ initApp: function() { var app = this; this.initPages(); $('#home').one( 'pagecreate', function() { var url = document.URL; var reg = /id=(\d+)/; var match = reg.exec(url); if ( match ) { app.saveToSessionStorage({ resource_id: match[1] }); $.mobile.changePage( '#full' ); } }); }, initPages: function() { this.initAZPage(); this.initSubjectsPage(); this.initResourcesPage(); this.initFullPage(); }, initAZPage: function() { var app = this; $('div#az').live('pagebeforecreate', function(event) { var page = $(event.currentTarget); var az_list = page.find('ul'); az_list.delegate('a', 'click', function() { app.saveToSessionStorage({ resources_search_type: 'name', resources_search_value: $(this).attr('letter'), resources_title_text: $(this).attr('letter') }, 'resources_reload'); }); }); }, initSubjectsPage: function() { var app = this; $('div#subjects').live('pagebeforecreate', function(event) { var page = $(event.currentTarget); var subject_list = page.find('ul'); var loader = app.createLoader(); page.append(loader); $.getJSON( app.subjects_json_url, function(data) { $.each(data.subjects, function(i,subject) { subject_list.append('<li><a href="#resources" subject-id="' + subject.value + '">' + subject.text + '</a></li>'); }); // When a subject is clicked, save the info to the HTML5 sessionStorage so that the // next page (list of resources) can pick it up and do the appropriate AJAX call. subject_list.delegate('a', 'click', function() { app.saveToSessionStorage({ resources_search_type: 'subject', resources_search_value: $(this).attr('subject-id'), resources_title_text: $(this).text() }, 'resources_reload'); }); loader.remove(); subject_list.listview('refresh'); }); }); }, initResourcesPage: function() { var app = this; $('div#resources').live('pagebeforeshow', function(event) { var page = $(event.currentTarget); var resource_list = page.find('ul'); // Don't bother reloading the list if the user hasn't clicked on a new subject/A-Z name if ( sessionStorage.resources_reload != 1 && resource_list.find('li').length > 0 ) { return; } // Use HTML5 sessionStorage to get the current browse type and value var search_type = sessionStorage.resources_search_type; var search_value = sessionStorage.resources_search_value; var title_text = sessionStorage.resources_title_text; // Set the title header page.find('[data-role="header"] h1').text(title_text); // Loop through the resources. If we find a "group" (A, B, C, Top Resources, Other Resources, etc.) we haven't seen before, print it as a list-divider resource_list.empty(); var loader = app.createLoader(); page.append(loader); var last_group = ''; $.getJSON( app.resources_json_url + '?' + app.URLEncode(search_type) + '=' + app.URLEncode(search_value), function(data) { $.each(data.resources, function(i,resource) { if ( resource.group != last_group ) { resource_list.append( $('<li>').attr('data-role', 'list-divider').text(resource.group) ); last_group = resource.group; } var resource_link = resource.url ? app.getGotoURL(resource.id).text(resource.name) : $('<a>').attr('href','#full').attr('resource-id', resource.id).text(resource.name); // TODO: Deal with the edge case of resources without a connect URL resource_list.append( $('<li>').append( resource_link.append( $('<br>'), $('<span>').attr('class', 'brief-description').text( app.capLongText(resource.description_brief, 95) ) ), $('<a>').attr('href','#full').attr('resource-id', resource.id).attr('data-icon','info').text('Info') ) ); }); // Use HTML5 sessionStorage to set the resource id for the full view resource_list.delegate('a[href=#full]', 'click', function() { app.saveToSessionStorage({ resource_id: $(this).attr('resource-id') }); }); loader.remove(); resource_list.listview('refresh'); }); // Reload is done, don't do it again. app.saveToSessionStorage({ resources_reload: 0 }); }); }, initFullPage: function() { var app = this; $('div#full').live('pagebeforeshow', function(event) { var page = $(event.currentTarget); var container = page.find('#resource'); var content = $('<div>');
// Use HTML5 sessionStorage to get the current browse type and value var resource_id = sessionStorage.resource_id; $.getJSON( app.resource_json_url + '?resource_id=' + app.URLEncode(resource_id), function(data) { var resource = data.resource; content.append( $('<h2>').attr('id', 'resource-data-name').text( resource['name'] ) ); $.each( data.display_fields, function(i,field) { app.fullDisplay( content, field.field, field.type, resource[field.field], resource ); }); loader.remove(); content.appendTo(container); content.page(); // Process the added fields with JQM so things like buttons get rendered }); }); }, /* --- Full display field rendering --- */ fullDisplay: function(content, field_name, field_type, value, resource) { var func = this.field_name_override_map[field_name]; if ( func != null && typeof(func) == 'string' ) { return this[func](content, field_name, value, resource); } func = this.field_type_map[field_type]; if ( func != null && typeof(func) == 'string' ) { return this[func](content, field_name, value, resource); } return this.fullDisplayDefault(content, field_name, value, resource); }, fullDisplayDefault: function(content, field_name, value, resource) { return this.fullDisplayText(field_name, value); }, fullDisplayText: function(content, field_name, value, resource) { if ( typeof(value) != 'undefined' && value != null ) { content.append( $('<h3>').text( this.getDisplayFieldLabel(field_name) ) ); content.append( $('<div>').attr('class', 'resource-data').attr('id', 'resource-data-' + field_name).html(value) ); } }, fullDisplayBoolean: function(content, field_name, value, resource) { if ( typeof(value) != 'undefined' && value != null ) { content.append( $('<h3>').text( this.getDisplayFieldLabel(field_name) ) ); content.append( $('<div>').attr('class', 'resource-data').attr('id', 'resource-data-' + field_name).text( value ? 'yes' : 'no' ) ); } }, fullDisplayFieldURL: function(content, field_name, value, resource) { if ( typeof(value) != 'undefined' && value != null ) { content.append( this.getGotoURL(resource.id).attr('data-role', 'button').text('Connect') ); } }, fullDisplayFieldGroupRecords: function(content, field_name, value, resource) { if ( typeof(value) != 'undefined' && value != null ) { var app = this; content.append( this.group_record_message ); $.each( value, function(i, group_record) { content.append( app.getGotoURL(group_record.id).attr('data-role', 'button').text(group_record.name) ); }); } }, field_name_override_map: { url: 'fullDisplayFieldURL', group_records: 'fullDisplayFieldGroupRecords', }, field_type_map: { boolean: 'fullDisplayBoolean', text: 'fullDisplayText' }, /* --- You generally don't want to override stuff past here... --- */ // These MUST be overridden in the mobile_app_setup template subjects_json_url: null, resources_json_url: null, resource_json_url: null, goto_url: null, /* --- Utility functions --- */ createLoader: function() { return $.mobile.loadingMessage ? $( "<div class='ui-loader crdb-loading ui-body-a ui-corner-all'>" + "<span class='ui-icon ui-icon-loading spin'></span>" + "<h1>" + $.mobile.loadingMessage + "</h1>" + "</div>" ) : undefined; }, getGotoURL: function(id) { return $('<a>').attr('href', this.goto_url.replace('XXX', id)).attr('rel', 'external'); }, getDisplayFieldLabel: function(field) { return typeof(this.field_map[field]) == 'undefined' ? field : this.field_map[field]; }, // Save data into HTML5 sessionStorage. If a flag name is passed in, set it to "1" if there were any changes saveToSessionStorage: function(data, flag) { var changes = 0; $.each(data, function(field, value) { if ( sessionStorage[field] != value ) { sessionStorage[field] = value; changes += 1; } }); if ( changes > 0 && typeof(flag) != 'undefined' ) { sessionStorage[flag] = 1; } return changes > 0; }, // Function to cap long text fields - used mainly for the brief descriptions in resource lists capLongText: function(text, max) { var output = text; if ( output.length > max ) { output = text.substring( 0, max+1 ); output = output.substring( 0, output.lastIndexOf(" ") ) + " ..."; } return(output); }, // URL encoding stolen from the JQuery plugin URLEncode: function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/; while(x<c.length){var m=r.exec(c.substr(x)); if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length; }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16); o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o; } }
container.empty(); var loader = app.createLoader(); page.append(loader);
random_line_split
crdb_mobile.js
var CRDB_mobile = { // Message displayed above group record buttons group_record_message: 'This resource is available from multiple vendors. Please select a link button below.', // Sets up a mapping of resource field internal names to display names. Customizable by sites. field_map: { access: 'Access', alert: 'Alert', allows_coursepacks: 'Allows Coursepacks', allows_ereserves: 'Allows Electronic Reserves', allows_ill: 'Allows Interlibrary Loans', coverage: 'Coverage', description_full: 'Description', ill_notes: 'Interlibrary Loan Notes', name: 'Name', open_access: 'Open Access', print_equivalents: 'Print Equivalents', refworks_compatible: 'Refworks Compatible', resolver_enabled: 'Resolver Enabled', resource_type: 'Resource Type', simultaneous_users: 'Simultaneous Users', subjects: 'Subjects', title_list_url: 'Title List URL', update_frequency: 'Update Frequency', url: 'Connect', user_documentation: 'User Documentation', vendor: 'Vendor' }, // Override display fields - if you want to show different fields in your mobile site than in your // main site, you can override the list of fields for display here. display_fields_override: null, /* --- jQuery Mobile page setups. These can be overridden if necessary, but I'm trying to add hooks to avoid that where I can --- */ initApp: function() { var app = this; this.initPages(); $('#home').one( 'pagecreate', function() { var url = document.URL; var reg = /id=(\d+)/; var match = reg.exec(url); if ( match ) { app.saveToSessionStorage({ resource_id: match[1] }); $.mobile.changePage( '#full' ); } }); }, initPages: function() { this.initAZPage(); this.initSubjectsPage(); this.initResourcesPage(); this.initFullPage(); }, initAZPage: function() { var app = this; $('div#az').live('pagebeforecreate', function(event) { var page = $(event.currentTarget); var az_list = page.find('ul'); az_list.delegate('a', 'click', function() { app.saveToSessionStorage({ resources_search_type: 'name', resources_search_value: $(this).attr('letter'), resources_title_text: $(this).attr('letter') }, 'resources_reload'); }); }); }, initSubjectsPage: function() { var app = this; $('div#subjects').live('pagebeforecreate', function(event) { var page = $(event.currentTarget); var subject_list = page.find('ul'); var loader = app.createLoader(); page.append(loader); $.getJSON( app.subjects_json_url, function(data) { $.each(data.subjects, function(i,subject) { subject_list.append('<li><a href="#resources" subject-id="' + subject.value + '">' + subject.text + '</a></li>'); }); // When a subject is clicked, save the info to the HTML5 sessionStorage so that the // next page (list of resources) can pick it up and do the appropriate AJAX call. subject_list.delegate('a', 'click', function() { app.saveToSessionStorage({ resources_search_type: 'subject', resources_search_value: $(this).attr('subject-id'), resources_title_text: $(this).text() }, 'resources_reload'); }); loader.remove(); subject_list.listview('refresh'); }); }); }, initResourcesPage: function() { var app = this; $('div#resources').live('pagebeforeshow', function(event) { var page = $(event.currentTarget); var resource_list = page.find('ul'); // Don't bother reloading the list if the user hasn't clicked on a new subject/A-Z name if ( sessionStorage.resources_reload != 1 && resource_list.find('li').length > 0 ) { return; } // Use HTML5 sessionStorage to get the current browse type and value var search_type = sessionStorage.resources_search_type; var search_value = sessionStorage.resources_search_value; var title_text = sessionStorage.resources_title_text; // Set the title header page.find('[data-role="header"] h1').text(title_text); // Loop through the resources. If we find a "group" (A, B, C, Top Resources, Other Resources, etc.) we haven't seen before, print it as a list-divider resource_list.empty(); var loader = app.createLoader(); page.append(loader); var last_group = ''; $.getJSON( app.resources_json_url + '?' + app.URLEncode(search_type) + '=' + app.URLEncode(search_value), function(data) { $.each(data.resources, function(i,resource) { if ( resource.group != last_group ) { resource_list.append( $('<li>').attr('data-role', 'list-divider').text(resource.group) ); last_group = resource.group; } var resource_link = resource.url ? app.getGotoURL(resource.id).text(resource.name) : $('<a>').attr('href','#full').attr('resource-id', resource.id).text(resource.name); // TODO: Deal with the edge case of resources without a connect URL resource_list.append( $('<li>').append( resource_link.append( $('<br>'), $('<span>').attr('class', 'brief-description').text( app.capLongText(resource.description_brief, 95) ) ), $('<a>').attr('href','#full').attr('resource-id', resource.id).attr('data-icon','info').text('Info') ) ); }); // Use HTML5 sessionStorage to set the resource id for the full view resource_list.delegate('a[href=#full]', 'click', function() { app.saveToSessionStorage({ resource_id: $(this).attr('resource-id') }); }); loader.remove(); resource_list.listview('refresh'); }); // Reload is done, don't do it again. app.saveToSessionStorage({ resources_reload: 0 }); }); }, initFullPage: function() { var app = this; $('div#full').live('pagebeforeshow', function(event) { var page = $(event.currentTarget); var container = page.find('#resource'); var content = $('<div>'); container.empty(); var loader = app.createLoader(); page.append(loader); // Use HTML5 sessionStorage to get the current browse type and value var resource_id = sessionStorage.resource_id; $.getJSON( app.resource_json_url + '?resource_id=' + app.URLEncode(resource_id), function(data) { var resource = data.resource; content.append( $('<h2>').attr('id', 'resource-data-name').text( resource['name'] ) ); $.each( data.display_fields, function(i,field) { app.fullDisplay( content, field.field, field.type, resource[field.field], resource ); }); loader.remove(); content.appendTo(container); content.page(); // Process the added fields with JQM so things like buttons get rendered }); }); }, /* --- Full display field rendering --- */ fullDisplay: function(content, field_name, field_type, value, resource) { var func = this.field_name_override_map[field_name]; if ( func != null && typeof(func) == 'string' ) { return this[func](content, field_name, value, resource); } func = this.field_type_map[field_type]; if ( func != null && typeof(func) == 'string' ) { return this[func](content, field_name, value, resource); } return this.fullDisplayDefault(content, field_name, value, resource); }, fullDisplayDefault: function(content, field_name, value, resource) { return this.fullDisplayText(field_name, value); }, fullDisplayText: function(content, field_name, value, resource) { if ( typeof(value) != 'undefined' && value != null ) { content.append( $('<h3>').text( this.getDisplayFieldLabel(field_name) ) ); content.append( $('<div>').attr('class', 'resource-data').attr('id', 'resource-data-' + field_name).html(value) ); } }, fullDisplayBoolean: function(content, field_name, value, resource) { if ( typeof(value) != 'undefined' && value != null )
}, fullDisplayFieldURL: function(content, field_name, value, resource) { if ( typeof(value) != 'undefined' && value != null ) { content.append( this.getGotoURL(resource.id).attr('data-role', 'button').text('Connect') ); } }, fullDisplayFieldGroupRecords: function(content, field_name, value, resource) { if ( typeof(value) != 'undefined' && value != null ) { var app = this; content.append( this.group_record_message ); $.each( value, function(i, group_record) { content.append( app.getGotoURL(group_record.id).attr('data-role', 'button').text(group_record.name) ); }); } }, field_name_override_map: { url: 'fullDisplayFieldURL', group_records: 'fullDisplayFieldGroupRecords', }, field_type_map: { boolean: 'fullDisplayBoolean', text: 'fullDisplayText' }, /* --- You generally don't want to override stuff past here... --- */ // These MUST be overridden in the mobile_app_setup template subjects_json_url: null, resources_json_url: null, resource_json_url: null, goto_url: null, /* --- Utility functions --- */ createLoader: function() { return $.mobile.loadingMessage ? $( "<div class='ui-loader crdb-loading ui-body-a ui-corner-all'>" + "<span class='ui-icon ui-icon-loading spin'></span>" + "<h1>" + $.mobile.loadingMessage + "</h1>" + "</div>" ) : undefined; }, getGotoURL: function(id) { return $('<a>').attr('href', this.goto_url.replace('XXX', id)).attr('rel', 'external'); }, getDisplayFieldLabel: function(field) { return typeof(this.field_map[field]) == 'undefined' ? field : this.field_map[field]; }, // Save data into HTML5 sessionStorage. If a flag name is passed in, set it to "1" if there were any changes saveToSessionStorage: function(data, flag) { var changes = 0; $.each(data, function(field, value) { if ( sessionStorage[field] != value ) { sessionStorage[field] = value; changes += 1; } }); if ( changes > 0 && typeof(flag) != 'undefined' ) { sessionStorage[flag] = 1; } return changes > 0; }, // Function to cap long text fields - used mainly for the brief descriptions in resource lists capLongText: function(text, max) { var output = text; if ( output.length > max ) { output = text.substring( 0, max+1 ); output = output.substring( 0, output.lastIndexOf(" ") ) + " ..."; } return(output); }, // URL encoding stolen from the JQuery plugin URLEncode: function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/; while(x<c.length){var m=r.exec(c.substr(x)); if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length; }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16); o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o; } }
{ content.append( $('<h3>').text( this.getDisplayFieldLabel(field_name) ) ); content.append( $('<div>').attr('class', 'resource-data').attr('id', 'resource-data-' + field_name).text( value ? 'yes' : 'no' ) ); }
conditional_block