Best Python code snippet using avocado_python
index.d.ts
Source:index.d.ts  
1import { Engine } from "./engine";2import type { IOptions } from "./Options/Interfaces/IOptions";3import type { RecursivePartial } from "./Types/RecursivePartial";4declare const tsParticles: Engine;5export * from "./Core/Interfaces/Colors";6export * from "./Core/Interfaces/Gradients";7export * from "./Core/Interfaces/IBounds";8export * from "./Core/Interfaces/IBubbleParticleData";9export * from "./Core/Interfaces/ICircleBouncer";10export * from "./Core/Interfaces/IContainerInteractivity";11export * from "./Core/Interfaces/IContainerPlugin";12export * from "./Core/Interfaces/ICoordinates";13export * from "./Core/Interfaces/IDelta";14export * from "./Core/Interfaces/IDimension";15export * from "./Core/Interfaces/IDistance";16export * from "./Core/Interfaces/IExternalInteractor";17export * from "./Core/Interfaces/IInteractor";18export * from "./Core/Interfaces/IMouseData";19export * from "./Core/Interfaces/IMovePathGenerator";20export * from "./Core/Interfaces/IParticle";21export * from "./Core/Interfaces/IParticleColorStyle";22export * from "./Core/Interfaces/IParticleGravity";23export * from "./Core/Interfaces/IParticleHslAnimation";24export * from "./Core/Interfaces/IParticlesInteractor";25export * from "./Core/Interfaces/IParticleLife";26export * from "./Core/Interfaces/IParticleLoops";27export * from "./Core/Interfaces/IParticleRetinaProps";28export * from "./Core/Interfaces/IParticleRoll";29export * from "./Core/Interfaces/IParticleUpdater";30export * from "./Core/Interfaces/IParticleValueAnimation";31export * from "./Core/Interfaces/IParticleWobble";32export * from "./Core/Interfaces/IParticlesMover";33export * from "./Core/Interfaces/IPlugin";34export * from "./Core/Interfaces/IRangeValue";35export * from "./Core/Interfaces/IRectSideResult";36export * from "./Core/Interfaces/IShapeDrawer";37export * from "./Core/Interfaces/IShapeValues";38export * from "./Core/Utils/Circle";39export * from "./Core/Utils/CircleWarp";40export * from "./Core/Utils/Constants";41export * from "./Core/Utils/EventListeners";42export * from "./Core/Utils/ExternalInteractorBase";43export * from "./Core/Utils/FrameManager";44export * from "./Core/Utils/InteractionManager";45export * from "./Core/Utils/ParticlesInteractorBase";46export * from "./Core/Utils/Plugins";47export * from "./Core/Utils/Point";48export * from "./Core/Utils/QuadTree";49export * from "./Core/Utils/Range";50export * from "./Core/Utils/Rectangle";51export * from "./Core/Utils/Vector";52export * from "./Core/Utils/Vector3d";53export * from "./Core/Canvas";54export * from "./Core/Container";55export * from "./Core/Loader";56export * from "./Core/Particle";57export * from "./Core/Particles";58export * from "./Core/Retina";59export * from "./Enums/Directions/MoveDirection";60export * from "./Enums/Directions/RotateDirection";61export * from "./Enums/Directions/OutModeDirection";62export * from "./Enums/Directions/TiltDirection";63export * from "./Enums/Modes/ClickMode";64export * from "./Enums/Modes/DestroyMode";65export * from "./Enums/Modes/DivMode";66export * from "./Enums/Modes/HoverMode";67export * from "./Enums/Modes/CollisionMode";68export * from "./Enums/Modes/OutMode";69export * from "./Enums/Modes/RollMode";70export * from "./Enums/Modes/SizeMode";71export * from "./Enums/Modes/ThemeMode";72export * from "./Enums/Modes/ResponsiveMode";73export * from "./Enums/Types/AlterType";74export * from "./Enums/Types/DestroyType";75export * from "./Enums/Types/GradientType";76export * from "./Enums/Types/InteractorType";77export * from "./Enums/Types/ParticleOutType";78export * from "./Enums/Types/StartValueType";79export * from "./Enums/Types/DivType";80export * from "./Enums/Types/EasingType";81export * from "./Enums/AnimationStatus";82export * from "./Enums/InteractivityDetect";83export { Engine, Engine as Main };84export * from "./Options/Classes/AnimatableColor";85export * from "./Options/Classes/AnimatableGradient";86export * from "./Options/Classes/AnimationOptions";87export * from "./Options/Classes/Background/Background";88export * from "./Options/Classes/BackgroundMask/BackgroundMask";89export * from "./Options/Classes/BackgroundMask/BackgroundMaskCover";90export * from "./Options/Classes/ColorAnimation";91export * from "./Options/Classes/FullScreen/FullScreen";92export * from "./Options/Classes/HslAnimation";93export * from "./Options/Classes/Interactivity/Events/ClickEvent";94export * from "./Options/Classes/Interactivity/Events/DivEvent";95export * from "./Options/Classes/Interactivity/Events/ClickEvent";96export * from "./Options/Classes/Interactivity/Events/DivEvent";97export * from "./Options/Classes/Interactivity/Events/Events";98export * from "./Options/Classes/Interactivity/Events/HoverEvent";99export * from "./Options/Classes/Interactivity/Events/Parallax";100export * from "./Options/Classes/Interactivity/Interactivity";101export * from "./Options/Classes/Interactivity/Modes/Attract";102export * from "./Options/Classes/Interactivity/Modes/Bounce";103export * from "./Options/Classes/Interactivity/Modes/Bubble";104export * from "./Options/Classes/Interactivity/Modes/BubbleBase";105export * from "./Options/Classes/Interactivity/Modes/BubbleDiv";106export * from "./Options/Classes/Interactivity/Modes/Connect";107export * from "./Options/Classes/Interactivity/Modes/ConnectLinks";108export * from "./Options/Classes/Interactivity/Modes/Grab";109export * from "./Options/Classes/Interactivity/Modes/GrabLinks";110export * from "./Options/Classes/Interactivity/Modes/Light";111export * from "./Options/Classes/Interactivity/Modes/LightArea";112export * from "./Options/Classes/Interactivity/Modes/LightGradient";113export * from "./Options/Classes/Interactivity/Modes/LightShadow";114export * from "./Options/Classes/Interactivity/Modes/Modes";115export * from "./Options/Classes/Interactivity/Modes/Push";116export * from "./Options/Classes/Interactivity/Modes/Remove";117export * from "./Options/Classes/Interactivity/Modes/Repulse";118export * from "./Options/Classes/Interactivity/Modes/RepulseBase";119export * from "./Options/Classes/Interactivity/Modes/RepulseDiv";120export * from "./Options/Classes/Interactivity/Modes/Slow";121export * from "./Options/Classes/Interactivity/Modes/Trail";122export * from "./Options/Classes/ManualParticle";123export * from "./Options/Classes/Motion/Motion";124export * from "./Options/Classes/Motion/MotionReduce";125export * from "./Options/Classes/Options";126export * from "./Options/Classes/OptionsColor";127export * from "./Options/Classes/Particles/Bounce/ParticlesBounce";128export * from "./Options/Classes/Particles/Bounce/ParticlesBounceFactor";129export * from "./Options/Classes/Particles/Collisions/Collisions";130export * from "./Options/Classes/Particles/Collisions/CollisionsOverlap";131export * from "./Options/Classes/Particles/Destroy/Destroy";132export * from "./Options/Classes/Particles/Destroy/Split";133export * from "./Options/Classes/Particles/Destroy/SplitFactor";134export * from "./Options/Classes/Particles/Destroy/SplitRate";135export * from "./Options/Classes/Particles/ParticlesOptions";136export * from "./Options/Classes/Particles/Shadow";137export * from "./Options/Classes/Particles/Stroke";138export * from "./Options/Classes/Particles/Life/Life";139export * from "./Options/Classes/Particles/Life/LifeDelay";140export * from "./Options/Classes/Particles/Life/LifeDuration";141export * from "./Options/Classes/Particles/Links/Links";142export * from "./Options/Classes/Particles/Links/LinksShadow";143export * from "./Options/Classes/Particles/Links/LinksTriangle";144export * from "./Options/Classes/Particles/Move/MoveAttract";145export * from "./Options/Classes/Particles/Move/Move";146export * from "./Options/Classes/Particles/Move/MoveAngle";147export * from "./Options/Classes/Particles/Move/MoveGravity";148export * from "./Options/Classes/Particles/Move/OutModes";149export * from "./Options/Classes/Particles/Move/Path/MovePath";150export * from "./Options/Classes/Particles/Move/Path/MovePathDelay";151export * from "./Options/Classes/Particles/Move/Spin";152export * from "./Options/Classes/Particles/Move/MoveTrail";153export * from "./Options/Classes/Particles/Number/ParticlesNumber";154export * from "./Options/Classes/Particles/Number/ParticlesDensity";155export * from "./Options/Classes/Particles/Opacity/Opacity";156export * from "./Options/Classes/Particles/Opacity/OpacityAnimation";157export * from "./Options/Classes/Particles/Orbit/Orbit";158export * from "./Options/Classes/Particles/Orbit/OrbitRotation";159export * from "./Options/Classes/Particles/Repulse/ParticlesRepulse";160export * from "./Options/Classes/Particles/Roll/Roll";161export * from "./Options/Classes/Particles/Roll/RollLight";162export * from "./Options/Classes/Particles/Rotate/Rotate";163export * from "./Options/Classes/Particles/Rotate/RotateAnimation";164export * from "./Options/Classes/Particles/Shape/Shape";165export * from "./Options/Classes/Particles/Size/Size";166export * from "./Options/Classes/Particles/Size/SizeAnimation";167export * from "./Options/Classes/Particles/Tilt/Tilt";168export * from "./Options/Classes/Particles/Tilt/TiltAnimation";169export * from "./Options/Classes/Particles/Twinkle/Twinkle";170export * from "./Options/Classes/Particles/Twinkle/TwinkleValues";171export * from "./Options/Classes/Particles/Wobble/Wobble";172export * from "./Options/Classes/Particles/ZIndex/ZIndex";173export * from "./Options/Classes/Responsive";174export * from "./Options/Classes/Theme/Theme";175export * from "./Options/Classes/Theme/ThemeDefault";176export * from "./Options/Classes/ValueWithRandom";177export * from "./Options/Interfaces/Background/IBackground";178export * from "./Options/Interfaces/BackgroundMask/IBackgroundMask";179export * from "./Options/Interfaces/BackgroundMask/IBackgroundMaskCover";180export * from "./Options/Interfaces/FullScreen/IFullScreen";181export * from "./Options/Interfaces/IAnimatable";182export * from "./Options/Interfaces/IAnimatableColor";183export * from "./Options/Interfaces/IAnimatableGradient";184export * from "./Options/Interfaces/IAnimation";185export * from "./Options/Interfaces/IColorAnimation";186export * from "./Options/Interfaces/IHslAnimation";187export * from "./Options/Interfaces/IManualParticle";188export * from "./Options/Interfaces/IOptionLoader";189export * from "./Options/Interfaces/IOptions";190export * from "./Options/Interfaces/IOptionsColor";191export * from "./Options/Interfaces/IOptionsGradient";192export * from "./Options/Interfaces/IResponsive";193export * from "./Options/Interfaces/IValueWithRandom";194export * from "./Options/Interfaces/Interactivity/Events/IClickEvent";195export * from "./Options/Interfaces/Interactivity/Events/IDivEvent";196export * from "./Options/Interfaces/Interactivity/Events/IEvents";197export * from "./Options/Interfaces/Interactivity/Events/IHoverEvent";198export * from "./Options/Interfaces/Interactivity/Events/IParallax";199export * from "./Options/Interfaces/Interactivity/Modes/IAttract";200export * from "./Options/Interfaces/Interactivity/Modes/IBounce";201export * from "./Options/Interfaces/Interactivity/Modes/IBubble";202export * from "./Options/Interfaces/Interactivity/Modes/IBubbleBase";203export * from "./Options/Interfaces/Interactivity/Modes/IBubbleDiv";204export * from "./Options/Interfaces/Interactivity/Modes/IConnect";205export * from "./Options/Interfaces/Interactivity/Modes/IConnectLinks";206export * from "./Options/Interfaces/Interactivity/Modes/IGrab";207export * from "./Options/Interfaces/Interactivity/Modes/IGrabLinks";208export * from "./Options/Interfaces/Interactivity/Modes/ILight";209export * from "./Options/Interfaces/Interactivity/Modes/ILightArea";210export * from "./Options/Interfaces/Interactivity/Modes/ILightGradient";211export * from "./Options/Interfaces/Interactivity/Modes/ILightShadow";212export * from "./Options/Interfaces/Interactivity/Modes/IModeDiv";213export * from "./Options/Interfaces/Interactivity/Modes/IModes";214export * from "./Options/Interfaces/Interactivity/Modes/IPush";215export * from "./Options/Interfaces/Interactivity/Modes/IRemove";216export * from "./Options/Interfaces/Interactivity/Modes/IRepulse";217export * from "./Options/Interfaces/Interactivity/Modes/IRepulseBase";218export * from "./Options/Interfaces/Interactivity/Modes/IRepulseDiv";219export * from "./Options/Interfaces/Interactivity/Modes/ISlow";220export * from "./Options/Interfaces/Interactivity/Modes/ITrail";221export * from "./Options/Interfaces/Interactivity/IInteractivity";222export * from "./Options/Interfaces/Motion/IMotion";223export * from "./Options/Interfaces/Motion/IMotionReduce";224export * from "./Options/Interfaces/Particles/Bounce/IParticlesBounce";225export * from "./Options/Interfaces/Particles/Collisions/ICollisions";226export * from "./Options/Interfaces/Particles/Collisions/ICollisionsOverlap";227export * from "./Options/Interfaces/Particles/Destroy/IDestroy";228export * from "./Options/Interfaces/Particles/Destroy/ISplit";229export * from "./Options/Interfaces/Particles/IParticlesOptions";230export * from "./Options/Interfaces/Particles/IShadow";231export * from "./Options/Interfaces/Particles/IStroke";232export * from "./Options/Interfaces/Particles/Life/ILife";233export * from "./Options/Interfaces/Particles/Life/ILifeDelay";234export * from "./Options/Interfaces/Particles/Life/ILifeDuration";235export * from "./Options/Interfaces/Particles/Links/ILinks";236export * from "./Options/Interfaces/Particles/Links/ILinksShadow";237export * from "./Options/Interfaces/Particles/Links/ILinksTriangle";238export * from "./Options/Interfaces/Particles/Move/IMoveAttract";239export * from "./Options/Interfaces/Particles/Move/IMove";240export * from "./Options/Interfaces/Particles/Move/IMoveAngle";241export * from "./Options/Interfaces/Particles/Move/IMoveGravity";242export * from "./Options/Interfaces/Particles/Move/Path/IMovePath";243export * from "./Options/Interfaces/Particles/Move/IOutModes";244export * from "./Options/Interfaces/Particles/Move/ISpin";245export * from "./Options/Interfaces/Particles/Move/IMoveTrail";246export * from "./Options/Interfaces/Particles/Number/IParticlesDensity";247export * from "./Options/Interfaces/Particles/Number/IParticlesNumber";248export * from "./Options/Interfaces/Particles/Opacity/IOpacity";249export * from "./Options/Interfaces/Particles/Opacity/IOpacityAnimation";250export * from "./Options/Interfaces/Particles/Orbit/IOrbit";251export * from "./Options/Interfaces/Particles/Repulse/IParticlesRepulse";252export * from "./Options/Interfaces/Particles/Roll/IRoll";253export * from "./Options/Interfaces/Particles/Roll/IRollLight";254export * from "./Options/Interfaces/Particles/Rotate/IRotate";255export * from "./Options/Interfaces/Particles/Rotate/IRotateAnimation";256export * from "./Options/Interfaces/Particles/Shape/ICharacterShape";257export * from "./Options/Interfaces/Particles/Shape/IImageShape";258export * from "./Options/Interfaces/Particles/Shape/IPolygonShape";259export * from "./Options/Interfaces/Particles/Shape/IShape";260export * from "./Options/Interfaces/Particles/Shape/IShapeValues";261export * from "./Options/Interfaces/Particles/Shape/IStarShape";262export * from "./Options/Interfaces/Particles/Size/ISize";263export * from "./Options/Interfaces/Particles/Size/ISizeAnimation";264export * from "./Options/Interfaces/Particles/Tilt/ITilt";265export * from "./Options/Interfaces/Particles/Tilt/ITiltAnimation";266export * from "./Options/Interfaces/Particles/Twinkle/ITwinkle";267export * from "./Options/Interfaces/Particles/Twinkle/ITwinkleValues";268export * from "./Options/Interfaces/Particles/Wobble/IWobble";269export * from "./Options/Interfaces/Particles/ZIndex/IZIndex";270export * from "./Options/Interfaces/Theme/ITheme";271export * from "./Options/Interfaces/Theme/IThemeDefault";272export * from "./Types/RangeValue";273export * from "./Types/RecursivePartial";274export * from "./Types/ShapeData";275export * from "./Types/ShapeDrawerFunctions";276export * from "./Types/SingleOrMultiple";277export * from "./Types/PathOptions";278export * from "./Utils/CanvasUtils";279export * from "./Utils/ColorUtils";280export * from "./Utils/NumberUtils";281export * from "./Utils/Utils";282export { tsParticles };283export declare type ISourceOptions = RecursivePartial<IOptions>;...compute_interfaces_info_overall.py
Source:compute_interfaces_info_overall.py  
1#!/usr/bin/python2#3# Copyright (C) 2013 Google Inc. All rights reserved.4#5# Redistribution and use in source and binary forms, with or without6# modification, are permitted provided that the following conditions are7# met:8#9#     * Redistributions of source code must retain the above copyright10# notice, this list of conditions and the following disclaimer.11#     * Redistributions in binary form must reproduce the above12# copyright notice, this list of conditions and the following disclaimer13# in the documentation and/or other materials provided with the14# distribution.15#     * Neither the name of Google Inc. nor the names of its16# contributors may be used to endorse or promote products derived from17# this software without specific prior written permission.18#19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.30"""Compute global interface information, including public information, dependencies, and inheritance.31Computed data is stored in a global variable, |interfaces_info|, and written as32output (concretely, exported as a pickle). This is then used by the IDL compiler33itself, so it does not need to compute global information itself, and so that34inter-IDL dependencies are clear, since they are all computed here.35The |interfaces_info| pickle is a *global* dependency: any changes cause a full36rebuild. This is to avoid having to compute which public data is visible by37which IDL files on a file-by-file basis, which is very complex for little38benefit.39|interfaces_info| should thus only contain data about an interface that40contains paths or is needed by *other* interfaces, e.g., path data (to abstract41the compiler from OS-specific file paths) or public data (to avoid having to42read other interfaces unnecessarily).43It should *not* contain full information about an interface (e.g., all44extended attributes), as this would cause unnecessary rebuilds.45|interfaces_info| is a dict, keyed by |interface_name|.46Current keys are:47* dependencies:48    'implements_interfaces': targets of 'implements' statements49    'referenced_interfaces': reference interfaces that are introspected50                             (currently just targets of [PutForwards])51* inheritance:52    'ancestors': all ancestor interfaces53    'inherited_extended_attributes': inherited extended attributes54                                     (all controlling memory management)55* public:56    'is_callback_interface': bool, callback interface or not57    'implemented_as': value of [ImplementedAs=...] on interface (C++ class name)58* paths:59    'full_path': path to the IDL file, so can lookup an IDL by interface name60    'include_path': path for use in C++ #include directives61    'dependencies_full_paths': paths to dependencies (for merging into main)62    'dependencies_include_paths': paths for use in C++ #include directives63    'dependencies_other_component_full_paths':64        paths to dependencies (cannot merge because of other component)65    'dependencies_other_component_include_paths':66        paths for use in C++ #include directives because of dependencies in67        other component68Note that all of these are stable information, unlikely to change without69moving or deleting files (hence requiring a full rebuild anyway) or significant70code changes (for inherited extended attributes).71Design doc: http://www.chromium.org/developers/design-documents/idl-build72"""73# pylint: disable=relative-import74import optparse75import sys76from collections import defaultdict77from utilities import idl_filename_to_component78from utilities import merge_dict_recursively79from utilities import read_pickle_files80from utilities import shorten_union_name81from utilities import write_pickle_file82INHERITED_EXTENDED_ATTRIBUTES = set([83    'ActiveScriptWrappable',84    'DependentLifetime',85])86# Main variable (filled in and exported)87interfaces_info = {}88# Interfaces referenced from partial interfaces to be merged into the full89# interface.90interfaces_referenced_from_partial_interfaces = {}91# Auxiliary variables (not visible to future build steps)92partial_interface_files = defaultdict(lambda: {93    'full_paths': [],94    'include_paths': [],95})96parent_interfaces = {}97inherited_extended_attributes_by_interface = {}  # interface name -> extended attributes98class IdlInterfaceFileNotFoundError(Exception):99    """Raised if the IDL file implementing an interface cannot be found."""100    pass101def parse_options():102    usage = 'Usage: %prog [InfoIndividual.pickle]... [Info.pickle]'103    parser = optparse.OptionParser(usage=usage)104    return parser.parse_args()105def dict_of_dicts_of_lists_update_or_append(existing, other):106    """Updates an existing dict of dicts of lists, or appends to lists if key already present.107    Needed for merging partial_interface_files across components.108    """109    for key, value in other.iteritems():110        if key not in existing:111            existing[key] = value112            continue113        existing_value = existing[key]114        for inner_key, inner_value in value.iteritems():115            existing_value[inner_key].extend(inner_value)116################################################################################117# Computations118################################################################################119def compute_inheritance_info(interface_name):120    """Compute inheritance information, namely ancestors and inherited extended attributes."""121    def generate_ancestors(interface_name):122        while interface_name in parent_interfaces:123            interface_name = parent_interfaces[interface_name]124            yield interface_name125    ancestors = list(generate_ancestors(interface_name))126    inherited_extended_attributes = inherited_extended_attributes_by_interface[interface_name]127    for ancestor in ancestors:128        # Ancestors may not be present, notably if an ancestor is a generated129        # IDL file and we are running this script from run-bindings-tests,130        # where we don't generate these files.131        ancestor_extended_attributes = inherited_extended_attributes_by_interface.get(ancestor, {})132        inherited_extended_attributes.update(ancestor_extended_attributes)133    interfaces_info[interface_name].update({134        'ancestors': ancestors,135        'inherited_extended_attributes': inherited_extended_attributes,136    })137def compute_global_type_info():138    ancestors = {}139    dictionaries = {}140    component_dirs = {}141    implemented_as_interfaces = {}142    garbage_collected_interfaces = set()143    callback_interfaces = set()144    for interface_name, interface_info in interfaces_info.iteritems():145        component_dirs[interface_name] = idl_filename_to_component(interface_info['full_path'])146        if interface_info['ancestors']:147            ancestors[interface_name] = interface_info['ancestors']148        if interface_info['is_callback_interface']:149            callback_interfaces.add(interface_name)150        if interface_info['is_dictionary']:151            dictionaries[interface_name] = interface_info['is_dictionary']152        if interface_info['implemented_as']:153            implemented_as_interfaces[interface_name] = interface_info['implemented_as']154        inherited_extended_attributes = interface_info['inherited_extended_attributes']155        garbage_collected_interfaces.add(interface_name)156    # Record a list of all interface names157    interfaces_info['all_interfaces'] = set(158        interface_name for interface_name, info in interfaces_info.iteritems()159            if not info['is_dependency'])160    interfaces_info['ancestors'] = ancestors161    interfaces_info['callback_interfaces'] = callback_interfaces162    interfaces_info['dictionaries'] = dictionaries163    interfaces_info['implemented_as_interfaces'] = implemented_as_interfaces164    interfaces_info['garbage_collected_interfaces'] = garbage_collected_interfaces165    interfaces_info['component_dirs'] = component_dirs166def compute_interfaces_info_overall(info_individuals):167    """Compute information about IDL files.168    Information is stored in global interfaces_info.169    """170    for info in info_individuals:171        merge_dict_recursively(interfaces_info, info['interfaces_info'])172        # Interfaces in one component may have partial interfaces in173        # another component. This is ok (not a layering violation), since174        # partial interfaces are used to *extend* interfaces.175        # We thus need to update or append if already present176        dict_of_dicts_of_lists_update_or_append(177                partial_interface_files, info['partial_interface_files'])178        interfaces_referenced_from_partial_interfaces.update(179                info['partial_interface_referenced_interfaces'])180    # Append interfaces referenced from partial interfaces into the full181    # interface's list of partial interfaces182    for interface_name, referenced_interfaces in interfaces_referenced_from_partial_interfaces.items():183        interface_info = interfaces_info[interface_name]184        interface_info['referenced_interfaces'].extend(referenced_interfaces)185    # Record inheritance information individually186    for interface_name, interface_info in interfaces_info.iteritems():187        extended_attributes = interface_info['extended_attributes']188        inherited_extended_attributes_by_interface[interface_name] = dict(189                (key, value)190                for key, value in extended_attributes.iteritems()191                if key in INHERITED_EXTENDED_ATTRIBUTES)192        parent = interface_info['parent']193        if parent:194            parent_interfaces[interface_name] = parent195    # Once all individual files handled, can compute inheritance information196    # and dependencies197    # Compute inheritance info198    for interface_name in interfaces_info:199        compute_inheritance_info(interface_name)200    # Compute dependencies201    # Move implements info from implement*ed* interface (rhs of 'implements')202    # to implement*ing* interface (lhs of 'implements').203    # Note that moving an 'implements' statement between implementing and204    # implemented files does not change the info (or hence cause a rebuild)!205    for right_interface_name, interface_info in interfaces_info.iteritems():206        for left_interface_name in interface_info['implemented_by_interfaces']:207            interfaces_info[left_interface_name]['implements_interfaces'].append(right_interface_name)208        del interface_info['implemented_by_interfaces']209    # An IDL file's dependencies are partial interface files that extend it,210    # and files for other interfaces that this interfaces implements.211    for interface_name, interface_info in interfaces_info.iteritems():212        partial_interface_paths = partial_interface_files[interface_name]213        partial_interfaces_full_paths = partial_interface_paths['full_paths']214        # Partial interface definitions each need an include, as they are215        # implemented in separate classes from the main interface.216        partial_interfaces_include_paths = partial_interface_paths['include_paths']217        implemented_interfaces = interface_info['implements_interfaces']218        try:219            implemented_interfaces_info = [220                interfaces_info[interface]221                for interface in implemented_interfaces]222        except KeyError as key_name:223            raise IdlInterfaceFileNotFoundError('Could not find the IDL file where the following implemented interface is defined: %s' % key_name)224        implemented_interfaces_full_paths = [225            implemented_interface_info['full_path']226            for implemented_interface_info in implemented_interfaces_info]227        # Implemented interfaces don't need includes, as this is handled in228        # the Blink implementation (they are implemented on |impl| itself,229        # hence header is included in implementing class).230        # However, they are needed for legacy implemented interfaces that231        # are being treated as partial interfaces, until we remove these.232        # http://crbug.com/360435233        implemented_interfaces_include_paths = [234            implemented_interface_info['include_path']235            for implemented_interface_info in implemented_interfaces_info236            if implemented_interface_info['is_legacy_treat_as_partial_interface']]237        dependencies_full_paths = implemented_interfaces_full_paths238        dependencies_include_paths = implemented_interfaces_include_paths239        dependencies_other_component_full_paths = []240        dependencies_other_component_include_paths = []241        component = idl_filename_to_component(interface_info['full_path'])242        for full_path in partial_interfaces_full_paths:243            partial_interface_component = idl_filename_to_component(full_path)244            if component == partial_interface_component:245                dependencies_full_paths.append(full_path)246            else:247                dependencies_other_component_full_paths.append(full_path)248        for include_path in partial_interfaces_include_paths:249            partial_interface_component = idl_filename_to_component(include_path)250            if component == partial_interface_component:251                dependencies_include_paths.append(include_path)252            else:253                dependencies_other_component_include_paths.append(include_path)254        for union_type in interface_info.get('union_types', []):255            name = shorten_union_name(union_type)256            dependencies_include_paths.append(257                'bindings/%s/v8/%s.h' % (component, name))258        interface_info.update({259            'dependencies_full_paths': dependencies_full_paths,260            'dependencies_include_paths': dependencies_include_paths,261            'dependencies_other_component_full_paths':262                dependencies_other_component_full_paths,263            'dependencies_other_component_include_paths':264                dependencies_other_component_include_paths,265        })266    # Clean up temporary private information267    for interface_info in interfaces_info.itervalues():268        del interface_info['extended_attributes']269        del interface_info['union_types']270        del interface_info['is_legacy_treat_as_partial_interface']271    # Compute global_type_info to interfaces_info so that idl_compiler does272    # not need to always calculate the info in __init__.273    compute_global_type_info()274################################################################################275def main():276    _, args = parse_options()277    # args = Input1, Input2, ..., Output278    interfaces_info_filename = args.pop()279    info_individuals = read_pickle_files(args)280    compute_interfaces_info_overall(info_individuals)281    write_pickle_file(interfaces_info_filename, interfaces_info)282if __name__ == '__main__':...netbox_interface_sync.py
Source:netbox_interface_sync.py  
...11from nornir_napalm.plugins.tasks import napalm_get12from netbox import NetBox13from dotenv import find_dotenv, load_dotenv14from helpers import get_device_id, is_interface_present, create_connection_options15def update_netbox_interfaces(task: Task, nb_interfaces: list, netbox) -> Result:16    """Nornir task to update interfaces in Netbox obtained via napalm_get from live devices.17    Args:18        task (Task): This.19        nb_interfaces (list): List of netbox interfaces.20        netbox (NetBox): Netbox instance21    Returns:22        Result: Nornir task result23    """24    task_result = task.run(task=napalm_get, getters=['interfaces'], severity_level=logging.FATAL)25    interfaces = task_result.result['interfaces']26    changed:bool = False27    changed_items:list = []28    for interface_name in interfaces.keys():29        enabled=interfaces[interface_name]['is_enabled']30        mtu=interfaces[interface_name]['mtu']31        description=interfaces[interface_name]['description']32        mac_address=interfaces[interface_name]['mac_address']33        if (is_interface_present(nb_interfaces=nb_interfaces,34                                device_name=f"{task.host}",35                                interface_name=interface_name)):36            print(37                f"* Updating Netbox Interface for device {task.host}, interface {interface_name}"38            )39            dcim_result = netbox.dcim.update_interface(40                device=f"{task.host}",41                interface=interface_name,42                description=description,43                enabled=enabled,44                mtu=mtu,45                mac_address=mac_address,46            )47            changed=True48            changed_items.append(f"{task.host} : {interface_name} Updated: {dcim_result}")49    return Result(host=task.host, result=changed_items, changed=changed)50def create_netbox_interfaces(task: Task, nb_interfaces: list, netbox: NetBox) -> Result:51    """Nornir task to create interfaces in Netbox obtained via napalm_get from live devices.52    Args:53        task (Task): This.54        nb_interfaces (list): List of netbox interfaces.55        netbox (NetBox): Netbox instance56    Returns:57        Result: Nornir task result58    """59    task_result = task.run(task=napalm_get, getters=['interfaces'], severity_level=logging.FATAL)60    interfaces = task_result.result['interfaces']61    changed:bool = False62    changed_items:list = []63    for interface_name in interfaces.keys():64        exists = is_interface_present(nb_interfaces=nb_interfaces,65                                    device_name=f"{task.host}",66                                    interface_name=interface_name)67        if not exists:68            print(69                f"* Creating Netbox Interface for device {task.host}, interface {interface_name}"70            )71            device_id = get_device_id(device_name=f"{task.host}", netbox=netbox)72            print (f"Device ID: {device_id}")73            dcim_result = netbox.dcim.create_interface(74                device_id=device_id,75                name=f"{interface_name}",76                interface_type="1000base-t",77                enabled=interfaces[interface_name]['is_enabled'],78                mtu=interfaces[interface_name]['mtu'],79                description=interfaces[interface_name]['description'],80                mac_address=interfaces[interface_name]['mac_address'],81            )82            changed_items.append(dcim_result)83            changed=True84    return Result(host=task.host,result=changed_items, changed=changed)85def main():86    """ Here's the good stuff87    """88    dotenv_file = find_dotenv()89    load_dotenv(dotenv_path=dotenv_file, verbose=True)90    ## NetBox Stuff91    nb_host=getenv('nb_host')92    nb_url=f"http://{nb_host}"93    nb_token=getenv('nb_token')94    ## Napalm Stuff95    username=getenv('username')96    password=getenv('password')97    secret=getenv('secret')98    netbox:NetBox = NetBox(host=nb_host, auth_token=nb_token,99                            ssl_verify=False, use_ssl=False,100                            port=80)101    nb_interfaces:list = netbox.dcim.get_interfaces()102    nornir_instance = InitNornir(103        inventory={104            "plugin":"NetBoxInventory2",105            "options": {106                "nb_url": nb_url,107                "nb_token": nb_token108            }109        },110        logging={111            "enabled": True,112            "level": "INFO", # DEBUG is most verbose113            "to_console": False, # True returns ALOT of stuff114        }115    )...ap_get_interface.py
Source:ap_get_interface.py  
1#!/usr/bin/env python32#3#   Copyright 2017 - Google, Inc.4#5#   Licensed under the Apache License, Version 2.0 (the "License");6#   you may not use this file except in compliance with the License.7#   You may obtain a copy of the License at8#9#       http://www.apache.org/licenses/LICENSE-2.010#11#   Unless required by applicable law or agreed to in writing, software12#   distributed under the License is distributed on an "AS IS" BASIS,13#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14#   See the License for the specific language governing permissions and15#   limitations under the License.16import logging17from acts.libs.proc import job18GET_ALL_INTERFACE = 'ls /sys/class/net'19GET_VIRTUAL_INTERFACE = 'ls /sys/devices/virtual/net'20BRCTL_SHOW = 'brctl show'21class ApInterfacesError(Exception):22    """Error related to AP interfaces."""23class ApInterfaces(object):24    """Class to get network interface information for the device.25    """26    def __init__(self, ap):27        """Initialize the ApInterface class.28        Args:29            ap: the ap object within ACTS30        """31        self.ssh = ap.ssh32    def get_all_interface(self):33        """Get all network interfaces on the device.34        Returns:35            interfaces_all: list of all the network interfaces on device36        """37        output = self.ssh.run(GET_ALL_INTERFACE)38        interfaces_all = output.stdout.split('\n')39        return interfaces_all40    def get_virtual_interface(self):41        """Get all virtual interfaces on the device.42        Returns:43            interfaces_virtual: list of all the virtual interfaces on device44        """45        output = self.ssh.run(GET_VIRTUAL_INTERFACE)46        interfaces_virtual = output.stdout.split('\n')47        return interfaces_virtual48    def get_physical_interface(self):49        """Get all the physical interfaces of the device.50        Get all physical interfaces such as eth ports and wlan ports51        Returns:52            interfaces_phy: list of all the physical interfaces53        """54        interfaces_all = self.get_all_interface()55        interfaces_virtual = self.get_virtual_interface()56        interfaces_phy = list(set(interfaces_all) - set(interfaces_virtual))57        return interfaces_phy58    def get_bridge_interface(self):59        """Get all the bridge interfaces of the device.60        Returns:61            interfaces_bridge: the list of bridge interfaces, return None if62                bridge utility is not available on the device63        """64        interfaces_bridge = []65        try:66            output = self.ssh.run(BRCTL_SHOW)67            lines = output.stdout.split('\n')68            for line in lines:69                interfaces_bridge.append(line.split('\t')[0])70            interfaces_bridge.pop(0)71            interfaces_bridge = [x for x in interfaces_bridge if x != '']72            return interfaces_bridge73        except job.Error:74            logging.info('No brctl utility is available')75            return None76    def get_wlan_interface(self):77        """Get all WLAN interfaces and specify 2.4 GHz and 5 GHz interfaces.78        Returns:79            interfaces_wlan: all wlan interfaces80        Raises:81            ApInterfacesError: Missing at least one WLAN interface82        """83        wlan_2g = None84        wlan_5g = None85        interfaces_phy = self.get_physical_interface()86        for iface in interfaces_phy:87            IW_LIST_FREQ = 'iwlist %s freq' % iface88            output = self.ssh.run(IW_LIST_FREQ)89            if 'Channel 06' in output.stdout and 'Channel 36' not in output.stdout:90                wlan_2g = iface91            elif 'Channel 36' in output.stdout and 'Channel 06' not in output.stdout:92                wlan_5g = iface93        interfaces_wlan = [wlan_2g, wlan_5g]94        if None not in interfaces_wlan:95            return interfaces_wlan96        raise ApInterfacesError('Missing at least one WLAN interface')97    def get_wan_interface(self):98        """Get the WAN interface which has internet connectivity.99        Returns:100            wan: the only one WAN interface101        Raises:102            ApInterfacesError: no running WAN can be found103        """104        wan = None105        interfaces_phy = self.get_physical_interface()106        interfaces_wlan = self.get_wlan_interface()107        interfaces_eth = list(set(interfaces_phy) - set(interfaces_wlan))108        for iface in interfaces_eth:109            network_status = self.check_ping(iface)110            if network_status == 1:111                wan = iface112                break113        if wan:114            return wan115        output = self.ssh.run('ifconfig')116        interfaces_all = output.stdout.split('\n')117        logging.info("IFCONFIG output = %s" % interfaces_all)118        raise ApInterfacesError('No WAN interface available')119    def get_lan_interface(self):120        """Get the LAN interface connecting to local devices.121        Returns:122            lan: the only one running LAN interface of the devices123            None, if nothing was found.124        """125        lan = None126        interfaces_phy = self.get_physical_interface()127        interfaces_wlan = self.get_wlan_interface()128        interfaces_eth = list(set(interfaces_phy) - set(interfaces_wlan))129        interface_wan = self.get_wan_interface()130        interfaces_eth.remove(interface_wan)131        for iface in interfaces_eth:132            LAN_CHECK = 'ifconfig %s' % iface133            output = self.ssh.run(LAN_CHECK)134            if 'RUNNING' in output.stdout:135                lan = iface136                break137        return lan138    def check_ping(self, iface):139        """Check the ping status on specific interface to determine the WAN.140        Args:141            iface: the specific interface to check142        Returns:143            network_status: the connectivity status of the interface144        """145        PING = 'ping -c 3 -I %s 8.8.8.8' % iface146        try:147            self.ssh.run(PING)148            return 1149        except job.Error:...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!!
