Best JavaScript code snippet using argos
conditions.py
Source:conditions.py
...27 for part in self.parts]28 method = getattr(self, method_name, self._propagate)29 return method(part_results, *args)30 def _propagate(self, parts, *args):31 return self.change_parts(parts)32 def simplified(self):33 return self._postorder_visit("_simplified")34 def relaxed(self):35 return self._postorder_visit("_relaxed")36 def untyped(self):37 return self._postorder_visit("_untyped")38 def uniquify_variables(self, type_map, renamings={}):39 # Cannot used _postorder_visit because this requires preorder40 # for quantified effects.41 if not self.parts:42 return self43 else:44 return self.__class__([part.uniquify_variables(type_map, renamings)45 for part in self.parts])46 def to_untyped_strips(self):47 raise ValueError("Not a STRIPS condition: %s" % self.__class__.__name__)48 def instantiate(self, var_mapping, init_facts, fluent_facts, result):49 raise ValueError("Cannot instantiate condition: not normalized")50 def free_variables(self):51 result = set()52 for part in self.parts:53 result |= part.free_variables()54 return result55 def has_disjunction(self):56 for part in self.parts:57 if part.has_disjunction():58 return True59 return False60 def has_existential_part(self):61 for part in self.parts:62 if part.has_existential_part():63 return True64 return False65 def has_universal_part(self):66 for part in self.parts:67 if part.has_universal_part():68 return True69 return False70class ConstantCondition(Condition):71 # Defining __eq__ blocks inheritance of __hash__, so must set it explicitly.72 __hash__ = Condition.__hash__73 parts = ()74 def __init__(self):75 self.hash = hash(self.__class__)76 def change_parts(self, parts):77 return self78 def __eq__(self, other):79 return self.__class__ is other.__class__80class Impossible(Exception):81 pass82class Falsity(ConstantCondition):83 def instantiate(self, var_mapping, init_facts, fluent_facts, result):84 raise Impossible()85 def negate(self):86 return Truth()87class Truth(ConstantCondition):88 def to_untyped_strips(self):89 return []90 def instantiate(self, var_mapping, init_facts, fluent_facts, result):91 pass92 def negate(self):93 return Falsity()94class JunctorCondition(Condition):95 # Defining __eq__ blocks inheritance of __hash__, so must set it explicitly.96 __hash__ = Condition.__hash__97 def __eq__(self, other):98 # Compare hash first for speed reasons.99 return (self.hash == other.hash and100 self.__class__ is other.__class__ and101 self.parts == other.parts)102 def change_parts(self, parts):103 return self.__class__(parts)104class Conjunction(JunctorCondition):105 def _simplified(self, parts):106 result_parts = []107 for part in parts:108 if isinstance(part, Conjunction):109 result_parts += part.parts110 elif isinstance(part, Falsity):111 return Falsity()112 elif not isinstance(part, Truth):113 result_parts.append(part)114 if not result_parts:115 return Truth()116 if len(result_parts) == 1:117 return result_parts[0]118 return Conjunction(result_parts)119 def to_untyped_strips(self):120 result = []121 for part in self.parts:122 result += part.to_untyped_strips()123 return result124 def instantiate(self, var_mapping, init_facts, fluent_facts, result):125 assert not result, "Condition not simplified"126 for part in self.parts:127 part.instantiate(var_mapping, init_facts, fluent_facts, result)128 def negate(self):129 return Disjunction([p.negate() for p in self.parts])130class Disjunction(JunctorCondition):131 def _simplified(self, parts):132 result_parts = []133 for part in parts:134 if isinstance(part, Disjunction):135 result_parts += part.parts136 elif isinstance(part, Truth):137 return Truth()138 elif not isinstance(part, Falsity):139 result_parts.append(part)140 if not result_parts:141 return Falsity()142 if len(result_parts) == 1:143 return result_parts[0]144 return Disjunction(result_parts)145 def negate(self):146 return Conjunction([p.negate() for p in self.parts])147 def has_disjunction(self):148 return True149class QuantifiedCondition(Condition):150 # Defining __eq__ blocks inheritance of __hash__, so must set it explicitly.151 __hash__ = Condition.__hash__152 def __init__(self, parameters, parts):153 self.parameters = tuple(parameters)154 self.parts = tuple(parts)155 self.hash = hash((self.__class__, self.parameters, self.parts))156 def __eq__(self, other):157 # Compare hash first for speed reasons.158 return (self.hash == other.hash and159 self.__class__ is other.__class__ and160 self.parameters == other.parameters and161 self.parts == other.parts)162 def _dump(self, indent=" "):163 arglist = ", ".join(map(str, self.parameters))164 return "%s %s" % (self.__class__.__name__, arglist)165 def _simplified(self, parts):166 if isinstance(parts[0], ConstantCondition):167 return parts[0]168 else:169 return self._propagate(parts)170 def uniquify_variables(self, type_map, renamings={}):171 renamings = dict(renamings) # Create a copy.172 new_parameters = [par.uniquify_name(type_map, renamings)173 for par in self.parameters]174 new_parts = (self.parts[0].uniquify_variables(type_map, renamings),)175 return self.__class__(new_parameters, new_parts)176 def free_variables(self):177 result = Condition.free_variables(self)178 for par in self.parameters:179 result.discard(par.name)180 return result181 def change_parts(self, parts):182 return self.__class__(self.parameters, parts)183class UniversalCondition(QuantifiedCondition):184 def _untyped(self, parts):185 type_literals = [par.get_atom().negate() for par in self.parameters]186 return UniversalCondition(self.parameters,187 [Disjunction(type_literals + parts)])188 def negate(self):189 return ExistentialCondition(self.parameters, [p.negate() for p in self.parts])190 def has_universal_part(self):191 return True192class ExistentialCondition(QuantifiedCondition):193 def _untyped(self, parts):194 type_literals = [par.get_atom() for par in self.parameters]195 return ExistentialCondition(self.parameters,196 [Conjunction(type_literals + parts)])197 def negate(self):198 return UniversalCondition(self.parameters, [p.negate() for p in self.parts])199 def instantiate(self, var_mapping, init_facts, fluent_facts, result):200 assert not result, "Condition not simplified"201 self.parts[0].instantiate(var_mapping, init_facts, fluent_facts, result)202 def has_existential_part(self):203 return True204class Literal(Condition):205 # Defining __eq__ blocks inheritance of __hash__, so must set it explicitly.206 __hash__ = Condition.__hash__207 parts = []208 def __init__(self, predicate, args):209 self.predicate = predicate210 self.args = tuple(args)211 self.hash = hash((self.__class__, self.predicate, self.args))212 def __eq__(self, other):213 # Compare hash first for speed reasons.214 return (self.hash == other.hash and215 self.__class__ is other.__class__ and216 self.predicate == other.predicate and217 self.args == other.args)218 def __ne__(self, other):219 return not self == other220 @property221 def key(self):222 return str(self.predicate), self.args223 def __lt__(self, other):224 return self.key < other.key225 def __le__(self, other):226 return self.key <= other.key227 def __str__(self):228 return "%s %s(%s)" % (self.__class__.__name__, self.predicate,229 ", ".join(map(str, self.args)))230 def __repr__(self):231 return '<%s>' % self232 def _dump(self):233 return str(self)234 def change_parts(self, parts):235 return self236 def uniquify_variables(self, type_map, renamings={}):237 return self.rename_variables(renamings)238 def rename_variables(self, renamings):239 new_args = tuple(renamings.get(arg, arg) for arg in self.args)240 return self.__class__(self.predicate, new_args)241 def replace_argument(self, position, new_arg):242 new_args = list(self.args)243 new_args[position] = new_arg244 return self.__class__(self.predicate, new_args)245 def free_variables(self):246 return set(arg for arg in self.args if arg[0] == "?")247class Atom(Literal):248 negated = False...
pretty_docs.py
Source:pretty_docs.py
1# Copyright 2015 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""A module for converting parsed doc content into markdown pages.16The adjacent `parser` module creates `PageInfo` objects, containing all data17necessary to document an element of the TensorFlow API.18This module contains one public function, which handels the conversion of these19`PageInfo` objects into a markdown string:20 md_page = build_md_page(page_info)21"""22from __future__ import absolute_import23from __future__ import division24from __future__ import print_function25import textwrap26def build_md_page(page_info):27 """Given a PageInfo object, return markdown for the page.28 Args:29 page_info: must be a `parser.FunctionPageInfo`, `parser.ClassPageInfo`, or30 `parser.ModulePageInfo`31 Returns:32 Markdown for the page33 Raises:34 ValueError: if `page_info` is an instance of an unrecognized class35 """36 if page_info.for_function():37 return _build_function_page(page_info)38 if page_info.for_class():39 return _build_class_page(page_info)40 if page_info.for_module():41 return _build_module_page(page_info)42 raise ValueError('Unknown Page Info Type: %s' % type(page_info))43def _build_function_page(page_info):44 """Given a FunctionPageInfo object Return the page as an md string."""45 parts = ['# %s\n\n' % page_info.full_name]46 if len(page_info.aliases) > 1:47 parts.append('### Aliases:\n\n')48 parts.extend('* `%s`\n' % name for name in page_info.aliases)49 parts.append('\n')50 if page_info.signature is not None:51 parts.append(_build_signature(page_info))52 if page_info.defined_in:53 parts.append('\n\n')54 parts.append(str(page_info.defined_in))55 parts.append(page_info.guides)56 parts.append(page_info.doc.docstring)57 parts.append(_build_function_details(page_info.doc.function_details))58 parts.append(_build_compatibility(page_info.doc.compatibility))59 return ''.join(parts)60def _build_class_page(page_info):61 """Given a ClassPageInfo object Return the page as an md string."""62 parts = ['# {page_info.full_name}\n\n'.format(page_info=page_info)]63 parts.append('## Class `%s`\n\n' % page_info.full_name.split('.')[-1])64 if page_info.bases:65 parts.append('Inherits From: ')66 link_template = '[`{short_name}`]({url})'67 parts.append(', '.join(68 link_template.format(**base._asdict()) for base in page_info.bases))69 parts.append('\n\n')70 if len(page_info.aliases) > 1:71 parts.append('### Aliases:\n\n')72 parts.extend('* Class `%s`\n' % name for name in page_info.aliases)73 parts.append('\n')74 if page_info.defined_in is not None:75 parts.append('\n\n')76 parts.append(str(page_info.defined_in))77 parts.append(page_info.guides)78 parts.append(page_info.doc.docstring)79 parts.append(_build_function_details(page_info.doc.function_details))80 parts.append(_build_compatibility(page_info.doc.compatibility))81 parts.append('\n\n')82 if page_info.classes:83 parts.append('## Child Classes\n')84 link_template = ('[`class {class_info.short_name}`]'85 '({class_info.url})\n\n')86 class_links = sorted(87 link_template.format(class_info=class_info)88 for class_info in page_info.classes)89 parts.extend(class_links)90 if page_info.properties:91 parts.append('## Properties\n\n')92 for prop_info in sorted(page_info.properties):93 h3 = '<h3 id="{short_name}"><code>{short_name}</code></h3>\n\n'94 parts.append(h3.format(short_name=prop_info.short_name))95 parts.append(prop_info.doc.docstring)96 parts.append(_build_function_details(prop_info.doc.function_details))97 parts.append(_build_compatibility(prop_info.doc.compatibility))98 parts.append('\n\n')99 parts.append('\n\n')100 if page_info.methods:101 parts.append('## Methods\n\n')102 # Sort the methods list, but make sure constructors come first.103 constructors = ['__init__', '__new__']104 inits = [method for method in page_info.methods105 if method.short_name in constructors]106 others = [method for method in page_info.methods107 if method.short_name not in constructors]108 for method_info in sorted(inits) + sorted(others):109 h3 = ('<h3 id="{short_name}">'110 '<code>{short_name}</code>'111 '</h3>\n\n')112 parts.append(h3.format(**method_info._asdict()))113 if method_info.signature is not None:114 parts.append(_build_signature(method_info, use_full_name=False))115 parts.append(method_info.doc.docstring)116 parts.append(_build_function_details(method_info.doc.function_details))117 parts.append(_build_compatibility(method_info.doc.compatibility))118 parts.append('\n\n')119 parts.append('\n\n')120 if page_info.other_members:121 parts.append('## Class Members\n\n')122 # TODO(markdaoust): Document the value of the members,123 # at least for basic types.124 h3 = '<h3 id="{short_name}"><code>{short_name}</code></h3>\n\n'125 others_member_headings = (h3.format(short_name=info.short_name)126 for info in sorted(page_info.other_members))127 parts.extend(others_member_headings)128 return ''.join(parts)129def _build_module_page(page_info):130 """Given a ClassPageInfo object Return the page as an md string."""131 parts = ['# Module: {full_name}\n\n'.format(full_name=page_info.full_name)]132 if len(page_info.aliases) > 1:133 parts.append('### Aliases:\n\n')134 parts.extend('* Module `%s`\n' % name for name in page_info.aliases)135 parts.append('\n')136 if page_info.defined_in is not None:137 parts.append('\n\n')138 parts.append(str(page_info.defined_in))139 parts.append(page_info.doc.docstring)140 parts.append(_build_compatibility(page_info.doc.compatibility))141 parts.append('\n\n')142 if page_info.modules:143 parts.append('## Modules\n\n')144 template = '[`{short_name}`]({url}) module'145 for item in page_info.modules:146 parts.append(template.format(**item._asdict()))147 if item.doc.brief:148 parts.append(': ' + item.doc.brief)149 parts.append('\n\n')150 if page_info.classes:151 parts.append('## Classes\n\n')152 template = '[`class {short_name}`]({url})'153 for item in page_info.classes:154 parts.append(template.format(**item._asdict()))155 if item.doc.brief:156 parts.append(': ' + item.doc.brief)157 parts.append('\n\n')158 if page_info.functions:159 parts.append('## Functions\n\n')160 template = '[`{short_name}(...)`]({url})'161 for item in page_info.functions:162 parts.append(template.format(**item._asdict()))163 if item.doc.brief:164 parts.append(': ' + item.doc.brief)165 parts.append('\n\n')166 if page_info.other_members:167 # TODO(markdaoust): Document the value of the members,168 # at least for basic types.169 parts.append('## Other Members\n\n')170 for item in page_info.other_members:171 parts.append('`{short_name}`\n\n'.format(**item._asdict()))172 return ''.join(parts)173def _build_signature(obj_info, use_full_name=True):174 """Returns a md code block showing the function signature."""175 # Special case tf.range, since it has an optional first argument176 if obj_info.full_name == 'tf.range':177 return (178 '``` python\n'179 "tf.range(limit, delta=1, dtype=None, name='range')\n"180 "tf.range(start, limit, delta=1, dtype=None, name='range')\n"181 '```\n\n')182 parts = ['``` python']183 parts.extend(['@' + dec for dec in obj_info.decorators])184 signature_template = '{name}({sig})'185 if not obj_info.signature:186 sig = ''187 elif len(obj_info.signature) == 1:188 sig = obj_info.signature[0]189 else:190 sig = ',\n'.join(' %s' % sig_item for sig_item in obj_info.signature)191 sig = '\n'+sig+'\n'192 if use_full_name:193 obj_name = obj_info.full_name194 else:195 obj_name = obj_info.short_name196 parts.append(signature_template.format(name=obj_name, sig=sig))197 parts.append('```\n\n')198 return '\n'.join(parts)199def _build_compatibility(compatibility):200 """Return the compatibility section as an md string."""201 parts = []202 sorted_keys = sorted(compatibility.keys())203 for key in sorted_keys:204 value = compatibility[key]205 # Dedent so that it does not trigger markdown code formatting.206 value = textwrap.dedent(value)207 parts.append('\n\n#### %s Compatibility\n%s\n' % (key.title(), value))208 return ''.join(parts)209def _build_function_details(function_details):210 """Return the function details section as an md string."""211 parts = []212 for detail in function_details:213 sub = []214 sub.append('#### ' + detail.keyword + ':\n\n')215 sub.append(textwrap.dedent(detail.header))216 for key, value in detail.items:217 sub.append('* <b>`%s`</b>: %s' % (key, value))218 parts.append(''.join(sub))...
daily_Parts_issuance_wizard_report.py
Source:daily_Parts_issuance_wizard_report.py
1# See LICENSE file for full copyright and licensing details.2"""Daily Parts issuance Wizard Report."""3from datetime import datetime, timedelta4from odoo import models5from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT6class DailyPartWizard(models.AbstractModel):7 """Daily Part Wizard."""8 _name = 'report.fleet_operations.daily.parts.issuance.wizard.xls'9 _description = 'Daily Parts Insurance'10 def get_heading(self):11 """Report Method."""12 head_title = {'name': '',13 'rev_no': '',14 'doc_no': '',15 }16 head_object = self.env['report.heading']17 head_ids = head_object.search([], order='id')18 if head_ids:19 head_rec = head_ids[0]20 if head_rec:21 head_title['name'] = head_rec.name or ''22 head_title['rev_no'] = head_rec.revision_no or ''23 head_title['doc_no'] = head_rec.document_no or ''24 head_title['image'] = head_rec.image or ''25 return head_title26 def get_work_order_detail(self, date_range):27 """Report Method to Get Work Order Details."""28 work_order_obj = self.env['task.line']29 start = datetime.strptime(date_range.get('date_from'), '%Y-%m-%d')30 end = datetime.strptime(date_range.get('date_to'), '%Y-%m-%d')31 step = timedelta(days=1)32 workorder_detail = []33 while start <= end:34 sdate = str(datetime.strptime(str(start.date()) + ' 00:00:00',35 DEFAULT_SERVER_DATETIME_FORMAT))36 edate = str(datetime.strptime(str(start.date()) + ' 23:59:59',37 DEFAULT_SERVER_DATETIME_FORMAT))38 work_order_ids = work_order_obj.search([('date_issued', '>=',39 sdate), ('date_issued',40 '<=', edate)])41 if work_order_ids:42 parts_data = {}43 parts_value = []44 for parts_line in work_order_ids:45 if parts_line.fleet_service_id and \46 parts_line.fleet_service_id.state == 'done':47 parts_dict = {48 'wo_name': parts_line.fleet_service_id and49 parts_line.fleet_service_id.name or '',50 'vehicle_id': parts_line.fleet_service_id and51 parts_line.fleet_service_id.vehicle_id and52 parts_line.fleet_service_id.vehicle_id.name or '',53 'part_no': parts_line.product_id and54 parts_line.product_id.default_code or '',55 'part_name': parts_line.product_id and56 parts_line.product_id.name or '',57 'vehicle_make': parts_line.vehicle_make_id and58 parts_line.vehicle_make_id.name or '',59 'qty': parts_line.qty or 0.0,60 'uom': parts_line.product_uom and61 parts_line.product_uom.name or '',62 'old_part_return': parts_line.old_part_return and63 'Yes' or 'No',64 'issued_by': parts_line.issued_by and65 parts_line.issued_by.name or '',66 'remarks': parts_line.fleet_service_id and67 parts_line.fleet_service_id.note or ''68 }69 parts_value.append(parts_dict)70 if parts_value:71 parts_value = sorted(parts_value,72 key=lambda k: k['wo_name'])73 parts_data = {74 'date': start.date(),75 'value': parts_value76 }77 workorder_detail.append(parts_data)78 start += step79 return workorder_detail80 def generate_xlsx_report(self, workbook, data, parts_data):81 """Generate xlsx format print report."""82 worksheet = workbook.add_worksheet('daily_parts_issuance_wizard')83 worksheet.set_column(0, 0, 10)84 worksheet.set_column(1, 1, 15)85 worksheet.set_column(2, 2, 20)86 worksheet.set_column(3, 3, 15)87 worksheet.set_column(4, 4, 10)88 worksheet.set_column(5, 5, 12)89 worksheet.set_column(6, 6, 10)90 worksheet.set_column(7, 7, 10)91 worksheet.set_column(8, 8, 15)92 worksheet.set_column(9, 9, 10)93 worksheet.set_column(10, 10, 15)94 worksheet.set_column(11, 11, 10)95 worksheet.set_column(12, 12, 20)96 worksheet.set_column(13, 13, 5)97 worksheet.set_column(14, 14, 5)98 worksheet.set_column(15, 15, 5)99 bold = workbook.add_format({'bold': True,100 'font_name': 'Arial',101 'font_size': '10'})102 tot = workbook.add_format({'border': 2,103 'bold': True,104 'font_name': 'Arial',105 'font_size': '10'})106 border = workbook.add_format({'border': 2,107 'font_name': 'Arial',108 'font_size': '10'})109 merge_format = workbook.add_format({'border': 2, 'align': 'center'})110 format1 = workbook.add_format({'border': 2,111 'bold': True,112 'font_name': 'Arial',113 'font_size': '10'})114 format1.set_bg_color('gray')115 date = workbook.add_format({'num_format': 'dd/mm/yy'})116 worksheet.merge_range('C3:F3', 'Merged Cells', merge_format)117 row = 0118 row += 1119 row += 1120 worksheet.write(row, 2, 'DAILY PARTS ISSUANCE', tot)121 row += 1122 worksheet.write(row, 2, 'Date From:', tot)123 worksheet.write(row, 3, data['form']['date_from'] or '', border)124 worksheet.write(row, 4, 'To:', tot)125 worksheet.write(row, 5, data['form']['date_to'] or '', border)126 row += 2127 worksheet.write(row, 0, 'CMF', bold)128 row = 3129 for objec in self.get_work_order_detail(data['form']):130 row += 3131 worksheet.write(row, 0, 'DATE ISSUED :', bold)132 worksheet.write(row, 1, objec.get('date') or '', date)133 row += 2134 worksheet.write(row, 0, 'NO.', format1)135 worksheet.write(row, 1, 'WO NO.', format1)136 worksheet.write(row, 2, 'VEHICLE ID', format1)137 worksheet.write(row, 3, 'PART NO.', format1)138 worksheet.write(row, 4, 'PART NAME', format1)139 worksheet.write(row, 5, 'VEHICLE MAKE', format1)140 worksheet.write(row, 6, 'USED', format1)141 worksheet.write(row, 7, 'UNIT TYPE', format1)142 worksheet.write(row, 8, 'OLD PART RETURND', format1)143 worksheet.write(row, 9, 'ISSUED BY', format1)144 worksheet.write(row, 10, 'REMARKS', format1)145 line_row = row + 1146 line_col = 0147 counter = 1148 for obj in objec.get('value'):149 worksheet.write(line_row, line_col, counter, border)150 line_col += 1151 worksheet.write(line_row, line_col,152 obj.get('wo_name') or '', border)153 line_col += 1154 worksheet.write(line_row, line_col,155 obj.get('vehicle_id') or '', border)156 line_col += 1157 worksheet.write(line_row, line_col,158 obj.get('part_no') or '', border)159 line_col += 1160 worksheet.write(line_row, line_col,161 obj.get('part_name') or '', border)162 line_col += 1163 worksheet.write(line_row, line_col,164 obj.get('vehicle_make') or '', border)165 line_col += 1166 worksheet.write(line_row, line_col,167 obj.get('qty') or '', border)168 line_col += 1169 worksheet.write(line_row, line_col,170 obj.get('uom') or '', border)171 line_col += 1172 worksheet.write(line_row, line_col,173 obj.get('old_part_return') or '', border)174 line_col += 1175 worksheet.write(line_row, line_col,176 obj.get('issued_by') or '', border)177 line_col += 1178 worksheet.write(line_row, line_col,179 obj.get('remarks') or '', border)180 line_col = 0181 line_row += 1182 counter += 1...
interpolation.py
Source:interpolation.py
1# -*- coding: utf-8 -*-2#3# Copyright (C) 2007 Edgewall Software4# All rights reserved.5#6# This software is licensed as described in the file COPYING, which7# you should have received as part of this distribution. The terms8# are also available at http://genshi.edgewall.org/wiki/License.9#10# This software consists of voluntary contributions made by many11# individuals. For the exact contribution history, see the revision12# history and logs, available at http://genshi.edgewall.org/log/.13import doctest14import sys15import unittest16from genshi.core import TEXT17from genshi.template.base import TemplateSyntaxError, EXPR18from genshi.template.interpolation import interpolate19class InterpolateTestCase(unittest.TestCase):20 def test_interpolate_string(self):21 parts = list(interpolate('bla'))22 self.assertEqual(1, len(parts))23 self.assertEqual(TEXT, parts[0][0])24 self.assertEqual('bla', parts[0][1])25 def test_interpolate_simple(self):26 parts = list(interpolate('${bla}'))27 self.assertEqual(1, len(parts))28 self.assertEqual(EXPR, parts[0][0])29 self.assertEqual('bla', parts[0][1].source)30 def test_interpolate_escaped(self):31 parts = list(interpolate('$${bla}'))32 self.assertEqual(1, len(parts))33 self.assertEqual(TEXT, parts[0][0])34 self.assertEqual('${bla}', parts[0][1])35 def test_interpolate_dobuleescaped(self):36 parts = list(interpolate('$$${bla}'))37 self.assertEqual(2, len(parts))38 self.assertEqual(TEXT, parts[0][0])39 self.assertEqual('$', parts[0][1])40 self.assertEqual(EXPR, parts[1][0])41 self.assertEqual('bla', parts[1][1].source)42 def test_interpolate_short(self):43 parts = list(interpolate('$bla'))44 self.assertEqual(1, len(parts))45 self.assertEqual(EXPR, parts[0][0])46 self.assertEqual('bla', parts[0][1].source)47 def test_interpolate_short_escaped(self):48 parts = list(interpolate('$$bla'))49 self.assertEqual(1, len(parts))50 self.assertEqual(TEXT, parts[0][0])51 self.assertEqual('$bla', parts[0][1])52 def test_interpolate_short_escaped_2(self):53 parts = list(interpolate('my $$bla = 2'))54 self.assertEqual(1, len(parts))55 self.assertEqual(TEXT, parts[0][0])56 self.assertEqual('my $bla = 2', parts[0][1])57 def test_interpolate_short_doubleescaped(self):58 parts = list(interpolate('$$$bla'))59 self.assertEqual(2, len(parts))60 self.assertEqual(TEXT, parts[0][0])61 self.assertEqual('$', parts[0][1])62 self.assertEqual(EXPR, parts[1][0])63 self.assertEqual('bla', parts[1][1].source)64 def test_interpolate_short_starting_with_underscore(self):65 parts = list(interpolate('$_bla'))66 self.assertEqual(1, len(parts))67 self.assertEqual(EXPR, parts[0][0])68 self.assertEqual('_bla', parts[0][1].source)69 def test_interpolate_short_containing_underscore(self):70 parts = list(interpolate('$foo_bar'))71 self.assertEqual(1, len(parts))72 self.assertEqual(EXPR, parts[0][0])73 self.assertEqual('foo_bar', parts[0][1].source)74 def test_interpolate_short_starting_with_dot(self):75 parts = list(interpolate('$.bla'))76 self.assertEqual(1, len(parts))77 self.assertEqual(TEXT, parts[0][0])78 self.assertEqual('$.bla', parts[0][1])79 def test_interpolate_short_containing_dot(self):80 parts = list(interpolate('$foo.bar'))81 self.assertEqual(1, len(parts))82 self.assertEqual(EXPR, parts[0][0])83 self.assertEqual('foo.bar', parts[0][1].source)84 def test_interpolate_short_starting_with_digit(self):85 parts = list(interpolate('$0bla'))86 self.assertEqual(1, len(parts))87 self.assertEqual(TEXT, parts[0][0])88 self.assertEqual('$0bla', parts[0][1])89 def test_interpolate_short_containing_digit(self):90 parts = list(interpolate('$foo0'))91 self.assertEqual(1, len(parts))92 self.assertEqual(EXPR, parts[0][0])93 self.assertEqual('foo0', parts[0][1].source)94 def test_interpolate_short_starting_with_digit(self):95 parts = list(interpolate('$0bla'))96 self.assertEqual(1, len(parts))97 self.assertEqual(TEXT, parts[0][0])98 self.assertEqual('$0bla', parts[0][1])99 def test_interpolate_short_containing_digit(self):100 parts = list(interpolate('$foo0'))101 self.assertEqual(1, len(parts))102 self.assertEqual(EXPR, parts[0][0])103 self.assertEqual('foo0', parts[0][1].source)104 def test_interpolate_full_nested_brackets(self):105 parts = list(interpolate('${{1:2}}'))106 self.assertEqual(1, len(parts))107 self.assertEqual(EXPR, parts[0][0])108 self.assertEqual('{1:2}', parts[0][1].source)109 def test_interpolate_full_mismatched_brackets(self):110 try:111 list(interpolate('${{1:2}'))112 except TemplateSyntaxError, e:113 pass114 else:115 self.fail('Expected TemplateSyntaxError')116 def test_interpolate_quoted_brackets_1(self):117 parts = list(interpolate('${"}"}'))118 self.assertEqual(1, len(parts))119 self.assertEqual(EXPR, parts[0][0])120 self.assertEqual('"}"', parts[0][1].source)121 def test_interpolate_quoted_brackets_2(self):122 parts = list(interpolate("${'}'}"))123 self.assertEqual(1, len(parts))124 self.assertEqual(EXPR, parts[0][0])125 self.assertEqual("'}'", parts[0][1].source)126 def test_interpolate_quoted_brackets_3(self):127 parts = list(interpolate("${'''}'''}"))128 self.assertEqual(1, len(parts))129 self.assertEqual(EXPR, parts[0][0])130 self.assertEqual("'''}'''", parts[0][1].source)131 def test_interpolate_quoted_brackets_4(self):132 parts = list(interpolate("${'''}\"\"\"'''}"))133 self.assertEqual(1, len(parts))134 self.assertEqual(EXPR, parts[0][0])135 self.assertEqual("'''}\"\"\"'''", parts[0][1].source)136 def test_interpolate_quoted_brackets_5(self):137 parts = list(interpolate(r"${'\'}'}"))138 self.assertEqual(1, len(parts))139 self.assertEqual(EXPR, parts[0][0])140 self.assertEqual(r"'\'}'", parts[0][1].source)141 def test_interpolate_mixed1(self):142 parts = list(interpolate('$foo bar $baz'))143 self.assertEqual(3, len(parts))144 self.assertEqual(EXPR, parts[0][0])145 self.assertEqual('foo', parts[0][1].source)146 self.assertEqual(TEXT, parts[1][0])147 self.assertEqual(' bar ', parts[1][1])148 self.assertEqual(EXPR, parts[2][0])149 self.assertEqual('baz', parts[2][1].source)150 def test_interpolate_mixed2(self):151 parts = list(interpolate('foo $bar baz'))152 self.assertEqual(3, len(parts))153 self.assertEqual(TEXT, parts[0][0])154 self.assertEqual('foo ', parts[0][1])155 self.assertEqual(EXPR, parts[1][0])156 self.assertEqual('bar', parts[1][1].source)157 self.assertEqual(TEXT, parts[2][0])158 self.assertEqual(' baz', parts[2][1])159def suite():160 suite = unittest.TestSuite()161 suite.addTest(doctest.DocTestSuite(interpolate.__module__))162 suite.addTest(unittest.makeSuite(InterpolateTestCase, 'test'))163 return suite164if __name__ == '__main__':...
scanner.py
Source:scanner.py
1class Util:2 @classmethod3 def read(cls, file_name):4 with open(file_name + '.txt', 'r') as content_file:5 content = content_file.read()6 return content7file = Util.read('input')8unread_parts = file9line_num = 110symbol_table = []11errors = {}12tokens = {}13# except for = and ==14symbols = [';', ':', ',', '[', ']', '(', ')', '{', '}', '+', '-', '*', '<']15keywords = ['if', 'else', 'void', 'int', 'while', 'break', 'switch', 'default', 'case', 'return']16spaces = [' ', '\n', '\t', '\r', '\v', '\f']17def generate_error(error_token_pair):18 error_type = error_token_pair[0]19 if error_type == 'UNFINISHED_COMMENT_ERROR':20 return f'({error_token_pair[1]}, Unclosed comment)'21 elif error_type == 'UNBALANCED_COMMENT_ERROR':22 return f'({error_token_pair[1]}, Unmatched comment)'23 elif error_type == 'INVALID_NUMBER_ERROR':24 return f'({error_token_pair[1]}, Invalid number)'25 else:26 return f'({error_token_pair[1]}, Invalid input)'27def report():28 global tokens, errors, symbol_table29 with open('symbol_table.txt', 'w') as sym_table_file:30 for i, token in enumerate(symbol_table):31 sym_table_file.write(f'{i + 1}.\t{token}\n')32 with open('lexical_errors.txt', 'w') as errors_file:33 if len(errors.keys()) == 0:34 errors_file.write("")35 else:36 for i in errors.keys():37 errors_file.write('{}.\t'.format(i))38 for v in errors[i]:39 errors_file.write('{}'.format(v))40 errors_file.write('\n')41 with open('tokens.txt', 'w') as tokens_file:42 for i in tokens.keys():43 tokens_file.write('{}.\t'.format(i))44 for v in tokens[i]:45 tokens_file.write('{}'.format(v))46 tokens_file.write('\n')47def omit_start(token_type, token_len):48 global unread_parts, symbol_table49 token = unread_parts[:token_len]50 unread_parts = unread_parts[token_len:]51 if token_type == 'ID':52 if token not in symbol_table:53 symbol_table.append(token)54 return token_type, token55def valid_char(char):56 return char.isalnum() or char in symbols + spaces + ['/', '=']57def get_next_token():58 global line_num, unread_parts59 if len(unread_parts) == 0:60 return 'EOF', 'EOF'61 if unread_parts[0].isspace():62 for i in range(len(unread_parts)):63 if not unread_parts[i].isspace():64 return omit_start('WHITESPACE', i)65 elif unread_parts[i] == '\n':66 line_num += 167 if unread_parts[0] == '/':68 if len(unread_parts) > 1 and unread_parts[1] == '/':69 for i in range(len(unread_parts)):70 if unread_parts[i] == '\n':71 return omit_start('COMMENT', i)72 return 'COMMENT', unread_parts73 elif len(unread_parts) > 1 and unread_parts[1] == '*':74 for i in range(len(unread_parts)):75 if unread_parts[i] == '*' and i + 1 < len(unread_parts) and unread_parts[i + 1] == '/':76 return omit_start('COMMENT', i + 2)77 # not sure of it78 comment_start = unread_parts[:min(len(unread_parts), 10)] + "..."79 unread_parts = ""80 return 'UNFINISHED_COMMENT_ERROR', comment_start81 return omit_start('ERROR', 1)82 if unread_parts[0] == '=':83 if len(unread_parts) > 1 and unread_parts[1] == '=':84 return omit_start('SYMBOL', 2)85 return omit_start('SYMBOL', 1)86 if len(unread_parts) > 1 and unread_parts[0] == '*' and unread_parts[1] == '/':87 return omit_start('UNBALANCED_COMMENT_ERROR', 2)88 if unread_parts[0] in symbols:89 return omit_start('SYMBOL', 1)90 if unread_parts[0].isalpha():91 length = len(unread_parts)92 for i in range(len(unread_parts)):93 if not unread_parts[i].isalnum():94 if valid_char(unread_parts[i]):95 length = i96 break97 else:98 return omit_start('ERROR', i + 1)99 if unread_parts[:length] in keywords:100 return omit_start('KEYWORD', length)101 else:102 return omit_start('ID', length)103 if unread_parts[0].isnumeric():104 for i in range(len(unread_parts)):105 if not unread_parts[i].isnumeric():106 if valid_char(unread_parts[i]):107 return omit_start('NUM', i)108 else:109 return omit_start('INVALID_NUMBER_ERROR', i + 1)110 if unread_parts[0] in spaces:111 return omit_start('WHITESPACE', 1)112 return omit_start('ERROR', 1)113for keyword in keywords:114 symbol_table.append(keyword)115while True:116 token = get_next_token()117 if token[0] == 'EOF':118 break119 if token[0].endswith('ERROR'):120 if line_num in errors.keys():121 errors[line_num] += ' ' + generate_error(token)122 else:123 errors[line_num] = generate_error(token)124 else:125 if token[0] == 'WHITESPACE' or token[0] == 'COMMENT':126 continue127 if line_num in tokens.keys():128 tokens[line_num] += ' (' + token[0] + ', ' + token[1] + ')'129 else:130 tokens[line_num] = '(' + token[0] + ', ' + token[1] + ')'...
Values.py
Source:Values.py
1from __future__ import absolute_import, division, print_function, unicode_literals2from echomesh.expression.parse import Functions3import echomesh.expression.parse.System4from echomesh.util import Call5from echomesh.util.registry.Registry import Registry6_REGISTRY = Registry('expression values')7def _get_value_function(value):8 parts = value.split('.')9 if len(parts) == 1:10 cmd = 'function'11 else:12 cmd = parts.pop(0)13 return _REGISTRY.function(cmd), parts14def is_constant(value, element):15 value_class, parts = _get_value_function(value)16 return value_class.is_constant(parts, element)17def evaluate(value, evaluator, element):18 value_class, parts = _get_value_function(value)19 return value_class.evaluate(parts, evaluator, element)20class ValueException(Exception):21 pass22class ValueRoot(object):23 def _get_function(self, parts, element):24 element = self._get_element(parts, element)25 variable = parts.pop()26 for p in parts:27 element = element.get_child(p)28 try:29 return element.variables[variable]30 except Exception as e:31 self._error('No such', parts + [variable], e)32 def _error(self, message, parts, exception):33 if isinstance(exception, ValueException):34 raise35 exception = (exception and str(exception)) or ''36 raise ValueException('%s %s variable "%s" %s' %37 (message, self.__class__.__name__.lower(), '.'.join(parts),38 exception))39 def evaluate(self, parts, evaluator, element):40 try:41 return self._evaluate(parts, evaluator, element)42 except Exception as e:43 self._error("Can't evaluate", parts, e)44 def is_constant(self, parts, element):45 try:46 return self._is_constant(parts, element)47 except Exception as e:48 self._error("Can't evaluate", parts, e)49 def _evaluate(self, parts, evaluator, element):50 return self._get_function(parts, element).evaluate()51 def _is_constant(self, parts, element):52 return self._get_function(parts, element).is_constant()53 def _get_element(self, parts, element):54 return element55class Settings(ValueRoot):56 def _evaluate(self, parts, evaluator, element):57 from echomesh.base import Settings58 return Settings.get(*parts)59 def _is_constant(self, parts, element):60 return False # TODO: it's inefficient that Settings are non-constant.61class Element(ValueRoot):62 def _get_element(self, parts, element):63 return element.get_root()64class Function(ValueRoot):65 def _evaluate(self, parts, evaluator, element):66 value = evaluator.pop_and_evaluate()67 return Functions.FUNCTIONS.get('.'.join(parts))(value)68 def _is_constant(self, parts, element):69 return True70class Global(ValueRoot):71 def _get_element(self, parts, element):72 from echomesh.element import ScoreMaster73 return ScoreMaster.INSTANCE.get_prefix(parts.pop(0))[1]74class Local(ValueRoot):75 pass76class Parent(ValueRoot):77 def _get_element(self, parts, element):78 return element.parent79class System(ValueRoot):80 def _get_system(self, parts):81 return echomesh.expression.parse.System.get('.'.join(parts))82 def _evaluate(self, parts, evaluator, element):83 return Call.call_recursive(self._get_system(parts).evaluate(element))84 def _is_constant(self, parts, element):85 return self._get_system(parts).is_constant86for c in Settings, Element, Function, Global, Local, Parent, System:...
timing.py
Source:timing.py
1#!/usr/bin/env python2import time3def run():4 timing([ 'foo', 'bar', 'baz', 'blorg' ], [ 'foo' ])5 timing([ 'foo', 'bar', 'baz', 'blorg' ], [ ])6 timing([ 'foo', 'bar', 'baz', 'blorg' ], [ 'foo', 'bar', 'baz' ])7 timing([ 'foo', 'bar', 'baz', 'blorg' ], [ 'foo.bar', 'bar', 'baz' ])8 timing([ 'foo', 'bar', 'baz', 'blorg' ], [ 'foo.bar.baz', 'bar', 'baz' ])9 timing([ 'foo', 'bar', 'baz', 'blorg' ], [ 'foo.bar.baz', 'foo.bar', 'foo' ])10 timing([ 'foo', 'bar', 'baz', 'blorg' ], [ 'foo', 'foo.bar', 'foo.bar.baz' ])11 timing([ 'foo' ], [ ])12 timing([ 'foo', 'bar' ], [ ])13def timing(parts, for_names):14 b, ignored = time_it(baseline, parts, for_names)15 t1, res1 = time_it(alg1, parts, for_names)16 t2, res2 = time_it(alg2, parts, for_names)17 t3, res3 = time_it(alg3, parts, for_names)18 f2 = [ ]19 for f in for_names:20 f2.append((len(f), f, f.count('.')+1))21 f2.sort()22 f2.reverse()23 t4, res4 = time_it(alg4, parts, f2)24 ### res3 is borken. ignore it.25 if res1 != res2 or res1 != res4:26 print(res1, res2, res3, res4)27 return28 print('%s %0.4f %0.4f %0.4f %0.4f %0.4f' % (res1, b, t1-b, t2-b, t3-b, t4-b))29def time_it(func, parts, for_names):30 t = time.time()31 for i in range(10000):32 res = func(parts[:], for_names)33 return time.time() - t, res34def baseline(parts, for_names):35 return '', []36def alg1(parts, for_names):37 rest = []38 while parts:39 start = '.'.join(parts)40 if start in for_names:41 return start, rest42 rest.insert(0, parts[-1])43 del parts[-1]44 return rest[0], rest[1:]45def alg2(parts, for_names):46 for i in range(len(parts), 0, -1):47 start = '.'.join(parts[:i])48 if start in for_names:49 return start, parts[i:]50 return parts[0], parts[1:]51def alg3(parts, for_names):52 all = '.'.join(parts)53 for f in for_names:54 l = len(f)55 if all[:l] == f:56 return f, all[l+1:].split('.')57 return parts[0], parts[1:]58def alg4(parts, for_names):59# print for_names60# import sys61# sys.exit(0)62 if for_names:63 all = '.'.join(parts)64 for l, f, s in for_names:65 if all[:l] == f:66 return f, parts[s:]67 return parts[0], parts[1:]68if __name__ == '__main__':...
setup.py
Source:setup.py
1import sys2from cx_Freeze import setup, Executable3includefiles = [4 "lidar_download_settings.json",5 "parts\parts_tiles\part_1.geojson",6 "parts\parts_tiles\part_2.geojson",7 "parts\parts_tiles\part_3.geojson",8 "parts\parts_tiles\part_4.geojson",9 "parts\parts_tiles\part_5.geojson",10 "parts\parts_tiles\part_6.geojson",11 "parts\parts_tiles_overlap\part_1_overlap.geojson",12 "parts\parts_tiles_overlap\part_2_overlap.geojson",13 "parts\parts_tiles_overlap\part_3_overlap.geojson",14 "parts\parts_tiles_overlap\part_4_overlap.geojson",15 "parts\parts_tiles_overlap\part_5_overlap.geojson",16 "parts\parts_tiles_overlap\part_6_overlap.geojson",17]18includes = []19excludes = ["Tkinter"]20setup(21 name="lidar_download",22 version="0.1",23 description="To download lidar files from ftp server",24 options={25 "build_exe": {26 "includes": includes,27 "excludes": excludes,28 "include_files": includefiles,29 }30 },31 executables=[Executable("lidar_download.py", base=None)],32)33"""34 'parts\parts_tiles\part_1.geojson',35 'parts\parts_tiles\part_2.geojson',36 'parts\parts_tiles\part_3.geojson',37 'parts\parts_tiles\part_4.geojson',38 'parts\parts_tiles\part_5.geojson',39 'parts\parts_tiles\part_6.geojson',40 'parts\parts_tiles_overlap\part_1_overlap.geojson',41 'parts\parts_tiles_overlap\part_2_overlap.geojson',42 'parts\parts_tiles_overlap\part_3_overlap.geojson',43 'parts\parts_tiles_overlap\part_4_overlap.geojson',44 'parts\parts_tiles_overlap\part_5_overlap.geojson',45 'parts\parts_tiles_overlap\part_6_overlap.geojson',...
Using AI Code Generation
1var parts = require('argosy-pattern').parts2var service = require('argosy-service')3var pattern = require('argosy-pattern')4var service = require('argosy-service')5var pattern = require('argosy-pattern')6var service = require('argosy-service')7var pattern = require('argosy-pattern')8var service = require('argosy-service')9var pattern = require('argosy-pattern')10var service = require('argosy-service')11var pattern = require('argosy-pattern')12var service = require('argosy-service')13var pattern = require('argosy-pattern')14var service = require('argosy-service')15var pattern = require('argosy-pattern')16var service = require('argosy-service')17var pattern = require('argosy-pattern')18var service = require('argosy-service')19var pattern = require('argosy-pattern')20var service = require('argosy-service')21var pattern = require('argosy-pattern')22var service = require('argosy-service')23var pattern = require('argosy-pattern')24var service = require('argosy-service')25var pattern = require('argosy-pattern')26var service = require('argosy-service')
Using AI Code Generation
1var argosy = require('argosy')2var argosyPattern = require('argosy-pattern')3var service = argosy()4service.accept({5 foo: parts('bar')6})7service.pipe(service)8service.on('foo', function (msg) {9 console.log(msg)10})11service.foo({12})
Using AI Code Generation
1var argosy = require('argosy')2var parts = require('argosy-patterns').parts3var service = argosy()4service.pipe(argosy.acceptor({ port: 8000 })).pipe(service)5service.use('hello', function (name, cb) {6 cb(null, 'hello ' + name)7})8service.use(parts({ hello: 'hello' }, function (request, cb) {9 request.hello('world', cb)10}))11service.act({ hello: 'world' }, function (err, response) {12})13service.act({ hello: 'world', goodbye: 'world' }, function (err, response) {14})15service.act({ goodbye: 'world' }, function (err, response) {16})17service.act({ goodbye: 'world', hello: 'world' }, function (err, response) {18})19service.act({ goodbye: 'world', hello: 'world', foo: 'bar' }, function (err, response) {20})21service.act({ goodbye: 'world', hello: 'world', foo: 'bar' }, function (err, response) {22})23service.act({ goodbye: 'world', hello: 'world' }, function (err, response) {24})25service.act({ goodbye: 'world' }, function (err, response) {26})27service.act({ goodbye: 'world', hello: 'world' }, function (err, response) {28})
Using AI Code Generation
1var argosyPattern = require('argosy-pattern')2var pattern = argosyPattern({3 parts: {4 a: {5 b: {6 }7 }8 }9})10console.log(pattern.parts)
Using AI Code Generation
1var pattern = require('argosy-pattern')2var pattern = require('argosy-pattern')3var pattern = require('argosy-pattern')4var pattern = require('argosy-pattern')5var pattern = require('argosy-pattern')6var pattern = require('argosy-pattern')7var pattern = require('argosy-pattern')8var pattern = require('argosy-pattern')9var pattern = require('argosy-pattern')10var pattern = require('argosy-pattern')11var pattern = require('argosy-pattern')12var pattern = require('argosy-pattern')13var pattern = require('argosy-pattern')
Using AI Code Generation
1var pattern = require('argosy-pattern')()2var pattern = parts('test', {foo: 'bar'})3console.log(pattern)4var pattern = require('argosy-pattern')()5var pattern = and('test', {foo: 'bar'})6console.log(pattern)7var pattern = require('argosy-pattern')()8var pattern = or('test', {foo: 'bar'})9console.log(pattern)10var pattern = require('argosy-pattern')()11var pattern = not('test', {foo: 'bar'})12console.log(pattern)13var pattern = require('argosy-pattern')()14var pattern = is('test', {foo: 'bar'})15console.log(pattern)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!