Build the DCAT catalog for this site
430010
def build_catalog(site, datasets, format=None):
    ''''''
    site_url = url_for('site.home_redirect', _external=True)
    catalog_url = url_for('site.rdf_catalog', _external=True)
    graph = Graph(namespace_manager=namespace_manager)
    catalog = graph.resource(URIRef(catalog_url))

    catalog.set(RDF.type, DCAT.Catalog)
    catalog.set(DCT.title, Literal(site.title))
    catalog.set(DCT.language,
                Literal(current_app.config['DEFAULT_LANGUAGE']))
    catalog.set(FOAF.homepage, URIRef(site_url))

    publisher = graph.resource(BNode())
    publisher.set(RDF.type, FOAF.Organization)
    publisher.set(FOAF.name, Literal(current_app.config['SITE_AUTHOR']))
    catalog.set(DCT.publisher, publisher)

    for dataset in datasets:
        catalog.add(DCAT.dataset, dataset_to_rdf(dataset, graph))

    if isinstance(datasets, Paginable):
        if not format:
            raise ValueError('Pagination requires format')
        catalog.add(RDF.type, HYDRA.Collection)
        catalog.set(HYDRA.totalItems, Literal(datasets.total))
        kwargs = {
            'format': format,
            'page_size': datasets.page_size,
            '_external': True,
        }

        first_url = url_for('site.rdf_catalog_format', page=1, **kwargs)
        page_url = url_for('site.rdf_catalog_format',
                           page=datasets.page, **kwargs)
        last_url = url_for('site.rdf_catalog_format',
                           page=datasets.pages, **kwargs)
        pagination = graph.resource(URIRef(page_url))
        pagination.set(RDF.type, HYDRA.PartialCollectionView)

        pagination.set(HYDRA.first, URIRef(first_url))
        pagination.set(HYDRA.last, URIRef(last_url))
        if datasets.has_next:
            next_url = url_for('site.rdf_catalog_format',
                               page=datasets.page + 1, **kwargs)
            pagination.set(HYDRA.next, URIRef(next_url))
        if datasets.has_prev:
            prev_url = url_for('site.rdf_catalog_format',
                               page=datasets.page - 1, **kwargs)
            pagination.set(HYDRA.previous, URIRef(prev_url))

        catalog.set(HYDRA.view, pagination)

    return catalog
351692
def build(ctx, builder="html", options=""):
    """"""
    sourcedir = ctx.config.sphinx.sourcedir
    destdir = Path(ctx.config.sphinx.destdir or "build")/builder
    destdir = destdir.abspath()
    with cd(sourcedir):
        destdir_relative = Path(".").relpathto(destdir)
        command = "sphinx-build {opts} -b {builder} {sourcedir} {destdir}" \
                    .format(builder=builder, sourcedir=".",
                            destdir=destdir_relative, opts=options)
        ctx.run(command)
580481
function(apiKey, pieceTitle, categories,
        fromAddress, toAddress, ccAddress, bccAddress, subject, textBody,
        htmlBody, contentType, mergeContext) {}
493430
public function buildContent()
	{
		$rows		= array();
		$services	= $this->servicePoint->getServices();
		natcasesort( $services );
		$heads		= array();
		
		$heads	= array( "<th>Service</th><th>Parameter</th>" );
		$cols	= array( "<col width='35%'/><col width='30%'/>" ); 
		foreach( $this->availableFormats as $format )
		{
			$cols[]		= "<col width='".round( ( 100 - 65 ) / count( $this->availableFormats ), 0 )."%'/>";
			$heads[]	= "<th><a href='#' onClick='$(\"#format\").val(\"".$format."\").trigger(\"change\")'>".strtoupper( $format )."</a></th>";
		}
		$cols	= "<colgroup>".implode( "", $cols )."</colgroup>";
		$heads	= "<tr>".implode( "", $heads )."</tr>";
		$counter	= 0;
		foreach( $services as $service )
		{
			$counter ++;
			//  --  FORMATS  --   //
			$cells		= array();
			$formats	= $this->servicePoint->getServiceFormats( $service );
			$default	= $this->servicePoint->getDefaultServiceFormat( $service );
			foreach( $this->availableFormats as $format )
			{
				if( $format == $default )
					$cells[]	= "<td class='preferred'><span class='".$format."'>+</span></td>";
				else if( in_array( $format, $formats ) )
					$cells[]	= "<td class='yes'><span class='".$format."'>+</span></td>";
				else
					$cells[]	= "<td class='no'>-</td>";
			}
						
			//  --  PARAMETERS  --   //
			$parameterList	= array();
			$parameters	= $this->servicePoint->getServiceParameters( $service );
			foreach( $parameters as $parameter => $rules )
			{
				$ruleList	= array();
				$mandatory	= FALSE;
				$type		= "";
				if( $rules )
				{
					foreach( $rules as $ruleKey => $ruleValue )
					{
						if( $ruleKey == "title" )
							continue;
						if( $ruleKey == "mandatory" )
						{
							$mandatory	= $ruleValue;
							$ruleValue	= $ruleValue ? "yes" : "no";
						}
						if( $ruleKey == "type" )
						{
							$type	= "<small><em>".$ruleValue."</em></small>&nbsp;";
						}
						$spanKey	= UI_HTML_Tag::create( "span", $ruleKey.":", array( 'class' => "key" ) );
						$spanValue	= UI_HTML_Tag::create( "span", htmlspecialchars( $ruleValue ), array( 'class' => "value" ) );
						$ruleList[]	= $spanKey." ".$spanValue;
					}
				}
				if( isset( $rules['title'] ) )
					$parameter	= UI_HTML_Elements::Acronym( $parameter, $rules['title'] );
				$parameter	= $type.$parameter;
				if( !$mandatory )
					$parameter	= "[".$parameter."]";
				$rules	= $ruleList ? '<div class="rules">'.implode( ", ", $ruleList ).'</div>' : "";
				$parameterList[]	= $rules.$parameter;
			}
			$parameters	= implode( "<br/>", $parameterList );

			$linkService	= UI_HTML_Tag::create( "a", $service, array( 'href' => "?service=".$service, 'title' => "Run this service" ) );
			$imageTest		= UI_HTML_Tag::create( "span", NULL, array( 'class' => 'linkTest', 'title' => 'Test this service' ) );
			$linkTest		= UI_HTML_Elements::Link( "?test=".$service, $imageTest );

			$serviceLink	= '<div class="serviceName">'.$linkTest.$linkService.'</div>';
			$serviceClass	= '<div class="className">'.$this->servicePoint->getServiceClass( $service ).'</div>';
			$description	= '<div class="description">'.$this->servicePoint->getServiceDescription( $service ).'</div>';
			$cellService	= '<td class="service">'.$serviceClass.$serviceLink.$description.'</td>';
			$cellParameters	= '<td class="parameter">'.$parameters.'</td>';
			$cellsFormats	= implode( "", $cells );
			$formats		= implode( " ", $formats );
			$row	= '<tr class="service '.$formats.'">'.$cellService.$cellParameters.$cellsFormats.'</tr>';
			$rows[]	= $row;
			if( $counter % 10 == 0 )
				$rows[]	= $heads;
		}
		return "<table class='".$this->tableClass."'>".$cols."<thead>".$heads."</thead><tbody>".implode( "", $rows )."</tbody></table>";
	}
352857
def stamp(directory, sql, tag, revision):
    """'"""
    _stamp(directory, revision, sql, tag)
112435
def load_existing_catalog(self, cat, **kwargs):
        
        coordsys = kwargs.get('coordsys', 'CEL')
        extdir = kwargs.get('extdir', self.extdir)
        srcname = kwargs.get('srcname', None)

        m0 = get_skydir_distance_mask(cat.skydir, self.skydir,
                                      self.config['src_radius'])
        m1 = get_skydir_distance_mask(cat.skydir, self.skydir,
                                      self.config['src_radius_roi'],
                                      square=True, coordsys=coordsys)
        m = (m0 & m1)
        if srcname is not None:
            m &= utils.find_rows_by_string(cat.table, [srcname],
                                           self.src_name_cols)

        offset = self.skydir.separation(cat.skydir).deg
        offset_cel = wcs_utils.sky_to_offset(self.skydir,
                                             cat.radec[:, 0], cat.radec[:, 1],
                                             'CEL')
        offset_gal = wcs_utils.sky_to_offset(self.skydir,
                                             cat.glonlat[
                                                 :, 0], cat.glonlat[:, 1],
                                             'GAL')

        for i, (row, radec) in enumerate(zip(cat.table[m],
                                             cat.radec[m])):
            catalog_dict = catalog.row_to_dict(row)
            src_dict = {'catalog': catalog_dict}
            src_dict['Source_Name'] = row['Source_Name']
            src_dict['SpectrumType'] = row['SpectrumType']

            if row['extended']:
                src_dict['SourceType'] = 'DiffuseSource'
                src_dict['SpatialType'] = str(row['Spatial_Function'])
                src_dict['SpatialModel'] = str(row['Spatial_Function'])

                search_dirs = []
                if extdir is not None:
                    search_dirs += [extdir, os.path.join(extdir, 'Templates')]

                search_dirs += [row['extdir'],
                                os.path.join(row['extdir'], 'Templates')]

                if src_dict['SpatialType'] == 'SpatialMap':
                    src_dict['Spatial_Filename'] = utils.resolve_file_path(
                        row['Spatial_Filename'],
                        search_dirs=search_dirs)

            else:
                src_dict['SourceType'] = 'PointSource'
                src_dict['SpatialType'] = 'SkyDirFunction'
                src_dict['SpatialModel'] = 'PointSource'

            src_dict['spectral_pars'] = spectral_pars_from_catalog(
                catalog_dict)
            src_dict['spatial_pars'] = spatial_pars_from_catalog(catalog_dict)

            src = Source(src_dict['Source_Name'], src_dict, radec=radec)
            src.data['offset'] = offset[m][i]
            src.data['offset_ra'] = offset_cel[:, 0][m][i]
            src.data['offset_dec'] = offset_cel[:, 1][m][i]
            src.data['offset_glon'] = offset_gal[:, 0][m][i]
            src.data['offset_glat'] = offset_gal[:, 1][m][i]
            self.load_source(src, False,
                             merge_sources=self.config['merge_sources'])

        self._build_src_index()
1176609
def rdf_catalog():
    ''''''
    format = RDF_EXTENSIONS[negociate_content()]
    url = url_for('site.rdf_catalog_format', format=format)
    return redirect(url)
160274
public function buildHeaders()
    {
        if ($this->use_cors) {
            if (strlen($this->cors_allow_origin) > 0) {
                header("Access-Control-Allow-Origin: $this->cors_allow_origin");
            }
            if ($this->cors_with_credentials) {
                header('Access-Control-Allow-Credentials: true');
            } else {
                header('Access-Control-Allow-Credentials: false');
            }
        }

        // Cache Control RFC: https://tools.ietf.org/html/rfc7234
        if ($this->nb_request instanceof CNabuHTTPRequest &&
            ($nb_site_target = $this->nb_request->getSiteTarget()) instanceof CNabuSiteTarget
        ) {
            if (($max_age = $nb_site_target->getDynamicCacheEffectiveMaxAge()) !== false) {
                $expire_date = gmdate("D, d M Y H:i:s", time() + $max_age);
                $this->setHeader('Expires', $expire_date . 'GMT');
                $this->setHeader('Cache-Control', "max-age=$max_age");
                $this->setHeader('User-Cache-Control', "max-age=$max_age");
                $this->setHeader('Pragma', 'cache');
            } else {
                $this->setHeader('Expires', 'Thu, 1 Jan 1981 00:00:00 GMT');
                $this->setheader('Cache-Control', 'no-store, no-cache, must-revalidate');
                $this->setHeader('Pragma', 'no-cache');
            }
            if ($nb_site_target->getAttachment() === 'T') {
                if (is_string($this->attachment_filename) && strlen($this->attachment_filename) > 0) {
                    $this->setHeader('Content-Disposition', 'attachment; filename=' . $this->attachment_filename);
                } else {
                    $this->setHeader('Content-Disposition', 'attachment');
                }
            }
        }

        if (($frame_options = $this->calculateFrameOptions()) !== null) {
            $this->setHeader('X-Frame-Options', $frame_options);
        }

        if (count($this->header_list) > 0) {
            foreach ($this->header_list as $name => $value) {
                header("$name: $value");
            }
        }
    }
616070
def build_catalog_info(self, catalog_info):
        
        cat = SourceFactory.build_catalog(**catalog_info)
        catalog_info['catalog'] = cat
        # catalog_info['catalog_table'] =
        #    Table.read(catalog_info['catalog_file'])
        catalog_info['catalog_table'] = cat.table
        catalog_info['roi_model'] =\
            SourceFactory.make_fermipy_roi_model_from_catalogs([cat])
        catalog_info['srcmdl_name'] =\
            self._name_factory.srcmdl_xml(sourcekey=catalog_info['catalog_name'])
        return CatalogInfo(**catalog_info)
683587
def setupitems(self):
        
        query = {
            "path": {
                "query": api.get_path(self.setup),
                "depth": 1,
            },
        }
        items = api.search(query, "portal_catalog")
        # filter out items
        items = filter(lambda item: not item.exclude_from_nav, items)

        # sort by (translated) title
        def cmp_by_translated_title(brain1, brain2):
            title1 = t(api.get_title(brain1))
            title2 = t(api.get_title(brain2))
            return cmp(title1, title2)

        return sorted(items, cmp=cmp_by_translated_title)
854516
def newCatalog(sgml):
    
    ret = libxml2mod.xmlNewCatalog(sgml)
    if ret is None:raise treeError('xmlNewCatalog() failed')
    return catalog(_obj=ret)
412216
protected function compileMonthlyMenu()
	{
		$arrData = array();
		$time = \Date::floorToMinute();
        $newsIds = $this->getFilteredNewsIds();

		// Get the dates
		$objDates = $this->Database->query("SELECT FROM_UNIXTIME(date, '%Y') AS year, FROM_UNIXTIME(date, '%m') AS month, COUNT(*) AS count FROM tl_news WHERE pid IN(" . implode(',', array_map('intval', $this->news_archives)) . ")" . ((!BE_USER_LOGGED_IN || TL_MODE == 'BE') ? " AND (start='' OR start<='$time') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1'" : "") . ((count($newsIds) > 0) ? (" AND id IN (" . implode(',', $newsIds) . ")") : "") . " GROUP BY year, month ORDER BY year DESC, month DESC");

		while ($objDates->next())
		{
			$arrData[$objDates->year][$objDates->month] = $objDates->count;
		}

		// Sort the data
		foreach (array_keys($arrData) as $key)
		{
			($this->news_order == 'ascending') ? ksort($arrData[$key]) : krsort($arrData[$key]);
		}

		($this->news_order == 'ascending') ? ksort($arrData) : krsort($arrData);

		$arrItems = array();

        // Prepare the navigation
		foreach ($arrData as $intYear=>$arrMonth)
		{
			$count = 0;
			$limit = count($arrMonth);

			foreach ($arrMonth as $intMonth=>$intCount)
			{
				$intDate = $intYear . $intMonth;
				$intMonth = (intval($intMonth) - 1);

				$quantity = sprintf((($intCount < 2) ? $GLOBALS['TL_LANG']['MSC']['entry'] : $GLOBALS['TL_LANG']['MSC']['entries']), $intCount);

				$arrItems[$intYear][$intMonth]['date'] = $intDate;
				$arrItems[$intYear][$intMonth]['link'] = $GLOBALS['TL_LANG']['MONTHS'][$intMonth] . ' ' . $intYear;
				$arrItems[$intYear][$intMonth]['href'] = $this->strUrl . '?month=' . $intDate;
				$arrItems[$intYear][$intMonth]['title'] = \StringUtil::specialchars($GLOBALS['TL_LANG']['MONTHS'][$intMonth].' '.$intYear . ' (' . $quantity . ')');
				$arrItems[$intYear][$intMonth]['class'] = trim(((++$count == 1) ? 'first ' : '') . (($count == $limit) ? 'last' : ''));
				$arrItems[$intYear][$intMonth]['isActive'] = (\Input::get('month') == $intDate);
				$arrItems[$intYear][$intMonth]['quantity'] = $quantity;
			}
		}

		$this->Template->items = $arrItems;
		$this->Template->showQuantity = ($this->news_showQuantity != '') ? true : false;
		$this->Template->url = $this->strUrl . '?';
		$this->Template->activeYear = \Input::get('year');
	}
450055
def display_direct():
    

    include_dirs, runtime_dirs, runtime = get_direct_config()
    print("Include Search Dirs: {}".format(include_dirs))
    print("\tContents: {}\n".format(get_dir_contents(include_dirs)))
    print("Runtime Search Dirs: {}".format(runtime_dirs))
    print("\tContents: {}\n".format(get_dir_contents(runtime_dirs)))
    print("Runtime Libs: '{}'".format(runtime))
1223664
def map_status_to_catalog(status):
    """"""
    catalog = dict()

    catalog_mapping = {
        "site_title": "title",
        "site_description": "description"
    }

    for status_key, catalog_key in iteritems(catalog_mapping):
        try:
            catalog[catalog_key] = status[status_key]
        except BaseException:
            logger.exception("""
            La clave '%s' no está en el endpoint de status. No se puede
            completar catalog['%s'].""", status_key, catalog_key)

    publisher_mapping = {
        "site_title": "name",
        "error_emails_to": "mbox"
    }

    if any([k in status for k in publisher_mapping.keys()]):
        catalog["publisher"] = dict()
        for status_key, publisher_key in iteritems(publisher_mapping):
            try:
                catalog['publisher'][publisher_key] = status[status_key]
            except BaseException:
                logger.exception("""
                La clave '%s' no está en el endpoint de status. No se puede
                completar catalog['publisher'['%s'].""",
                                 status_key, publisher_key)
    else:
        logger.info("""
        No hay ninguna información sobre catalog['publisher'] en el endpoint
        de 'status'.""")

    catalog['superThemeTaxonomy'] = (
        'http://datos.gob.ar/superThemeTaxonomy.json')

    return catalog
530684
def catalog(self, table='', column=''):
        """"""
        lookup_table = self.lookup_table
        if lookup_table is not None:
            if table:
                if column:
                    column = column.upper()
                    return lookup_table[table][column]
                return lookup_table[table]
            # Show what methods are available.
            return self.lookup_methods
        return None
766235
def generate_categories():
    
    # inspired by https://gist.github.com/anonymous/2204527
    code_points_ranges = []
    iso_15924_aliases = []
    categories = []

    match = re.compile(r'([0-9A-F]+)(?:\.\.([0-9A-F]+))?\W+(\w+)\s*#\s*(\w+)',
                       re.UNICODE)

    url = 'ftp://ftp.unicode.org/Public/UNIDATA/Scripts.txt'
    file = get(url)
    for line in file:
        p = re.findall(match, line)
        if p:
            code_point_range_from, code_point_range_to, alias, category = p[0]
            alias = u(alias.upper())
            category = u(category)
            if alias not in iso_15924_aliases:
                iso_15924_aliases.append(alias)
            if category not in categories:
                categories.append(category)
            code_points_ranges.append((
                int(code_point_range_from, 16),
                int(code_point_range_to or code_point_range_from, 16),
                iso_15924_aliases.index(alias), categories.index(category))
            )
    code_points_ranges.sort()

    categories_data = {
        'iso_15924_aliases': iso_15924_aliases,
        'categories': categories,
        'code_points_ranges': code_points_ranges,
    }

    dump('categories.json', categories_data)
736468
def get_category_files_from_api(category_name):
    """"""
    import mwclient
    site = mwclient.Site('commons.wikimedia.org')
    category = site.Categories[category_name]
    return (x.page_title.encode('utf-8')
            for x in category.members(namespace=6))