[START create_source]
17099
static Source createSource(OrganizationName organizationName) {
    try (SecurityCenterClient client = SecurityCenterClient.create()) {
      // Start setting up a request to create a source in an organization.
      // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");
      Source source =
          Source.newBuilder()
              .setDisplayName("Customized Display Name")
              .setDescription("A new custom source that does X")
              .build();

      CreateSourceRequest.Builder request =
          CreateSourceRequest.newBuilder().setParent(organizationName.toString()).setSource(source);

      // Call the API.
      Source response = client.createSource(request.build());

      System.out.println("Created Source: " + response);
      return response;
    } catch (IOException e) {
      throw new RuntimeException("Couldn't create client.", e);
    }
  }
752819
def add_source(self, allow_alias=False, **kwargs):
        """"""
        if not allow_alias and SOURCE.ALIAS in kwargs:
            err_str = "`{}` passed in kwargs, this shouldn't happen!".format(
                SOURCE.ALIAS)
            self._log.error(err_str)
            raise RuntimeError(err_str)

        # Set alias number to be +1 of current number of sources
        if SOURCE.ALIAS not in kwargs:
            kwargs[SOURCE.ALIAS] = str(self.num_sources() + 1)
        source_obj = self._init_cat_dict(Source, self._KEYS.SOURCES, **kwargs)
        if source_obj is None:
            return None

        for item in self.get(self._KEYS.SOURCES, ''):
            if source_obj.is_duplicate_of(item):
                return item[item._KEYS.ALIAS]

        self.setdefault(self._KEYS.SOURCES, []).append(source_obj)
        return source_obj[source_obj._KEYS.ALIAS]
248271
def main():
    
    # Define Parser object and add to jobTree
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)

    # Generate subparsers
    subparsers = parser.add_subparsers(dest='command')
    subparsers.add_parser('generate-config',
                          help='Generates an editable config in the current working directory.')
    subparsers.add_parser('generate-manifest',
                          help='Generates an editable manifest in the current working directory.')
    subparsers.add_parser('generate',
                          help='Generates a config and manifest in the current working directory.')

    # Run subparser
    parser_run = subparsers.add_parser('run', help='Runs the GATK germline pipeline')
    parser_run.add_argument('--config',
                            required=True,
                            type=str,
                            help='Path to the (filled in) config file, generated with '
                                 '"generate-config".')
    parser_run.add_argument('--manifest',
                            type=str,
                            help='Path to the (filled in) manifest file, generated with '
                                 '"generate-manifest".\nDefault value: "%(default)s".')
    parser_run.add_argument('--sample',
                            default=None,
                            nargs=2,
                            type=str,
                            help='Input sample identifier and BAM file URL or local path')
    parser_run.add_argument('--output-dir',
                            default=None,
                            help='Path/URL to output directory')
    parser_run.add_argument('-s', '--suffix',
                            default=None,
                            help='Additional suffix to add to the names of the output files')
    parser_run.add_argument('--preprocess-only',
                            action='store_true',
                            help='Only runs preprocessing steps')

    Job.Runner.addToilOptions(parser_run)
    options = parser.parse_args()

    cwd = os.getcwd()
    if options.command == 'generate-config' or options.command == 'generate':
        generate_file(os.path.join(cwd, 'config-toil-germline.yaml'), generate_config)
    if options.command == 'generate-manifest' or options.command == 'generate':
        generate_file(os.path.join(cwd, 'manifest-toil-germline.tsv'), generate_manifest)
    elif options.command == 'run':
        # Program checks
        for program in ['curl', 'docker']:
            require(next(which(program)),
                    program + ' must be installed on every node.'.format(program))

        require(os.path.exists(options.config), '{} not found. Please run "generate-config"'.format(options.config))

        # Read sample manifest
        samples = []
        if options.manifest:
            samples.extend(parse_manifest(options.manifest))

        # Add BAM sample from command line
        if options.sample:
            uuid, url = options.sample
            # samples tuple: (uuid, url, paired_url, rg_line)
            # BAM samples should not have as paired URL or read group line
            samples.append(GermlineSample(uuid, url, None, None))

        require(len(samples) > 0,
                'No samples were detected in the manifest or on the command line')

        # Parse inputs
        inputs = {x.replace('-', '_'): y for x, y in
                  yaml.load(open(options.config).read()).iteritems()}

        required_fields = {'genome_fasta',
                           'output_dir',
                           'run_bwa',
                           'sorted',
                           'snp_filter_annotations',
                           'indel_filter_annotations',
                           'preprocess',
                           'preprocess_only',
                           'run_vqsr',
                           'joint_genotype',
                           'run_oncotator',
                           'cores',
                           'file_size',
                           'xmx',
                           'suffix'}

        input_fields = set(inputs.keys())
        require(input_fields > required_fields,
                'Missing config parameters:\n{}'.format(', '.join(required_fields - input_fields)))

        if inputs['output_dir'] is None:
            inputs['output_dir'] = options.output_dir

        require(inputs['output_dir'] is not None,
                'Missing output directory PATH/URL')

        if inputs['suffix'] is None:
            inputs['suffix'] = options.suffix if options.suffix else ''

        if inputs['preprocess_only'] is None:
            inputs['preprocess_only'] = options.preprocess_only

        if inputs['run_vqsr']:
            # Check that essential VQSR parameters are present
            vqsr_fields = {'g1k_snp', 'mills', 'dbsnp', 'hapmap', 'omni'}
            require(input_fields > vqsr_fields,
                    'Missing parameters for VQSR:\n{}'.format(', '.join(vqsr_fields - input_fields)))

        # Check that hard filtering parameters are present. If only running preprocessing steps, then we do
        # not need filtering information.
        elif not inputs['preprocess_only']:
            hard_filter_fields = {'snp_filter_name', 'snp_filter_expression',
                                  'indel_filter_name', 'indel_filter_expression'}
            require(input_fields > hard_filter_fields,
                    'Missing parameters for hard filtering:\n{}'.format(', '.join(hard_filter_fields - input_fields)))

            # Check for falsey hard filtering parameters
            for hard_filter_field in hard_filter_fields:
                require(inputs[hard_filter_field], 'Missing %s value for hard filtering, '
                                                   'got %s.' % (hard_filter_field, inputs[hard_filter_field]))

        # Set resource parameters
        inputs['xmx'] = human2bytes(inputs['xmx'])
        inputs['file_size'] = human2bytes(inputs['file_size'])
        inputs['cores'] = int(inputs['cores'])

        inputs['annotations'] = set(inputs['snp_filter_annotations'] + inputs['indel_filter_annotations'])

        # HaplotypeCaller test data for testing
        inputs['hc_output'] = inputs.get('hc_output', None)

        # It is a toil-scripts convention to store input parameters in a Namespace object
        config = argparse.Namespace(**inputs)

        root = Job.wrapJobFn(run_gatk_germline_pipeline, samples, config)
        Job.Runner.startToil(root, options)
1212419
def add_source(self, name, location, schedule='Daily', op=''):
        
        if op == '':
            op = name + '.log'
        self.data_sources.append([name, location, schedule, op])
1320010
def create
      Dir.mktmpdir do |tmp_dir|
        project_dir = Pathname.new(@config[:app_dir])
        package_dir = Pathname.new(tmp_dir)
        build_dir = Pathname.new(@config[:build_dir])
        copy_source(project_dir, package_dir)
        copy_executables(project_dir, package_dir)
        create_gem_shims(package_dir)
        install_dependencies(package_dir, fetcher)
        Dir.chdir(tmp_dir) do
          create_archive(build_dir)
        end
        File.join(build_dir, @config[:archive_name])
      end
    end
677061
function createResource(url, params, methods) {
      var resource;

      params = _.defaults({}, params, defaultParams);
      methods = _.defaults({}, methods, defaultMethods);
      resource = $resource(url, params, methods);

      // overwrite $save to automatically call $create or $update
      resource.prototype.$save = function save() {
        if (!this._id) {
          return this.$create();
        }

        return this.$update();
      };

      return resource;
    }
867949
def build_source(self, stage, source, ps, force=False):
        """"""
        from ambry.bundle.process import call_interval

        assert source.is_processable, source.name

        if source.state == self.STATES.BUILT and not force:
            ps.update(message='Source {} already built'.format(source.name), state='skipped')
            return

        pl = self.pipeline(source, ps=ps)

        source.state = self.STATES.BUILDING

        # Doing this before hand to get at least some information about the pipline,
        # in case there is an error during the run. It will get overwritten with more information
        # after successful run
        self.log_pipeline(pl)

        try:

            source_name = source.name  # In case the source drops out of the session, which is does.
            s_vid = source.vid

            ps.update(message='Running pipeline {}'.format(pl.name), s_vid=s_vid, item_type='rows', item_count=0)

            @call_interval(5)
            def run_progress_f(sink_pipe, rows):
                (n_records, rate) = sink_pipe.report_progress()
                if n_records > 0:
                    ps.update(message='Running pipeline {}: rate: {}'
                              .format(pl.name, rate),
                              s_vid=s_vid, item_type='rows', item_count=n_records)


            pl.run(callback=run_progress_f)

            # Run the final routines at the end of the pipelin
            for f in pl.final:
                ps.update(message='Run final routine: {}'.format(f.__name__))
                f(pl)

            ps.update(message='Finished building source')

        except:
            self.log_pipeline(pl)
            raise

        self.commit()

        try:
            partitions = list(pl[ambry.etl.PartitionWriter].partitions)
            ps.update(message='Finalizing segment partition',
                      item_type='partitions', item_total=len(partitions), item_count=0)
            for i, p in enumerate(partitions):

                ps.update(message='Finalizing segment partition {}'.format(p.name), item_count=i, p_vid=p.vid)

                try:
                    p.finalize()
                except AttributeError:
                    print(self.table(p.table_name))
                    raise

                # FIXME Shouldn't need to do this commit, but without it, some stats get added multiple
                # times, causing an error later. Probably could be avoided by adding the stats to the
                # collection in the dataset

                self.commit()

        except IndexError:
            self.error("Pipeline didn't have a PartitionWriters, won't try to finalize")

        self.log_pipeline(pl)
        source.state = self.STATES.BUILT

        self.commit()

        return source.name
1042952
def process_source(source)
        return source if source.is_a?(String) && source =~ /\n/

        source, _ = engine.fetch_source(source, { :view_path => options[:view_path] })
        source
      end
76606
def declare_example(self, source):
        """"""
        with patch_modules():
            code = compile(source, "<docs>", "exec")
            exec(code, self.namespace)
895244
def create(
        ctx,
        archive_name,
        authority_name,
        versioned=True,
        tag=None,
        helper=False):
    '''
    
    '''

    tags = list(tag)

    _generate_api(ctx)
    args, kwargs = _parse_args_and_kwargs(ctx.args)
    assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args)

    var = ctx.obj.api.create(
        archive_name,
        authority_name=authority_name,
        versioned=versioned,
        metadata=kwargs,
        tags=tags,
        helper=helper)

    verstring = 'versioned archive' if versioned else 'archive'
    click.echo('created {} {}'.format(verstring, var))
36479
def build_source_files(self):
        """"""

        from .files import BuildSourceFileAccessor
        return BuildSourceFileAccessor(self, self.dataset, self.source_fs)
275222
def create(source, dest, tracker, open_trackers, comment, cache):
    """"""

    source_title = path.basename(source).replace('.', '_').replace(' ', '_')
    dest = '%s.torrent' % path.join(dest, source_title)

    click.secho('Creating torrent from %s ...' % source)

    my_torrent = Torrent.create_from(source)

    if comment:
        my_torrent.comment = comment

    urls = []

    if tracker:
        urls = tracker.split(',')

    if open_trackers:
        click.secho('Fetching an up-to-date open tracker list ...')
        try:
            urls.extend(get_open_trackers_from_remote())
        except RemoteDownloadError:
            click.secho('Failed. Using built-in open tracker list.', fg='red', err=True)
            urls.extend(get_open_trackers_from_local())

    if urls:
        my_torrent.announce_urls = urls

    my_torrent.to_file(dest)

    click.secho('Torrent file created: %s' % dest, fg='green')
    click.secho('Torrent info hash: %s' % my_torrent.info_hash, fg='blue')

    if cache:
        click.secho('Uploading to %s torrent cache service ...')
        try:
            result = upload_to_cache_server(dest)
            click.secho('Cached torrent URL: %s' % result, fg='yellow')

        except RemoteUploadError as e:
            click.secho('Failed: %s' % e, fg='red', err=True)
313068
function createResource (req) {
  let resource = new Resource(req.path);

  if (!_.isEmpty(req.files)) {
    // Save file data too
    resource.data = _.extend({}, req.body, req.files);
  }
  else {
    resource.data = req.body;
  }

  return resource;
}
119364
public function GenerateCustomSources()
    {
        // Variables used by some template files.
        $authors = \Peg\Lib\Settings::GetAuthors();
        $contributors = \Peg\Lib\Settings::GetContributors();
        $extension = \Peg\Lib\Settings::GetExtensionName();
        $version = \Peg\Lib\Settings::GetVersion();

        // Variable to temporarily store a template file content.
        $content = "";

        // Generate custom sources list
        $custom_sources = $this->GetCustomSources();

        if(count($custom_sources) > 0)
        {
            foreach($custom_sources as $custom_source)
            {
                if($custom_source != "." && $custom_source != "..")
                {
                    ob_start();
                        include($this->GetGenericTemplate(
                            $custom_source, "custom_sources"
                        ));
                        $content = ob_get_contents();
                    ob_end_clean();

                    if(
                        (strpos($custom_source, ".c") !== false)
                        ||
                        (strpos($custom_source, ".cpp") !== false)
                    )
                    {
                        $this->AddGenericFile(
                            $custom_source,
                            $content,
                            "src"
                        );
                    }
                    elseif(
                        (strpos($custom_source, ".h") !== false)
                        ||
                        (strpos($custom_source, ".hpp") !== false)
                    )
                    {
                        $this->AddGenericFile(
                            $custom_source,
                            $content,
                            "includes"
                        );
                    }
                }
            }
        }
    }
440188
def start
      puts "\n******************************************************************************************************************************************\n\n"
      puts "  JumpStarting....\n".purple
      check_setup
      execute_install_command
      run_scripts_from_yaml(:run_after_install_command)
      parse_template_dir
      create_dirs
      populate_files_from_whole_templates
      populate_files_from_append_templates
      populate_files_from_line_templates
      remove_unwanted_files
      run_scripts_from_yaml(:run_after_jumpstart)
      check_for_strings_to_replace
      run_scripts_from_yaml(:run_after_string_replace)
      check_local_nginx_configuration
      exit_with_success
    end
20795
def _loadOneSource(self, sourceFName):
        
        sourceLines = open(sourceFName).readlines()
        del sourceLines[0]
        if len(sourceLines[0].split("\t"))==2:
            self._loadTwoPartSource(sourceFName, sourceLines)
        elif len(sourceLines[0].split("\t"))==3:
            self._loadThreePartSource(sourceFName, sourceLines)
        else:
            raise Error, "%s does not appear to be a source authority file"
145505
async function create(sourcedir) {
	const target = join(sourcedir, FILENAME);
	const exists = await exist(target);

	const source = exists
		? target
		: join(__dirname, FILENAME)
	;

	const content = await readFile(source);
	await writeFile(primed, content.toString());

	return exists
		?	'Creating a new Dangerfile'
		: 'Creating a default Dangerfile'
	;
}