generate a migrator for the given at-based portal type
17975
def makeMigrator(context, portal_type, remove_old_value=True):
    
    meta_type = portal_type

    class BlobMigrator(BaseInlineMigrator):
        """in-place migrator for archetypes based content that copies
        file/image data from old non-blob fields to new fields with the same
        name  provided by archetypes.schemaextender.

        see `plone3 to 4 migration guide`__

        .. __: https://plone.org/documentation/manual/upgrade-guide/version
        /upgrading-plone-3-x-to-4.0/updating-add-on-products-for-plone-4.0
        /use-plone.app.blob-based-blob-storage
        """

        src_portal_type = portal_type
        src_meta_type = meta_type
        dst_portal_type = portal_type
        dst_meta_type = meta_type
        fields = []

        def getFields(self, obj):
            if not self.fields:
                # get the blob fields to migrate from the first object
                for field in ISchema(obj).fields():
                    if IBlobField.providedBy(field):
                        self.fields.append(field.getName())
            return self.fields

        @property
        def fields_map(self):
            fields = self.getFields(None)
            return dict([(name, None) for name in fields])

        def migrate_data(self):
            fields = self.getFields(self.obj)
            for name in fields:
                # access old field by not using schemaextender
                oldfield = self.obj.schema[name]
                is_imagefield = False
                if hasattr(oldfield, 'removeScales'):
                    # clean up old image scales
                    is_imagefield = True
                    oldfield.removeScales(self.obj)
                value = oldfield.get(self.obj)

                if not value:
                    # no image/file data: don't copy it over to blob field
                    # this way it's save to run migration multiple times w/o
                    # overwriting existing data
                    continue

                if isinstance(aq_base(value), BlobWrapper):
                    # already a blob field, no need to migrate it
                    continue

                # access new field via schemaextender
                field = self.obj.getField(name)
                field.getMutator(self.obj)(value)

                if remove_old_value:
                    # Remove data from old field to not end up with data
                    # stored twice - in ZODB and blobstorage
                    if is_imagefield:
                        oldfield.set(self.obj, 'DELETE_IMAGE')
                    else:
                        oldfield.set(self.obj, 'DELETE_FILE')

        def last_migrate_reindex(self):
            # The original method checks the modification date in order to
            # keep the old one, but we don't care about it.
            self.obj.reindexObject()

    return BlobMigrator
340342
def create_object(container, portal_type, **data):
    

    if "id" in data:
        # always omit the id as senaite LIMS generates a proper one
        id = data.pop("id")
        logger.warn("Passed in ID '{}' omitted! Senaite LIMS "
                    "generates a proper ID for you" .format(id))

    try:
        # Special case for ARs
        # => return immediately w/o update
        if portal_type == "AnalysisRequest":
            obj = create_analysisrequest(container, **data)
            # Omit values which are already set through the helper
            data = u.omit(data, "SampleType", "Analyses")
            # Set the container as the client, as the AR lives in it
            data["Client"] = container
        # Standard content creation
        else:
            # we want just a minimun viable object and set the data later
            obj = api.create(container, portal_type)
            # obj = api.create(container, portal_type, **data)
    except Unauthorized:
        fail(401, "You are not allowed to create this content")

    # Update the object with the given data, but omit the id
    try:
        update_object_with_data(obj, data)
    except APIError:

        # Failure in creation process, delete the invalid object
        container.manage_delObjects(obj.id)
        # reraise the error
        raise

    return obj
413120
def portalAdmin(self):
        """"""
        from ..manageportal import PortalAdministration
        return PortalAdministration(admin_url="https://%s/portaladmin" % self.portalHostname,
                                    securityHandler=self._securityHandler,
                                    proxy_url=self._proxy_url,
                                    proxy_port=self._proxy_port,
                                    initalize=False)
638561
def set_id_format(portal, format):
    
    bs = portal.bika_setup
    if 'portal_type' not in format:
        return
    logger.info("Applying format {} for {}".format(format.get('form', ''),
                                                   format.get(
                                                       'portal_type')))
    portal_type = format['portal_type']
    ids = list()
    id_map = bs.getIDFormatting()
    for record in id_map:
        if record.get('portal_type', '') == portal_type:
            continue
        ids.append(record)
    ids.append(format)
    bs.setIDFormatting(ids)
1027026
function buildNatGateway(position, zone) {
  const cfName = `NatGateway${position}`;
  return {
    [cfName]: {
      Type: 'AWS::EC2::NatGateway',
      Properties: {
        AllocationId: {
          'Fn::GetAtt': [`EIP${position}`, 'AllocationId'],
        },
        SubnetId: {
          Ref: `${PUBLIC_SUBNET}Subnet${position}`,
        },
        Tags: [
          {
            Key: 'Name',
            Value: {
              'Fn::Join': [
                '-',
                [
                  {
                    Ref: 'AWS::StackName',
                  },
                  zone,
                ],
              ],
            },
          },
        ],
      },
    },
  };
}
799321
def _generate_route_objects_m(self, route_schema, namespace):
        """"""
        output_path = 'Routes/RouteObjects/{}.m'.format(
            fmt_route_obj_class(namespace.name))

        with self.output_to_relative_path(output_path):
            self.emit_raw(base_file_comment)

            import_classes = [
                fmt_route_obj_class(namespace.name),
                'DBStoneBase',
                'DBRequestErrors',
            ]

            for auth_type in self.namespace_to_has_route_auth_list[namespace]:
                import_classes.append(
                    fmt_routes_class(namespace.name, auth_type))

            imports_classes_m = import_classes + \
                self._get_imports_m(
                    self._get_namespace_route_imports(namespace, include_route_args=False), [])
            self._generate_imports_m(imports_classes_m)

            with self.block_m(fmt_route_obj_class(namespace.name)):
                for route in namespace.routes:
                    route_name = fmt_route_var(namespace.name, route)
                    self.emit('static DBRoute *{};'.format(route_name))
                self.emit()

                for route in namespace.routes:
                    route_name = fmt_route_var(namespace.name, route)
                    if route.version == 1:
                        route_path = route.name
                    else:
                        route_path = '{}_v{}'.format(route.name, route.version)

                    if route.deprecated:
                        deprecated = '@{}'.format('YES')
                    else:
                        deprecated = '@{}'.format('NO')

                    if not is_void_type(route.result_data_type):
                        caller = fmt_class_type(
                            route.result_data_type, suppress_ptr=True)
                        result_type = fmt_func_call(
                            caller=caller, callee='class')
                    else:
                        result_type = 'nil'

                    if not is_void_type(route.error_data_type):
                        caller = fmt_class_type(
                            route.error_data_type, suppress_ptr=True)
                        error_type = fmt_func_call(
                            caller=caller, callee='class')
                    else:
                        error_type = 'nil'

                    if is_list_type(route.arg_data_type) or is_map_type(route.arg_data_type):
                        dataStructSerialBlock = '^id(id dataStruct) {{ return {}; }}'.format(
                            self._fmt_serialization_call(
                                route.result_data_type, 'dataStruct', True))
                    else:
                        dataStructSerialBlock = 'nil'

                    if is_list_type(route.result_data_type) or is_map_type(route.result_data_type):
                        dataStructDeserialBlock = '^id(id dataStruct) {{ return {}; }}'.format(
                            self._fmt_serialization_call(
                                route.result_data_type, 'dataStruct', False))
                    else:
                        dataStructDeserialBlock = 'nil'

                    with self.block_func(
                            func=route_name,
                            args=[],
                            return_type='DBRoute *',
                            class_func=True):
                        with self.block('if (!{})'.format(route_name)):
                            with self.block(
                                    '{} = [[DBRoute alloc] init:'.format(
                                        route_name),
                                    delim=(None, None),
                                    after='];'):
                                self.emit('@\"{}\"'.format(route_path))
                                self.emit('namespace_:@\"{}\"'.format(
                                    namespace.name))
                                self.emit('deprecated:{}'.format(deprecated))
                                self.emit('resultType:{}'.format(result_type))
                                self.emit('errorType:{}'.format(error_type))

                                attrs = []
                                for field in route_schema.fields:
                                    attr_key = field.name
                                    attr_val = ("@\"{}\"".format(route.attrs
                                            .get(attr_key)) if route.attrs
                                        .get(attr_key)
                                        else 'nil')
                                    attrs.append('@\"{}\": {}'.format(
                                        attr_key, attr_val))

                                self.generate_multiline_list(
                                    attrs,
                                    delim=('attrs:@{', '}'),
                                    compact=True)

                                self.emit('dataStructSerialBlock:{}'.format(
                                    dataStructSerialBlock))
                                self.emit('dataStructDeserialBlock:{}'.format(
                                    dataStructDeserialBlock))

                        self.emit('return {};'.format(route_name))
                    self.emit()
1279120
def portalSelf(self):
        """"""
        url = "%s/self" % self.root
        return Portal(url=url,
                      securityHandler=self._securityHandler,
                      proxy_url=self._proxy_url,
                      proxy_port=self._proxy_port,
                      )
503405
def generate_http_manifest(self):
        
        base_path = os.path.dirname(self.translate_path(self.path))
        self.dataset = dtoolcore.DataSet.from_uri(base_path)

        admin_metadata_fpath = os.path.join(base_path, ".dtool", "dtool")
        with open(admin_metadata_fpath) as fh:
            admin_metadata = json.load(fh)

        http_manifest = {
            "admin_metadata": admin_metadata,
            "manifest_url": self.generate_url(".dtool/manifest.json"),
            "readme_url": self.generate_url("README.yml"),
            "overlays": self.generate_overlay_urls(),
            "item_urls": self.generate_item_urls()
        }
        return bytes(json.dumps(http_manifest), "utf-8")
843891
def gen(name, data):
        """"""
        return '---- dataentry %s ----\n%s\n----' % (name, '\n'.join(
            '%s:%s' % (attr, value) for attr, value in data.items()))
887012
def create(resource_path, previous_version=None, package='perch.migrations'):
    """"""
    pkg, obj = resource_path.rsplit('.', 1)
    module = importlib.import_module(pkg)
    resource = getattr(module, obj)
    version = uuid4().hex
    target_module = importlib.import_module(package)
    target_dir = os.path.dirname(target_module.__file__)
    target_file = os.path.join(target_dir, resource.resource_type + '_' + version + '.py')

    with open(target_file, 'w') as f:
        f.write(MIGRATION_TEMPLATE.format(
            resource_path=resource_path,
            resource_type=resource.resource_type,
            version=version,
            previous_version=previous_version or '',
        ))

    return target_file
738888
def _GenerateApiFileDetails(path_infos):
  """"""

  type_attrs = []
  hash_attrs = []
  size_attrs = []
  stat_attrs = []
  pathspec_attrs = []

  def _Value(age, value):
    """Generate ApiAff4ObjectAttributeValue from an age and a value."""

    v = ApiAff4ObjectAttributeValue()
    # TODO(user): get rid of RDF builtin "age" property.
    v.Set("age", age)
    # With dynamic values we first have to set the type and
    # then the value itself.
    # TODO(user): refactor dynamic values logic so that it's not needed,
    # possibly just removing the "type" attribute completely.
    v.Set("type", compatibility.GetName(value.__class__))
    v.value = value
    return v

  for pi in path_infos:
    if pi.directory:
      object_type = "VFSDirectory"
    else:
      object_type = "VFSFile"

    type_attrs.append(_Value(pi.timestamp, rdfvalue.RDFString(object_type)))

    if pi.hash_entry:
      hash_attrs.append(_Value(pi.timestamp, pi.hash_entry))
      size_attrs.append(
          _Value(pi.timestamp, rdfvalue.RDFInteger(pi.hash_entry.num_bytes)))
    if pi.stat_entry:
      stat_attrs.append(_Value(pi.timestamp, pi.stat_entry))

      if pi.stat_entry.pathspec:
        pathspec_attrs.append(_Value(pi.timestamp, pi.stat_entry.pathspec))

  return ApiAff4ObjectRepresentation(types=[
      ApiAff4ObjectType(
          name="AFF4Object",
          attributes=[
              ApiAff4ObjectAttribute(
                  name="TYPE",
                  values=type_attrs,
              ),
          ],
      ),
      ApiAff4ObjectType(
          name="AFF4Stream",
          attributes=[
              ApiAff4ObjectAttribute(
                  name="HASH",
                  values=hash_attrs,
              ),
              ApiAff4ObjectAttribute(
                  name="SIZE",
                  values=size_attrs,
              ),
          ],
      ),
      ApiAff4ObjectType(
          name="VFSFile",
          attributes=[
              ApiAff4ObjectAttribute(
                  name="PATHSPEC",
                  values=pathspec_attrs,
              ),
              ApiAff4ObjectAttribute(
                  name="STAT",
                  values=stat_attrs,
              ),
          ],
      ),
  ])
988872
def _generate_client_m(self, api):
        """"""
        self.emit_raw(base_file_comment)

        import_classes = [self.args.module_name]
        import_classes += [
            fmt_routes_class(ns.name, self.args.auth_type)
            for ns in api.namespaces.values()
            if ns.routes and self.namespace_to_has_routes[ns]
        ]
        import_classes.append(
            '{}Protocol'.format(self.args.transport_client_name))
        self._generate_imports_m(import_classes)

        with self.block_m(self.args.class_name):
            client_args = fmt_func_args_declaration(
                [('client',
                  'id<{}>'.format(self.args.transport_client_name))])
            with self.block_func(
                    func='initWithTransportClient',
                    args=client_args,
                    return_type='instancetype'):
                self.emit('self = [super init];')

                with self.block_init():
                    self.emit('_transportClient = client;')
                    for namespace in api.namespaces.values():
                        if namespace.routes and self.namespace_to_has_routes[namespace]:
                            base_string = '_{}Routes = [[{} alloc] init:client];'
                            self.emit(
                                base_string.format(
                                    fmt_var(namespace.name),
                                    fmt_routes_class(namespace.name,
                                                     self.args.auth_type)))
767219
def generate_modules_cache(self, modules, underlined=None,
                               task_handle=taskhandle.NullTaskHandle()):
        """"""
        job_set = task_handle.create_jobset(
            'Generatig autoimport cache for modules', len(modules))
        for modname in modules:
            job_set.started_job('Working on <%s>' % modname)
            if modname.endswith('.*'):
                mod = self.project.find_module(modname[:-2])
                if mod:
                    for sub in submodules(mod):
                        self.update_resource(sub, underlined)
            else:
                self.update_module(modname, underlined)
            job_set.finished_job()
170564
def generate(self, data, *args, **kwargs):
        
        with tempfile.TemporaryDirectory() as tmpdirname:
            self.options.setdefault('package_build_dir', tmpdirname)
            crawler = CrawlerScript(self.options)
            crawler.crawl(data, self.spider, *args, **kwargs)

            output_file = os.path.join(
                self.options['package_build_dir'], 'source', 'moear.mobi')
            with open(output_file, 'rb') as fh:
                content = fh.read()

        return content
817190
protected function generatePortalLocalizations(\DOMNode $portalNode, Portal $portal)
    {
        if ($this->xpath->query('x:localizations', $portalNode)->length > 0) {
            // set localizations from portal, if they are set
            $localizationNodes = $this->xpath->query('x:localizations/x:localization', $portalNode);
            $this->generateLocalizationsFromNodeList($localizationNodes, $portal);
        } else {
            // if the portal has no localizations fallback to the localizations from the webspace
            $localizationNodes = $this->xpath->query('/x:webspace/x:localizations//x:localization');
            $this->generateLocalizationsFromNodeList($localizationNodes, $portal, true);
        }
    }
315367
def generate_bbox(self, collision_function=None, tag=""):
        """"""
        boundingBox = AABoundingBox(None, collision_function, tag)
        CollisionManager.add_object(boundingBox)
703454
def migrator(state):
    """"""
    cleverbot_kwargs, convos_kwargs = state
    cb = Cleverbot(**cleverbot_kwargs)
    for convo_kwargs in convos_kwargs:
        cb.conversation(**convo_kwargs)
    return cb