Create new shm segment and write base meta data
774927
protected function createSegment() {
		$this->shm = shmop_open(
			$this->getIdentifier(),
			self::SHM_CREATE_MODE,
			self::SHM_CREATE_PERMISSIONS,
			$this->size
		);

		if (false === $this->shm) {
			throw new RuntimeException(sprintf('Unable to create shared memory segment with key: %s', $this->getIdentifier()));
		}

		$this->updateSize(0);
	}
1274107
def create_archive(
    source: Path,
    target: Path,
    interpreter: str,
    main: str,
    compressed: bool = True
) -> None:
    
    # Check that main has the right format.
    mod, sep, fn = main.partition(":")
    mod_ok = all(part.isidentifier() for part in mod.split("."))
    fn_ok = all(part.isidentifier() for part in fn.split("."))
    if not (sep == ":" and mod_ok and fn_ok):
        raise zipapp.ZipAppError("Invalid entry point: " + main)

    main_py = MAIN_TEMPLATE.format(module=mod, fn=fn)

    with maybe_open(target, "wb") as fd:
        # write shebang
        write_file_prefix(fd, interpreter)

        # determine compression
        compression = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED

        # create zipapp
        with zipfile.ZipFile(fd, "w", compression=compression) as z:
            for child in source.rglob("*"):

                # skip compiled files
                if child.suffix == '.pyc':
                    continue

                arcname = child.relative_to(source)
                z.write(str(child), str(arcname))

            # write main
            z.writestr("__main__.py", main_py.encode("utf-8"))

    # make executable
    # NOTE on windows this is no-op
    target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
734416
def _write_segments(self, filename):
        
        # Column headers
        shead = '\t'.join(['id', 'multiplicon', 'genome', 'list', 'first',
                           'last', 'order'])
        with open(filename, 'w') as fhandle:
            fhandle.write(shead + '\n')
            for mrow in self.segments:
                fhandle.write('\t'.join([str(e) for e in mrow]) + '\n')
1118553
private void createJmsTemplate() {
        Assert.isTrue(this.connectionFactory != null,
                "Neither 'jmsTemplate' nor 'connectionFactory' is set correctly.");

        jmsTemplate = new JmsTemplate();

        jmsTemplate.setConnectionFactory(this.connectionFactory);

        if (this.destination != null) {
            jmsTemplate.setDefaultDestination(this.destination);
        } else if (this.destinationName != null) {
            jmsTemplate.setDefaultDestinationName(this.destinationName);
        }

        if (this.destinationResolver != null) {
            jmsTemplate.setDestinationResolver(this.destinationResolver);
        }

        jmsTemplate.setPubSubDomain(pubSubDomain);
    }
36366
function construct(data) {
  const basepath = process.cwd();

  const files = data.map((f) => {
    const fullpath = p.join(basepath, f);

    const src = fs.readFileSync(fullpath, 'utf8');
    const t = yaml.load(src, {
      schema: YAML_FILES_SCHEMA,
      filename: fullpath
    });
    return t;
  });

  const t = files.reduce((m, f) => merge(m, f));
  return t;
}
365840
def process_output(meta_file, outfile_name, code_links):
    '''
    '''

    # Markdown title line
    doc_str = '# ' + meta_file['header'] + '\n'
    doc_str += 'Generated by [py2md](https://github.com/gbowerman/py2md) on '
    doc_str += strftime("%Y-%m-%d %H:%M:%S ") + '\n\n'

    # Create a table of contents if more than one module (i.e. more than one
    # source file)
    if len(meta_file['modules']) > 1:
        doc_str += "## Contents\n"
        chapter_num = 1
        for meta_doc in meta_file['modules']:
            chapter_name = meta_doc['summary_comment']
            chapter_link = chapter_name.lstrip().replace('.', '').replace(' ', '-').lower()
            doc_str += str(chapter_num) + \
                '. [' + chapter_name + '](#' + chapter_link + ')\n'
            chapter_num += 1


    # Document each meta-file
    for meta_doc in meta_file['modules']:
        doc_str += '## ' + meta_doc['summary_comment'] + '\n'
        doc_str += '[source file](' + meta_doc['source_file'] + ')' + '\n'
        for function_info in meta_doc['functions']:
            doc_str += '### ' + function_info['name'] + '\n'
            doc_str += function_info['definition'] + '\n\n'
            if 'comments' in function_info:
                doc_str += '```\n' + function_info['comments'] + '\n```\n\n'

    # write the markdown to file
    print('Writing file: ' + outfile_name)
    out_file = open(outfile_name, 'w')
    out_file.write(doc_str)
    out_file.close()
98436
def create(cls, options, session, build_root=None, exclude_patterns=None, tags=None):
    
    # Determine the literal target roots.
    spec_roots = cls.parse_specs(
      target_specs=options.target_specs,
      build_root=build_root,
      exclude_patterns=exclude_patterns,
      tags=tags)

    # Determine `Changed` arguments directly from options to support pre-`Subsystem`
    # initialization paths.
    changed_options = options.for_scope('changed')
    changed_request = ChangedRequest.from_options(changed_options)

    # Determine the `--owner-of=` arguments provided from the global options
    owned_files = options.for_global_scope().owner_of

    logger.debug('spec_roots are: %s', spec_roots)
    logger.debug('changed_request is: %s', changed_request)
    logger.debug('owned_files are: %s', owned_files)
    targets_specified = sum(1 for item
                         in (changed_request.is_actionable(), owned_files, spec_roots.dependencies)
                         if item)

    if targets_specified > 1:
      # We've been provided more than one of: a change request, an owner request, or spec roots.
      raise InvalidSpecConstraint(
        'Multiple target selection methods provided. Please use only one of '
        '--changed-*, --owner-of, or target specs'
      )

    if changed_request.is_actionable():
      scm = get_scm()
      if not scm:
        raise InvalidSpecConstraint(
          'The --changed-* options are not available without a recognized SCM (usually git).'
        )
      changed_files = cls.changed_files(
          scm,
          changes_since=changed_request.changes_since,
          diffspec=changed_request.diffspec)
      # We've been provided no spec roots (e.g. `./pants list`) AND a changed request. Compute
      # alternate target roots.
      request = OwnersRequest(sources=tuple(changed_files),
                              include_dependees=str(changed_request.include_dependees))
      changed_addresses, = session.product_request(BuildFileAddresses, [request])
      logger.debug('changed addresses: %s', changed_addresses)
      dependencies = tuple(SingleAddress(a.spec_path, a.target_name) for a in changed_addresses)
      return TargetRoots(Specs(dependencies=dependencies, exclude_patterns=exclude_patterns, tags=tags))

    if owned_files:
      # We've been provided no spec roots (e.g. `./pants list`) AND a owner request. Compute
      # alternate target roots.
      request = OwnersRequest(sources=tuple(owned_files), include_dependees=str('none'))
      owner_addresses, = session.product_request(BuildFileAddresses, [request])
      logger.debug('owner addresses: %s', owner_addresses)
      dependencies = tuple(SingleAddress(a.spec_path, a.target_name) for a in owner_addresses)
      return TargetRoots(Specs(dependencies=dependencies, exclude_patterns=exclude_patterns, tags=tags))

    return TargetRoots(spec_roots)
915781
def write(filename, mesh, write_binary=True):
    
    if mesh.points.shape[1] == 2:
        logging.warning(
            "msh2 requires 3D points, but 2D points given. "
            "Appending 0 third component."
        )
        mesh.points = numpy.column_stack(
            [mesh.points[:, 0], mesh.points[:, 1], numpy.zeros(mesh.points.shape[0])]
        )

    if write_binary:
        for key, value in mesh.cells.items():
            if value.dtype != c_int:
                logging.warning(
                    "Binary Gmsh needs 32-bit integers (got %s). Converting.",
                    value.dtype,
                )
                mesh.cells[key] = numpy.array(value, dtype=c_int)

    # Gmsh cells are mostly ordered like VTK, with a few exceptions:
    cells = mesh.cells.copy()
    if "tetra10" in cells:
        cells["tetra10"] = cells["tetra10"][:, [0, 1, 2, 3, 4, 5, 6, 7, 9, 8]]
    if "hexahedron20" in cells:
        cells["hexahedron20"] = cells["hexahedron20"][
            :, [0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 13, 9, 16, 18, 19, 17, 10, 12, 14, 15]
        ]

    with open(filename, "wb") as fh:
        mode_idx = 1 if write_binary else 0
        size_of_double = 8
        fh.write(
            ("$MeshFormat\n2.2 {} {}\n".format(mode_idx, size_of_double)).encode(
                "utf-8"
            )
        )
        if write_binary:
            fh.write(struct.pack("i", 1))
            fh.write("\n".encode("utf-8"))
        fh.write("$EndMeshFormat\n".encode("utf-8"))

        if mesh.field_data:
            _write_physical_names(fh, mesh.field_data)

        # Split the cell data: gmsh:physical and gmsh:geometrical are tags, the
        # rest is actual cell data.
        tag_data = {}
        other_data = {}
        for cell_type, a in mesh.cell_data.items():
            tag_data[cell_type] = {}
            other_data[cell_type] = {}
            for key, data in a.items():
                if key in ["gmsh:physical", "gmsh:geometrical"]:
                    tag_data[cell_type][key] = data.astype(c_int)
                else:
                    other_data[cell_type][key] = data

        _write_nodes(fh, mesh.points, write_binary)
        _write_elements(fh, cells, tag_data, write_binary)
        if mesh.gmsh_periodic is not None:
            _write_periodic(fh, mesh.gmsh_periodic)
        for name, dat in mesh.point_data.items():
            _write_data(fh, "NodeData", name, dat, write_binary)
        cell_data_raw = raw_from_cell_data(other_data)
        for name, dat in cell_data_raw.items():
            _write_data(fh, "ElementData", name, dat, write_binary)

    return
434720
def _write_out_argfile(argfile, out, fnargs, parallel, out_keys, input_files, work_dir):
    
    with open(argfile, "w") as out_handle:
        if argfile.endswith(".json"):
            record_name, record_attrs = _get_record_attrs(out_keys)
            if record_name:
                if parallel in ["multi-batch"]:
                    recs = _nested_cwl_record(out, record_attrs, input_files)
                elif parallel in ["single-split", "multi-combined", "multi-parallel", "batch-single",
                                  "single-single"]:
                    recs = [_collapse_to_cwl_record_single(utils.to_single_data(xs), record_attrs, input_files)
                            for xs in out]
                else:
                    samples = [utils.to_single_data(xs) for xs in out]
                    recs = [_collapse_to_cwl_record(samples, record_attrs, input_files)]
                json.dump(_combine_cwl_records(recs, record_name, parallel),
                            out_handle, sort_keys=True, indent=4, separators=(', ', ': '))
            elif parallel in ["single-split", "multi-combined", "batch-split"]:
                json.dump(_convert_to_cwl_json([utils.to_single_data(xs) for xs in out], fnargs, input_files),
                            out_handle, sort_keys=True, indent=4, separators=(', ', ': '))
            else:
                json.dump(_convert_to_cwl_json(utils.to_single_data(utils.to_single_data(out)), fnargs, input_files),
                            out_handle, sort_keys=True, indent=4, separators=(', ', ': '))
        else:
            yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False)
633887
protected void writeMetadata() throws IOException {
    Set<GlobalMetadata> collectedMetadata = metadataCollector.getMetadataRecords();

    if (collectedMetadata.isEmpty()) {
      return;
    }

    String propName =
        ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_METADATA_KEY, numBranches, branchId);
    String metadataStr;
    if (collectedMetadata.size() == 1) {
      metadataStr = collectedMetadata.iterator().next().toJson();
    } else {
      StringBuilder sb = new StringBuilder();
      sb.append('[');
      boolean first = true;

      for (GlobalMetadata md : collectedMetadata) {
        if (!first) {
          sb.append(',');
        }
        sb.append(md.toJson());
        first = false;
      }
      sb.append(']');
      metadataStr = sb.toString();
    }

    this.properties.setProp(propName, metadataStr);
  }
173397
def create_shn (archive, compression, cmd, verbosity, interactive, filenames):
    """"""
    if len(filenames) > 1:
        raise util.PatoolError("multiple filenames for shorten not supported")
    cmdlist = [util.shell_quote(cmd)]
    cmdlist.extend(['-', util.shell_quote(archive), '<',
        util.shell_quote(filenames[0])])
    return (cmdlist, {'shell': True})
153363
def build_one(self, object, lines, fasta, fw, newagp=None):
        
        components = []

        total_bp = 0
        for line in lines:

            if line.is_gap:
                seq = 'N' * line.gap_length
                if newagp:
                    print(line, file=newagp)
            else:
                seq = fasta.sequence(dict(chr=line.component_id,
                        start=line.component_beg,
                        stop=line.component_end,
                        strand=line.orientation))
                # Check for dangling N's
                if newagp:
                    trimNs(seq, line, newagp)

            components.append(seq)
            total_bp += len(seq)

            if self.validate:
                assert total_bp == line.object_end, \
                        "cumulative base pairs (%d) does not match (%d)" % \
                        (total_bp, line.object_end)

        if not newagp:
            rec = SeqRecord(Seq(''.join(components)), id=object, description="")
            SeqIO.write([rec], fw, "fasta")
            if len(rec) > 1000000:
                logging.debug("Write object %s to `%s`" % (object, fw.name))
1185909
def ndarray_shm(shape, dtype, location, readonly=False, order='F', **kwargs):
  """"""
  nbytes = Vec(*shape).rectVolume() * np.dtype(dtype).itemsize
  available = psutil.virtual_memory().available

  preexisting = 0
  # This might only work on Ubuntu
  shmloc = os.path.join(SHM_DIRECTORY, location)
  if os.path.exists(shmloc):
    preexisting = os.path.getsize(shmloc)
  elif readonly:
    raise SharedMemoryReadError(shmloc + " has not been allocated. Requested " + str(nbytes) + " bytes.")

  if readonly and preexisting != nbytes:
    raise SharedMemoryReadError("{} exists, but the allocation size ({} bytes) does not match the request ({} bytes).".format(
      shmloc, preexisting, nbytes
    ))

  if (nbytes - preexisting) > available:
    overallocated = nbytes - preexisting - available
    overpercent = (100 * overallocated / (preexisting + available))
    raise SharedMemoryAllocationError("""
      Requested more memory than is available. 

      Shared Memory Location:  {}

      Shape:                   {}
      Requested Bytes:         {} 
      
      Available Bytes:         {} 
      Preexisting Bytes*:      {} 

      Overallocated Bytes*:    {} (+{:.2f}%)

      * Preexisting is only correct on linux systems that support /dev/shm/""" \
        .format(location, shape, nbytes, available, preexisting, overallocated, overpercent))

  # This might seem like we're being "extra safe" but consider
  # a threading condition where the condition of the shared memory
  # was adjusted between the check above and now. Better to make sure
  # that we don't accidently change anything if readonly is set.
  flags = 0 if readonly else O_CREAT 
  size = 0 if readonly else int(nbytes) 

  try:
    shared = posix_ipc.SharedMemory(location, flags=flags, size=size)
    array_like = mmap.mmap(shared.fd, shared.size)
    os.close(shared.fd)
    renderbuffer = np.ndarray(buffer=array_like, dtype=dtype, shape=shape, order=order, **kwargs)
  except OSError as err:
    if err.errno == errno.ENOMEM: # Out of Memory
      posix_ipc.unlink_shared_memory(location)      
    raise

  renderbuffer.setflags(write=(not readonly))
  return array_like, renderbuffer
667270
private Segment createMappedSegment(SegmentDescriptor descriptor) {
    File segmentFile = SegmentFile.createSegmentFile(name, storage.directory(), descriptor.id(), descriptor.version());
    Buffer buffer = MappedBuffer.allocate(segmentFile, Math.min(DEFAULT_BUFFER_SIZE, descriptor.maxSegmentSize()), Integer.MAX_VALUE);
    descriptor.copyTo(buffer);
    Segment segment = new Segment(new SegmentFile(segmentFile), buffer.slice(), descriptor, createIndex(descriptor), new OffsetPredicate(), serializer.clone(), this);
    LOGGER.debug("Created segment: {}", segment);
    return segment;
  }
524324
def write_mps(filename)
      # Make a new model and ensure everything is added
      old_ptr = @ptr
      @ptr = new_model
      parent_update

      Cbc.Cbc_writeMps @ptr, filename.chomp('.mps')
      contents = Zlib::GzipReader.open(filename + '.gz').read
      File.delete(filename + '.gz')
      File.open(filename, 'w').write contents

      # Reset to the original model
      @ptr = old_ptr
      reset_model
    end
151594
def buildDiscover(base_url, out_dir):
    """"""
    test_data = discoverdata.readTests(discoverdata.default_test_file)

    def writeTestFile(test_name):
        template = test_data[test_name]

        data = discoverdata.fillTemplate(
            test_name, template, base_url, discoverdata.example_xrds)

        out_file_name = os.path.join(out_dir, test_name)
        out_file = file(out_file_name, 'w')
        out_file.write(data)

    manifest = [manifest_header]
    for success, input_name, id_name, result_name in discoverdata.testlist:
        if not success:
            continue
        writeTestFile(input_name)

        input_url = urlparse.urljoin(base_url, input_name)
        id_url = urlparse.urljoin(base_url, id_name)
        result_url = urlparse.urljoin(base_url, result_name)

        manifest.append('\t'.join((input_url, id_url, result_url)))
        manifest.append('\n')

    manifest_file_name = os.path.join(out_dir, 'manifest.txt')
    manifest_file = file(manifest_file_name, 'w')
    for chunk in manifest:
        manifest_file.write(chunk)
    manifest_file.close()
1143064
private void writeBeanDefinitionsToMetaInf() {
        try {
            classWriterOutputVisitor.finish();
        } catch (Exception e) {
            String message = e.getMessage();
            error("Error occurred writing META-INF files: %s", message != null ? message : e);
        }
    }