Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _summarize_accessible_fields(field_descriptions, width=40, section_title='Accessible fields'): key_str = "{:<{}}: {}" items = [] items.append(section_title) items.append("-" * len(section_title)) for field_name,...
[ "\n Create a summary string for the accessible fields in a model. Unlike\n `_toolkit_repr_print`, this function does not look up the values of the\n fields, it just formats the names and descriptions.\n\n Parameters\n ----------\n field_descriptions : dict{str: str}\n Name of each field and...
Please provide a description of the function:def _is_valid_datatype(datatype_instance): # Remap so we can still use the python types for the simple cases global _simple_type_remap if datatype_instance in _simple_type_remap: return True # Now set the protobuf from this interface. if is...
[ "\n Returns true if datatype_instance is a valid datatype object and false otherwise.\n " ]
Please provide a description of the function:def _normalize_datatype(datatype_instance): global _simple_type_remap if datatype_instance in _simple_type_remap: return _simple_type_remap[datatype_instance] # Now set the protobuf from this interface. if isinstance(datatype_instance, (Int64, D...
[ "\n Translates a user specified datatype to an instance of the ones defined above.\n\n Valid data types are passed through, and the following type specifications\n are translated to the proper instances:\n\n str, \"String\" -> String()\n int, \"Int64\" -> Int64()\n float, \"Double\" -> Double()\n\...
Please provide a description of the function:def convert(model, feature_names, target): if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') _sklearn_util.check_expected_type(model, _ensemble.GradientBoostingClassifier) def is_gbr_model(m...
[ "Convert a boosted tree model to protobuf format.\n\n Parameters\n ----------\n decision_tree : GradientBoostingClassifier\n A trained scikit-learn tree model.\n\n feature_names: [str]\n Name of the input columns.\n\n target: str\n Name of the output column.\n\n Returns\n -...
Please provide a description of the function:def get_symbols(node, ctx_types=(ast.Load, ast.Store)): ''' Returns all symbols defined in an ast node. if ctx_types is given, then restrict the symbols to ones with that context. :param node: ast node :param ctx_types: type or tuple of types t...
[]
Please provide a description of the function:def order (self, objects): # The algorithm used is the same is standard transitive closure, # except that we're not keeping in-degree for all vertices, but # rather removing edges. result = [] if not objects: retu...
[ " Given a list of objects, reorder them so that the constains specified\n by 'add_pair' are satisfied.\n\n The algorithm was adopted from an awk script by Nikita Youshchenko\n (yoush at cs dot msu dot su)\n " ]
Please provide a description of the function:def __eliminate_unused_constraits (self, objects): result = [] for c in self.constraints_: if c [0] in objects and c [1] in objects: result.append (c) return result
[ " Eliminate constraints which mention objects not in 'objects'.\n In graph-theory terms, this is finding subgraph induced by\n ordered vertices.\n " ]
Please provide a description of the function:def __has_no_dependents (self, obj, constraints): failed = False while constraints and not failed: c = constraints [0] if c [1] == obj: failed = True constraints = constraints [1:] return...
[ " Returns true if there's no constraint in 'constraints' where\n 'obj' comes second.\n " ]
Please provide a description of the function:def path_order (x, y): if x == y: return 0 xg = get_grist (x) yg = get_grist (y) if yg and not xg: return -1 elif xg and not yg: return 1 else: if not xg: x = feature.expand_subfeatures([x]) ...
[ " Helper for as_path, below. Orders properties with the implicit ones\n first, and within the two sections in alphabetical order of feature\n name.\n " ]
Please provide a description of the function:def refine (properties, requirements): assert is_iterable_typed(properties, Property) assert is_iterable_typed(requirements, Property) # The result has no duplicates, so we store it in a set result = set() # Records all requirements. required = ...
[ " Refines 'properties' by overriding any non-free properties\n for which a different value is specified in 'requirements'.\n Conditional requirements are just added without modification.\n Returns the resulting list of properties.\n " ]
Please provide a description of the function:def translate_paths (properties, path): assert is_iterable_typed(properties, Property) result = [] for p in properties: if p.feature.path: values = __re_two_ampersands.split(p.value) new_value = "&&".join(os.path.normpath(o...
[ " Interpret all path properties in 'properties' as relative to 'path'\n The property values are assumed to be in system-specific form, and\n will be translated into normalized form.\n " ]
Please provide a description of the function:def translate_indirect(properties, context_module): assert is_iterable_typed(properties, Property) assert isinstance(context_module, basestring) result = [] for p in properties: if p.value[0] == '@': q = qualify_jam_action(p.value[1:]...
[ "Assumes that all feature values that start with '@' are\n names of rules, used in 'context-module'. Such rules can be\n either local to the module or global. Qualified local rules\n with the name of the module." ]
Please provide a description of the function:def validate (properties): if isinstance(properties, Property): properties = [properties] assert is_iterable_typed(properties, Property) for p in properties: __validate1(p)
[ " Exit with error if any of the properties is not valid.\n properties may be a single property or a sequence of properties.\n " ]
Please provide a description of the function:def split_conditional (property): assert isinstance(property, basestring) m = __re_split_conditional.match (property) if m: return (m.group (1), '<' + m.group (2)) return None
[ " If 'property' is conditional property, returns\n condition and the property, e.g\n <variant>debug,<toolset>gcc:<inlining>full will become\n <variant>debug,<toolset>gcc <inlining>full.\n Otherwise, returns empty string.\n " ]
Please provide a description of the function:def select (features, properties): assert is_iterable_typed(properties, basestring) result = [] # add any missing angle brackets features = add_grist (features) return [p for p in properties if get_grist(p) in features]
[ " Selects properties which correspond to any of the given features.\n " ]
Please provide a description of the function:def evaluate_conditionals_in_context (properties, context): if __debug__: from .property_set import PropertySet assert is_iterable_typed(properties, Property) assert isinstance(context, PropertySet) base = [] conditional = [] for...
[ " Removes all conditional properties which conditions are not met\n For those with met conditions, removes the condition. Properies\n in conditions are looked up in 'context'\n " ]
Please provide a description of the function:def change (properties, feature, value = None): assert is_iterable_typed(properties, basestring) assert isinstance(feature, basestring) assert isinstance(value, (basestring, type(None))) result = [] feature = add_grist (feature) for p in proper...
[ " Returns a modified version of properties with all values of the\n given feature replaced by the given value.\n If 'value' is None the feature will be removed.\n " ]
Please provide a description of the function:def __validate1 (property): assert isinstance(property, Property) msg = None if not property.feature.free: feature.validate_value_string (property.feature, property.value)
[ " Exit with error if property is not valid.\n " ]
Please provide a description of the function:def remove(attributes, properties): if isinstance(attributes, basestring): attributes = [attributes] assert is_iterable_typed(attributes, basestring) assert is_iterable_typed(properties, basestring) result = [] for e in properties: at...
[ "Returns a property sets which include all the elements\n in 'properties' that do not have attributes listed in 'attributes'." ]
Please provide a description of the function:def take(attributes, properties): assert is_iterable_typed(attributes, basestring) assert is_iterable_typed(properties, basestring) result = [] for e in properties: if b2.util.set.intersection(attributes, feature.attributes(get_grist(e))): ...
[ "Returns a property set which include all\n properties in 'properties' that have any of 'attributes'." ]
Please provide a description of the function:def insert (self, properties, value): assert is_iterable_typed(properties, basestring) assert isinstance(value, basestring) self.__properties.append(properties) self.__values.append(value)
[ " Associate value with properties.\n " ]
Please provide a description of the function:def benchmark_command(cmd, progress): full_cmd = '/usr/bin/time --format="%U %M" {0}'.format(cmd) print '{0:6.2f}% Running {1}'.format(100.0 * progress, full_cmd) (_, err) = subprocess.Popen( ['/bin/sh', '-c', full_cmd], stdin=subprocess.PIPE...
[ "Benchmark one command execution" ]
Please provide a description of the function:def benchmark_file( filename, compiler, include_dirs, (progress_from, progress_to), iter_count, extra_flags = ''): time_sum = 0 mem_sum = 0 for nth_run in xrange(0, iter_count): (time_spent, mem_used) = benchmark_command( ...
[ "Benchmark one file" ]
Please provide a description of the function:def compiler_info(compiler): (out, err) = subprocess.Popen( ['/bin/sh', '-c', '{0} -v'.format(compiler)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).communicate('') gcc_clang = re.compile('(gcc|cl...
[ "Determine the name + version of the compiler" ]
Please provide a description of the function:def files_in_dir(path, extension): ends = '.{0}'.format(extension) return (f for f in os.listdir(path) if f.endswith(ends))
[ "Enumartes the files in path with the given extension" ]
Please provide a description of the function:def format_time(seconds): minute = 60 hour = minute * 60 day = hour * 24 week = day * 7 result = [] for name, dur in [ ('week', week), ('day', day), ('hour', hour), ('minute', minute), ('second', 1) ]: if seco...
[ "Format a duration" ]
Please provide a description of the function:def benchmark(src_dir, compiler, include_dirs, iter_count): files = list(files_in_dir(src_dir, 'cpp')) random.shuffle(files) has_string_templates = True string_template_file_cnt = sum(1 for file in files if 'bmp' in file) file_count = len(files) + s...
[ "Do the benchmarking" ]
Please provide a description of the function:def plot(values, mode_names, title, (xlabel, ylabel), out_file): matplotlib.pyplot.clf() for mode, mode_name in mode_names.iteritems(): vals = values[mode] matplotlib.pyplot.plot( [x for x, _ in vals], [y for _, y in vals]...
[ "Plot a diagram" ]
Please provide a description of the function:def configs_in(src_dir): for filename in files_in_dir(src_dir, 'json'): with open(os.path.join(src_dir, filename), 'rb') as in_f: yield json.load(in_f)
[ "Enumerate all configs in src_dir" ]
Please provide a description of the function:def join_images(img_files, out_file): images = [PIL.Image.open(f) for f in img_files] joined = PIL.Image.new( 'RGB', (sum(i.size[0] for i in images), max(i.size[1] for i in images)) ) left = 0 for img in images: joined.paste(i...
[ "Join the list of images into the out file" ]
Please provide a description of the function:def plot_temp_diagrams(config, results, temp_dir): display_name = { 'time': 'Compilation time (s)', 'memory': 'Compiler memory usage (MB)', } files = config['files'] img_files = [] if any('slt' in result for result in results) and '...
[ "Plot temporary diagrams" ]
Please provide a description of the function:def plot_diagram(config, results, images_dir, out_filename): img_files = plot_temp_diagrams(config, results, images_dir) join_images(img_files, out_filename) for img_file in img_files: os.remove(img_file)
[ "Plot one diagram" ]
Please provide a description of the function:def plot_diagrams(results, configs, compiler, out_dir): compiler_fn = make_filename(compiler) total = psutil.virtual_memory().total # pylint:disable=I0011,E1101 memory = int(math.ceil(byte_to_gb(total))) images_dir = os.path.join(out_dir, 'images') ...
[ "Plot all diagrams specified by the configs", "{0}\nMeasured on a {2} host with {3} GB memory. Compiler used: {4}.\n\n[$images/metaparse/{1}.png [width 100%]]\n" ]
Please provide a description of the function:def main(): desc = 'Benchmark the files generated by generate.py' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src_dir', default='generated', help='The directory containing the sources...
[ "The main function of the script" ]
Please provide a description of the function:def load_model(location): # Check if the location is a dir_archive, if not, use glunpickler to load # as pure python model # If the location is a http location, skip the check, and directly proceed # to load model as dir_archive. This is because # 1...
[ "\n Load any Turi Create model that was previously saved.\n\n This function assumes the model (can be any model) was previously saved in\n Turi Create model format with model.save(filename).\n\n Parameters\n ----------\n location : string\n Location of the model to load. Can be a local path...
Please provide a description of the function:def _get_default_options_wrapper(unity_server_model_name, module_name='', python_class_name='', sdk_model = False): def get_default_options_for_model(output_type = 'sfram...
[ "\n Internal function to return a get_default_options function.\n\n Parameters\n ----------\n unity_server_model_name: str\n Name of the class/toolkit as registered with the unity server\n\n module_name: str, optional\n Name of the module.\n\n python_class_name: str, optional\n ...
Please provide a description of the function:def reset (): global __had_unspecified_value, __had_value, __declared_subfeature global __init_loc global __all_signatures, __debug_configuration, __show_configuration # Stores toolsets without specified initialization values. __had_unspecified_valu...
[ " Clear the module state. This is mainly for testing purposes.\n Note that this must be called _after_ resetting the module 'feature'.\n " ]
Please provide a description of the function:def check_init_parameters(toolset, requirement, *args): assert isinstance(toolset, basestring) assert is_iterable_typed(requirement, basestring) or requirement is None from b2.build import toolset as b2_toolset if requirement is None: requirement...
[ " The rule for checking toolset parameters. Trailing parameters should all be\n parameter name/value pairs. The rule will check that each parameter either has\n a value in each invocation or has no value in each invocation. Also, the rule\n will check that the combination of all parameter value...
Please provide a description of the function:def get_invocation_command_nodefault( toolset, tool, user_provided_command=[], additional_paths=[], path_last=False): assert isinstance(toolset, basestring) assert isinstance(tool, basestring) assert is_iterable_typed(user_provided_command, basestring) ...
[ "\n A helper rule to get the command to invoke some tool. If\n 'user-provided-command' is not given, tries to find binary named 'tool' in\n PATH and in the passed 'additional-path'. Otherwise, verifies that the first\n element of 'user-provided-command' is an existing program.\n\n ...
Please provide a description of the function:def get_invocation_command(toolset, tool, user_provided_command = [], additional_paths = [], path_last = False): assert isinstance(toolset, basestring) assert isinstance(tool, basestring) assert is_iterable_typed(user_provided_comm...
[ " Same as get_invocation_command_nodefault, except that if no tool is found,\n returns either the user-provided-command, if present, or the 'tool' parameter.\n " ]
Please provide a description of the function:def get_absolute_tool_path(command): assert isinstance(command, basestring) if os.path.dirname(command): return os.path.dirname(command) else: programs = path.programs_path() m = path.glob(programs, [command, command + '.exe' ]) ...
[ "\n Given an invocation command,\n return the absolute path to the command. This works even if commnad\n has not path element and is present in PATH.\n " ]
Please provide a description of the function:def find_tool(name, additional_paths = [], path_last = False): assert isinstance(name, basestring) assert is_iterable_typed(additional_paths, basestring) assert isinstance(path_last, (int, bool)) programs = path.programs_path() match = path.glob(pro...
[ " Attempts to find tool (binary) named 'name' in PATH and in\n 'additional-paths'. If found in path, returns 'name'. If\n found in additional paths, returns full name. If the tool\n is found in several directories, returns the first path found.\n Otherwise, returns the empty string. ...
Please provide a description of the function:def check_tool_aux(command): assert isinstance(command, basestring) dirname = os.path.dirname(command) if dirname: if os.path.exists(command): return command # Both NT and Cygwin will run .exe files by their unqualified names. ...
[ " Checks if 'command' can be found either in path\n or is a full name to an existing file.\n " ]
Please provide a description of the function:def check_tool(command): assert is_iterable_typed(command, basestring) #FIXME: why do we check the first and last elements???? if check_tool_aux(command[0]) or check_tool_aux(command[-1]): return command
[ " Checks that a tool can be invoked by 'command'.\n If command is not an absolute path, checks if it can be found in 'path'.\n If comand is absolute path, check that it exists. Returns 'command'\n if ok and empty string otherwise.\n " ]
Please provide a description of the function:def handle_options(tool, condition, command, options): from b2.build import toolset assert isinstance(tool, basestring) assert is_iterable_typed(condition, basestring) assert command and isinstance(command, basestring) assert is_iterable_typed(optio...
[ " Handle common options for toolset, specifically sets the following\n flag variables:\n - CONFIG_COMMAND to 'command'\n - OPTIOns for compile to the value of <compileflags> in options\n - OPTIONS for compile.c to the value of <cflags> in options\n - OPTIONS for compile.c++ to the...
Please provide a description of the function:def get_program_files_dir(): ProgramFiles = bjam.variable("ProgramFiles") if ProgramFiles: ProgramFiles = ' '.join(ProgramFiles) else: ProgramFiles = "c:\\Program Files" return ProgramFiles
[ " returns the location of the \"program files\" directory on a windows\n platform\n " ]
Please provide a description of the function:def variable_setting_command(variable, value): assert isinstance(variable, basestring) assert isinstance(value, basestring) if os_name() == 'NT': return "set " + variable + "=" + value + os.linesep else: # (todo) # The followin...
[ "\n Returns the command needed to set an environment variable on the current\n platform. The variable setting persists through all following commands and is\n visible in the environment seen by subsequently executed commands. In other\n words, on Unix systems, the variable is exported, w...
Please provide a description of the function:def path_variable_setting_command(variable, paths): assert isinstance(variable, basestring) assert is_iterable_typed(paths, basestring) sep = os.path.pathsep return variable_setting_command(variable, sep.join(paths))
[ "\n Returns a command to sets a named shell path variable to the given NATIVE\n paths on the current platform.\n " ]
Please provide a description of the function:def prepend_path_variable_command(variable, paths): assert isinstance(variable, basestring) assert is_iterable_typed(paths, basestring) return path_variable_setting_command( variable, paths + [expand_variable(variable)])
[ "\n Returns a command that prepends the given paths to the named path variable on\n the current platform.\n " ]
Please provide a description of the function:def format_name(format, name, target_type, prop_set): if __debug__: from ..build.property_set import PropertySet assert is_iterable_typed(format, basestring) assert isinstance(name, basestring) assert isinstance(target_type, basestrin...
[ " Given a target, as given to a custom tag rule, returns a string formatted\n according to the passed format. Format is a list of properties that is\n represented in the result. For each element of format the corresponding target\n information is obtained and added to the result string. For all...
Please provide a description of the function:def get(self, id, param): assert isinstance(id, basestring) assert isinstance(param, basestring) return self.params_.get(param, {}).get(id)
[ " Returns the value of a configuration parameter. " ]
Please provide a description of the function:def set (self, id, param, value): assert isinstance(id, basestring) assert isinstance(param, basestring) assert is_iterable_typed(value, basestring) self.params_.setdefault(param, {})[id] = value
[ " Sets the value of a configuration parameter. " ]
Please provide a description of the function:def get_gpus_in_use(max_devices=None): from turicreate.util import _get_cuda_gpus gpu_indices = get_gpu_ids_in_use(max_devices=max_devices) gpus = _get_cuda_gpus() return [gpus[index] for index in gpu_indices]
[ "\n Like get_num_gpus_in_use, but returns a list of dictionaries with just\n queried GPU information.\n " ]
Please provide a description of the function:def make_unity_server_env(): env = os.environ.copy() # Add hadoop class path classpath = get_hadoop_class_path() if ("CLASSPATH" in env): env["CLASSPATH"] = env['CLASSPATH'] + (os.path.pathsep + classpath if classpath != '' else '') else: ...
[ "\n Returns the environment for unity_server.\n\n The environment is necessary to start the unity_server\n by setting the proper environments for shared libraries,\n hadoop classpath, and module search paths for python lambda workers.\n\n The environment has 3 components:\n 1. CLASSPATH, contains ...
Please provide a description of the function:def set_windows_dll_path(): lib_path = os.path.dirname(os.path.abspath(_pylambda_worker.__file__)) lib_path = os.path.abspath(os.path.join(lib_path, os.pardir)) def errcheck_bool(result, func, args): if not result: last_error = ctypes.g...
[ "\n Sets the dll load path so that things are resolved correctly.\n " ]
Please provide a description of the function:def dump_directory_structure(out = sys.stdout): "Dumping Installation Directory Structure for Debugging: " import sys, os from os.path import split, abspath, join from itertools import chain main_dir = split(abspath(sys.modules[__name__].__file__))...
[ "\n Dumps a detailed report of the turicreate/sframe directory structure\n and files, along with the output of os.lstat for each. This is useful\n for debugging purposes.\n " ]
Please provide a description of the function:def _get_expanded_classpath(classpath): if classpath is None or classpath == '': return '' # so this set comprehension takes paths that end with * to be globbed to find the jars, and then # recombined back into a colon separated list of jar paths,...
[ "\n Take a classpath of the form:\n /etc/hadoop/conf:/usr/lib/hadoop/lib/*:/usr/lib/hadoop/.//*: ...\n\n and return it expanded to all the JARs (and nothing else):\n /etc/hadoop/conf:/usr/lib/hadoop/lib/netty-3.6.2.Final.jar:/usr/lib/hadoop/lib/jaxb-api-2.2.2.jar: ...\n\n mentioned in the path\n ...
Please provide a description of the function:def get_library_name(): from os.path import split, abspath __lib_name = split(split(abspath(sys.modules[__name__].__file__))[0])[1] assert __lib_name in ["sframe", "turicreate"] return __lib_name
[ "\n Returns either sframe or turicreate depending on which library\n this file is bundled with.\n " ]
Please provide a description of the function:def get_config_file(): import os from os.path import abspath, expanduser, join, exists __lib_name = get_library_name() assert __lib_name in ["sframe", "turicreate"] __default_config_path = join(expanduser("~"), ".%s" % __lib_name, "config") i...
[ "\n Returns the file name of the config file from which the environment\n variables are written.\n " ]
Please provide a description of the function:def setup_environment_from_config_file(): from os.path import exists config_file = get_config_file() if not exists(config_file): return try: config = _ConfigParser.SafeConfigParser() config.read(config_file) __section...
[ "\n Imports the environmental configuration settings from the\n config file, if present, and sets the environment\n variables to test it.\n " ]
Please provide a description of the function:def write_config_file_value(key, value): filename = get_config_file() config = _ConfigParser.SafeConfigParser() config.read(filename) __section = "Environment" if not(config.has_section(__section)): config.add_section(__section) conf...
[ "\n Writes an environment variable configuration to the current\n config file. This will be read in on the next restart.\n The config file is created if not present.\n\n Note: The variables will not take effect until after restart.\n " ]
Please provide a description of the function:def BuildService(self, cls): # CallMethod needs to operate with an instance of the Service class. This # internal wrapper function exists only to be able to pass the service # instance to the method that does the real CallMethod work. def _WrapCallMetho...
[ "Constructs the service class.\n\n Args:\n cls: The class that will be constructed.\n " ]
Please provide a description of the function:def _CallMethod(self, srvc, method_descriptor, rpc_controller, request, callback): if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'CallMethod() given method descriptor for wrong service type.') m...
[ "Calls the method described by a given method descriptor.\n\n Args:\n srvc: Instance of the service for which this method is called.\n method_descriptor: Descriptor that represent the method to call.\n rpc_controller: RPC controller to use for this method's execution.\n request: Request proto...
Please provide a description of the function:def _GetRequestClass(self, method_descriptor): if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'GetRequestClass() given method descriptor for wrong service type.') return method_descriptor.input_type._concrete_clas...
[ "Returns the class of the request protocol message.\n\n Args:\n method_descriptor: Descriptor of the method for which to return the\n request protocol message class.\n\n Returns:\n A class that represents the input protocol message of the specified\n method.\n " ]
Please provide a description of the function:def _GetResponseClass(self, method_descriptor): if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'GetResponseClass() given method descriptor for wrong service type.') return method_descriptor.output_type._concrete_c...
[ "Returns the class of the response protocol message.\n\n Args:\n method_descriptor: Descriptor of the method for which to return the\n response protocol message class.\n\n Returns:\n A class that represents the output protocol message of the specified\n method.\n " ]
Please provide a description of the function:def _GenerateNonImplementedMethod(self, method): return lambda inst, rpc_controller, request, callback: ( self._NonImplementedMethod(method.name, rpc_controller, callback))
[ "Generates and returns a method that can be set for a service methods.\n\n Args:\n method: Descriptor of the service method for which a method is to be\n generated.\n\n Returns:\n A method that can be added to the service class.\n " ]
Please provide a description of the function:def BuildServiceStub(self, cls): def _ServiceStubInit(stub, rpc_channel): stub.rpc_channel = rpc_channel self.cls = cls cls.__init__ = _ServiceStubInit for method in self.descriptor.methods: setattr(cls, method.name, self._GenerateStubMethod...
[ "Constructs the stub class.\n\n Args:\n cls: The class that will be constructed.\n " ]
Please provide a description of the function:def _StubMethod(self, stub, method_descriptor, rpc_controller, request, callback): return stub.rpc_channel.CallMethod( method_descriptor, rpc_controller, request, method_descriptor.output_type._concrete_class, callback)
[ "The body of all service methods in the generated stub class.\n\n Args:\n stub: Stub instance.\n method_descriptor: Descriptor of the invoked method.\n rpc_controller: Rpc controller to execute the method.\n request: Request protocol message.\n callback: A callback to execute when the me...
Please provide a description of the function:def MessageToString(message, as_utf8=False, as_one_line=False, pointy_brackets=False, use_index_order=False, float_format=None, use_field_number=False, ...
[ "Convert protobuf message to text format.\n\n Floating point values can be formatted compactly with 15 digits of\n precision (which is the most that IEEE 754 \"double\" can guarantee)\n using float_format='.15g'. To ensure that converting to text and back to a\n proto will result in an identical value, float_fo...
Please provide a description of the function:def PrintFieldValue(field, value, out, indent=0, as_utf8=False, as_one_line=False, pointy_brackets=False, use_index_order=False, ...
[ "Print a single field value (not including name)." ]
Please provide a description of the function:def _BuildMessageFromTypeName(type_name, descriptor_pool): # pylint: disable=g-import-not-at-top from google.protobuf import symbol_database database = symbol_database.Default() try: message_descriptor = descriptor_pool.FindMessageTypeByName(type_name) excep...
[ "Returns a protobuf message instance.\n\n Args:\n type_name: Fully-qualified protobuf message type name string.\n descriptor_pool: DescriptorPool instance.\n\n Returns:\n A Message instance of type matching type_name, or None if the a Descriptor\n wasn't found matching type_name.\n " ]
Please provide a description of the function:def Parse(text, message, allow_unknown_extension=False, allow_field_number=False, descriptor_pool=None): if not isinstance(text, str): text = text.decode('utf-8') return ParseLines(text.split('\n'), messa...
[ "Parses a text representation of a protocol message into a message.\n\n Args:\n text: Message text representation.\n message: A protocol buffer message to merge into.\n allow_unknown_extension: if True, skip over missing extensions and keep\n parsing\n allow_field_number: if True, both field numbe...
Please provide a description of the function:def _SkipFieldContents(tokenizer): # Try to guess the type of this field. # If this field is not a message, there should be a ":" between the # field name and the field value and also the field value should not # start with "{" or "<" which indicates the beginning...
[ "Skips over contents (value or message) of a field.\n\n Args:\n tokenizer: A tokenizer to parse the field name and values.\n " ]
Please provide a description of the function:def _SkipField(tokenizer): if tokenizer.TryConsume('['): # Consume extension name. tokenizer.ConsumeIdentifier() while tokenizer.TryConsume('.'): tokenizer.ConsumeIdentifier() tokenizer.Consume(']') else: tokenizer.ConsumeIdentifier() _Ski...
[ "Skips over a complete field (name and value/message).\n\n Args:\n tokenizer: A tokenizer to parse the field name and values.\n " ]
Please provide a description of the function:def _SkipFieldMessage(tokenizer): if tokenizer.TryConsume('<'): delimiter = '>' else: tokenizer.Consume('{') delimiter = '}' while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('}'): _SkipField(tokenizer) tokenizer.Consume(delimiter)
[ "Skips over a field message.\n\n Args:\n tokenizer: A tokenizer to parse the field name and values.\n " ]
Please provide a description of the function:def _SkipFieldValue(tokenizer): # String/bytes tokens can come in multiple adjacent string literals. # If we can consume one, consume as many as we can. if tokenizer.TryConsumeByteString(): while tokenizer.TryConsumeByteString(): pass return if (not...
[ "Skips over a field value.\n\n Args:\n tokenizer: A tokenizer to parse the field name and values.\n\n Raises:\n ParseError: In case an invalid field value is found.\n " ]
Please provide a description of the function:def _ConsumeInteger(tokenizer, is_signed=False, is_long=False): try: result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long) except ValueError as e: raise tokenizer.ParseError(str(e)) tokenizer.NextToken() return result
[ "Consumes an integer number from tokenizer.\n\n Args:\n tokenizer: A tokenizer used to parse the number.\n is_signed: True if a signed integer must be parsed.\n is_long: True if a long integer must be parsed.\n\n Returns:\n The integer parsed.\n\n Raises:\n ParseError: If an integer with given cha...
Please provide a description of the function:def ParseInteger(text, is_signed=False, is_long=False): # Do the actual parsing. Exception handling is propagated to caller. result = _ParseAbstractInteger(text, is_long=is_long) # Check if the integer is sane. Exceptions handled by callers. checker = _INTEGER_CH...
[ "Parses an integer.\n\n Args:\n text: The text to parse.\n is_signed: True if a signed integer must be parsed.\n is_long: True if a long integer must be parsed.\n\n Returns:\n The integer value.\n\n Raises:\n ValueError: Thrown Iff the text is not a valid integer.\n " ]
Please provide a description of the function:def _ParseAbstractInteger(text, is_long=False): # Do the actual parsing. Exception handling is propagated to caller. try: # We force 32-bit values to int and 64-bit values to long to make # alternate implementations where the distinction is more significant ...
[ "Parses an integer without checking size/signedness.\n\n Args:\n text: The text to parse.\n is_long: True if the value should be returned as a long integer.\n\n Returns:\n The integer value.\n\n Raises:\n ValueError: Thrown Iff the text is not a valid integer.\n " ]
Please provide a description of the function:def ParseFloat(text): try: # Assume Python compatible syntax. return float(text) except ValueError: # Check alternative spellings. if _FLOAT_INFINITY.match(text): if text[0] == '-': return float('-inf') else: return float('i...
[ "Parse a floating point number.\n\n Args:\n text: Text to parse.\n\n Returns:\n The number parsed.\n\n Raises:\n ValueError: If a floating point number couldn't be parsed.\n " ]
Please provide a description of the function:def ParseEnum(field, value): enum_descriptor = field.enum_type try: number = int(value, 0) except ValueError: # Identifier. enum_value = enum_descriptor.values_by_name.get(value, None) if enum_value is None: raise ValueError('Enum type "%s" has...
[ "Parse an enum value.\n\n The value can be specified by a number (the enum value), or by\n a string literal (the enum name).\n\n Args:\n field: Enum field descriptor.\n value: String value.\n\n Returns:\n Enum value number.\n\n Raises:\n ValueError: If the enum value could not be parsed.\n " ]
Please provide a description of the function:def _TryPrintAsAnyMessage(self, message): packed_message = _BuildMessageFromTypeName(message.TypeName(), self.descriptor_pool) if packed_message: packed_message.MergeFromString(message.value) self.out.wr...
[ "Serializes if message is a google.protobuf.Any field." ]
Please provide a description of the function:def PrintMessage(self, message): if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and self.descriptor_pool and self._TryPrintAsAnyMessage(message)): return fields = message.ListFields() if self.use_index_order: fields.sort(key=lamb...
[ "Convert protobuf message to text format.\n\n Args:\n message: The protocol buffers message.\n " ]
Please provide a description of the function:def PrintField(self, field, value): out = self.out out.write(' ' * self.indent) if self.use_field_number: out.write(str(field.number)) else: if field.is_extension: out.write('[') if (field.containing_type.GetOptions().message_...
[ "Print a single field name/value pair." ]
Please provide a description of the function:def ParseFromString(self, text, message): if not isinstance(text, str): text = text.decode('utf-8') return self.ParseLines(text.split('\n'), message)
[ "Parses a text representation of a protocol message into a message." ]
Please provide a description of the function:def ParseLines(self, lines, message): self._allow_multiple_scalars = False self._ParseOrMerge(lines, message) return message
[ "Parses a text representation of a protocol message into a message." ]
Please provide a description of the function:def MergeLines(self, lines, message): self._allow_multiple_scalars = True self._ParseOrMerge(lines, message) return message
[ "Merges a text representation of a protocol message into a message." ]
Please provide a description of the function:def _ParseOrMerge(self, lines, message): tokenizer = Tokenizer(lines) while not tokenizer.AtEnd(): self._MergeField(tokenizer, message)
[ "Converts a text representation of a protocol message into a message.\n\n Args:\n lines: Lines of a message's text representation.\n message: A protocol buffer message to merge into.\n\n Raises:\n ParseError: On text parsing problems.\n " ]
Please provide a description of the function:def _MergeField(self, tokenizer, message): message_descriptor = message.DESCRIPTOR if (hasattr(message_descriptor, 'syntax') and message_descriptor.syntax == 'proto3'): # Proto3 doesn't represent presence so we can't test if multiple # scalar...
[ "Merges a single protocol message field into a message.\n\n Args:\n tokenizer: A tokenizer to parse the field name and values.\n message: A protocol message to record the data.\n\n Raises:\n ParseError: In case of text parsing problems.\n " ]
Please provide a description of the function:def _ConsumeAnyTypeUrl(self, tokenizer): # Consume "type.googleapis.com/". tokenizer.ConsumeIdentifier() tokenizer.Consume('.') tokenizer.ConsumeIdentifier() tokenizer.Consume('.') tokenizer.ConsumeIdentifier() tokenizer.Consume('/') # Co...
[ "Consumes a google.protobuf.Any type URL and returns the type name." ]
Please provide a description of the function:def _MergeMessageField(self, tokenizer, message, field): is_map_entry = _IsMapEntry(field) if tokenizer.TryConsume('<'): end_token = '>' else: tokenizer.Consume('{') end_token = '}' if (field.message_type.full_name == _ANY_FULL_TYPE_N...
[ "Merges a single scalar field into a message.\n\n Args:\n tokenizer: A tokenizer to parse the field value.\n message: The message of which field is a member.\n field: The descriptor of the field to be merged.\n\n Raises:\n ParseError: In case of text parsing problems.\n " ]
Please provide a description of the function:def _MergeScalarField(self, tokenizer, message, field): _ = self.allow_unknown_extension value = None if field.type in (descriptor.FieldDescriptor.TYPE_INT32, descriptor.FieldDescriptor.TYPE_SINT32, descriptor.Fie...
[ "Merges a single scalar field into a message.\n\n Args:\n tokenizer: A tokenizer to parse the field value.\n message: A protocol message to record the data.\n field: The descriptor of the field to be merged.\n\n Raises:\n ParseError: In case of text parsing problems.\n RuntimeError: O...
Please provide a description of the function:def TryConsume(self, token): if self.token == token: self.NextToken() return True return False
[ "Tries to consume a given piece of text.\n\n Args:\n token: Text to consume.\n\n Returns:\n True iff the text was consumed.\n " ]
Please provide a description of the function:def ConsumeCommentOrTrailingComment(self): # Tokenizer initializes _previous_line and _previous_column to 0. As the # tokenizer starts, it looks like there is a previous token on the line. just_started = self._line == 0 and self._column == 0 before_par...
[ "Consumes a comment, returns a 2-tuple (trailing bool, comment str)." ]
Please provide a description of the function:def ConsumeIdentifier(self): result = self.token if not self._IDENTIFIER.match(result): raise self.ParseError('Expected identifier.') self.NextToken() return result
[ "Consumes protocol message field identifier.\n\n Returns:\n Identifier string.\n\n Raises:\n ParseError: If an identifier couldn't be consumed.\n " ]
Please provide a description of the function:def ConsumeIdentifierOrNumber(self): result = self.token if not self._IDENTIFIER_OR_NUMBER.match(result): raise self.ParseError('Expected identifier or number.') self.NextToken() return result
[ "Consumes protocol message field identifier.\n\n Returns:\n Identifier string.\n\n Raises:\n ParseError: If an identifier couldn't be consumed.\n " ]
Please provide a description of the function:def ConsumeInteger(self, is_long=False): try: result = _ParseAbstractInteger(self.token, is_long=is_long) except ValueError as e: raise self.ParseError(str(e)) self.NextToken() return result
[ "Consumes an integer number.\n\n Args:\n is_long: True if the value should be returned as a long integer.\n Returns:\n The integer parsed.\n\n Raises:\n ParseError: If an integer couldn't be consumed.\n " ]
Please provide a description of the function:def ConsumeString(self): the_bytes = self.ConsumeByteString() try: return six.text_type(the_bytes, 'utf-8') except UnicodeDecodeError as e: raise self._StringParseError(e)
[ "Consumes a string value.\n\n Returns:\n The string parsed.\n\n Raises:\n ParseError: If a string value couldn't be consumed.\n " ]
Please provide a description of the function:def ConsumeByteString(self): the_list = [self._ConsumeSingleByteString()] while self.token and self.token[0] in _QUOTES: the_list.append(self._ConsumeSingleByteString()) return b''.join(the_list)
[ "Consumes a byte array value.\n\n Returns:\n The array parsed (as a string).\n\n Raises:\n ParseError: If a byte array value couldn't be consumed.\n " ]
Please provide a description of the function:def NextToken(self): self._previous_line = self._line self._previous_column = self._column self._column += len(self.token) self._SkipWhitespace() if not self._more_lines: self.token = '' return match = self._TOKEN.match(self._curre...
[ "Reads the next meaningful token." ]