text:
package com.github.wrdlbrnft.gluemeister.config;

import com.github.wrdlbrnft.gluemeister.GlueMeisterException;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.tools.JavaFileManager;

/**
 * Created with Android Studio

 * User: Xaver

 * Date: 01/02/2017
 */

class GlueMeisterConfigWriter {

    private final Gson mGson = new Gson();

    private final ProcessingEnvironment mProcessingEnvironment;

    GlueMeisterConfigWriter(ProcessingEnvironment processingEnvironment) {
        mProcessingEnvironment = processingEnvironment;
    }

    void writeConfigFile(GlueMeisterConfig config, JavaFileManager.Location location, String packageName, String fileName) {
        try (final Writer writer = mProcessingEnvironment.getFiler()
                .createResource(location, packageName, fileName)
                .openWriter()) {
            final GlueMeisterConfigFile file = formatConfig(config);
            final String json = mGson.toJson(file);
            writer.append(json);
        } catch (IOException e) {
            throw new GlueMeisterException("Failed to generate glue-meister.json", null, e);
        }
    }

    private GlueMeisterConfigFile formatConfig(GlueMeisterConfig config) {
        final List<GlueEntityConfigEntry> entityConfigEntries = config.getGlueModuleInfos().stream()
                .map(info -> new GlueEntityConfigEntry(
                        info.getEntityElement().getQualifiedName().toString(),
                        info.getFactoryPackageName(),
                        info.getFactoryName()
                ))
                .collect(Collectors.toList());
        final List<GlueableConfigEntry> glueableConfigEntries = config.getGlueableInfos().stream()
                .map(info -> new GlueableConfigEntry(
                        createIdentifier(info.getElement()),
                        info.getKind(),
                        info.getKey(),
                        info.isEnabled()
                ))
                .collect(Collectors.toList());
        return new GlueMeisterConfigFile(
                entityConfigEntries,
                glueableConfigEntries
        );
    }

    private String createIdentifier(Element element) {
        if (element instanceof TypeElement) {
            final TypeElement typeElement = (TypeElement) element;
            return typeElement.getQualifiedName().toString();
        }

        if (element instanceof VariableElement) {
            final VariableElement variableElement = (VariableElement) element;
            final TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
            return enclosingElement.getQualifiedName() + "#" + variableElement.getSimpleName();
        }

        if (element instanceof ExecutableElement) {
            final ExecutableElement executableElement = (ExecutableElement) element;
            final TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();
            return enclosingElement.getQualifiedName() + "::" + executableElement.getSimpleName();
        }

        throw new GlueMeisterException("Failed to create identifier for element: " + element, null);
    }
}

redpajama_set_name: RedPajamaGithub


text:
Register

back to tedxberkeley.org
{% include "form.html" %}
Already have an account?


text:
// Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Unit tests for blog-post-summary-model.
 */

import { TestBed } from '@angular/core/testing';

import { BlogPostSummary } from 'domain/blog/blog-post-summary.model';

describe('Blog post summary object factory', () => {
  let sampleSummary: BlogPostSummary;
  let sampleSummaryBackendObject = {
    id: 'sampleId',
    author_username: 'test_user',
    title: 'Title',
    summary: 'Hello World',
    tags: ['news'],
    thumbnail_filename: 'image.png',
    url_fragment: 'title',
    last_updated: '3232323',
    published_on: '3232323',
  };

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [BlogPostSummary]
    });
  });

  it('should create correct BlogPostSummary object from' +
    ' backend dict', () => {
    sampleSummary = BlogPostSummary.createFromBackendDict(
      sampleSummaryBackendObject);

    expect(sampleSummary.id).toEqual('sampleId');
    expect(sampleSummary.authorUsername).toEqual('test_user');
    expect(sampleSummary.title).toEqual('Title');
    expect(sampleSummary.tags).toEqual(['news']);
    expect(sampleSummary.summary).toEqual('Hello World');
    expect(sampleSummary.urlFragment).toEqual('title');
    expect(sampleSummary.lastUpdated).toEqual('3232323');
    expect(sampleSummary.publishedOn).toEqual('3232323');
    expect(sampleSummary.thumbnailFilename).toEqual('image.png');
  });
});


text:
This is a library that allows you to embed a podcast in your web page.

## Features
- Provide a podcast URL, see a podcast rendered
- Total library size is `~4.5kb`
- Optionally provide a limit to the number of episodes displayed
- Each episode has its own audio player

__Note:__ To parse the RSS/podcast/XML feed into usable JSON, the podcast is loaded through [Narro](https://www.narro.co) (using a simple pass of the [rss-parser](https://github.com/rbren/rss-parser#readme) library). This avoids bloating the client library with an RSS parser.

## Usage
1. Create an element on your page with the class `pb-embed` and attribute `data-feed="<podcast-url-here>"`.
2. Include the `bundle.js` either in your own compiled js or as a `script` tag before the `body` closing tag.
3. Optionally, provide your own styling of the embed (see `./example/example.css`).
4. Optionally, provide an attribute of `data-limit="<some number>"` to limit the number of episodes displayed.

## Methods
~~~js
// Initialize all nodes with class 'pb-embed' on the page
pb.init();

// Initialize an embedded feed inside a given DOM node
var node = document.querySelector('#myId');
var embed = pb.createEmbed(node);

// Initialize an embedded feed inside a given DOM node, with a feed URL
var feed = 'http://mypodcast.com/feed.xml';
embed = pb.createEmbed(node, feed);

// Reload a given feed/embed
embed.reload();
~~~

### Example
See [https://github.com/NarroApp/Pb/tree/master/example](https://github.com/NarroApp/Pb/tree/master/example)

~~~html
<div class="pb-embed" data-feed="http://on.narro.co/foobar" data-limit="5">
</div>
~~~

Working usage: [https://narroapp.github.io/Pb/](https://narroapp.github.io/Pb/)


text:
package gocore

import (
	"fmt"
	"math"
	"sort"

	"golang.org/x/debug/internal/core"
)

type module struct {
	r             region       // inferior region holding a runtime.moduledata
	types, etypes core.Address // range that holds all the runtime._type data in this module
	p             *Process     // The parent process of this module.
}

func (p *Process) readModules() {
	// Note: the cast is necessary for cores generated by Go 1.9, where
	// runtime.moduledata is just an unsafe.Pointer.
	ms := p.rtGlobals["modulesSlice"].Cast("*[]*runtime.moduledata").Deref()
	n := ms.SliceLen()
	for i := int64(0); i < n; i++ {
		md := ms.SliceIndex(i).Deref()
		p.modules = append(p.modules, p.readModule(md))
	}
	p.funcTab.sort()
}

func (p *Process) readModule(r region) *module {
	m := &module{p: p, r: r}
	m.types = core.Address(r.Field("types").Uintptr())
	m.etypes = core.Address(r.Field("etypes").Uintptr())

	// Read the pc->function table
	pcln := r.Field("pclntable")
	var pctab, funcnametab region
	havePCtab := r.HasField("pctab")
	if havePCtab {
		// In 1.16, pclntable was split up into pctab and funcnametab.
		pctab = r.Field("pctab")
		funcnametab = r.Field("funcnametab")
	}
	ftab := r.Field("ftab")
	n := ftab.SliceLen() - 1 // last slot is a dummy, just holds entry
	for i := int64(0); i < n; i++ {
		ft := ftab.SliceIndex(i)
		var min, max core.Address
		var funcoff int64
		if ft.HasField("entryoff") {
			min = m.textAddr(ft.Field("entryoff").Uint32())
			max = m.textAddr(ftab.SliceIndex(i + 1).Field("entryoff").Uint32())
			funcoff = int64(ft.Field("funcoff").Uint32())
		} else {
			// Prior to 1.18, functab.entry directly referenced the
			// entries.
			min = core.Address(ft.Field("entry").Uintptr())
			max = core.Address(ftab.SliceIndex(i + 1).Field("entry").Uintptr())
			// funcoff changed type, but had the same meaning.
			funcoff = int64(ft.Field("funcoff").Uintptr())
		}
		fr := pcln.SliceIndex(funcoff).Cast("runtime._func")
		var f *Func
		if havePCtab {
			f = m.readFunc(fr, pctab, funcnametab)
		} else {
			f = m.readFunc(fr, pcln, pcln)
		}
		if f.entry != min {
			panic(fmt.Errorf("entry %x and min %x don't match for %s", f.entry, min, f.name))
		}
		p.funcTab.add(min, max, f)
	}

	return m
}

// readFunc parses a runtime._func and returns a *Func.
// r must have type runtime._func.
// pcln must have type []byte and represent the module's pcln table region.
func (m *module) readFunc(r region, pctab region, funcnametab region) *Func {
	f := &Func{module: m, r: r}
	var nameOff int32
	switch {
	case r.HasField("entryOff"):
		f.entry = m.textAddr(r.Field("entryOff").Uint32())
		nameOff = r.Field("nameOff").Int32()
	case r.HasField("entryoff"):
		// Prior to 1.20, entryOff and nameOff were named entryoff and
		// nameoff, respectively.
		f.entry = m.textAddr(r.Field("entryoff").Uint32())
		nameOff = r.Field("nameoff").Int32()
	default:
		// Prior to 1.18, _func.entry directly referenced the entries.
		f.entry = core.Address(r.Field("entry").Uintptr())
		nameOff = r.Field("nameoff").Int32()
	}
	f.name = r.p.proc.ReadCString(funcnametab.SliceIndex(int64(nameOff)).a)
	pcsp := r.Field("pcsp")
	var pcspIdx int64
	if pcsp.typ.Kind == KindUint {
		// In 1.16, pcsp changed to be a uint32 from an int32.
		pcspIdx = int64(pcsp.Uint32())
	} else {
		pcspIdx = int64(pcsp.Int32())
	}
	f.frameSize.read(r.p.proc, pctab.SliceIndex(pcspIdx).a)

	// Parse pcdata and funcdata, which are laid out beyond the end of the _func.
	// In 1.16, npcdata changed to be a uint32 from an int32.
	npcdata := r.Field("npcdata")
	var n uint32
	if npcdata.typ.Kind == KindUint {
		// In 1.16, pcsp changed to be a uint32 from an int32.
		n = npcdata.Uint32()
	} else {
		n = uint32(npcdata.Int32())
	}
	nfd := r.Field("nfuncdata")
	a := nfd.a.Add(nfd.typ.Size)

	for i := uint32(0); i < n; i++ {
		f.pcdata = append(f.pcdata, r.p.proc.ReadInt32(a))
		a = a.Add(4)
	}
	a = a.Align(r.p.proc.PtrSize())

	if nfd.typ.Size == 1 { // go 1.12 and beyond, this is a uint8
		n = uint32(nfd.Uint8())
	} else { // go 1.11 and earlier, this is an int32
		n = uint32(nfd.Int32())
	}
	for i := uint32(0); i < n; i++ {
		if m.r.HasField("gofunc") {
			// Since 1.18, funcdata contains offsets from go.func.*.
			off := r.p.proc.ReadUint32(a)
			if off == ^uint32(0) {
				// No entry.
				f.funcdata = append(f.funcdata, 0)
			} else {
				f.funcdata = append(f.funcdata, core.Address(m.r.Field("gofunc").Uintptr()+uint64(off)))
			}
			a = a.Add(4)
		} else {
			// Prior to 1.18, funcdata contains pointers directly
			// to the data.
			f.funcdata = append(f.funcdata, r.p.proc.ReadPtr(a))
			a = a.Add(r.p.proc.PtrSize())
		}
	}

	// Read pcln tables we need.
	if stackmap := int(r.p.rtConstants["_PCDATA_StackMapIndex"]); stackmap < len(f.pcdata) {
		f.stackMap.read(r.p.proc, pctab.SliceIndex(int64(f.pcdata[stackmap])).a)
	} else {
		f.stackMap.setEmpty()
	}

	return f
}

// textAddr returns the address of a text offset.
//
// Equivalent to runtime.moduledata.textAddr.
func (m *module) textAddr(off32 uint32) core.Address {
	off := uint64(off32)
	res := m.r.Field("text").Uintptr() + off

	textsectmap := m.r.Field("textsectmap")
	length := textsectmap.SliceLen()
	if length > 1 {
		for i := int64(0); i < length; i++ {
			sect := textsectmap.SliceIndex(i)

			vaddr := sect.Field("vaddr").Uintptr()
			end := sect.Field("end").Uintptr()
			baseaddr := sect.Field("baseaddr").Uintptr()

			if off >= vaddr && off < end || (i == length-1 && off == end) {
				res = baseaddr + off - vaddr
			}
		}
	}

	return core.Address(res)
}

type funcTabEntry struct {
	min, max core.Address
	f        *Func
}

type funcTab struct {
	entries []funcTabEntry
}

// add records that PCs in the range [min,max) map to function f.
func (t *funcTab) add(min, max core.Address, f *Func) {
	t.entries = append(t.entries, funcTabEntry{min: min, max: max, f: f})
}

// sort must be called after all the adds, but before any find.
func (t *funcTab) sort() {
	sort.Slice(t.entries, func(i, j int) bool {
		return t.entries[i].min < t.entries[j].min
	})
}

// Finds a Func for the given address.  Sort must have been called already.
func (t *funcTab) find(pc core.Address) *Func {
	n := sort.Search(len(t.entries), func(i int) bool {
		return t.entries[i].max > pc
	})
	if n == len(t.entries) || pc < t.entries[n].min || pc >= t.entries[n].max {
		return nil
	}
	return t.entries[n].f
}

// a pcTab maps from an offset in a function to an int64.
type pcTab struct {
	entries []pcTabEntry
}

type pcTabEntry struct {
	bytes int64 // # of bytes this entry covers
	val   int64 // value over that range of bytes
}

// read parses a pctab from the core file at address data.
func (t *pcTab) read(core *core.Process, data core.Address) {
	var pcQuantum int64
	switch core.Arch() {
	case "386", "amd64", "amd64p32":
		pcQuantum = 1
	case "s390x":
		pcQuantum = 2
	case "arm", "arm64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le":
		pcQuantum = 4
	default:
		panic("unknown architecture " + core.Arch())
	}
	val := int64(-1)
	first := true
	for {
		// Advance value.
		v, n := readVarint(core, data)
		if v == 0 && !first {
			return
		}
		data = data.Add(n)
		if v&1 != 0 {
			val += ^(v >> 1)
		} else {
			val += v >> 1
		}

		// Advance pc.
		v, n = readVarint(core, data)
		data = data.Add(n)
		t.entries = append(t.entries, pcTabEntry{bytes: v * pcQuantum, val: val})
		first = false
	}
}

func (t *pcTab) setEmpty() {
	t.entries = []pcTabEntry{{bytes: math.MaxInt64, val: -1}}
}

func (t *pcTab) find(off int64) (int64, error) {
	for _, e := range t.entries {
		if off < e.bytes {
			return e.val, nil
		}
		off -= e.bytes
	}
	return 0, fmt.Errorf("can't find pctab entry for offset %#x", off)
}

// readVarint reads a varint from the core file.
// val is the value, n is the number of bytes consumed.
func readVarint(core *core.Process, a core.Address) (val, n int64) {
	for {
		b := core.ReadUint8(a)
		val |= int64(b&0x7f) << uint(n*7)
		n++
		a++
		if b&0x80 == 0 {
			return
		}
	}
}


text:
from __future__ import absolute_import
from optparse import make_option

from django.conf import settings
from django.core.management.base import BaseCommand
from zerver.lib.actions import do_create_realm, set_default_streams
from zerver.models import RealmAlias

if not settings.VOYAGER:
    from zilencer.models import Deployment

import re
import sys

class Command(BaseCommand):
    help = """Create a realm for the specified domain.

Usage: python2.7 manage.py create_realm --domain=foo.com --name='Foo, Inc.'"""

    option_list = BaseCommand.option_list + (
        make_option('-o', '--open-realm',
                    dest='open_realm',
                    action="store_true",
                    default=False,
                    help='Make this an open realm.'),
        make_option('-d', '--domain',
                    dest='domain',
                    type='str',
                    help='The domain for the realm.'),
        make_option('-n', '--name',
                    dest='name',
                    type='str',
                    help='The user-visible name for the realm.'),
        make_option('--deployment',
                    dest='deployment_id',
                    type='int',
                    default=None,
                    help='Optionally, the ID of the deployment you want to associate the realm with.'),
        )

    def validate_domain(self, domain):
        # Domains can't contain whitespace if they are to be used in memcached
        # keys.
        if re.search("\s", domain):
            raise ValueError("Domains can't contain whitespace")

        # Domains must look like domains, ie have the structure of
        # <subdomain(s)>.<tld>. One reason for this is that bots need
        # to have valid looking emails.
        if len(domain.split(".")) < 2:
            raise ValueError("Domains must contain a '.'")

        if RealmAlias.objects.filter(domain=domain).count() > 0:
            raise ValueError("Cannot create a new realm that is already an alias for an existing realm")

    def handle(self, *args, **options):
        if options["domain"] is None or options["name"] is None:
            print >>sys.stderr, "\033[1;31mPlease provide both a domain and name.\033[0m\n"
            self.print_help("python2.7 manage.py", "create_realm")
            exit(1)

        if options["open_realm"] and options["deployment_id"] is not None:
            print >>sys.stderr, "\033[1;31mExternal deployments cannot be open realms.\033[0m\n"
            self.print_help("python2.7 manage.py", "create_realm")
            exit(1)
        if options["deployment_id"] is not None and settings.VOYAGER:
            print >>sys.stderr, "\033[1;31mExternal deployments are not supported on voyager deployments.\033[0m\n"
            exit(1)

        domain = options["domain"]
        name = options["name"]

        self.validate_domain(domain)

        realm, created = do_create_realm(
            domain, name, restricted_to_domain=not options["open_realm"])
        if created:
            print domain, "created."
            if options["deployment_id"] is not None:
                deployment = Deployment.objects.get(id=options["deployment_id"])
                deployment.realms.add(realm)
                deployment.save()
                print "Added to deployment", str(deployment.id)
            elif settings.ZULIP_COM:
                deployment = Deployment.objects.get(base_site_url="https://zulip.com/")
                deployment.realms.add(realm)
                deployment.save()
            # In the else case, we are not using the Deployments feature.

            set_default_streams(realm, ["social", "engineering"])

            print "\033[1;36mDefault streams set to social,engineering,zulip!\033[0m"
        else:
            print domain, "already exists."


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ext2conv2
{
    public partial class InvisibleForm : Form
    {
        public InvisibleForm()
        {
            InitializeComponent();
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ext2conv2.Visible = false;
            Application.Exit();
        }
    }
}


text:
<?php

namespace Wilsonpinto\Blade;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Wilsonpinto\Blade\Directives\AssignmentDirectives;
use Wilsonpinto\Blade\Directives\IteratorDirectives;

class BladeDirectivesServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/blade-directives.php' => config_path('blade-directives.php')
        ]);

        $blade = $this->app->make('blade.compiler');

        $filesystem = $this->app->make('files');

        $config = $this->app->make('config');

        AssignmentDirectives::register($blade, IteratorDirectives::get($filesystem, $config));
    }
}


text:
Alloy.Globals.Cloud = require('ti.cloud');
Alloy.Globals.SocialT = require('alloy/social').create({
    consumerSecret: '58hSfSQThA50MDk4XbjwXWblrnXKxeS2bZnEuAZzOiquSKzmT1',
    consumerKey: 'Pt0TamfxGAt3AyOIwrZdaMyFx'
});

var nube = Alloy.Globals.Cloud;
function definirGlobals(){
	Alloy.Globals.newData = {peliculas:[],cines:[],cinesPeliculas:[],obras:[],teatros:[],teatrosObras:[]};
	Alloy.Globals.usuarioLogeado = {nombre:null,apellido:null,usuario:null,email:null,tiUsuer:false,idUsuario:null};
}
definirGlobals();
definirListeners();

Alloy.Globals.fbModule = require('facebook');
inicializarFbModule();
function inicializarFbModule(){
	Alloy.Globals.fbModule = require('facebook');
	var fb = Alloy.Globals.fbModule;
	fb.appid = '702388679841824';
	fb.permissions = ['public_profile','email','publish_stream','publish_actions'];
	fb.forceDialogAuth = false;
	fb.addEventListener('login',function(event){
		if(event.success){
			alert("logout Done");
			fb.requestWithGraphPath('me', {}, 'GET', function(e) {
			    if (e.success) {
			       Ti.API.info(JSON.stringify(e.result));
			    } else if (e.error) {
			       Ti.API.info(JSON.stringify(e.error));
			    } else {
			        Ti.API.info('Unknown response');
			    }
			});
		}
	});

//	fb.authorize();

	fb.addEventListener('logout',function(event){
		alert("logout Done");
	});
}

Alloy.Globals.shareF = function shareFacebook(msg){
	Alloy.Globals.fbModule.requestWithGraphPath('me/feed',
		{message:msg},
		'POST',
		function(event){
			if(event.success){
				 Ti.API.info(JSON.stringify(event.result));
				alert('Compartido con Exito');
			}else if (event.error) {
			       Ti.API.info(JSON.stringify(event.error));
			} else {
			        Ti.API.info('Unknown response');
			}
		});
};

Alloy.Globals.shareT = function shareTwitter(msg){
	Alloy.Globals.SocialT.share({
    	message: msg,
    	success: function(e) {alert('Compartido con Exito')},
    	error: function(e) {alert('Error!')}
	});
};

if (OS_ANDROID) {
	Alloy.Globals.Android = {
		"Api" : Ti.Platform.Android.API_LEVEL
	};
}

Alloy.Globals.actualizarData = function actualizarData() {
	Titanium.API.info("versionDeLosDatos from Titanium");
	 var versionDeLosDatos = {};
	nube.Objects.query({
    classname: 'versionDeLosDatos'
	}, function (e) {
			var dataOnDB = Alloy.Collections.instance('versionDeLosDatos');
			dataOnDB.fetch();
			//Titanium.API.info(dataOnDB.length+"--------------------------");
	    if (e.success) {
	        for (var i = 0; i < e.versionDeLosDatos.length; i++) {
	            var dataTemp = e.versionDeLosDatos[i];
	            versionDeLosDatos =Alloy.createModel('versionDeLosDatos', {
	            peliculas : dataTemp.peliculas,
				cines : dataTemp.cines,
				cinesPeliculas : dataTemp.cinesPeliculas,
				obras:dataTemp.obras,
				teatros:dataTemp.teatros,
				teatrosObras:dataTemp.teatrosObras,
				tiCloudID:dataTemp.id
				});
	        }
			if (dataOnDB.length < 1) {
				Titanium.API.info("no data found");
				versionDeLosDatos.save();
				cargarDataDePeliculas();
				cargarDataDeCines();
				cargarDataDeCinesPeliculas();
				cargarDataDeObras();
				cargarDataDeTeatros();
				cargarDataDeTeatrosObras();
			}else if(versionDeLosDatos.get('peliculas') > dataOnDB.at(0).get('peliculas')){
				Titanium.API.info(dataOnDB.length+" update peliculas");
				dataOnDB.at(0).set('peliculas', versionDeLosDatos.get('peliculas'));
				dataOnDB.at(0).save();
				cargarDataDePeliculas();
			}else if(versionDeLosDatos.get('cines') > dataOnDB.at(0).get('cines')){
				dataOnDB.at(0).set('cines' ,versionDeLosDatos.get('cines'));
				dataOnDB.at(0).save();
				cargarDataDeCines();
			}else if(versionDeLosDatos.get('cinesPeliculas') > dataOnDB.at(0).get('cinesPeliculas')){
				dataOnDB.at(0).set('cinesPeliculas',versionDeLosDatos.get('cinesPeliculas'));
				dataOnDB.at(0).save();
				cargarDataDeCinesPeliculas();
			}else if(versionDeLosDatos.get('obras') > dataOnDB.at(0).get('obras')){
				dataOnDB.at(0).set('obras', versionDeLosDatos.get('obras'));
				dataOnDB.at(0).save();
				cargarDataDeObras();
			}else if(versionDeLosDatos.get('teatros') > dataOnDB.at(0).get('teatros')){
				dataOnDB.at(0).set('teatros',versionDeLosDatos.get('teatros'));
				dataOnDB.at(0).save();
				cargarDataDeTeatros();
			}else if(versionDeLosDatos.get('teatrosObras') > dataOnDB.at(0).get('teatrosObras')){
				dataOnDB.at(0).set('teatrosObras',versionDeLosDatos.get('teatrosObras'));
				dataOnDB.at(0).save();
				cargarDataDeTeatrosObras();
			}
	    } else {
	        Titanium.API.info('Error:' + JSON.stringify(e));
	        alert('No fue posible actualizar los Datos, for favor asegúrese de tener acceso a internet');
	    }
	});
}

Alloy.Globals.actualizarData();

function cargarDataDePeliculas() {
	Titanium.API.info("inicializarListadoDePeliculas from Titanium");
	nube.Objects.query({
    classname: 'pelicula'
	}, function (e) {
	    if (e.success) {
	        for (var i = 0; i < e.pelicula.length; i++) {
	            var dataTemp = e.pelicula[i];
	            var votos = 0;
	            var stars = 0;
	            if(dataTemp.reviews_count){
	            	votos = dataTemp.reviews_count;
	            }
	            if(dataTemp.ratings_average){
	            	if(parseInt(dataTemp.ratings_average) > 0){
	            		stars = parseInt(dataTemp.ratings_average);
	            	}
	            }

	            var currentData = Alloy.createModel('pelicula', {
					identificador:dataTemp.identificador,
					generos :dataTemp.generos,
					trailer :dataTemp.trailer,
					sinopsis :dataTemp.sinopsis,
					titulo :dataTemp.titulo,
					duracion :dataTemp.duracion,
					stars :stars,
					votos :votos,
					tiCloudID:dataTemp.id
				});
				Alloy.Globals.newData.peliculas.push(currentData);
			if(!(typeof dataTemp.photo === "undefined")){
               var portada = dataTemp.photo;
				var xhr = Titanium.Network.createHTTPClient({
					onload: function() {
						// first, grab a "handle" to the file where you'll store the downloaded data
						var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,portada.filename);
						f.write(this.responseData); // write to the file
						Ti.App.fireEvent('graphic_downloaded', {filepath:f.nativePath,data:currentData});
					},
					timeout: 10000
				});
				xhr.open('GET',portada.urls.small_240);
				xhr.send();

				Ti.App.addEventListener('graphic_downloaded', function(e) {
					// you don't have to fire an event like this, but perhaps multiple components will
					// want to know when the image has been downloaded and saved
					e.data.set("portada",e.filepath);
					e.data.save();
					Ti.App.fireEvent('nuevaDataDePeliculaDelServer');
				});

				 }

	        }
	        Titanium.API.info('Recived data de peliculas del server');
	        Ti.App.fireEvent('nuevaDataDePeliculaDelServer');
	    } else {
	        Titanium.API.info('Error:' + JSON.stringify(e));
	    }
	});
}

function cargarDataDeCines() {
	Titanium.API.info("inicializarListadoDeCines  from Titanium");
	nube.Objects.query({
    classname: 'cine'
	}, function (e) {
	    if (e.success) {
	        for (var i = 0; i < e.cine.length; i++) {
	            var dataTemp = e.cine[i];
	            Alloy.Globals.newData.cines.push(Alloy.createModel('cine', {
					identificador:dataTemp.identificador,
					nombre :dataTemp.nombre,
					telefono :dataTemp.telefono,
					direccion :dataTemp.direccion,
					tiCloudID:dataTemp.id
				}));
	        }
	        Ti.App.fireEvent('nuevaDataDeCineDelServer');
	    } else {
	        Titanium.API.info('Error:' + JSON.stringify(e));
	    }
	});

}

function cargarDataDeCinesPeliculas() {
	Titanium.API.info("inicializarListadoDeCinesPeliculas  from Titanium");
	nube.Objects.query({
    classname: 'cinePelicula'
	}, function (e) {
	    if (e.success) {
	        for (var i = 0; i < e.cinePelicula.length; i++) {
	            var dataTemp = e.cinePelicula[i];
	           Alloy.Globals.newData.cinesPeliculas.push( Alloy.createModel('cinePelicula', {
					idPelicula : dataTemp.idPelicula  ,
					idCine : dataTemp.idCine,
					lunes : dataTemp.lunes,
					martes :dataTemp.martes,
					miercoles :dataTemp.miercoles,
					jueves :dataTemp.jueves,
					viernes :dataTemp.viernes,
					sabado :dataTemp.sabado,
					domingo :dataTemp.domingo,
					tiCloudID:dataTemp.id
			}));
	        }
	        Ti.App.fireEvent('nuevaDataDeCinePeliculaDelServer');
	    } else {
	        Titanium.API.info('Error:' + JSON.stringify(e));
	    }
	});

}

function cargarDataDeTeatros() {
	Titanium.API.info("inicializarListadoDeTeatros from Titanium");
	nube.Objects.query({
    classname: 'teatro'
	}, function (e) {
	    if (e.success) {
	        for (var i = 0; i < e.teatro.length; i++) {
	            var dataTemp = e.teatro[i];
	            Alloy.Globals.newData.teatros.push(Alloy.createModel('teatro', {
	            identificador : dataTemp.identificador,
				nombre : dataTemp.nombre,
				telefono : dataTemp.telefono,
				direccion : dataTemp.direccion,
				tiCloudID:dataTemp.id
				}));
	        }
	        Ti.App.fireEvent('nuevaDataDeTeatroDelServer');
	    } else {
	        Titanium.API.info('Error:' + JSON.stringify(e));
	    }
	});

}

function cargarDataDeTeatrosObras() {
	Titanium.API.info("inicializarListadoDeTeatrosObras from Titanium");
	nube.Objects.query({
    classname: 'teatroObra'
	}, function (e) {
	    if (e.success) {
	        for (var i = 0; i < e.teatroObra.length; i++) {
	            var dataTemp = e.teatroObra[i];
	            Alloy.Globals.newData.teatrosObras.push(Alloy.createModel('teatroObra', {
	            idObra : dataTemp.idObra,
				idTeatro : dataTemp.idTeatro,
				horarios : dataTemp.horarios,
				tiCloudID:dataTemp.id
				}));
	        }
	        Ti.App.fireEvent('nuevaDataDeTeatroObraDelServer');
	    } else {
	        Titanium.API.info('Error:' + JSON.stringify(e));
	    }
	});
}

function cargarDataDeObras() {
	Titanium.API.info("inicializarListadoDeObras from Titanium");
	nube.Objects.query({
    classname: 'obra'
	}, function (e) {
	    if (e.success) {
	        for (var i = 0; i < e.obra.length; i++) {
	            var dataTemp = e.obra[i];
	            var votos = 0;
	            var stars = 0;
	            if(dataTemp.reviews_count){
	            	votos = dataTemp.reviews_count;
	            }
	            if(dataTemp.ratings_average){
	            	if(parseInt(dataTemp.ratings_average) > 0){
	            		stars = parseInt(dataTemp.ratings_average);
	            	}
	            }

	           var currentData = Alloy.createModel('obra', {
				identificador:dataTemp.identificador,
				generos : dataTemp.generos,
				trailer : dataTemp.trailer,
				sinopsis: dataTemp.sinopsis,
				titulo : dataTemp.titulo,
				stars : stars,
				votos : votos,
				tiCloudID:dataTemp.id
               });
               Alloy.Globals.newData.obras.push(currentData);

               if(!(typeof dataTemp.photo === "undefined")){
               var portada = dataTemp.photo;
				var xhr = Titanium.Network.createHTTPClient({
					onload: function() {
						// first, grab a "handle" to the file where you'll store the downloaded data
						var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,portada.filename);
						f.write(this.responseData); // write to the file
						Ti.App.fireEvent('graphic_downloaded', {filepath:f.nativePath,data:currentData});
					},
					timeout: 10000
				});
				xhr.open('GET',portada.urls.small_240);
				xhr.send();

				Ti.App.addEventListener('graphic_downloaded', function(e) {
					// you don't have to fire an event like this, but perhaps multiple components will
					// want to know when the image has been downloaded and saved
					e.data.set("portada",e.filepath);
					e.data.save();
					Ti.App.fireEvent('nuevaDataDeObrasRecibidaDelServer');
				});

				 }

	        }

	       Ti.App.fireEvent('nuevaDataDeObrasRecibidaDelServer');
	    } else {
	        Titanium.API.info('Error:' + JSON.stringify(e));
	    }
	});
}

function cleanDataBaseCines(){
	var db = Ti.Database.open('_alloy_');
	db.execute('DROP TABLE IF EXISTS cines;');
	db.execute('CREATE TABLE IF NOT EXISTS cines(identificador TEXT PRIMARY KEY, nombre TEXT, telefono TEXT,direccion TEXT,tiCloudID TEXT);');
	db.close();
}
function cleanDataBaseCinesPeliculas(){
	var db = Ti.Database.open('_alloy_');
	db.execute('DROP TABLE IF EXISTS cinesPeliculas;');
	db.execute('CREATE TABLE IF NOT EXISTS cinesPeliculas(alloy_id TEXT, idPelicula TEXT, idCine TEXT, lunes TEXT, martes TEXT, miercoles TEXT, jueves TEXT, viernes TEXT, sabado TEXT, domingo TEXT,tiCloudID TEXT);');
	db.close();
}
function cleanDataBaseObras(){
	var db = Ti.Database.open('_alloy_');
	db.execute('DROP TABLE IF EXISTS obras;');
	db.execute('CREATE TABLE IF NOT EXISTS obras(identificador TEXT PRIMARY KEY, generos TEXT, trailer TEXT, sinopsis TEXT, titulo TEXT, stars INTEGER, votos INTEGER, portada TEXT,tiCloudID TEXT);');
	db.close();
}
function cleanDataBasePeliculas(){
	var db = Ti.Database.open('_alloy_');
	db.execute('DROP TABLE IF EXISTS peliculas;');
	db.execute('CREATE TABLE IF NOT EXISTS peliculas(identificador TEXT PRIMARY KEY, generos TEXT, trailer TEXT, sinopsis TEXT, titulo TEXT, duracion TEXT, stars INTEGER, votos INTEGER, portada TEXT,tiCloudID TEXT);');
	db.close();
}
function cleanDataBaseTeatros(){
	var db = Ti.Database.open('_alloy_');
	db.execute('DROP TABLE IF EXISTS teatros;');
	db.execute('CREATE TABLE IF NOT EXISTS teatros(identificador TEXT PRIMARY KEY, nombre TEXT, telefono TEXT, direccion TEXT,tiCloudID TEXT);');
	db.close();
}
function cleanDataBaseTeatrosObras(){
	var db = Ti.Database.open('_alloy_');
	db.execute('DROP TABLE IF EXISTS teatrosObras;');
	db.execute('CREATE TABLE IF NOT EXISTS teatrosObras(alloy_id TEXT, idObra TEXT, idTeatro TEXT, horarios TEXT,tiCloudID TEXT);');
	db.close();
}

function definirListeners(){
	Ti.App.addEventListener('nuevaDataDePeliculaDelServer', function(e){
		var data = Alloy.Globals.newData.peliculas;
		if(data.length > 0){
			cleanDataBasePeliculas();
			for(var i=0;i< data.length;i++) {
				data[i].save();
			}
			Ti.App.fireEvent('dataDePeliculaCargada');
		}
	});
	Ti.App.addEventListener('nuevaDataDeCineDelServer', function(e){
		var data = Alloy.Globals.newData.cines;
		if(data.length > 0){
			cleanDataBaseCines();
			for(var i=0;i< data.length;i++) {
				data[i].save();
			}
			Ti.App.fireEvent('dataDeCineCargada');
		}
	});
	Ti.App.addEventListener('nuevaDataDeCinePeliculaDelServer', function(e){
		var data = Alloy.Globals.newData.cinesPeliculas;
		if(data.length > 0){
			cleanDataBaseCinesPeliculas();
			for(var i=0;i< data.length;i++) {
				data[i].save();
			}
		}
	});
	Ti.App.addEventListener('nuevaDataDeTeatroDelServer', function(e){
		var data = Alloy.Globals.newData.teatros;
		if(data.length > 0){
			cleanDataBaseTeatros();
			for(var i=0;i< data.length;i++) {
				data[i].save();
			}
			Ti.App.fireEvent('dataDeTeatroCargada');
		}
	});
	Ti.App.addEventListener('nuevaDataDeTeatroObraDelServer', function(e){
		var data = Alloy.Globals.newData.teatrosObras;
		if(data.length > 0){
			cleanDataBaseTeatrosObras();
			for(var i=0;i< data.length;i++) {
				data[i].save();
			}
		}
	});
	Ti.App.addEventListener('nuevaDataDeObrasRecibidaDelServer', function(e){
		var data = Alloy.Globals.newData.obras;
		if(data.length > 0){
			cleanDataBaseObras();
			for(var i=0;i< data.length;i++) {
				data[i].save();
			}
			Ti.App.fireEvent('dataDeObrasCargada');
		}
	});
}


text:
class DictionaryValue;
class Extension;
class ExtensionsService;
class FilePath;
class UserScript;
class Value;

// Information about a page running in an extension, for example a toolstrip,
// a background page, or a tab contents.
struct ExtensionPage {
  ExtensionPage(const GURL& url, int render_process_id, int render_view_id)
    : url(url), render_process_id(render_process_id),
      render_view_id(render_view_id) {}
  GURL url;
  int render_process_id;
  int render_view_id;
};

class ExtensionsUIHTMLSource : public ChromeURLDataManager::DataSource {
 public:
  ExtensionsUIHTMLSource();

  // Called when the network layer has requested a resource underneath
  // the path we registered.
  virtual void StartDataRequest(const std::string& path, int request_id);
  virtual std::string GetMimeType(const std::string&) const {
    return "text/html";
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ExtensionsUIHTMLSource);
};

// The handler for Javascript messages related to the "extensions" view.
class ExtensionsDOMHandler : public DOMMessageHandler {
 public:
  explicit ExtensionsDOMHandler(ExtensionsService* extension_service);
  virtual ~ExtensionsDOMHandler();

  // DOMMessageHandler implementation.
  virtual void RegisterMessages();

  // Extension Detail JSON Struct for page. (static for ease of testing).
  static DictionaryValue* CreateExtensionDetailValue(
      const Extension *extension,
      const std::vector<ExtensionPage>&);

  // ContentScript JSON Struct for page. (static for ease of testing).
  static DictionaryValue* CreateContentScriptDetailValue(
      const UserScript& script,
      const FilePath& extension_path);

 private:
  // Callback for "requestExtensionsData" message.
  void HandleRequestExtensionsData(const Value* value);

  // Callback for "inspect" message.
  void HandleInspectMessage(const Value* value);

  // Callback for "uninstall" message.
  void HandleUninstallMessage(const Value* value);

  // Helper that lists the current active html pages for an extension.
  std::vector<ExtensionPage> GetActivePagesForExtension(
      const std::string& extension_id);

  // Our model.
  scoped_refptr<ExtensionsService> extensions_service_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionsDOMHandler);
};

class ExtensionsUI : public DOMUI {
 public:
  explicit ExtensionsUI(TabContents* contents);

 private:
  DISALLOW_COPY_AND_ASSIGN(ExtensionsUI);
};

#endif  // CHROME_BROWSER_EXTENSIONS_EXTENSIONS_UI_H_


text:
<?php

namespace Site\UtilityBundle\Encoder;

/**
 * Handles slug encoding/decoding
 *
 * @author  Yan Barreta
*/
class SlugEncoder
{

    /**
     * Encode text to be more url friendly
     *
     * @param String $text - text to be encoded
     * @param String $prefix [optional] - text to prepend the slug after creation
     * @param String $postfix [optional] - text to append to the slug after creation
     * @param Array $excludedWords [optional] - array of words to remove from the slug
     * @param boolean $retainAllCaps [optional] - prevent words with all uppercase letters from being excluded
     * @return String - slug, a url friendly string
     */
    public function encode($text, $prefix = '', $postfix = '', $excludedWords = array(), $retainAllCaps = false)
    {
        // transliterate
        if (function_exists('iconv')) {
            $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        }

        $basePlaceholder = 'autodealslugwildcard';
        $placeholderValues = array();
        if($retainAllCaps){
            // find words with all uppercase letters
            foreach (explode(' ', $text) as $word) {
                if (strlen(trim($word)) > 1 && ctype_upper(trim($word))) {
                    $placeholderValues[$word] = $word;
                }
            }

            $placeholderValues = array_values($placeholderValues);

            // set placeholders
            foreach ($placeholderValues as $key => $val) {
                $text = preg_replace("/$val/u", $basePlaceholder.$key, $text);
            }
        }

        // lowercase
        if (function_exists('mb_strtolower')) {
            $text = mb_strtolower($text);
        } else {
            $text = strtolower($text);
        }

        // remove accents resulting from OSX's iconv
        $text = str_replace(array('\'', '`', '^', '"'), '', $text);

        // replace non letter or digits with separator
        $text = preg_replace('/[^\\pL\\d]+/u', '-', $text);

        if (!empty($excludedWords)) {
            // append - at start and end of every slug component, as delimiter for whole words
            $text = '-'.preg_replace("/-/u", '--', $text).'-';

            // create pattern for regex
            $pattern = '-'.implode('-|-',$excludedWords).'-';

            // remove excluded words to shorten url
            $text = preg_replace("/$pattern/u", '', $text);

            // revert remaining -- to -
            $text = preg_replace("/--/u", '-', $text);
        }

        // trim
        $text = trim($text, '-');

        if (empty($text)) {
            return null;
        }

        // revert placeholders if any
        if (!empty($placeholderValues)) {
            foreach ($placeholderValues as $key => $val) {
                $placeholder = $basePlaceholder.$key;
                $text = preg_replace("/$placeholder/u", $val, $text);
            }
        }

        $slug = $prefix.$text.$postfix;

        // convert to lowercase any remaining uppercase letters
        if (function_exists('mb_strtolower')) {
            $slug = mb_strtolower($slug);
        } else {
            $slug = strtolower($slug);
        }

        return $slug;
    }

    public function decode()
    {}

}


text:
---
uid: SolidEdgeConstants.FrequencyPrecisionConstants
summary: Frequency Precision Constants
remarks:
---


text:
'''
Created on 26 Mar 2016

@author: alex
'''

from django.shortcuts import render
from django.http.response import HttpResponse
from django.shortcuts import HttpResponseRedirect
from .exceptions import RedirectException

try:
    from useful_inkleby.decorators import GenericDecorator
except:
    from ..decorators import GenericDecorator

def handle_redirect(func):

    def inner(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except RedirectException as new_url:
            return HttpResponseRedirect(new_url)

    return inner

class FunctionalView(object):
    """
    Very simple class-based view that simple expects the class to have a
    'template' variable and a 'view' function that expects (self, request).

    Idea is to preserve cleanness of functional view logic but tidy up the
    most common operation.

    """

    template = ""
    require_staff = False
    require_login = False
    login_test = staticmethod(lambda u: u.is_authenticated())
    staff_test = staticmethod(lambda u: u.is_staff)
    view_decorators = []

    @classmethod
    def as_view(cls, decorators=True, no_auth=False):
        """
        if decorators is True - we apply any view_decorators listed for the class
        if no_auth = True, we bypass staff and user testing(useful for baking)

        """

        def render_func(request, *args, **kwargs):

            view = cls()

            if no_auth == False:
                if cls.require_login and cls.login_test(request.user) == False:
                    return view.access_denied_no_auth(request)

                if cls.require_staff and cls.staff_test(request.user) == False:
                    return view.access_denied_no_staff(request)

            context = view._get_view_context(request, *args, **kwargs)

            if isinstance(context, dict):
                context = view.extra_params(context)
                return view.context_to_html(request, context)
            else:
                # if we're returning a redirect view
                return context

        func = render_func
        func = handle_redirect(func)  # allow RedirectException
        if decorators:
            for v in cls.view_decorators:
                func = v(func)

        return func

    def access_denied_no_auth(self, request):
        """
        override to provide a better response if someone needs to login
        """
        return HttpResponse("No Access")

    def access_denied_no_staff(self, request):
        """
        override to provide a better response if someone needs to be staff
        """
        return HttpResponse("No Access")

    def _get_view_context(self, request, *args, **kwargs):
        context = self.view(request, *args, **kwargs)

        if isinstance(context, dict):
            context = self.extra_params(context)
        return context

    def extra_params(self, context):
        return context

    def context_to_html(self, request, context):
        html = render(request,
                      self.__class__.template,
                      context=context
                      )
        return html

    def view(self, request):
        return {}

class LogicalView(FunctionalView):
    """
    Runs with class-based logic while trying to keep the guts exposed.

    request becomes self.request

    expects a 'logic' rather than a view function (no args).

    giving the class an 'args' list of strings tells it what to convert
    view arguments into.

    e.g. args = ['id_no'] - will create self.id_no from the view argument.
    if an arg is a tuple ('id_no','5') - will set a default value.

    Use prelogic and postlogic decorators to run functions before or afer logic.
    These accept an optional order paramter.
    Lower order have priority.
    Default order is 5.

    """

    args = []

    def __init__(self):
        self.record_new = False
        self.values = []

    def __setattr__(self, key, value):
        if hasattr(self, "record_new") and self.record_new:
            self.values.append(key)
        super(FunctionalView, self).__setattr__(key, value)

    def view(self, request, *args, **kwargs):
        """
        override with something that returns a dictionary
        to use plain functional view logic
        """
        self.request = request
        self.record_new = True  # enable new value recording

        arg_mappings = []
        """
        assign any default values
        """
        for a in self.__class__.args:
            if isinstance(a, tuple):
                setattr(self, a[0], a[1])
                arg_mappings.append(a[0])
            else:
                arg_mappings.append(a)
        """
        assign other results
        """
        for x, a in enumerate(args):
            try:
                arg_name = arg_mappings[x]
            except IndexError:
                raise ValueError("Mapping not assigned for {0}".format(a))
            setattr(self, arg_name, a)

        for k, v in kwargs.iteritems():
            setattr(self, k, v)

        prelogic = self._prelogic()
        if prelogic:
            return prelogic
        logic = self.logic()
        if logic:
            return logic
        postlogic = self._postlogic()
        if postlogic:
            return postlogic

        return {k: getattr(self, k) for k in self.values}

    def _logic_processing(self, prefix):
        """
        run all pre and post logic functions in order.
        """
        def keying(v):
            if hasattr(v, "order"):
                return v.order
            else:
                return 5

        def ga(k):
            return getattr(self, k)
        """
        has a function had either a decorator or a name prefix assigned to it
        """
        def passes_func_test(k): return hasattr(
            k, "_prefix") and k._prefix == prefix

        def passes_test(k): return prefix + "_" in k or passes_func_test(ga(k))
        funcs = [k for k in dir(self) if passes_test(k)]
        funcs = [ga(k) for k in funcs]
        funcs.sort(key=lambda x: keying(x))
        for f in funcs:
            r = f()
            if r:  # if any value is returned, escalate
                return r

    def _prelogic(self):
        return self._logic_processing("prelogic")

    def _postlogic(self):
        return self._logic_processing("postlogic")

    def logic(self):
        """
        any new values assigned to self will be passed to the template
        self.value becomes value
        """
        pass

class prelogic(GenericDecorator):
    """
    decorates a function to run before the logic view
    accepts an order kwarg to manage competing functions
    """
    prefix = "prelogic"
    default_kwargs = {"order": 5}

    def post_creation(self, obj):
        obj._prefix = self.__class__.prefix
        obj.order = self.order
        return obj

class postlogic(GenericDecorator):
    """
    decorates a function to run after the logic view
    accepts an order kwarg to manage competing functions
    """

    prefix = "postlogic"
    default_kwargs = {"order": 5}

    def post_creation(self, obj):
        obj._prefix = self.__class__.prefix
        obj.order = self.order
        return obj


text:
import { Component, EventEmitter, Input, Output, ViewEncapsulation } from '@angular/core';
import { Md2AccordionTab } from './accordiontab';
import { coerceBooleanProperty } from '../core/core';
@Component({
  moduleId: module.id,
  selector: 'md2-accordion',
  template: `<ng-content></ng-content>`,
  styleUrls: ['accordion.css'],
  host: {
    '[class]': 'class',
    '[class.md2-accordion]': 'true'
  },
  encapsulation: ViewEncapsulation.None
})

export class Md2Accordion {

  private _multiple: boolean;

  @Input()
  get multiple(): boolean { return this._multiple; }
  set multiple(value) { this._multiple = coerceBooleanProperty(value); }

  @Input() class: string = '';

  @Output() close: EventEmitter<any> = new EventEmitter<any>();

  @Output() open: EventEmitter<any> = new EventEmitter<any>();

  public tabs: Md2AccordionTab[] = [];

  /**
   * Add or append tab in accordion
   * @param tab object of Md2AccordionTab
   */
  addTab(tab: Md2AccordionTab) {
    this.tabs.push(tab);
  }
}


text:
package app.services.impl;

import app.dto.exportingDtos.CategoryByProductsCountDto;
import app.dto.seedingDtos.CategoryDetailsDto;
import app.dto.seedingDtos.CategorySeedDto;
import app.entities.Category;
import app.repository.CategoryRepository;
import app.services.api.CategoryService;
import app.utilities.io.EntityConverter;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService{

    private final CategoryRepository repository;

    public CategoryServiceImpl(CategoryRepository repository) {
        this.repository = repository;
    }

    @Override
    public void save(CategorySeedDto categorySeedDto) {
        Category convert = EntityConverter.convert(categorySeedDto, Category.class);
        repository.save(convert);
    }

    @Override
    public CategoryDetailsDto findById(Long id) {
        Category one = repository.findOne(id);
        CategoryDetailsDto convert = EntityConverter.convert(one, CategoryDetailsDto.class);
        return convert;
    }

    @Override
    public List<CategoryByProductsCountDto> categoriesDetails() {
        List<Object[]> objects = repository.categoryDetails();
        List<CategoryByProductsCountDto> results = new ArrayList<>();
        for (Object[] object : objects) {
            CategoryByProductsCountDto category = new CategoryByProductsCountDto();
            category.setName(object[0].toString());
            category.setTotalCount(Integer.valueOf(object[1].toString()));
            category.setAvgPrice(BigDecimal.valueOf(Double.parseDouble(object[2].toString())));
            category.setTotalRevenue(BigDecimal.valueOf(Double.parseDouble(object[3].toString())));
            results.add(category);
        }
        return results;
    }
}


text:
<?xml version="1.0"?>
<doc>
<assembly>
<name>
ZS.Images
</name>
</assembly>
<members>
<member name="T:ZS.Images.My.Resources.Resources">
<summary>
  A strongly-typed resource class, for looking up localized strings, etc.
</summary>
</member>
<member name="P:ZS.Images.My.Resources.Resources.ResourceManager">
<summary>
  Returns the cached ResourceManager instance used by this class.
</summary>
</member>
<member name="P:ZS.Images.My.Resources.Resources.Culture">
<summary>
  Overrides the current thread's CurrentUICulture property for all
  resource lookups using this strongly typed resource class.
</summary>
</member>
<member name="T:ZS.Images.ImageAdapter">
 <summary>
 图片读取
 </summary>
 <remarks></remarks>
</member>
<member name="M:ZS.Images.ImageAdapter.Instance">
 <summary>
 获取图片容器类的单例
 </summary>
 <returns></returns>
 <remarks></remarks>
</member>
<member name="M:ZS.Images.ImageAdapter.GetImage(System.String)">
 <summary>
 获取指定名称的图片,以System.Drawing.Image形式返回。
 </summary>
 <param name="imgUrl">。图片路径,不包含根Image目录。例如:Actions/Add_16x16.png</param>
 <returns></returns>
 <remarks></remarks>
</member>
<member name="M:ZS.Images.ImageAdapter.GetImageAsStream(System.String)">
 <summary>
 获取指定名称的图片,以System.IO.Stream形式返回。
 </summary>
 <param name="imgUrl">。图片路径,不包含根Image目录。例如:Actions/Add_16x16.png</param>
 <returns></returns>
</member>
</members>
</doc>


text:
"""SQLAlchemy storage backend."""

from __future__ import absolute_import
import datetime
import hashlib
import os

from oslo_config import cfg
from oslo_db import api
from oslo_db import exception as dbexc
from oslo_db.sqlalchemy import session as db_session
from oslo_log import log
from oslo_serialization import jsonutils
from oslo_utils import timeutils
import six
import sqlalchemy as sa
from sqlalchemy import and_
from sqlalchemy import distinct
from sqlalchemy import func
from sqlalchemy.orm import aliased
from sqlalchemy.sql.expression import cast

import ceilometer
from ceilometer.i18n import _, _LI
from ceilometer import storage
from ceilometer.storage import base
from ceilometer.storage import models as api_models
from ceilometer.storage.sqlalchemy import models
from ceilometer.storage.sqlalchemy import utils as sql_utils
from ceilometer import utils

LOG = log.getLogger(__name__)

STANDARD_AGGREGATES = dict(
    avg=func.avg(models.Sample.volume).label('avg'),
    sum=func.sum(models.Sample.volume).label('sum'),
    min=func.min(models.Sample.volume).label('min'),
    max=func.max(models.Sample.volume).label('max'),
    count=func.count(models.Sample.volume).label('count')
)

UNPARAMETERIZED_AGGREGATES = dict(
    stddev=func.stddev_pop(models.Sample.volume).label('stddev')
)

PARAMETERIZED_AGGREGATES = dict(
    validate=dict(
        cardinality=lambda p: p in ['resource_id', 'user_id', 'project_id']
    ),
    compute=dict(
        cardinality=lambda p: func.count(
            distinct(getattr(models.Resource, p))
        ).label('cardinality/%s' % p)
    )
)

AVAILABLE_CAPABILITIES = {
    'meters': {'query': {'simple': True,
                         'metadata': True}},
    'resources': {'query': {'simple': True,
                            'metadata': True}},
    'samples': {'query': {'simple': True,
                          'metadata': True,
                          'complex': True}},
    'statistics': {'groupby': True,
                   'query': {'simple': True,
                             'metadata': True},
                   'aggregation': {'standard': True,
                                   'selectable': {
                                       'max': True,
                                       'min': True,
                                       'sum': True,
                                       'avg': True,
                                       'count': True,
                                       'stddev': True,
                                       'cardinality': True}}
                   },
}

AVAILABLE_STORAGE_CAPABILITIES = {
    'storage': {'production_ready': True},
}

def apply_metaquery_filter(session, query, metaquery):
    """Apply provided metaquery filter to existing query.

    :param session: session used for original query
    :param query: Query instance
    :param metaquery: dict with metadata to match on.
    """
    for k, value in six.iteritems(metaquery):
        key = k[9:]  # strip out 'metadata.' prefix
        try:
            _model = sql_utils.META_TYPE_MAP[type(value)]
        except KeyError:
            raise ceilometer.NotImplementedError(
                'Query on %(key)s is of %(value)s '
                'type and is not supported' %
                {"key": k, "value": type(value)})
        else:
            meta_alias = aliased(_model)
            on_clause = and_(models.Resource.internal_id == meta_alias.id,
                             meta_alias.meta_key == key)
            # outer join is needed to support metaquery
            # with or operator on non existent metadata field
            # see: test_query_non_existing_metadata_with_result
            # test case.
            query = query.outerjoin(meta_alias, on_clause)
            query = query.filter(meta_alias.value == value)

    return query

def make_query_from_filter(session, query, sample_filter, require_meter=True):
    """Return a query dictionary based on the settings in the filter.

    :param session: session used for original query
    :param query: Query instance
    :param sample_filter: SampleFilter instance
    :param require_meter: If true and the filter does not have a meter,
                          raise an error.
    """

    if sample_filter.meter:
        query = query.filter(models.Meter.name == sample_filter.meter)
    elif require_meter:
        raise RuntimeError('Missing required meter specifier')
    if sample_filter.source:
        query = query.filter(
            models.Resource.source_id == sample_filter.source)
    if sample_filter.start_timestamp:
        ts_start = sample_filter.start_timestamp
        if sample_filter.start_timestamp_op == 'gt':
            query = query.filter(models.Sample.timestamp > ts_start)
        else:
            query = query.filter(models.Sample.timestamp >= ts_start)
    if sample_filter.end_timestamp:
        ts_end = sample_filter.end_timestamp
        if sample_filter.end_timestamp_op == 'le':
            query = query.filter(models.Sample.timestamp <= ts_end)
        else:
            query = query.filter(models.Sample.timestamp < ts_end)
    if sample_filter.user:
        query = query.filter(models.Resource.user_id == sample_filter.user)
    if sample_filter.project:
        query = query.filter(
            models.Resource.project_id == sample_filter.project)
    if sample_filter.resource:
        query = query.filter(
            models.Resource.resource_id == sample_filter.resource)
    if sample_filter.message_id:
        query = query.filter(
            models.Sample.message_id == sample_filter.message_id)

    if sample_filter.metaquery:
        query = apply_metaquery_filter(session, query,
                                       sample_filter.metaquery)

    return query

class Connection(base.Connection):
    """Put the data into a SQLAlchemy database.

    Tables::

        - meter
          - meter definition
          - { id: meter id
              name: meter name
              type: meter type
              unit: meter unit
              }
        - resource
          - resource definition
          - { internal_id: resource id
              resource_id: resource uuid
              user_id: user uuid
              project_id: project uuid
              source_id: source id
              resource_metadata: metadata dictionary
              metadata_hash: metadata dictionary hash
              }
        - sample
          - the raw incoming data
          - { id: sample id
              meter_id: meter id            (->meter.id)
              resource_id: resource id      (->resource.internal_id)
              volume: sample volume
              timestamp: datetime
              recorded_at: datetime
              message_signature: message signature
              message_id: message uuid
              }
    """
    CAPABILITIES = utils.update_nested(base.Connection.CAPABILITIES,
                                       AVAILABLE_CAPABILITIES)
    STORAGE_CAPABILITIES = utils.update_nested(
        base.Connection.STORAGE_CAPABILITIES,
        AVAILABLE_STORAGE_CAPABILITIES,
    )

    def __init__(self, url):
        # Set max_retries to 0, since oslo.db in certain cases may attempt
        # to retry making the db connection retried max_retries ^ 2 times
        # in failure case and db reconnection has already been implemented
        # in storage.__init__.get_connection_from_config function
        options = dict(cfg.CONF.database.items())
        options['max_retries'] = 0
        self._engine_facade = db_session.EngineFacade(url, **options)

    def upgrade(self):
        # NOTE(gordc): to minimise memory, only import migration when needed
        from oslo_db.sqlalchemy import migration
        path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                            'sqlalchemy', 'migrate_repo')
        migration.db_sync(self._engine_facade.get_engine(), path)

    def clear(self):
        engine = self._engine_facade.get_engine()
        for table in reversed(models.Base.metadata.sorted_tables):
            engine.execute(table.delete())
        engine.dispose()

    @staticmethod
    def _create_meter(conn, name, type, unit):
        # TODO(gordc): implement lru_cache to improve performance
        try:
            meter = models.Meter.__table__
            trans = conn.begin_nested()
            if conn.dialect.name == 'sqlite':
                trans = conn.begin()
            with trans:
                meter_row = conn.execute(
                    sa.select([meter.c.id])
                    .where(sa.and_(meter.c.name == name,
                                   meter.c.type == type,
                                   meter.c.unit == unit))).first()
                meter_id = meter_row[0] if meter_row else None
                if meter_id is None:
                    result = conn.execute(meter.insert(), name=name,
                                          type=type, unit=unit)
                    meter_id = result.inserted_primary_key[0]
        except dbexc.DBDuplicateEntry:
            # retry function to pick up duplicate committed object
            meter_id = Connection._create_meter(conn, name, type, unit)

        return meter_id

    @staticmethod
    def _create_resource(conn, res_id, user_id, project_id, source_id,
                         rmeta):
        # TODO(gordc): implement lru_cache to improve performance
        try:
            res = models.Resource.__table__
            m_hash = jsonutils.dumps(rmeta, sort_keys=True)
            if six.PY3:
                m_hash = m_hash.encode('utf-8')
            m_hash = hashlib.md5(m_hash).hexdigest()
            trans = conn.begin_nested()
            if conn.dialect.name == 'sqlite':
                trans = conn.begin()
            with trans:
                res_row = conn.execute(
                    sa.select([res.c.internal_id])
                    .where(sa.and_(res.c.resource_id == res_id,
                                   res.c.user_id == user_id,
                                   res.c.project_id == project_id,
                                   res.c.source_id == source_id,
                                   res.c.metadata_hash == m_hash))).first()
                internal_id = res_row[0] if res_row else None
                if internal_id is None:
                    result = conn.execute(res.insert(), resource_id=res_id,
                                          user_id=user_id,
                                          project_id=project_id,
                                          source_id=source_id,
                                          resource_metadata=rmeta,
                                          metadata_hash=m_hash)
                    internal_id = result.inserted_primary_key[0]
                    if rmeta and isinstance(rmeta, dict):
                        meta_map = {}
                        for key, v in utils.dict_to_keyval(rmeta):
                            try:
                                _model = sql_utils.META_TYPE_MAP[type(v)]
                                if meta_map.get(_model) is None:
                                    meta_map[_model] = []
                                meta_map[_model].append(
                                    {'id': internal_id, 'meta_key': key,
                                     'value': v})
                            except KeyError:
                                LOG.warn(_("Unknown metadata type. Key (%s) "
                                         "will not be queryable."), key)
                        for _model in meta_map.keys():
                            conn.execute(_model.__table__.insert(),
                                         meta_map[_model])

        except dbexc.DBDuplicateEntry:
            # retry function to pick up duplicate committed object
            internal_id = Connection._create_resource(
                conn, res_id, user_id, project_id, source_id, rmeta)

        return internal_id

    @api.wrap_db_retry(retry_interval=cfg.CONF.database.retry_interval,
                       max_retries=cfg.CONF.database.max_retries,
                       retry_on_deadlock=True)
    def record_metering_data(self, data):
        """Write the data to the backend storage system.

        :param data: a dictionary such as returned by
                     ceilometer.meter.meter_message_from_counter
        """
        engine = self._engine_facade.get_engine()
        with engine.begin() as conn:
            # Record the raw data for the sample.
            m_id = self._create_meter(conn,
                                      data['counter_name'],
                                      data['counter_type'],
                                      data['counter_unit'])
            res_id = self._create_resource(conn,
                                           data['resource_id'],
                                           data['user_id'],
                                           data['project_id'],
                                           data['source'],
                                           data['resource_metadata'])
            sample = models.Sample.__table__
            conn.execute(sample.insert(), meter_id=m_id,
                         resource_id=res_id,
                         timestamp=data['timestamp'],
                         volume=data['counter_volume'],
                         message_signature=data['message_signature'],
                         message_id=data['message_id'])

    def clear_expired_metering_data(self, ttl):
        """Clear expired data from the backend storage system.

        Clearing occurs according to the time-to-live.
        :param ttl: Number of seconds to keep records for.
        """
        # Prevent database deadlocks from occurring by
        # using separate transaction for each delete
        session = self._engine_facade.get_session()
        with session.begin():
            end = timeutils.utcnow() - datetime.timedelta(seconds=ttl)
            sample_q = (session.query(models.Sample)
                        .filter(models.Sample.timestamp < end))
            rows = sample_q.delete()
            LOG.info(_LI("%d samples removed from database"), rows)

        if not cfg.CONF.sql_expire_samples_only:
            with session.begin():
                # remove Meter definitions with no matching samples
                (session.query(models.Meter)
                 .filter(~models.Meter.samples.any())
                 .delete(synchronize_session=False))

            with session.begin():
                resource_q = (session.query(models.Resource.internal_id)
                              .filter(~models.Resource.samples.any()))
                # mark resource with no matching samples for delete
                resource_q.update({models.Resource.metadata_hash: "delete_"
                                  + cast(models.Resource.internal_id,
                                         sa.String)},
                                  synchronize_session=False)

            # remove metadata of resources marked for delete
            for table in [models.MetaText, models.MetaBigInt,
                          models.MetaFloat, models.MetaBool]:
                with session.begin():
                    resource_q = (session.query(models.Resource.internal_id)
                                  .filter(models.Resource.metadata_hash
                                          .like('delete_%')))
                    resource_subq = resource_q.subquery()
                    (session.query(table)
                     .filter(table.id.in_(resource_subq))
                     .delete(synchronize_session=False))

            # remove resource marked for delete
            with session.begin():
                resource_q = (session.query(models.Resource.internal_id)
                              .filter(models.Resource.metadata_hash
                                      .like('delete_%')))
                resource_q.delete(synchronize_session=False)
            LOG.info(_LI("Expired residual resource and"
                         " meter definition data"))

    def get_resources(self, user=None, project=None, source=None,
                      start_timestamp=None, start_timestamp_op=None,
                      end_timestamp=None, end_timestamp_op=None,
                      metaquery=None, resource=None, limit=None):
        """Return an iterable of api_models.Resource instances

        :param user: Optional ID for user that owns the resource.
        :param project: Optional ID for project that owns the resource.
        :param source: Optional source filter.
        :param start_timestamp: Optional modified timestamp start range.
        :param start_timestamp_op: Optional start time operator, like gt, ge.
        :param end_timestamp: Optional modified timestamp end range.
        :param end_timestamp_op: Optional end time operator, like lt, le.
        :param metaquery: Optional dict with metadata to match on.
        :param resource: Optional resource filter.
        :param limit: Maximum number of results to return.
        """
        if limit == 0:
            return
        s_filter = storage.SampleFilter(user=user,
                                        project=project,
                                        source=source,
                                        start_timestamp=start_timestamp,
                                        start_timestamp_op=start_timestamp_op,
                                        end_timestamp=end_timestamp,
                                        end_timestamp_op=end_timestamp_op,
                                        metaquery=metaquery,
                                        resource=resource)

        session = self._engine_facade.get_session()
        # get list of resource_ids
        res_q = session.query(distinct(models.Resource.resource_id)).join(
            models.Sample,
            models.Sample.resource_id == models.Resource.internal_id)
        res_q = make_query_from_filter(session, res_q, s_filter,
                                       require_meter=False)
        res_q = res_q.limit(limit) if limit else res_q
        for res_id in res_q.all():

            # get max and min sample timestamp value
            min_max_q = (session.query(func.max(models.Sample.timestamp)
                                       .label('max_timestamp'),
                                       func.min(models.Sample.timestamp)
                                       .label('min_timestamp'))
                                .join(models.Resource,
                                      models.Resource.internal_id ==
                                      models.Sample.resource_id)
                                .filter(models.Resource.resource_id ==
                                        res_id[0]))

            min_max_q = make_query_from_filter(session, min_max_q, s_filter,
                                               require_meter=False)

            min_max = min_max_q.first()

            # get resource details for latest sample
            res_q = (session.query(models.Resource.resource_id,
                                   models.Resource.user_id,
                                   models.Resource.project_id,
                                   models.Resource.source_id,
                                   models.Resource.resource_metadata)
                            .join(models.Sample,
                                  models.Sample.resource_id ==
                                  models.Resource.internal_id)
                            .filter(models.Sample.timestamp ==
                                    min_max.max_timestamp)
                            .filter(models.Resource.resource_id ==
                                    res_id[0])
                            .order_by(models.Sample.id.desc()).limit(1))

            res = res_q.first()

            yield api_models.Resource(
                resource_id=res.resource_id,
                project_id=res.project_id,
                first_sample_timestamp=min_max.min_timestamp,
                last_sample_timestamp=min_max.max_timestamp,
                source=res.source_id,
                user_id=res.user_id,
                metadata=res.resource_metadata
            )

    def get_meters(self, user=None, project=None, resource=None, source=None,
                   metaquery=None, limit=None):
        """Return an iterable of api_models.Meter instances

        :param user: Optional ID for user that owns the resource.
        :param project: Optional ID for project that owns the resource.
        :param resource: Optional ID of the resource.
        :param source: Optional source filter.
        :param metaquery: Optional dict with metadata to match on.
        :param limit: Maximum number of results to return.
        """
        if limit == 0:
            return
        s_filter = storage.SampleFilter(user=user,
                                        project=project,
                                        source=source,
                                        metaquery=metaquery,
                                        resource=resource)

        # NOTE(gordc): get latest sample of each meter/resource. we do not
        #              filter here as we want to filter only on latest record.
        session = self._engine_facade.get_session()
        subq = session.query(func.max(models.Sample.id).label('id')).join(
            models.Resource,
            models.Resource.internal_id == models.Sample.resource_id).group_by(
            models.Sample.meter_id, models.Resource.resource_id)
        if resource:
            subq = subq.filter(models.Resource.resource_id == resource)
        subq = subq.subquery()

        # get meter details for samples.
        query_sample = (session.query(models.Sample.meter_id,
                                      models.Meter.name, models.Meter.type,
                                      models.Meter.unit,
                                      models.Resource.resource_id,
                                      models.Resource.project_id,
                                      models.Resource.source_id,
                                      models.Resource.user_id).join(
            subq, subq.c.id == models.Sample.id)
            .join(models.Meter, models.Meter.id == models.Sample.meter_id)
            .join(models.Resource,
                  models.Resource.internal_id == models.Sample.resource_id))
        query_sample = make_query_from_filter(session, query_sample, s_filter,
                                              require_meter=False)

        query_sample = query_sample.limit(limit) if limit else query_sample
        for row in query_sample.all():
            yield api_models.Meter(
                name=row.name,
                type=row.type,
                unit=row.unit,
                resource_id=row.resource_id,
                project_id=row.project_id,
                source=row.source_id,
                user_id=row.user_id)

    @staticmethod
    def _retrieve_samples(query):
        samples = query.all()

        for s in samples:
            # Remove the id generated by the database when
            # the sample was inserted. It is an implementation
            # detail that should not leak outside of the driver.
            yield api_models.Sample(
                source=s.source_id,
                counter_name=s.counter_name,
                counter_type=s.counter_type,
                counter_unit=s.counter_unit,
                counter_volume=s.counter_volume,
                user_id=s.user_id,
                project_id=s.project_id,
                resource_id=s.resource_id,
                timestamp=s.timestamp,
                recorded_at=s.recorded_at,
                resource_metadata=s.resource_metadata,
                message_id=s.message_id,
                message_signature=s.message_signature,
            )

    def get_samples(self, sample_filter, limit=None):
        """Return an iterable of api_models.Samples.

        :param sample_filter: Filter.
        :param limit: Maximum number of results to return.
        """
        if limit == 0:
            return []

        session = self._engine_facade.get_session()
        query = session.query(models.Sample.timestamp,
                              models.Sample.recorded_at,
                              models.Sample.message_id,
                              models.Sample.message_signature,
                              models.Sample.volume.label('counter_volume'),
                              models.Meter.name.label('counter_name'),
                              models.Meter.type.label('counter_type'),
                              models.Meter.unit.label('counter_unit'),
                              models.Resource.source_id,
                              models.Resource.user_id,
                              models.Resource.project_id,
                              models.Resource.resource_metadata,
                              models.Resource.resource_id).join(
            models.Meter, models.Meter.id == models.Sample.meter_id).join(
            models.Resource,
            models.Resource.internal_id == models.Sample.resource_id).order_by(
            models.Sample.timestamp.desc())
        query = make_query_from_filter(session, query, sample_filter,
                                       require_meter=False)
        if limit:
            query = query.limit(limit)
        return self._retrieve_samples(query)

    def query_samples(self, filter_expr=None, orderby=None, limit=None):
        if limit == 0:
            return []

        session = self._engine_facade.get_session()
        engine = self._engine_facade.get_engine()
        query = session.query(models.FullSample)
        transformer = sql_utils.QueryTransformer(models.FullSample, query,
                                                 dialect=engine.dialect.name)
        if filter_expr is not None:
            transformer.apply_filter(filter_expr)

        transformer.apply_options(orderby, limit)
        return self._retrieve_samples(transformer.get_query())

    @staticmethod
    def _get_aggregate_functions(aggregate):
        if not aggregate:
            return [f for f in STANDARD_AGGREGATES.values()]

        functions = []

        for a in aggregate:
            if a.func in STANDARD_AGGREGATES:
                functions.append(STANDARD_AGGREGATES[a.func])
            elif a.func in UNPARAMETERIZED_AGGREGATES:
                functions.append(UNPARAMETERIZED_AGGREGATES[a.func])
            elif a.func in PARAMETERIZED_AGGREGATES['compute']:
                validate = PARAMETERIZED_AGGREGATES['validate'].get(a.func)
                if not (validate and validate(a.param)):
                    raise storage.StorageBadAggregate('Bad aggregate: %s.%s'
                                                      % (a.func, a.param))
                compute = PARAMETERIZED_AGGREGATES['compute'][a.func]
                functions.append(compute(a.param))
            else:
                raise ceilometer.NotImplementedError(
                    'Selectable aggregate function %s'
                    ' is not supported' % a.func)

        return functions

    def _make_stats_query(self, sample_filter, groupby, aggregate):

        select = [
            func.min(models.Sample.timestamp).label('tsmin'),
            func.max(models.Sample.timestamp).label('tsmax'),
            models.Meter.unit
        ]
        select.extend(self._get_aggregate_functions(aggregate))

        session = self._engine_facade.get_session()

        if groupby:
            group_attributes = []
            for g in groupby:
                if g != 'resource_metadata.instance_type':
                    group_attributes.append(getattr(models.Resource, g))
                else:
                    group_attributes.append(
                        getattr(models.MetaText, 'value')
                        .label('resource_metadata.instance_type'))

            select.extend(group_attributes)

        query = (
            session.query(*select)
            .join(models.Meter,
                  models.Meter.id == models.Sample.meter_id)
            .join(models.Resource,
                  models.Resource.internal_id == models.Sample.resource_id)
            .group_by(models.Meter.unit))

        if groupby:
            for g in groupby:
                if g == 'resource_metadata.instance_type':
                    query = query.join(
                        models.MetaText,
                        models.Resource.internal_id == models.MetaText.id)
                    query = query.filter(
                        models.MetaText.meta_key == 'instance_type')
            query = query.group_by(*group_attributes)

        return make_query_from_filter(session, query, sample_filter)

    @staticmethod
    def _stats_result_aggregates(result, aggregate):
        stats_args = {}
        if isinstance(result.count, six.integer_types):
            stats_args['count'] = result.count
        for attr in ['min', 'max', 'sum', 'avg']:
            if hasattr(result, attr):
                stats_args[attr] = getattr(result, attr)
        if aggregate:
            stats_args['aggregate'] = {}
            for a in aggregate:
                key = '%s%s' % (a.func, '/%s' % a.param if a.param else '')
                stats_args['aggregate'][key] = getattr(result, key)
        return stats_args

    @staticmethod
    def _stats_result_to_model(result, period, period_start,
                               period_end, groupby, aggregate):
        stats_args = Connection._stats_result_aggregates(result, aggregate)
        stats_args['unit'] = result.unit
        duration = (timeutils.delta_seconds(result.tsmin, result.tsmax)
                    if result.tsmin is not None and result.tsmax is not None
                    else None)
        stats_args['duration'] = duration
        stats_args['duration_start'] = result.tsmin
        stats_args['duration_end'] = result.tsmax
        stats_args['period'] = period
        stats_args['period_start'] = period_start
        stats_args['period_end'] = period_end
        stats_args['groupby'] = (dict(
            (g, getattr(result, g)) for g in groupby) if groupby else None)
        return api_models.Statistics(**stats_args)

    def get_meter_statistics(self, sample_filter, period=None, groupby=None,
                             aggregate=None):
        """Return an iterable of api_models.Statistics instances.

        Items are containing meter statistics described by the query
        parameters. The filter must have a meter value set.
        """
        if groupby:
            for group in groupby:
                if group not in ['user_id', 'project_id', 'resource_id',
                                 'resource_metadata.instance_type']:
                    raise ceilometer.NotImplementedError('Unable to group by '
                                                         'these fields')

        if not period:
            for res in self._make_stats_query(sample_filter,
                                              groupby,
                                              aggregate):
                if res.count:
                    yield self._stats_result_to_model(res, 0,
                                                      res.tsmin, res.tsmax,
                                                      groupby,
                                                      aggregate)
            return

        if not (sample_filter.start_timestamp and sample_filter.end_timestamp):
            res = self._make_stats_query(sample_filter,
                                         None,
                                         aggregate).first()
            if not res:
                # NOTE(liusheng):The 'res' may be NoneType, because no
                # sample has found with sample filter(s).
                return

        query = self._make_stats_query(sample_filter, groupby, aggregate)
        # HACK(jd) This is an awful method to compute stats by period, but
        # since we're trying to be SQL agnostic we have to write portable
        # code, so here it is, admire! We're going to do one request to get
        # stats by period. We would like to use GROUP BY, but there's no
        # portable way to manipulate timestamp in SQL, so we can't.
        for period_start, period_end in base.iter_period(
                sample_filter.start_timestamp or res.tsmin,
                sample_filter.end_timestamp or res.tsmax,
                period):
            q = query.filter(models.Sample.timestamp >= period_start)
            q = q.filter(models.Sample.timestamp < period_end)
            for r in q.all():
                if r.count:
                    yield self._stats_result_to_model(
                        result=r,
                        period=int(timeutils.delta_seconds(period_start,
                                                           period_end)),
                        period_start=period_start,
                        period_end=period_end,
                        groupby=groupby,
                        aggregate=aggregate
                    )


text:
from django.db import models
from candidatos.models import Candidato
from jornadas.models import Jornada_Corporacion

class Plancha(models.Model):
    numeroplancha = models.IntegerField(null=False, unique=False)
    jornada_corporacion = models.ForeignKey(Jornada_Corporacion, null=False)
    candidato_principal = models.ForeignKey(Candidato, null=True, related_name='principal')
    candidato_suplente = models.ForeignKey(Candidato, null=True, blank=True, unique=False, default=None)
    is_active = models.BooleanField(default=True)
    url_propuesta = models.URLField(null=True, blank=True)
    num_votos = models.IntegerField(null=True, default= 0)

    class Meta:
        ordering = ["numeroplancha"]
        db_table = 'planchas'

    def __str__(self):
        return '%s - %s  %s - %s - %s' % (self.numeroplancha, self.jornada_corporacion.corporacion, self.candidato_principal,
                                     self.candidato_suplente, self.url_propuesta)