text:
require 'spec_helper'
require 'shared-examples'
manifest = 'openstack-network/server-config.pp'

describe manifest do
  shared_examples 'catalog' do
    if (Noop.hiera('use_neutron') == true and Noop.hiera('role') =~ /controller/)

      let(:facts) {
        Noop.ubuntu_facts.merge({
          :processorcount => '6'
        })
      }

      let(:processorcount) do
        6
      end

      context 'with Neutron-server' do
        neutron_config = Noop.hiera_hash('neutron_config')
        management_vip = Noop.hiera('management_vip')
        service_endpoint = Noop.hiera('service_endpoint', management_vip)

        it 'database options' do
          database_vip        = Noop.hiera('database_vip')
          neutron_db_password = neutron_config.fetch('database', {}).fetch('passwd')
          neutron_db_user     = neutron_config.fetch('database', {}).fetch('user', 'neutron')
          neutron_db_name     = neutron_config.fetch('database', {}).fetch('name', 'neutron')
          neutron_db_host     = neutron_config.fetch('database', {}).fetch('host', database_vip)
          neutron_db_uri = "mysql://#{neutron_db_user}:#{neutron_db_password}@#{neutron_db_host}/#{neutron_db_name}?&read_timeout=60"
          should contain_class('neutron::server').with(
            'sync_db'                 => 'false',
            'database_retry_interval' => '2',
            'database_connection'     => neutron_db_uri,
            'database_max_retries'    => '-1',
          )
        end

        it 'auth options' do
          identity_uri     = "http://#{service_endpoint}:5000/"
          ks = neutron_config['keystone']
          should contain_class('neutron::server').with(
            'auth_password' => ks.fetch('admin_password'),
            'auth_tenant'   => ks.fetch('admin_tenant', 'services'),
            'auth_region'   => Noop.hiera('region', 'RegionOne'),
            'auth_user'     => ks.fetch('admin_user', 'neutron'),
            'identity_uri'  => identity_uri,
            'auth_uri'      => identity_uri,
          )
        end

        it { should contain_class('neutron::server').with('manage_service' => 'true')}
        it { should contain_class('neutron::server').with('enabled' => 'false')} # bacause server should be started after plugin configured
        it { should contain_class('neutron::server').with('agent_down_time' => '30')}
        it { should contain_class('neutron::server').with('allow_automatic_l3agent_failover' => 'true')}

        it 'dvr' do
          dvr = Noop.hiera_hash('neutron_advanced_configuration', {}).fetch('neutron_dvr', false)
          should contain_class('neutron::server').with('router_distributed' => dvr)
        end

        it 'worker count' do
          fallback_workers = [[processorcount, 2].max, 16].min
          workers = neutron_config.fetch('workers', fallback_workers)
          should contain_class('neutron::server').with(
            'api_workers' => workers,
            'rpc_workers' => workers,
          )
        end

        it 'neutron::server::notifications' do
          nova_admin_auth_url = "http://#{service_endpoint}:35357/"
          nova_endpoint       = Noop.hiera('nova_endpoint', management_vip)
          nova_url            = "http://#{nova_endpoint}:8774/v2"
          nova_hash           = Noop.hiera_hash('nova', {})
          should contain_class('neutron::server::notifications').with(
            'nova_url'    => nova_url,
            'auth_url'    => nova_admin_auth_url,
            'region_name' => Noop.hiera('region', 'RegionOne'),
            'username'    => nova_hash.fetch('user', 'nova'),
            'tenant_name' => nova_hash.fetch('tenant', 'services'),
            'password'    => nova_hash.fetch('user_password'),
          )
        end

        it { should contain_service('neutron-server').with(
          'ensure' => 'stopped',
          'enable' => 'false',
        )}

      end
    end
  end
  test_ubuntu_and_centos manifest
end


text:
@echo off

echo ==================================
echo = GENERATE THE KAFKAGUST JAVADOC =
echo ==================================

set MODULE_DIR=%~dp0

set WORK_DIR=%MODULE_DIR%\.gen

set LOG_FILE_NAME=Gen_Javadoc.log
set LOG_DIR=log
if not exist "%WORK_DIR%\%LOG_DIR%" (
    mkdir "%WORK_DIR%\%LOG_DIR%"
)

echo.
echo - Please wait...
call "%M2_HOME%\bin\mvn" generate-sources javadoc:javadoc > "%WORK_DIR%\%LOG_DIR%\%LOG_FILE_NAME%"

echo.
echo [ GENERATION ENDED ]
echo.
echo - Logs in the file ".\.gen\%LOG_DIR%\%LOG_FILE_NAME%".
echo.

pause

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Servelat\Base;

/**
 * Interface ComponentInterface.
 * Servelat Component interface.
 *
 * @author Ivan Zinovyev <vanyazin@gmail.com>
 */
interface ComponentInterface
{
    /**
     * Get the name of the component.
     * Used to register unique component.
     *
     * @return string
     */
    public function getName();

    /**
     * Register component.
     * Component can access application configuration, dispatcher and
     *
     * @param AbstractApplication $application
     * @return mixed
     */
    public function register(AbstractApplication $application);
}


text:
<?php

namespace JVJ\PlantillaBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class JVJPlantillaBundle extends Bundle
{
}


text:
var generators = require('yeoman-generator');
var inquirer = require("inquirer");
var chalk = require('chalk');
var yosay = require('yosay');

module.exports = generators.Base.extend({

    initializing: function () {
        this.store = {
            "bower-dependencies": []
        }
    },

    writing: function () {
        // App directory structure
        this.directory('app', 'app');
        this.directory('specs', 'specs');

        this.template('_bower.json', 'bower.json');
        this.template('_.bowerrc', '.bowerrc');
        this.template('_package.json', 'package.json');
        this.template('_gulpfile.js', 'gulpfile.js');
        this.template('_.gitignore', '.gitignore');
        this.template('_index.jade', './app/index.jade');
        this.template('_conf.js', 'conf.js');
    },

    install: function () {
        this.installDependencies();
    },

    end: function () {
        this.log(yosay('Almost done! ' + chalk.green('running default gulp task')));
        this.spawnCommand('node_modules/gulp/bin/gulp.js');
    }
});


text:
![My Site Index Wireframe](/phase-0/week-2/imgs/wireframe-index.png)
![My Blog Wireframe](/phase-0/week-2/imgs/wireframe-blog-index.png)

**1. What is a wireframe?**

 A wireframe is the layout of the elements of the webpage.

**2. What are the benefits of wireframing?**

The functionality of the webpage can be adjusted to how the developer wants the user to interact and navigate with the web page without the distraction of colors or typeface.

**3. Did you enjoy wireframing your site?**

I would prefer proceeding from sketch to visual.

**4. Did you revise your wireframe or stick with your first idea?**

I stuck with my first idea.

**5. What questions did you ask during this challenge? What resources did you find to help you answer them?**

How does the target user think? What are his aims and interests? What qualities of me would he like to find while navigating my web-site? What tools, colors, organisation of information can help to present my mindset, skills, interests to the user?

At the end of the day, I'm looking for likely-minded users who can become my employers or customers.

I read articles from Smashingmagazine.

**6. Which parts of the challenge did you enjoy and which parts did you find tedious?**

I found making a wireframe tedious.


text:
package org.alicebot.ab;

public class Clause {
  public String subj;
  public String pred;
  public String obj;
  public Boolean affirm;

  public Clause(String s, String p, String o) {
    this(s, p, o, true);
  }

  public Clause(String s, String p, String o, Boolean affirm) {
    subj = s;
    pred = p;
    obj = o;
    this.affirm = affirm;
  }

  public Clause(Clause clause) {
    this(clause.subj, clause.pred, clause.obj, clause.affirm);
  }
}


text:
"""Unit tests for Superset"""
from datetime import datetime
import imp
import json
from contextlib import contextmanager
from typing import Any, Dict, Union, List, Optional
from unittest.mock import Mock, patch, MagicMock

import pandas as pd
from flask import Response
from flask_appbuilder.security.sqla import models as ab_models
from flask_testing import TestCase
from sqlalchemy.engine.interfaces import Dialect
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.orm import Session
from sqlalchemy.sql import func
from sqlalchemy.dialects.mysql import dialect

from tests.integration_tests.test_app import app, login
from superset.sql_parse import CtasMethod
from superset import db, security_manager
from superset.connectors.base.models import BaseDatasource
from superset.connectors.sqla.models import SqlaTable
from superset.models import core as models
from superset.models.slice import Slice
from superset.models.core import Database
from superset.models.dashboard import Dashboard
from superset.models.datasource_access_request import DatasourceAccessRequest
from superset.utils.core import get_example_default_schema
from superset.utils.database import get_example_database
from superset.views.base_api import BaseSupersetModelRestApi

FAKE_DB_NAME = "fake_db_100"
test_client = app.test_client()

def get_resp(
    client: Any,
    url: str,
    data: Any = None,
    follow_redirects: bool = True,
    raise_on_error: bool = True,
    json_: Optional[str] = None,
):
    """Shortcut to get the parsed results while following redirects"""
    if data:
        resp = client.post(url, data=data, follow_redirects=follow_redirects)
    elif json_:
        resp = client.post(url, json=json_, follow_redirects=follow_redirects)
    else:
        resp = client.get(url, follow_redirects=follow_redirects)
    if raise_on_error and resp.status_code > 400:
        raise Exception("http request failed with code {}".format(resp.status_code))
    return resp.data.decode("utf-8")

def post_assert_metric(
    client: Any, uri: str, data: Dict[str, Any], func_name: str
) -> Response:
    """
    Simple client post with an extra assertion for statsd metrics

    :param client: test client for superset api requests
    :param uri: The URI to use for the HTTP POST
    :param data: The JSON data payload to be posted
    :param func_name: The function name that the HTTP POST triggers
    for the statsd metric assertion
    :return: HTTP Response
    """
    with patch.object(
        BaseSupersetModelRestApi, "incr_stats", return_value=None
    ) as mock_method:
        rv = client.post(uri, json=data)
    if 200 <= rv.status_code < 400:
        mock_method.assert_called_once_with("success", func_name)
    else:
        mock_method.assert_called_once_with("error", func_name)
    return rv

class SupersetTestCase(TestCase):
    default_schema_backend_map = {
        "sqlite": "main",
        "mysql": "superset",
        "postgresql": "public",
        "presto": "default",
        "hive": "default",
    }

    maxDiff = -1

    def create_app(self):
        return app

    @staticmethod
    def get_nonexistent_numeric_id(model):
        return (db.session.query(func.max(model.id)).scalar() or 0) + 1

    @staticmethod
    def get_birth_names_dataset() -> SqlaTable:
        return SupersetTestCase.get_table(name="birth_names")

    @staticmethod
    def create_user_with_roles(
        username: str, roles: List[str], should_create_roles: bool = False
    ):
        user_to_create = security_manager.find_user(username)
        if not user_to_create:
            security_manager.add_user(
                username,
                username,
                username,
                f"{username}@superset.com",
                security_manager.find_role("Gamma"),  # it needs a role
                password="general",
            )
            db.session.commit()
            user_to_create = security_manager.find_user(username)
            assert user_to_create
        user_to_create.roles = []
        for chosen_user_role in roles:
            if should_create_roles:
                # copy role from gamma but without data permissions
                security_manager.copy_role("Gamma", chosen_user_role, merge=False)
            user_to_create.roles.append(security_manager.find_role(chosen_user_role))
        db.session.commit()
        return user_to_create

    @staticmethod
    def create_user(
        username: str,
        password: str,
        role_name: str,
        first_name: str = "admin",
        last_name: str = "user",
        email: str = "admin@fab.org",
    ) -> Union[ab_models.User, bool]:
        role_admin = security_manager.find_role(role_name)
        return security_manager.add_user(
            username, first_name, last_name, email, role_admin, password
        )

    @staticmethod
    def get_user(username: str) -> ab_models.User:
        user = (
            db.session.query(security_manager.user_model)
            .filter_by(username=username)
            .one_or_none()
        )
        return user

    @staticmethod
    def get_role(name: str) -> Optional[ab_models.User]:
        user = (
            db.session.query(security_manager.role_model)
            .filter_by(name=name)
            .one_or_none()
        )
        return user

    @staticmethod
    def get_table_by_id(table_id: int) -> SqlaTable:
        return db.session.query(SqlaTable).filter_by(id=table_id).one()

    @staticmethod
    def is_module_installed(module_name):
        try:
            imp.find_module(module_name)
            return True
        except ImportError:
            return False

    def get_or_create(self, cls, criteria, session, **kwargs):
        obj = session.query(cls).filter_by(**criteria).first()
        if not obj:
            obj = cls(**criteria)
        obj.__dict__.update(**kwargs)
        session.add(obj)
        session.commit()
        return obj

    def login(self, username="admin", password="general"):
        return login(self.client, username, password)

    def get_slice(
        self, slice_name: str, session: Session, expunge_from_session: bool = True
    ) -> Slice:
        slc = session.query(Slice).filter_by(slice_name=slice_name).one()
        if expunge_from_session:
            session.expunge_all()
        return slc

    @staticmethod
    def get_table(
        name: str, database_id: Optional[int] = None, schema: Optional[str] = None
    ) -> SqlaTable:
        schema = schema or get_example_default_schema()

        return (
            db.session.query(SqlaTable)
            .filter_by(
                database_id=database_id
                or SupersetTestCase.get_database_by_name("examples").id,
                schema=schema,
                table_name=name,
            )
            .one()
        )

    @staticmethod
    def get_database_by_id(db_id: int) -> Database:
        return db.session.query(Database).filter_by(id=db_id).one()

    @staticmethod
    def get_database_by_name(database_name: str = "main") -> Database:
        if database_name == "examples":
            return get_example_database()
        else:
            raise ValueError("Database doesn't exist")

    @staticmethod
    def get_datasource_mock() -> BaseDatasource:
        datasource = MagicMock()
        results = Mock()
        results.query = Mock()
        results.status = Mock()
        results.error_message = None
        results.df = pd.DataFrame()
        datasource.type = "table"
        datasource.query = Mock(return_value=results)
        mock_dttm_col = Mock()
        datasource.get_col = Mock(return_value=mock_dttm_col)
        datasource.query = Mock(return_value=results)
        datasource.database = Mock()
        datasource.database.db_engine_spec = Mock()
        datasource.database.db_engine_spec.mutate_expression_label = lambda x: x
        datasource.owners = MagicMock()
        return datasource

    def get_resp(
        self, url, data=None, follow_redirects=True, raise_on_error=True, json_=None
    ):
        return get_resp(self.client, url, data, follow_redirects, raise_on_error, json_)

    def get_json_resp(
        self, url, data=None, follow_redirects=True, raise_on_error=True, json_=None
    ):
        """Shortcut to get the parsed results while following redirects"""
        resp = self.get_resp(url, data, follow_redirects, raise_on_error, json_)
        return json.loads(resp)

    def get_access_requests(self, username, ds_type, ds_id):
        DAR = DatasourceAccessRequest
        return (
            db.session.query(DAR)
            .filter(
                DAR.created_by == security_manager.find_user(username=username),
                DAR.datasource_type == ds_type,
                DAR.datasource_id == ds_id,
            )
            .first()
        )

    def logout(self):
        self.client.get("/logout/", follow_redirects=True)

    def grant_public_access_to_table(self, table):
        role_name = "Public"
        self.grant_role_access_to_table(table, role_name)

    def grant_role_access_to_table(self, table, role_name):
        role = security_manager.find_role(role_name)
        perms = db.session.query(ab_models.PermissionView).all()
        for perm in perms:
            if (
                perm.permission.name == "datasource_access"
                and perm.view_menu
                and table.perm in perm.view_menu.name
            ):
                security_manager.add_permission_role(role, perm)

    def revoke_public_access_to_table(self, table):
        role_name = "Public"
        self.revoke_role_access_to_table(role_name, table)

    def revoke_role_access_to_table(self, role_name, table):
        public_role = security_manager.find_role(role_name)
        perms = db.session.query(ab_models.PermissionView).all()
        for perm in perms:
            if (
                perm.permission.name == "datasource_access"
                and perm.view_menu
                and table.perm in perm.view_menu.name
            ):
                security_manager.del_permission_role(public_role, perm)

    def run_sql(
        self,
        sql,
        client_id=None,
        username=None,
        raise_on_error=False,
        query_limit=None,
        database_name="examples",
        sql_editor_id=None,
        select_as_cta=False,
        tmp_table_name=None,
        schema=None,
        ctas_method=CtasMethod.TABLE,
        template_params="{}",
    ):
        if username:
            self.logout()
            self.login(username=username)
        dbid = SupersetTestCase.get_database_by_name(database_name).id
        json_payload = {
            "database_id": dbid,
            "sql": sql,
            "client_id": client_id,
            "queryLimit": query_limit,
            "sql_editor_id": sql_editor_id,
            "ctas_method": ctas_method,
            "templateParams": template_params,
        }
        if tmp_table_name:
            json_payload["tmp_table_name"] = tmp_table_name
        if select_as_cta:
            json_payload["select_as_cta"] = select_as_cta
        if schema:
            json_payload["schema"] = schema

        resp = self.get_json_resp(
            "/superset/sql_json/", raise_on_error=False, json_=json_payload
        )
        if raise_on_error and "error" in resp:
            raise Exception("run_sql failed")
        return resp

    def create_fake_db(self):
        self.login(username="admin")
        database_name = FAKE_DB_NAME
        db_id = 100
        extra = """{
            "schemas_allowed_for_file_upload":
            ["this_schema_is_allowed", "this_schema_is_allowed_too"]
        }"""

        return self.get_or_create(
            cls=models.Database,
            criteria={"database_name": database_name},
            session=db.session,
            sqlalchemy_uri="sqlite:///:memory:",
            id=db_id,
            extra=extra,
        )

    def delete_fake_db(self):
        database = (
            db.session.query(Database)
            .filter(Database.database_name == FAKE_DB_NAME)
            .scalar()
        )
        if database:
            db.session.delete(database)

    def create_fake_db_for_macros(self):
        self.login(username="admin")
        database_name = "db_for_macros_testing"
        db_id = 200
        database = self.get_or_create(
            cls=models.Database,
            criteria={"database_name": database_name},
            session=db.session,
            sqlalchemy_uri="db_for_macros_testing://user@host:8080/hive",
            id=db_id,
        )

        def mock_get_dialect() -> Dialect:
            return dialect()

        database.get_dialect = mock_get_dialect
        return database

    @staticmethod
    def delete_fake_db_for_macros():
        database = (
            db.session.query(Database)
            .filter(Database.database_name == "db_for_macros_testing")
            .scalar()
        )
        if database:
            db.session.delete(database)
            db.session.commit()

    def validate_sql(
        self,
        sql,
        client_id=None,
        username=None,
        raise_on_error=False,
        database_name="examples",
        template_params=None,
    ):
        if username:
            self.logout()
            self.login(username=username)
        dbid = SupersetTestCase.get_database_by_name(database_name).id
        resp = self.get_json_resp(
            "/superset/validate_sql_json/",
            raise_on_error=False,
            data=dict(
                database_id=dbid,
                sql=sql,
                client_id=client_id,
                templateParams=template_params,
            ),
        )
        if raise_on_error and "error" in resp:
            raise Exception("validate_sql failed")
        return resp

    def get_dash_by_slug(self, dash_slug):
        sesh = db.session()
        return sesh.query(Dashboard).filter_by(slug=dash_slug).first()

    def get_assert_metric(self, uri: str, func_name: str) -> Response:
        """
        Simple client get with an extra assertion for statsd metrics

        :param uri: The URI to use for the HTTP GET
        :param func_name: The function name that the HTTP GET triggers
        for the statsd metric assertion
        :return: HTTP Response
        """
        with patch.object(
            BaseSupersetModelRestApi, "incr_stats", return_value=None
        ) as mock_method:
            rv = self.client.get(uri)
        if 200 <= rv.status_code < 400:
            mock_method.assert_called_once_with("success", func_name)
        else:
            mock_method.assert_called_once_with("error", func_name)
        return rv

    def delete_assert_metric(self, uri: str, func_name: str) -> Response:
        """
        Simple client delete with an extra assertion for statsd metrics

        :param uri: The URI to use for the HTTP DELETE
        :param func_name: The function name that the HTTP DELETE triggers
        for the statsd metric assertion
        :return: HTTP Response
        """
        with patch.object(
            BaseSupersetModelRestApi, "incr_stats", return_value=None
        ) as mock_method:
            rv = self.client.delete(uri)
        if 200 <= rv.status_code < 400:
            mock_method.assert_called_once_with("success", func_name)
        else:
            mock_method.assert_called_once_with("error", func_name)
        return rv

    def post_assert_metric(
        self, uri: str, data: Dict[str, Any], func_name: str
    ) -> Response:
        return post_assert_metric(self.client, uri, data, func_name)

    def put_assert_metric(
        self, uri: str, data: Dict[str, Any], func_name: str
    ) -> Response:
        """
        Simple client put with an extra assertion for statsd metrics

        :param uri: The URI to use for the HTTP PUT
        :param data: The JSON data payload to be posted
        :param func_name: The function name that the HTTP PUT triggers
        for the statsd metric assertion
        :return: HTTP Response
        """
        with patch.object(
            BaseSupersetModelRestApi, "incr_stats", return_value=None
        ) as mock_method:
            rv = self.client.put(uri, json=data)
        if 200 <= rv.status_code < 400:
            mock_method.assert_called_once_with("success", func_name)
        else:
            mock_method.assert_called_once_with("error", func_name)
        return rv

    @classmethod
    def get_dttm(cls):
        return datetime.strptime("2019-01-02 03:04:05.678900", "%Y-%m-%d %H:%M:%S.%f")

@contextmanager
def db_insert_temp_object(obj: DeclarativeMeta):
    """Insert a temporary object in database; delete when done."""
    session = db.session
    try:
        session.add(obj)
        session.commit()
        yield obj
    finally:
        session.delete(obj)
        session.commit()


text:
import os
from django.db import models
from core.models import PlCoreBase,ModelLink
from core.models import Slice
from core.models.plcorebase import StrippedCharField

class SliceTag(PlCoreBase):
    slice = models.ForeignKey(Slice, related_name='slicetags')

    NAME_CHOICES = (('privatekey', 'Private Key'), ('publickey', 'Public Key'))
    name = StrippedCharField(help_text="The name of this tag", max_length=30, choices=NAME_CHOICES)
    value = StrippedCharField(help_text="The value of this tag", max_length=1024)

    xos_links = [ModelLink(Slice,via='slice')]

    def can_update(self, user):
        return user.can_update_slice(self.slice)

    @staticmethod
    def select_by_user(user):
        if user.is_admin:
            qs = SliceTag.objects.all()
        else:
            slices = Slice.select_by_user(user)
            qs = SliceTag.objects.filter(slice__in=slices)
        return qs


text:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using GSoft.Dynamite.Globalization.Variations;
using GSoft.Dynamite.Lists;
using GSoft.Dynamite.Logging;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace GSoft.Dynamite.Helpers
{
    /// <summary>
    /// Forces the synchronization (i.e. copy from source label to destination language)
    /// of lists and webs in the variations process
    /// </summary>
    public class VariationSyncHelper : IVariationSyncHelper
    {
        private const string PublishingAssemblyPath = @"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Publishing.dll";

        private readonly ILogger _logger;
        private readonly IListHelper _listHelper;
        private readonly IVariationHelper _variationHelper;

        /// <summary>
        /// Initializes a new <see cref="VariationSyncHelper"/> instance
        /// </summary>
        /// <param name="logger">Logging utility</param>
        /// <param name="variationHelper">Variations helper</param>
        /// <param name="listHelper">List helper</param>
        public VariationSyncHelper(ILogger logger, IVariationHelper variationHelper, IListHelper listHelper)
        {
            this._logger = logger;
            this._listHelper = listHelper;
            this._variationHelper = variationHelper;
        }

        /// <summary>
        /// Sync a SPList for multiple target labels
        /// </summary>
        /// <param name="web">The web</param>
        /// <param name="listInfo">The source list metadata</param>
        /// <param name="labels">The destination labels</param>
        public void SyncList(SPWeb web, ListInfo listInfo, IList<VariationLabelInfo> labels)
        {
            var list = this._listHelper.EnsureList(web, listInfo);

            foreach (VariationLabelInfo label in labels)
            {
                // Synchronize only target labels
                if (!label.IsSource)
                {
                    this.SyncList(list, label.Title);
                }
            }
        }

        /// <summary>
        /// Sync a SPList for a target label
        /// </summary>
        /// <param name="listToSync">The source SPList instance to sync.</param>
        /// <param name="labelToSync">The label name to Sync. example: <c>"en"</c> or <c>"fr"</c>.</param>
        public void SyncList(SPList listToSync, string labelToSync)
        {
            this._logger.Info("Start method 'SyncList' for list: '{0}' with label '{1}'", listToSync.Title, labelToSync);

            var sourceWeb = listToSync.ParentWeb;
            Guid sourceListGuid = listToSync.ID;

            /* Note: This code is dessigned for work with internals SharePoint methods implemented in the Microsoft.SharePoint.Publishing assembly
             * See "PerformListLabelAction" method in "CreateVariationsPage" (Microsoft.SharePoint.Publishing.Internal.CodeBehind)
             * See "EnqueueWorkItemsForList" method in "VariationWorkItemHelper" (Microsoft.SharePoint.Publishing.Internal)
             */
            SPSecurity.RunWithElevatedPrivileges((SPSecurity.CodeToRunElevated)(() =>
            {
                using (var elevatedSite = new SPSite(sourceWeb.Site.ID))
                {
                    using (var elevatedWeb = elevatedSite.OpenWeb(sourceWeb.ID))
                    {
                        var list = elevatedWeb.Lists[sourceListGuid];

                        var publishingAssembly = Assembly.LoadFrom(PublishingAssemblyPath);
                        var workItemHelper = publishingAssembly.GetType("Microsoft.SharePoint.Publishing.Internal.VariationWorkItemHelper");
                        var multiLingualResourceList = publishingAssembly.GetType("Microsoft.SharePoint.Publishing.Internal.MultiLingualResourceList");

                        var types = new Type[1];
                        types[0] = typeof(SPList);

                        var args = new object[1];
                        args[0] = list;

                        var resParam = new object[2];
                        resParam[0] = list;
                        resParam[1] = true;

                        // Initialize the list
                        var nominateResources = multiLingualResourceList.GetMethod("NominateResource", BindingFlags.Public | BindingFlags.Static);
                        nominateResources.Invoke(null, resParam);

                        var ctor = multiLingualResourceList.GetConstructor(types);
                        var multilingualList = ctor.Invoke(args);

                        // Very important to set the HttpContext to null (AllowUnsafeUpdates is ignored by the SharePoint method)
                        HttpContext.Current = null;

                        var workItemParam = new object[3];
                        workItemParam[0] = elevatedSite;
                        workItemParam[1] = elevatedWeb;
                        workItemParam[2] = multilingualList;

                        // Method "EnqueueCreateListWorkItem" process one label at time!
                        var bindingFlags = BindingFlags.NonPublic | BindingFlags.Static;
                        var method = workItemHelper.GetMethod("EnqueueWorkItemsForList", bindingFlags);
                        method.Invoke(null, workItemParam);
                    }
                }
            }));
        }

        /// <summary>
        /// Sync a SPList for multiple target labels
        /// </summary>
        /// <param name="web">The web</param>
        /// <param name="labels">Variations labels</param>
        public void SyncWeb(SPWeb web, IList<VariationLabelInfo> labels)
        {
            foreach (VariationLabelInfo label in labels)
            {
                // Synchronize only target labels
                if (!label.IsSource)
                {
                    this.SyncWeb(web, label.Title);
                }
            }
        }

        /// <summary>
        /// Sync a SPWeb with variations
        /// </summary>
        /// <param name="web">The source web instance to sync.</param>
        /// <param name="labelToSync">Source label to sync</param>
        public void SyncWeb(SPWeb web, string labelToSync)
        {
            this._logger.Info("Start method 'SyncWeb' for web: '{0}' with label '{1}'", web.Url, labelToSync);

            var publishingAssembly = Assembly.LoadFrom(PublishingAssemblyPath);
            var workItemHelper = publishingAssembly.GetType("Microsoft.SharePoint.Publishing.Internal.VariationWorkItemHelper");
            var cachedVariationSettings = publishingAssembly.GetType("Microsoft.SharePoint.Publishing.Internal.CachedVariationSettings");

            // Get the labels to sync
            var labels = this._variationHelper.GetVariationLabels(web.Site, labelToSync);

            // Very important to set the HttpContext to null (AllowUnsafeUpdates is ignored by the SharePoint method)
            HttpContext.Current = null;

            Type[] methodParam = new Type[3];
            methodParam[0] = typeof(SPSite);
            methodParam[1] = typeof(SPUrlZone);
            methodParam[2] = typeof(bool);

            var bindingFlags = BindingFlags.NonPublic | BindingFlags.Static;

            object[] cvsParam = new object[3];
            cvsParam[0] = web.Site;
            cvsParam[1] = web.Site.Zone;
            cvsParam[2] = true;

            var cvsMethod = cachedVariationSettings.GetMethod("CreateVariationSettings", bindingFlags, null, methodParam, null);
            var cvs = cvsMethod.Invoke(null, cvsParam);

            object[] workItemParam = new object[3];
            workItemParam[0] = web;
            workItemParam[1] = labels;
            workItemParam[2] = cvs;

            var method = workItemHelper.GetMethod("EnqueueCreateSiteJobs", bindingFlags);
            method.Invoke(null, workItemParam);
        }
    }
}


text:
/**
 * @ngdoc directive
 * @name patternfly.filters.directive:pfFilterPanel
 * @restrict E
 *
 * @description
 *   The Filter Panel is opened and closed by clicking on the Filter button.  It can contain any HTML desired by
 *   the application developer.  As such, the application developer is repsonsible for constructing the appliedFilters array which is passed to
 *   the filter results tags.
 *   The application developer is responsible for filtering items based on the appliedFilters array; both when a
 *   filter is changed on the panel, or when a filter tag is 'cleared' (by user clicking on 'x' in the filter results tag).
 *

 *
 * @param {object} config configuration settings for the filters:

 *

 *
.appliedFilters - (Array) List of the currently applied filters. Used to render the filter results tags and returned
 * in the onFilterChange function where it can be used to filter a set of items.
 *

 *
.id          - (String) Id for the filter, useful for comparisons
 *
.title       - (String) The title to display for the filter results tag
 *
.values      - (Array) The value(s) to display for the filter results tag. Ie. [title: [value1 x] [value2 x]]
 *

 *
.resultsCount   - (int) The number of results returned after the current applied filters have been applied
 *
.totalCount     - (int) The total number of items before any filters have been applied. The 'm' in the label: 'n' of 'm'
 *
.resultsLabel   - (String) Optional label for the result units.  Default is "Results".  Ex: "'n' of 'm' Results"
 *
.onFilterChange - ( function(appliedFilters, changedFilterId, changedFilterValue) ) Function to call when the applied
 * filters list changes.  Triggered by user clicking on 'x' or 'Clear All Filters' in the filter result tags.
 * changedFilterId and changedFilterValue are returned after user clicks on an 'x' in a tag to
 * denote which filter and filter value was cleared.  changedFilterId and changedFilterValue are
 * not returned when 'Clear All Filters' link is clicked.
 *

 *
 * @example
<example module="patternfly.filters">
  <file name="index.html">

        <pf-filter-panel id="exampleFilter" config="filterConfig">

            <input type="text" ng-model="filterPanelModel[0].value"
                   class="keyword-filter"
                   placeholder="{{filterPanelModel[0].placeholder}}"
                   ng-keypress="onKeywordKeyPress($event)"/>

{{filter.title}}

                  <input type="checkbox" ng-model="value.selected" ng-change="filterChanged()"/>
                  {{value.title}}

        </pf-filter-panel>

        Valid Items:

ID

Keyword

Category One

Category Two

               {{item.id}}

              {{item.keyword}}

              {{item.categoryOne}}

              {{item.categoryTwo}}

  </file>

  <file name="script.js">
    angular.module('patternfly.filters').controller('ViewCtrl', ['$scope',
      function ($scope) {
        $scope.filterPanelModel = [
          {
            id: 'keyword',
            title:  'Keyword',
            placeholder: 'Filter by Keyword',
            filterType: 'input',
            values: []
          },
          {
            id: 'category1',
            title:  'Category One',
            filterType: 'checkbox',
            values: [
              {
                id: 'val1',
                title: 'Value 1',
                value: 'Value 1',
                selected: false
              },
              {
                id: 'val2',
                title: 'Value 2',
                value: 'Value 2',
                selected: false
              },
              {
                id: 'val3',
                title: 'Value 3',
                value: 'Value 3',
                selected: false
              }
            ]
          },
          {
            id: 'category2',
            title:  'Category Two',
            filterType: 'checkbox',
            values: [
              {
                id: 'val1',
                title: 'Value 1',
                value: 'Value 1',
                selected: false
              },
              {
                id: 'val2',
                title: 'Value 2',
                value: 'Value 2',
                selected: false
              },
              {
                id: 'val3',
                title: 'Value 3',
                value: 'Value 3',
                selected: false
              }
            ]
          }
        ];

        $scope.filtersText = '';

        $scope.allItems = [
          {
            id: "1",
            keyword: "Foo",
            categoryOne: "Value 1",
            categoryTwo: "Value 1"
          },
          {
            id: "2",
            keyword: "Bar",
            categoryOne: "Value 2",
            categoryTwo: "Value 1"
          },
          {
            id: "3",
            keyword: "Foo",
            categoryOne: "Value 3",
            categoryTwo: "Value 1"
          },
          {
            id: "4",
            keyword: "Bar",
            categoryOne: "Value 1",
            categoryTwo: "Value 2"
          },
          {
            id: "5",
            keyword: "Foo",
            categoryOne: "Value 2",
            categoryTwo: "Value 2"
          },
          {
            id: "6",
            keyword: "Bar",
            categoryOne: "Value 3",
            categoryTwo: "Value 2"
          },
          {
            id: "7",
            keyword: "Foo",
            categoryOne: "Value 1",
            categoryTwo: "Value 3"
          },
          {
            id: "8",
            keyword: "Bar",
            categoryOne: "Value 2",
            categoryTwo: "Value 3"
          },
          {
            id: "9",
            keyword: "Foo",
            categoryOne: "Value 3",
            categoryTwo: "Value 3"
          }
        ];
        $scope.items = $scope.allItems;

        // called when filter cleared by hitting 'x' in filter results tag, or 'Clear All Filters' link
        var onFilterChange = function (appliedFilters, changedFilterId, changedFilterValue) {
          if (angular.isDefined(changedFilterId) && angular.isDefined(changedFilterValue)) {
            updateFilterPanelModel(changedFilterId, changedFilterValue);
          } else {
            // the 'Clear All Filters' link was clicked
            resetFilterPanelModel();
          }
          // filter items
          filterItems(appliedFilters);
        };

        $scope.filterConfig = {
          resultsLabel: "Items",
          resultsCount: $scope.items.length,
          totalCount: $scope.allItems.length,
          appliedFilters: [],
          onFilterChange: onFilterChange
        };

        // called when filter is changed in the filter panel
        $scope.filterChanged = function() {
          applyFilters();
        };

        $scope.onKeywordKeyPress = function(keyEvent) {
          if (keyEvent.which === 13 && $scope.filterPanelModel[0].value.length > 0) {
            var currentKeyword = $scope.filterPanelModel[0].value;
            if(!keywordFilterExists(currentKeyword)) {
              // store new keywoard filter value in values array
              $scope.filterPanelModel[0].values.push(currentKeyword);
              applyFilters();
            }
            // remove the keyword value to show placeholder text
            delete $scope.filterPanelModel[0].value;
          }
        };

        var keywordFilterExists = function (keyword) {
          return _.some( $scope.filterPanelModel[0].values, function(existingKeyword) {
            // case sensitive
            //   return keyword === existingKeyword;
            // case insensitive:
            return keyword.toLowerCase() === existingKeyword.toLowerCase();
          });
        }

        var applyFilters = function () {
          var newAppliedFilters = [];
          _.forEach($scope.filterPanelModel, function(filter) {
            var filterValues = [];
            if (angular.isDefined(filter.values) && filter.values.length > 0) {
              if(filter.filterType === "checkbox") {
                // the values of the selected checkboxes are stored in a single new appliedFilter
                _.forEach(filter.values, function(value) {
                  if(value.selected) {
                    filterValues.push(value.value)
                  }
                });
                if (filterValues.length > 0) {
                  newAppliedFilters.push( createAppliedFilter (filter, filterValues) );
                }
              } else {
                // each keyword value gets a new appliedFilter
                _.forEach(filter.values, function(value) {
                  filterValues = [value];
                  newAppliedFilters.push( createAppliedFilter (filter, filterValues) );
                });
              }
            }
          });

          // sets the filter result tags
          $scope.filterConfig.appliedFilters = newAppliedFilters;
          // filter items
          filterItems($scope.filterConfig.appliedFilters);
        };

        var createAppliedFilter = function(filter, values) {
          return {
                    id: filter.id,
                    title: filter.title,
                    values: values
                 };
        };

        var updateFilterPanelModel = function (changedFilterId, changedFilterValue) {
          var changedFilter = _.find($scope.filterPanelModel, function(f) { return f.id === changedFilterId});
          if(changedFilter.filterType === "checkbox") {
             // unselect the checkbox
             _.find(changedFilter.values, function(v) {return v.value == changedFilterValue}).selected = false;
          } else {
             // remove keyword from values array
             _.remove(changedFilter.values, function(v) {return v == changedFilterValue});
          }
        };

        var resetFilterPanelModel = function () {
          _.forEach($scope.filterPanelModel, function(filter) {
            if (angular.isDefined(filter.values) && filter.values.length > 0) {
              if(filter.filterType === "checkbox") {
                // unselect all checkboxes
                filter.values.forEach(function (value) {
                  value.selected = false;
                });
              } else {
                // clear all keyword filter values
                filter.values = [];
              }
            }
          });
        };

        var filterItems = function (filters) {
          $scope.items = [];
          if (filters && filters.length > 0) {
           _.forEach($scope.allItems, function(item) {
              if (matchesFilters(item, filters)) {
                $scope.items.push(item);
              }
            });
          } else {
            $scope.items = $scope.allItems;
          }
          $scope.filterConfig.resultsCount = $scope.items.length;
        };

        var matchesFilters = function (item, filters) {
          var matches = true;

          _.forEach(filters, function(filter) {
              if (!matchesFilter(item, filter)) {
                matches = false;
                return false;
              }
          });
          return matches;
        };

        var matchesFilter = function (item, filter) {
          var match = true;

          if (filter.id === 'keyword') {
            var re = new RegExp(filter.values[0], 'i');
            match = item.keyword.match(re) !== null;
          } else if (filter.id === 'category1') {
            // values are OR'ed
            _.forEach(filter.values, function(value) {
              match = item.categoryOne === value;
              return !match;
            });
          } else if (filter.id === 'category2') {
            // values are OR'ed
            _.forEach(filter.values, function(value) {
              match = item.categoryTwo === value;
              return !match;
            });
          }
          return match;
        };
      }
    ]);
  </file>
</example>
*/


text:
using System;
using System.Collections.Generic;

namespace Stencil.SDK
{
    public static class _ResultExtensions
    {
        public static string GetMessage(this ActionResult result, string messageIfNull = "Error Processing Request")
        {
            if (result != null && !string.IsNullOrEmpty(result.message))
            {
                return result.message;
            }
            return messageIfNull;
        }
        public static string GetMessage<ActionResult>(this ItemResult<ActionResult> result, string messageIfNull = "Error Processing Request")
        {
            if (result != null)
            {
                if (result.item != null)
                {
                    return result.GetMessage();
                }
                return result.message;
            }
            return messageIfNull;
        }
        public static bool IsSuccess(this ActionResult result)
        {
            if (result != null && result.success)
            {
                return true;
            }
            return false;
        }
        public static bool IsSuccess<T>(this ItemResult<T> result)
        {
            if (result != null && (result.success || !EqualityComparer<T>.Default.Equals(result.item, default(T))))
            {
                return true;
            }
            return false;
        }
        public static bool IsSuccess<T>(this ListResult<T> result)
        {
            if (result != null && (result.success || result.items != null))
            {
                return true;
            }
            return false;
        }
        public static bool IsSuccess<T, K>(this ListResult<T, K> result)
            where K : new()
        {
            if (result != null && result.success)
            {
                return true;
            }
            return false;
        }
    }
}


text:
Details about bouncy

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
                praesentium

Creative ideas

At vero eos et accusamus et iusto odio
                        dignissimos ducimus qui
                        blanditiis praesentium voluptatum deleniti atque corrupti quos dolores

At vero eos et accusamus et iusto odio dignissimos ducimus qui
                        blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas
                        molestias
                        excepturi sint occaecati cupiditate non provident, similique
                        sunt in culpa qui officia deserunt
                        mollitia animi, id est laborum et dolorum fuga. Et harum quidem r


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="LENGTH function" />
<meta name="abstract" content="The LENGTH function is applied to either a character string expression or a bit string expression and returns the number of characters in the result." />
<meta name="description" content="The LENGTH function is applied to either a character string expression or a bit string expression and returns the number of characters in the result." />
<meta content="LENGTH function" name="DC.subject" />
<meta content="LENGTH function" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj29026.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsqlj16762" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>LENGTH function</title>

LENGTH function

The LENGTH function is applied to either a character string
expression or a bit string expression and returns the number of characters in
the result.

Because all built-in data types are implicitly converted to strings,
this function can act on all built-in data types.

Syntax

LENGTH ( characterExpression | bitExpression )

Examples

-- returns 20
VALUES LENGTH('supercalifragilistic')
-- returns 1
VALUES LENGTH(X'FF')
-- returns 4
VALUES LENGTH(1234567890)

Parent topic: Built-in functions


text:
Hashtags

#{{tag}}

#{{ tag }}

{{isEditing ? '#' : '+'}}
<input *ngIf="isEditing" type="text" pattern="^[A-Za-z0-9]+$" placeholder="hashtag"
      #newHashtag (keyup.enter)="addNewHashtag(newHashtag.value); newHashtag.value=''" (blur)="addNewHashtag(newHashtag.value); newHashtag.value=''" autofocus>


text:
/**
 * @file epit.c
 * @brief Enhanced.Periodic.Interrupt.Timer driver
 * @author Puranjay Mohan <puranjay12@gmail.com>
 * @version 0.1
 * @date 2020-03-05
 */

#include <drivers/common/memory.h>
#include <hal/clock.h>
#include <hal/reg.h>
#include <kernel/irq.h>
#include <kernel/printk.h>
#include <kernel/time/clock_source.h>
#include <kernel/time/time_device.h>

#include <framework/mod/options.h>
#include <embox/unit.h>

#define EPIT_BASE		OPTION_GET(NUMBER, base_addr)
#define EPIT_IRQ		OPTION_GET(NUMBER, irq_nr)
#define EPIT_TARGET_HZ	OPTION_GET(NUMBER, freq)
#define EPIT_FREQ		66000000

#define EPIT_CR		(EPIT_BASE + 0x00) /* Control Register */
#define EPIT_SR		(EPIT_BASE + 0x04) /* Status Register */
#define EPIT_LR		(EPIT_BASE + 0x08) /* Load Register */
#define EPIT_CMPR		(EPIT_BASE + 0x0C) /* Compare Register */
#define EPIT_CNR		(EPIT_BASE + 0x10) /* Counter Register */

#define EPIT_PRESCALER	66 /* prescaler value of 66 */
#define EPIT_CR_PRESCLR	(EPIT_PRESCALER << 4) /* Prescaler value of 66 */
#define EPIT_CR_EN		(1 << 0) /* Enable Bit */
#define EPIT_CR_ENMOD		(1 << 1) /* Enable Mode Bit */
#define EPIT_CR_OCIEN		(1 << 2) /* Output compare Interrupt Enable bit*/
#define EPIT_CR_RLD		(1 << 3) /* Counter Reload Control bit */
#define EPIT_SR_CLEAR		(1 << 0) /* Clear the status register*/
#define EPIT_CR_CLKSRC	(1 << 24) /* Use peripheral clock as input, 66MHz */
#define EPIT_CR_IOVW		(1 << 17) /* Load Immidiate Override*/
#define EPIT_LR_VALUE		((EPIT_FREQ)/(EPIT_PRESCALER * EPIT_TARGET_HZ))

static irq_return_t clock_handler(unsigned int irq_nr, void *data) {
	clock_tick_handler(data);
	REG32_STORE(EPIT_SR, EPIT_SR_CLEAR);
	return IRQ_HANDLED;
}

static int epit_init(struct clock_source *cs) {
	return irq_attach(EPIT_IRQ,
			clock_handler,
			0,
			cs,
			"EPIT");
}

static int epit_set_periodic(struct clock_source *cs) {
	/* changin clock source to peripheral clock */
	REG32_STORE(EPIT_CR, REG32_LOAD(EPIT_CR) & (~EPIT_CR_OCIEN)); /* Turn off the interrupt */
	REG32_STORE(EPIT_CR, REG32_LOAD(EPIT_CR) & (~EPIT_CR_EN)); /* disable the timer*/
	REG32_STORE(EPIT_CR, REG32_LOAD(EPIT_CR) | EPIT_CR_CLKSRC); /* Select the clock source */
	REG32_STORE(EPIT_SR, EPIT_SR_CLEAR); /* Clear the status register */
	REG32_STORE(EPIT_CR, REG32_LOAD(EPIT_CR) | EPIT_CR_ENMOD); /* Set enable mode = 1 */
	REG32_STORE(EPIT_CR, REG32_LOAD(EPIT_CR) | EPIT_CR_EN); /* enable the timer */
	REG32_STORE(EPIT_CR, REG32_LOAD(EPIT_CR) | EPIT_CR_OCIEN); /* Enable Interrupts */

	/* setting the load and compare registers */
	REG32_STORE(EPIT_CR, REG32_LOAD(EPIT_CR) | EPIT_CR_RLD | EPIT_CR_IOVW | EPIT_CR_PRESCLR); /* Set reload and overrite */
	REG32_STORE(EPIT_LR, EPIT_LR_VALUE); /* Load regiter set to (clck_src)/(presclr*target_freq) */
	REG32_STORE(EPIT_CMPR, 0x0); /* Compare register set to 0 */
	return 0;
}

static cycle_t epit_read(struct clock_source *cs) {
	return REG32_LOAD(EPIT_CNR);
}

static struct time_event_device epit_event = {
	.set_periodic   = epit_set_periodic,
	.irq_nr   = EPIT_IRQ,
};

static struct time_counter_device epit_counter = {
	.read     = epit_read,
	.cycle_hz = EPIT_TARGET_HZ,
};

STATIC_IRQ_ATTACH(EPIT_IRQ, clock_handler, &imx6_clock_source);

PERIPH_MEMORY_DEFINE(epit_mem, EPIT_BASE, 0x14);

CLOCK_SOURCE_DEF(epit, epit_init, NULL,
	&epit_event, &epit_counter);


text:
export default router => {
	return router;
};


text:
<?php
/**
 * Created by PhpStorm.
 * User: yk
 * Date: 2017/4/18
 * Time: 10:38
 */

namespace App\Admin\Extensions\Column;

use Encore\Admin\Admin;
use Encore\Admin\Grid\Displayers\AbstractDisplayer;

class ExpandRow extends AbstractDisplayer
{
    public function display(\Closure $callback = null, $btn = '')
    {
        $callback = $callback->bindTo($this->row);

        $html = call_user_func($callback);

        $script = <<<EOT

$('.grid-expand').on('click', function () {
    if ($(this).data('inserted') == '0') {
        var key = $(this).data('key');
        var row = $(this).closest('tr');
        var html = $('template.grid-expand-'+key).html();

        row.after("
"+html+"
");

        $(this).data('inserted', 1);
    }

    $("i", this).toggleClass("fa-caret-right fa-caret-down");
});
EOT;
        Admin::script($script);

        $btn = $btn ?: $this->column->getName();

        $key = $this->getKey();

        return <<<EOT

     $btn

<template class="grid-expand-{$key}">

$html

</template>
EOT;
    }
}


text:
<?php

class MageWorx_SeoBase_Model_Mysql4_Hreflang_Catalog_Ee_Product extends MageWorx_SeoBase_Model_Mysql4_Hreflang_Catalog_AbstractProduct
{
    public function getAllProductUrls($storeIds, $arrayTargetPath = false, $productId = false, $categoryId = false)
    {
        $categoryId    = null; // Magento EE (> 1.13.x) gets category id from session, but not from current request path
        $alternateUrls = array();
        $read = $this->_getReadAdapter();
        $this->_select = $read->select();

        if($productId) {

            $targetPath = 'catalog/product/view/id/' . $productId;

            if(!$categoryId && Mage::registry('current_category')) {
                $product       = Mage::registry('current_product');
                $categoryIds   = $product->getCategoryIds();
                $rawCategoryId = $this->_getCategoryIdByRequestPath();

                if($categoryIds && in_array($rawCategoryId, $categoryIds)) {
                    $categoryId = $rawCategoryId;
                }
            }

            if($categoryId) {
                $targetPath .= '/category/' . $categoryId;
                $useRootUrls = false;
            } else {
                $useRootUrls = true;
            }

            $arrayTargetPath = array($targetPath);
        } else {
            $useRootUrls = (Mage::helper('mageworx_seobase')->getProductCanonicalType() ==
                MageWorx_SeoBase_Model_Canonical_Product::ROOT);
        }

        if (!empty($arrayTargetPath)) {
            $stringTargetPath = "'" . trim(implode("','", $arrayTargetPath),"'") . "'";

            if($useRootUrls) {

                $concatSql = $read->getConcatSql(
                    array('"catalog/product/view/id/"', 'e.entity_id')
                );

                $this->_select = $read->select()
                    ->from(
                        array('e' => $this->getMainTable()),
                        array(
                            'product_id' => 'e.entity_id',
                            'cstore.store_id',
                            'product_url_part' => new Zend_Db_Expr(
                                $read->getIfNullSql('rwp.identifier', 'rwp_default.identifier')
                                )
                            )
                        )
                    ->join(
                        array(
                            'cstore' => $this->getTable('core/store')
                        ),
                        new Zend_Db_Expr('1'),
                        array()
                        )
                    ->joinLeft(
                        array('ecp' => $this->getTable('enterprise_catalog/product')),
                        'ecp.product_id = e.entity_id ' . 'AND ecp.store_id = cstore.store_id',
                        array()
                    )
                    ->joinLeft(
                        array('rwp' => $this->getTable('enterprise_urlrewrite/url_rewrite')),
                        'ecp.url_rewrite_id = rwp.url_rewrite_id' . ' AND ' .
                        $read->quoteInto('rwp.entity_type = ?', Enterprise_Catalog_Model_Product::URL_REWRITE_ENTITY_TYPE),
                        array()
                    )
                    ->joinLeft(
                        array('ecp_default' => $this->getTable('enterprise_catalog/product')),
                        'ecp_default.product_id = e.entity_id ' . 'AND ecp_default.store_id = 0',
                        array()
                    )
                    ->joinLeft(
                        array('rwp_default' => $this->getTable('enterprise_urlrewrite/url_rewrite')),
                        'rwp_default.url_rewrite_id = ecp_default.url_rewrite_id' . ' AND ' .
                        $read->quoteInto('rwp_default.entity_type = ?', Enterprise_Catalog_Model_Product::URL_REWRITE_ENTITY_TYPE),
                        array()
                    )
                    ->where('cstore.store_id IN(?)', $storeIds)
                    ->where("$concatSql IN(?)", $arrayTargetPath)
                    ->group(array('e.entity_id', 'cstore.store_id')
                );

            } else {

                $whereCondition = "
                    CONCAT('catalog/product/view/id/', e.entity_id, '/category/', ecc.category_id)
                    IN (" . $stringTargetPath . ")
                    OR
                    CONCAT('catalog/product/view/id/', e.entity_id)
                    IN (" . $stringTargetPath . ")
                ";

                $this->_select = $read->select()
                    ->from(
                        array('e' => $this->getMainTable()),
                        array(
                            'product_id' => 'e.entity_id',
                            'cstore.store_id',
                            'product_url_part' => new Zend_Db_Expr(
                                $read->getIfNullSql('rwp.identifier', 'rwp_default.identifier')
                                ),
                            'category_url_part' => new Zend_Db_Expr(
                                $read->getIfNullSql('rwc.request_path', 'rwc_default.request_path')
                                )
                            )
                        )
                    ->join(
                        array(
                            'cstore' => $this->getTable('core/store')
                        ),
                        new Zend_Db_Expr("1"),
                        array()
                        )
                    ->joinLeft(
                        array('ccp' => $this->getTable('catalog/category_product')),
                        'ccp.product_id = e.entity_id ',
                        array()
                    )
                    ->joinLeft(
                        array('ecc' => $this->getTable('enterprise_catalog/category')),
                        'ecc.category_id = ccp.category_id AND ecc.store_id = cstore.store_id',
                        array()
                    )
                    ->joinLeft(
                        array('rwc' => $this->getTable('enterprise_urlrewrite/url_rewrite')),
                        'ecc.url_rewrite_id = rwc.url_rewrite_id',
                        array()
                    )
                    ->joinLeft(
                        array('ecc_default' => $this->getTable('enterprise_catalog/category')),
                        'ecc_default.category_id = ccp.category_id AND ecc_default.store_id = 0',
                        array()
                    )
                    ->joinLeft(
                        array('rwc_default' => $this->getTable('enterprise_urlrewrite/url_rewrite')),
                        'ecc_default.url_rewrite_id = rwc_default.url_rewrite_id',
                        array()
                    )
                    ->joinLeft(
                        array('ecp' => $this->getTable('enterprise_catalog/product')),
                        'ecp.product_id = e.entity_id ' . 'AND ecp.store_id = cstore.store_id',
                        array()
                    )
                    ->joinLeft(
                        array('rwp' => $this->getTable('enterprise_urlrewrite/url_rewrite')),
                        'ecp.url_rewrite_id = rwp.url_rewrite_id' . ' AND ' .
                        $read->quoteInto('rwp.entity_type = ?', Enterprise_Catalog_Model_Product::URL_REWRITE_ENTITY_TYPE),
                        array()
                    )
                    ->joinLeft(
                        array('ecp_default' => $this->getTable('enterprise_catalog/product')),
                        'ecp_default.product_id = e.entity_id ' . 'AND ecp_default.store_id = 0',
                        array()
                    )
                    ->joinLeft(
                        array('rwp_default' => $this->getTable('enterprise_urlrewrite/url_rewrite')),
                        'rwp_default.url_rewrite_id = ecp_default.url_rewrite_id'. ' AND ' .
                        $read->quoteInto('rwp_default.entity_type = ?', Enterprise_Catalog_Model_Product::URL_REWRITE_ENTITY_TYPE),
                        array()
                    )

                    ->where('cstore.store_id IN(?)', $storeIds)
                    ->where(new Zend_Db_Expr($whereCondition))
                    ->group(array('e.entity_id', 'cstore.store_id')
                );
            }
        }

        $result = $read->fetchAll($this->_select);

        $products[$productId] = array();
        $products[$productId]['alternateUrls'] = array();

        foreach ($result as $row) {
            if(!empty($row['category_url_part'])) {
                $row['url'] = $row['category_url_part'] . '/' . $row['product_url_part'];
            } else {
                $row['url'] = $row['product_url_part'];
            }

            if (array_key_exists($row['product_id'], $products)) {
                $alternateUrls = $products[$row['product_id']]['alternateUrls'];
            }
            else {
                $products[$row['product_id']]  = array();
                $alternateUrls                 = array();
            }
            $alternateUrls[$row['store_id']] = $this->_addProductSuffix($this->_baseStoreUrls[$row['store_id']] . $row['url'], $row['store_id']);
            $products[$row['product_id']] = array('requestPath'   => $row['url'], 'alternateUrls' => $alternateUrls);
        }

        return $products;
    }

    protected function _getCategoryIdByRequestPath()
    {
        $productUrlKey = Mage::registry('current_product')->getUrlKey();
        $storeId       = Mage::app()->getStore()->getStoreId();
        $requestString = Mage::app()->getRequest()->getRequestString();

        $pos = strpos($requestString, $productUrlKey);

        if($pos !== false) {
            $requestPath = trim(substr_replace($requestString, '', $pos), '/');
        }

        if($requestPath) {
            $read = $this->_getReadAdapter();
            $select = $read->select()
                    ->from(
                        $this->getTable('enterprise_urlrewrite/url_rewrite'),
                        array('target_path')
                    )
                    ->where('request_path = (?)', $requestPath)
                    ->where('store_id = (?)', $storeId)
                    ->where('is_system = (?)', 1)
                    ->where('entity_type = (?)', 2)
                    ->order('store_id');

            $query    = $read->query($select);
            $result   = $query->fetchAll();
            if(!empty($result[0]['target_path'])) {
                return (int)ltrim($result[0]['target_path'], 'catalog/category/view/id/');
            }
        }
        return null;
    }

    protected function _addProductSuffix($rawUrl, $storeId)
    {
        $rawSeoSuffix = Mage::helper('catalog/product')->getProductUrlSuffix($storeId);
        $seoSuffix = !empty($rawSeoSuffix) ? '.' . $rawSeoSuffix : '';
        return $rawUrl .= $seoSuffix;
    }
}


text:
import os, sys
from collections import namedtuple

from PyQt4.QtCore import *
from PyQt4.QtGui import *

from .aboutdialog import AboutDialog
from .highscoresdialog import HighscoresDialog
from .highscores import HighScores
from .images import get_icon_pixmap
from .enum import Enum
from .tetrismodel import TetrisBoard, Figure, FigureBank
from .version import pyqtris_version

class DrawabaleTetrisBoard(QWidget):
    """ A base class for tetris board widgets that can draw
        themselves.
    """
    def __init__(self, parent, nrows, ncols, blocksize):
        super(DrawabaleTetrisBoard, self).__init__(parent)

        self.nrows = nrows
        self.ncols = ncols
        self.blocksize = blocksize

        self.nrows = nrows
        self.ncols = ncols
        self.blocksize = blocksize
        self.showgrid = True
        self.gridwidth = 2
        self.gridcolor = QColor(204, 204, 204)

        # the "sink" is the white border around the actual
        # tetris grid
        #
        self.sinkwidth = 4
        self.sinkcolor = 'white'
        self.block_border_color = 'black'
        self.bgcolor = QColor(234, 234, 244)

        self.setSizePolicy(QSizePolicy(
                            QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.width = self.sinkwidth * 2 + ncols * blocksize + (ncols + 1) * self.gridwidth
        self.height = self.sinkwidth * 2 + nrows * blocksize + (nrows + 1) * self.gridwidth

        self.board = TetrisBoard(nrows, ncols)

    def minimumSizeHint(self):
        return QSize(self.width, self.height)

    def sizeHint(self):
        return self.minimumSizeHint()

    def paintEvent(self, event=None):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        painter.fillRect(0, 0, self.width, self.height, QBrush(self.bgcolor, Qt.SolidPattern))

        if self.showgrid: self._draw_grid(painter)
        self._draw_sink(painter)

        self._draw_all_blocks(painter)

    def _draw_sink(self, painter):
        sink_pen = QPen(QColor(self.sinkcolor))
        sink_pen.setWidth(self.sinkwidth)
        painter.setPen(sink_pen)

        halfsink = self.sinkwidth / 2
        painter.drawLine(halfsink, 0, halfsink, self.height)
        painter.drawLine(
            self.width - halfsink, 0,
            self.width - halfsink, self.height)
        painter.drawLine(0, halfsink, self.width, halfsink)
        painter.drawLine(
            0, self.height - halfsink,
            self.width, self.height - halfsink)

    def _draw_grid(self, painter):
        grid_pen = QPen(QColor(self.gridcolor))
        grid_pen.setWidth(self.gridwidth)
        painter.setPen(grid_pen)

        # combined size of a block with a single grid line
        blockgrid_size = self.blocksize + self.gridwidth

        # horizontal
        for row in range(self.nrows + 1):
            painter.drawLine(
                self.sinkwidth,
                self.sinkwidth + row * blockgrid_size + 1,
                self.width - 1 - self.sinkwidth,
                self.sinkwidth + row * blockgrid_size + 1)

        # vertical
        for col in range(self.ncols + 1):
            painter.drawLine(
                self.sinkwidth + col * blockgrid_size + 1,
                self.sinkwidth,
                self.sinkwidth + col * blockgrid_size + 1,
                self.height - 1 - self.sinkwidth)

    def _draw_all_blocks(self, painter):
        board = self.board.board_with_active_figure()

        for row in range(self.nrows):
            for col in range(self.ncols):
                color = board[row][col]

                if color != 0:
                    self._draw_block(painter, row, col, color)

    def _draw_block(self, painter, row, col, color):
        block_pen = QPen(QColor(self.block_border_color))
        block_pen.setWidth(self.gridwidth)
        painter.setPen(block_pen)

        blockgrid_size = self.blocksize + self.gridwidth
        block_rect = QRect(
            self.sinkwidth + col * blockgrid_size + 1,
            self.sinkwidth + row * blockgrid_size + 1,
            blockgrid_size,
            blockgrid_size)

        painter.fillRect(block_rect, QBrush(color, Qt.SolidPattern))
        painter.drawRect(block_rect)

class MainTetrisWidget(DrawabaleTetrisBoard):
    """ The main tetris window type, with an active figure that can be moved
        around, dropped, etc. and a bunch of inactive blocks.
        Supports all the expected tetris operations, like removing completed
        rows and generating new figures.
    """
    def __init__(self, parent, nrows, ncols, blocksize, startfigure):
        super(MainTetrisWidget, self).__init__(parent, nrows, ncols, blocksize)

        self.board.spawn_figure(startfigure)

        # Keeps track of the amount of rows the active figure
        # fell in the last "drop" command. This is used to
        # update the score.
        #
        self.last_drop_height = 0

    def restart(self, startfigure):
        self.board = TetrisBoard(self.nrows, self.ncols)
        self.board.spawn_figure(startfigure)
        self.update()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Up:
            self.board.rotate_figure()
        elif event.key() == Qt.Key_Down:
            self.board.move_figure_down()
        elif event.key() == Qt.Key_Left:
            self.board.move_figure_left()
        elif event.key() == Qt.Key_Right:
            self.board.move_figure_right()
        elif event.key() == Qt.Key_Space:
            for i in range(self.nrows):
                if not self.board.move_figure_down():
                    self.last_drop_height = i
                    break
        else:
            return

        self.update()

    Result = namedtuple('Result', 'state completed_rows drop_height')

    def timer_tick(self, nextfigure):
        """ One timer tick for the tetris game.

            Advances the game by one step and returns a result as
            a namedtuple:

                result.state:
                    The game state.
                        running -   The current figure was moved
                                    down by one cell successfully.
                        newfigure - The current figure could no
                                    longer be moved down, so a new
                                    figure was created.
                        gameover -  The current figure could no
                                    longer be moved down, and a
                                    new figure could not be
                                    created.

                result.completed_rows:
                    A list of row numbers that were completed with
                    the current figure reaching bottom. It is
                    applicable in the "newfigure" state

                result.drop_height:
                    The amount of lines the figure was dropped in
                    the last drop.
        """
        state = 'running'
        completed_rows = []
        drop_height = 0

        if self.board.move_figure_down():
            state = 'running'
        else:
            completed_rows = self.board.finish_fall()

            if self.board.spawn_figure(nextfigure):
                state = 'newfigure'
            else:
                state = 'gameover'

        drop_height = self.last_drop_height
        self.last_drop_height = 0

        self.update()
        return self.Result(state, completed_rows, drop_height)

class TetrisPreviewWidget(DrawabaleTetrisBoard):
    """ A preview window for figures. Only shows a single figure, trying to
        center it vertically.
        Note: the success of this method depends on the actual figures that
        participate in the game. It works well for the default 7 Tetris
        figures.
    """
    def __init__(self, parent, nrows, ncols, blocksize):
        super(TetrisPreviewWidget, self).__init__(parent, nrows, ncols, blocksize)

        self.showgrid = False
        self.figure = None

    def set_figure(self, figure):
        self.figure = figure
        self.board = TetrisBoard(self.nrows, self.ncols)
        self.board.spawn_figure(figure)
        self.board.move_figure_down()
        self.board.move_figure_down()

        self.update()

class SizedButton(QPushButton):
    def __init__(self, text, size, parent=None):
        super(SizedButton, self).__init__(text, parent)
        self.size = size

    def sizeHint(self):
        return self.size

class StatsLabel(QLabel):
    def __init__(self, text, align_right=False, parent=None):
        super(StatsLabel, self).__init__('', parent)

        self.format_text = '%s'
        self.setText(text)

        if align_right:
            self.setAlignment(Qt.AlignRight)
        else:
            self.setAlignment(Qt.AlignLeft)

    def setText(self, text):
        super(StatsLabel, self).setText(self.format_text % text)

GameState = Enum('running', 'paused', 'gameover')

class TetrisMainWindow(QMainWindow):
    """ The main tetris game window.
    """
    def __init__(self, parent=None):
        super(TetrisMainWindow, self).__init__(parent)
        self.setWindowTitle('PyQtris v%s' % pyqtris_version)

        self.setWindowIcon(QIcon(get_icon_pixmap()))

        self.figurebank = self.make_figure_bank()

        self.create_main_frame()
        self.create_menu()
        self.create_status_bar()

        self.timer = QTimer()
        self.timer_interval = 1000
        self.connect(self.timer, SIGNAL('timeout()'), self.on_timer)
        self.timer.start(self.timer_interval)

        self.init_highscores()
        self.restart_game()

    def on_restart(self):
        if self.state == GameState.gameover:
            self.restart_game()
        else:
            saved_state = self.state
            self.pause_game()

            reply = QMessageBox.question(self,
                'Restart confirmation',
                'Are you sure you want to restart the game?',
                QMessageBox.Yes | QMessageBox.No)

            if reply == QMessageBox.Yes:
                self.restart_game()
            else:
                self.set_game_state(saved_state)

    def on_pause(self):
        if self.state == GameState.paused:
            self.resume_game()
        elif self.state == GameState.running:
            self.pause_game()

    def on_about(self):
        saved_state = self.state
        self.pause_game()

        dialog = AboutDialog(self)
        dialog.exec_()

        self.set_game_state(saved_state)

    def on_highscores(self):
        saved_state = self.state
        self.pause_game()
        self.show_highscores()
        self.set_game_state(saved_state)

    def set_game_state(self, state):
        if state == GameState.paused:
            self.pause_game()
        elif state == GameState.running:
            self.resume_game()
        elif state == GameState.gameover:
            self.state = GameState.gameover
            self.status_text.setText('Game over!')
            self.timer.stop()
        else:
            assert False

    def pause_game(self):
        self.state = GameState.paused
        self.status_text.setText('Paused')
        self.pause_button.setText('Resume')
        self.timer.stop()

    def resume_game(self):
        self.state = GameState.running
        self.status_text.setText('Playing')
        self.pause_button.setText('Pause')
        self.timer.start(self.timer_interval)

    def game_over(self):
        self.state = GameState.gameover

        self.status_text.setText('Game over!')
        self.timer.stop()

        if self.game_score > self.highscores.lowest_score():
            text, ok = QInputDialog.getText(self,
                "High score!",
                'Your name:')

            if ok and not text.isEmpty():
                self.highscores.add_score(text, self.game_score)
                self.save_highscores()
                self.show_highscores()

    def restart_game(self):
        self.game_level = 1
        self.game_lines = 0
        self.game_score = 0
        self.timer_interval = 1000

        self.resume_game()
        self.update_stats()

        self.board_widget.restart(self.figurebank.get_random())
        self.preview_figure = self.figurebank.get_random()
        self.preview_widget.set_figure(self.preview_figure)
        self.timer.start(self.timer_interval)

    def on_timer(self):
        if self.state == GameState.running:
            result = self.board_widget.timer_tick(self.preview_figure)
            num_rows = len(result.completed_rows)

            if result.state == 'gameover':
                self.game_over()
            elif result.state == 'newfigure':
                old_line_count = self.game_lines
                self.game_lines += num_rows
                score_bonus = result.drop_height + num_rows ** 2 * 30
                score_bonus = int(score_bonus * (1 + 0.1 * (self.game_level - 1)))
                self.game_score += score_bonus

                self.preview_figure = self.figurebank.get_random()
                self.preview_widget.set_figure(self.preview_figure)

                if num_rows > 0 and old_line_count % 10 + num_rows >= 10:
                    self.game_level += 1
                    self.timer_interval = 1000 - self.game_level * 100
                    if self.timer_interval < 100:
                        self.timer_interval = 100
                    self.timer.stop()
                    self.timer.start(self.timer_interval)

            self.update_stats()

    def update_stats(self):
        self.level_text.setText(str(self.game_level))
        self.lines_text.setText(str(self.game_lines))
        self.score_text.setText(str(self.game_score))

    def create_main_frame(self):
        self.board_widget = MainTetrisWidget(self,
            nrows=20,
            ncols=10,
            blocksize=25,
            startfigure=self.figurebank.get_random())
        self.board_widget.setFocus()

        self.control_panel = QFrame(self)
        self.control_panel.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.control_panel.setFocusPolicy(Qt.NoFocus)

        self.populate_control_panel()

        main_layout = QHBoxLayout()
        main_layout.addWidget(self.board_widget)
        main_layout.addWidget(self.control_panel)
        main_layout.setSizeConstraint(QLayout.SetFixedSize)

        main_frame = QWidget()
        main_frame.setLayout(main_layout)
        self.setCentralWidget(main_frame)

    def populate_control_panel(self):
        self.preview_widget = TetrisPreviewWidget(
            self.control_panel,
            nrows=7,
            ncols=7,
            blocksize=10)

        # preview_group is the group-box for titling the preview
        # widget. preview_box is its internal layout.
        # finally, preview_layout is used to add stretchers around
        # the group box (to keep it slim)
        #
        preview_group = QGroupBox('Preview')
        preview_box = QHBoxLayout()
        preview_box.addWidget(self.preview_widget)
        preview_group.setLayout(preview_box)
        preview_layout = QHBoxLayout()
        preview_layout.addStretch()
        preview_layout.addWidget(preview_group)
        preview_layout.addStretch()

        text_layout = QGridLayout()

        level_label = StatsLabel('Level')
        self.level_text = StatsLabel('1', True)
        lines_label = StatsLabel('Lines')
        self.lines_text = StatsLabel('0', True)
        score_label = StatsLabel('Score')
        self.score_text = StatsLabel('0', True)

        text_layout.addWidget(level_label, 0, 0)
        text_layout.addWidget(self.level_text, 0, 1)
        text_layout.addWidget(lines_label, 1, 0)
        text_layout.addWidget(self.lines_text, 1, 1)
        text_layout.addWidget(score_label, 2, 0)
        text_layout.addWidget(self.score_text, 2, 1)

        self.pause_button = SizedButton('&Pause', QSize(90, 40))
        self.pause_button.setFocusPolicy(Qt.NoFocus)
        self.connect(self.pause_button, SIGNAL('clicked()'), self.on_pause)

        self.restart_button = SizedButton('&New game', QSize(90, 40))
        self.restart_button.setFocusPolicy(Qt.NoFocus)
        self.connect(self.restart_button, SIGNAL('clicked()'), self.on_restart)

        button_layout = QHBoxLayout()
        button_layout.addWidget(self.pause_button)
        button_layout.addSpacing(40)
        button_layout.addWidget(self.restart_button)

        vbox = QVBoxLayout()
        vbox.addSpacing(15)
        vbox.addLayout(preview_layout)
        vbox.addSpacing(40)
        vbox.addLayout(text_layout)
        vbox.addSpacing(40)
        vbox.addLayout(button_layout)
        vbox.addStretch()

        hbox = QHBoxLayout()
        hbox.addStretch()
        hbox.addLayout(vbox)
        hbox.addStretch()

        self.control_panel.setLayout(hbox)

    def create_status_bar(self):
        self.status_text = QLabel('Playing')
        self.statusBar().addWidget(self.status_text, 1)

    def create_menu(self):
        self.game_menu = self.menuBar().addMenu("&Game")
        self.help_menu = self.menuBar().addMenu("&Help")

        new_game_action = self.create_action("&New",
            shortcut='Ctrl+N', slot=self.on_restart,
            tip='New game')
        pause_game_action = self.create_action("&Pause",
            shortcut='Ctrl+P', slot=self.on_pause,
            tip='Pause game')
        highscores_action = self.create_action("&High Scores",
            shortcut='Ctrl+H', slot=self.on_highscores,
            tip='Pause game')
        quit_action = self.create_action("&Quit",
            shortcut='Ctrl+Q', slot=self.close,
            tip='Quit')

        about_action = self.create_action("&About",
            shortcut='F1', slot=self.on_about,
            tip='About PyQtris')

        self.add_actions(self.game_menu,
            (   new_game_action, pause_game_action, None,
                highscores_action, None, quit_action))

        self.add_actions(self.help_menu, (about_action,))

    def add_actions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def create_action(  self, text, slot=None, shortcut=None,
                        icon=None, tip=None, checkable=False,
                        signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action

    def make_figure_bank(self):
        # The standard 7 Tetris figures, in the orientation
        # in which they appear from the top of the screen
        #

        #  oo
        # oO
        S = Figure([(0,0), (-1,0), (0,-1), (-1,1)], color=QColor(122, 197, 205))

        # oo
        #  Oo
        Z = Figure([(0,0), (0,1), (-1,-1), (-1,0)], color=QColor(0, 205, 0))

        # oOo
        #  o
        T = Figure([(0,0), (0,1), (0,-1), (1,0)], color=QColor(238, 238, 0))

        # oOoo
        #
        I = Figure([(0,0), (0,-1), (0,1), (0,2)], color=QColor(238, 118, 33))

        # oo
        # Oo
        O = Figure([(0,0), (-1,0), (-1,1), (0,1)], rotatable=False, color=QColor(238, 44, 44))

        # oOo
        # o
        L = Figure([(0,0), (0,-1), (0,1), (1,-1)], color=QColor(0, 0, 225))

        # oOo
        #   o
        J = Figure([(0,0), (0,-1), (0,1), (1,1)], color=QColor(148, 0, 211))

        return FigureBank([S, Z, T, I, O, L, J])

    def keyPressEvent(self, event):
        if self.state == GameState.running:
            self.board_widget.keyPressEvent(event)

    HS_FILENAME = 'pyqtris_highscores'

    def init_highscores(self):
        self.highscores = HighScores(10)

        if os.path.exists(self.HS_FILENAME):
            self.highscores.load_from_file(self.HS_FILENAME)

    def save_highscores(self):
        self.highscores.save_to_file(self.HS_FILENAME)

    def show_highscores(self):
        dialog = HighscoresDialog(self.highscores.get_list(), self)
        dialog.exec_()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = TetrisMainWindow()
    form.show()
    app.exec_()


text:
layout: page
title: Getting started with Github desktop app
---

##### First, download the app from [desktop.github.com](https://desktop.github.com/)

##### Install the app and start it up.

##### Login with the username you've created

##### You can let it search for any **.git** files that already exist on your computer or just skip for now.

##### This is how the app looks below. This is where you can track, commit, or sync changes.

* If you wanted, you could upload any folder you want to your github account. But not right now.
* But if you wanted to later, click **File > Add Local Repository...** find the folder you want on your computer to upload, click the **Create and Add** button when a pop-up says **This folder is not a repository**, make sure all the files you want to upload are checked, then fill out the summary and description fields before clicking the **Commit to master** button. Finally, hit the **Publish** button on the top right. Select your account and github folder name. Hit **Publish Repository** and you're all set.

##### But for now, let's get the private repo I've set up for you.

* Click **File > Clone Repository** and a list of all the repos I've shared with you will show up. Select your personal private repository (the one with the lock next to it) and save it to whatever folder you want.

##### Now the folder is where you saved it.

* From here, you can drag and drop or copy and paste whatever files you want to it (**Note:** into the folder on your computer, not the Github app).
* But to save the changes you've made online, you need to **commit** and **publish**
* So after moving in the file you want to upload to the repo to the folder where you saved it, refresh the folder in the app and you should see the file listed.
* Fill in the summary and description fields.
* Click **Commit to master**

##### Finally, click **sync** at the top right
* Give your private repo a refresh and your file should be there if it worked successfully
* It might take a couple minutes or it might show up right away

##### Congratulations, you've completed a big step.


text:
package com.sysview.docauto.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.sysview.docauto.dao.UsuarioDAO;
import com.sysview.docauto.model.Usuario;

@Component("usuarioDao")
public class UsuarioDAOImpl implements UsuarioDAO{

	private static final Logger log = LoggerFactory.getLogger(UsuarioDAOImpl.class);
	DataSource dataSource;

	public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

	@Autowired
	JdbcTemplate jdbcTemplate;

	@Override
	public List<Usuario> getUsuario() {
		log.debug("Consultando Usuarios...");

        List<Usuario> user= jdbcTemplate.query(
        "select * from USUARIOPROPIO",
        new RowMapper<Usuario>() {
            public Usuario mapRow(ResultSet rs, int rowNum) throws SQLException {
            	Usuario user = new Usuario();
            	user.setUsuario(rs.getString("USUARIOPROPIO"));
            	user.setNombreusr(rs.getString("USUARIOPROPIONOMBRE"));
            	user.setApellidopat(rs.getString("USUARIOPROPIOPATERNO"));
            	user.setApellidomat(rs.getString("USUARIOPROPIOMATERNO"));
                user.setPassword(rs.getString("USUARIOPROPIOPASSWORD"));
                user.setCorreo(rs.getString("USUARIOPROPIOCORREO"));
                return user;
            }
        });
        log.debug("usuario: {}", user.toString());
        return user;
	}

		public void insertUsuario(Usuario user) {	//, String nombre, String appat, String apmat, String pswd, String correo
		log.debug("Creando Usuario...");
		String sql="insert into USUARIOPROPIO values(?,?,?,?,?,?)";
		jdbcTemplate.update(sql, new Object[] {user.getUsuario(),user.getNombreusr(),user.getApellidopat(),user.getApellidomat(),
				user.getPassword(),user.getCorreo()});
	}

	@Override
	public void updateUsuario(Usuario user) {
		String sql="UPDATE USUARIOPROPIO set USUARIOPROPIONOMBRE = ?, USUARIOPROPIOPATERNO = ?, "
				+ "USUARIOPROPIOMATERNO = ?, USUARIOPROPIOPASSWORD = ?, USUARIOPROPIOCORREO = ? where USUARIOPROPIO=?";

		jdbcTemplate.update(sql, new Object[]{user.getNombreusr(), user.getApellidopat(),
				user.getApellidomat(),user.getPassword(),user.getCorreo(),user.getUsuario()});
	}

	@Override
	public void deleteUsuario(Usuario user) {
		String sql="delete from USUARIOPROPIO where USUARIOPROPIO=?";
		jdbcTemplate.update(sql, user.getUsuario());
	}

	/*
	@Override
	public Usuario getuser(String usuario) {
		Usuario gusuario = new Usuario();
		return gusuario;
	}

	@Override
	public Usuario getuser(suario usuario) {
		// TODO Auto-generated method stub
		return null;
	}*/

	/*public Usuario get(Usuario user) {
		String sql= "select * from USUARIOPROPIO where USUARIOPROPIO=?";
		return jdbcTemplate.query(sql,new ResultSetExtractor<Usuario>(){

			//@Override
            public Usuario extractuser(ResultSet rs) throws SQLException,
            DataAccessException{
				if(rs.next()){
	            	Usuario miuser = new Usuario();
	            	miuser.setUsuario(rs.getString("USUARIOPROPIO"));
	            	miuser.setNombreusr(rs.getString("USUARIOPROPIONOMBRE"));
	            	miuser.setApellidopat(rs.getString("USUARIOPROPIOPATERNO"));
	            	miuser.setApellidomat(rs.getString("USUARIOPROPIOMATERNO"));
	                miuser.setPassword(rs.getString("USUARIOPROPIOPASSWORD"));
	                miuser.setCorreo(rs.getString("USUARIOPROPIOCORREO"));
	                return miuser;
				}
		return null;
	}

			@Override
			public Usuario extractData(ResultSet rs) throws SQLException, DataAccessException {
				// TODO Auto-generated method stub
				return null;
			}
		});
	}*/
}


text:
'use strict';

describe('Controller Tests', function() {

    describe('CodigoCancelamento Management Detail Controller', function() {
        var $scope, $rootScope;
        var MockEntity, MockPreviousState, MockCodigoCancelamento;
        var createController;

        beforeEach(inject(function($injector) {
            $rootScope = $injector.get('$rootScope');
            $scope = $rootScope.$new();
            MockEntity = jasmine.createSpy('MockEntity');
            MockPreviousState = jasmine.createSpy('MockPreviousState');
            MockCodigoCancelamento = jasmine.createSpy('MockCodigoCancelamento');

            var locals = {
                '$scope': $scope,
                '$rootScope': $rootScope,
                'entity': MockEntity,
                'previousState': MockPreviousState,
                'CodigoCancelamento': MockCodigoCancelamento
            };
            createController = function() {
                $injector.get('$controller')("CodigoCancelamentoDetailController", locals);
            };
        }));

        describe('Root Scope Listening', function() {
            it('Unregisters root scope listener upon scope destruction', function() {
                var eventType = 'g2MatriculaApp:codigoCancelamentoUpdate';

                createController();
                expect($rootScope.$$listenerCount[eventType]).toEqual(1);

                $scope.$destroy();
                expect($rootScope.$$listenerCount[eventType]).toBeUndefined();
            });
        });
    });

});


text:
package org.fenixedu.notifications.core.json;

import org.fenixedu.bennu.core.json.JsonBuilder;
import org.fenixedu.bennu.core.json.JsonViewer;
import org.fenixedu.notifications.core.view.UserView;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class UserViewJsonViewer implements JsonViewer<UserView> {

    @Override
    public JsonElement view(UserView obj, JsonBuilder ctx) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("user", ctx.view(obj.getUser()));
        jsonObject.addProperty("notifications", obj.getNotificationsUrl());

        return jsonObject;
    }

}


text:
package org.innovateuk.ifs.testdata.builders.data;

import org.innovateuk.ifs.user.resource.Role;

/**
 * Running data context for generating Internal Users (e.g. comp admins)
 */
public class InternalUserData extends BaseUserData {

    private Role role;

    private String emailAddress;

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getEmailAddress() {
        return emailAddress;
    }
}


text:
* This blog is powered by Jekyll and Github Pages.
* This blog's main design comes from [so-simple-theme](https://github.com/mmistakes/so-simple-theme).Thanks very much for the original programmer.


text:
sap.ui.define(["sap/ui/webc/fiori/thirdparty/illustrations/Tent"], function() {
	"use strict";
});


text:
package sun.jvm.hotspot.debugger.win32;

import java.io.*;
import java.util.*;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.debugger.cdbg.*;
import sun.jvm.hotspot.debugger.cdbg.basic.x86.*;
import sun.jvm.hotspot.debugger.x86.*;
import sun.jvm.hotspot.utilities.AddressOps;

class Win32CDebugger implements CDebugger, ProcessControl {
  // FIXME: think about how to make this work in a remote debugging
  // scenario; who should keep open DLLs? Need local copies of these
  // DLLs on the debugging machine?
  private Win32Debugger dbg;

  Win32CDebugger(Win32Debugger dbg) {
    this.dbg = dbg;
  }

  public List getThreadList() throws DebuggerException {
    return dbg.getThreadList();
  }

  public List/*<LoadObject>*/ getLoadObjectList() throws DebuggerException{
    return dbg.getLoadObjectList();
  }

  public LoadObject loadObjectContainingPC(Address pc) throws DebuggerException {
    // FIXME: could keep sorted list of these to be able to do binary
    // searches, for better scalability
    if (pc == null) {
      return null;
    }
    List objs = getLoadObjectList();
    for (Iterator iter = objs.iterator(); iter.hasNext(); ) {
      LoadObject obj = (LoadObject) iter.next();
      if (AddressOps.lte(obj.getBase(), pc) && (pc.minus(obj.getBase()) < obj.getSize())) {
        return obj;
      }
    }
    return null;
  }

  public CFrame topFrameForThread(ThreadProxy thread) throws DebuggerException {
    X86ThreadContext context = (X86ThreadContext) thread.getContext();
    Address ebp = context.getRegisterAsAddress(X86ThreadContext.EBP);
    if (ebp == null) return null;
    Address pc  = context.getRegisterAsAddress(X86ThreadContext.EIP);
    if (pc == null) return null;
    return new X86CFrame(this, ebp, pc);
  }

  public String getNameOfFile(String fileName) {
    return new File(fileName).getName();
  }

  public ProcessControl getProcessControl() throws DebuggerException {
    return this;
  }

  // C++ name demangling
  public boolean canDemangle() {
    return false;
  }

  public String demangle(String sym) {
    throw new UnsupportedOperationException();
  }

  //
  // Support for ProcessControl interface
  //

  public void suspend() throws DebuggerException {
    dbg.suspend();
  }
  public void resume() throws DebuggerException {
    dbg.resume();
  }
  public boolean isSuspended() throws DebuggerException {
    return dbg.isSuspended();
  }
  public void setBreakpoint(Address addr) throws DebuggerException {
    dbg.setBreakpoint(addr);
  }
  public void clearBreakpoint(Address addr) throws DebuggerException {
    dbg.clearBreakpoint(addr);
  }
  public boolean isBreakpointSet(Address addr) throws DebuggerException {
    return dbg.isBreakpointSet(addr);
  }
  public DebugEvent debugEventPoll() throws DebuggerException {
    return dbg.debugEventPoll();
  }
  public void debugEventContinue() throws DebuggerException {
    dbg.debugEventContinue();
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0"
    android:toDegrees="360">

    <shape android:shape="ring" android:innerRadiusRatio="3"
        android:thicknessRatio="8" android:useLevel="false">

        <size android:width="48dip" android:height="48dip" />

        <gradient android:type="sweep" android:useLevel="false"
            android:startColor="#4c737373" android:centerColor="#4c737373"
            android:centerY="0.50" android:endColor="#ffffd300" />

    </shape>

</rotate>