text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _getShadowHost = require('../get/shadow-host');

var _getShadowHost2 = _interopRequireDefault(_getShadowHost);

exports['default'] = function (element) {
  if (element === document) {
    element = document.documentElement;
  }

  if (!element || element.nodeType !== Node.ELEMENT_NODE) {
    throw new TypeError('is/shadowed requires an argument of type Element');
  }

  return Boolean((0, _getShadowHost2['default'])({ context: element }));
};

module.exports = exports['default'];
//# sourceMappingURL=shadowed.js.map


text:
Ext.define('TouchTomatoes.proxy.RottenTomatoes', {
    extend: 'Ext.data.proxy.JsonP',
    alias: 'proxy.rottentomatoes',

    config: {
        url: "http://api.rottentomatoes.com/api/public/v1.0/",
        extraParams: {
            apikey: 'zsthp6qfmzr6nbk64pu92w9s'
        },
        filterParam: "q",
        limitParam: "page_limit",
        service: "movies.json",
        reader: {
            type: "json",
            rootProperty: "movies"
        }
    },
    getUrl: function() {
        return this.url + this.getService();
    },
    encodeFilters: function(filters) {
        if (Ext.isArray(filters) && filters.length > 0) return filters[0].getValue();
        return "";
    }
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace SiteApiTest\Service;

use DvsaAuthorisation\Service\AuthorisationServiceInterface;
use DvsaCommon\Auth\Assertion\UpdateVtsAssertion;
use DvsaCommon\Enum\PhoneContactTypeCode;
use DvsaCommon\Enum\SiteContactTypeCode;
use DvsaCommon\Utility\Hydrator;
use DvsaCommon\Validator\EmailAddressValidator;
use DvsaCommonApi\Filter\XssFilter;
use DvsaCommonApi\Service\AddressService;
use DvsaCommonApi\Service\ContactDetailsService;
use DvsaCommonApi\Service\Validator\AddressValidator;
use DvsaCommonApi\Service\Validator\ContactDetailsValidator;
use DvsaCommonApiTest\Service\AbstractServiceTestCase;
use DvsaCommonTest\TestUtils\MethodSpy;
use DvsaCommonTest\TestUtils\XMock;
use DvsaEntities\Entity\ContactDetail;
use DvsaEntities\Entity\Email;
use DvsaEntities\Entity\Phone;
use DvsaEntities\Entity\PhoneContactType;
use DvsaEntities\Entity\Site;
use DvsaEntities\Entity\SiteContact;
use DvsaEntities\Entity\SiteContactType;
use DvsaEntities\Mapper\AddressMapper;
use DvsaEntities\Repository\PhoneContactTypeRepository;
use DvsaEntities\Repository\SiteContactRepository;
use DvsaEntities\Repository\SiteContactTypeRepository;
use PHPUnit\Framework\MockObject\MockObject as MockObj;
use SiteApi\Service\SiteContactService;

/**
 * Class SiteContactServiceTest.
 */
class SiteContactServiceTest extends AbstractServiceTestCase
{
    const SITE_ID = 99999;
    const CONTACT_ID = 88888;

    /** @var SiteContactService */
    private $siteContactSrv;
    /** @var SiteContactRepository|MockObj */
    private $mockSiteContactRepo;
    /** @var SiteContactTypeRepository|MockObj */
    private $mockSiteContactTypeRepo;
    /** @var AuthorisationServiceInterface|MockObj */
    private $mockAuthService;
    /** @var UpdateVtsAssertion */
    private $updateVtsAssertion;
    /** @var UpdateVtsAssertion */
    private $mockUpdateVtsAssertion;

    public function setup()
    {
        $this->mockSiteContactRepo = XMock::of(SiteContactRepository::class);
        $this->mockSiteContactTypeRepo = XMock::of(SiteContactTypeRepository::class);
        $this->mockAuthService = $this->getMockAuthorizationService();

        $this->updateVtsAssertion = new UpdateVtsAssertion($this->mockAuthService);
        $this->mockUpdateVtsAssertion = Xmock::of(UpdateVtsAssertion::class);

        $this->siteContactSrv = new SiteContactService(
            $this->getMockEntityManager(),
            $this->createContactDetailsService(),
            $this->createXssFilterMock(),
            $this->updateVtsAssertion
        );

        XMock::mockClassField($this->siteContactSrv, 'siteContactRepo', $this->mockSiteContactRepo);
        XMock::mockClassField($this->siteContactSrv, 'siteContactTypeRepo', $this->mockSiteContactTypeRepo);
    }

    /**
     * @return ContactDetailsService
     */
    private function createContactDetailsService()
    {
        $entityManager = $this->getMockEntityManager();

        /** @var PhoneContactTypeRepository|MockObj $phoneContactTypeRepository */
        $phoneContactTypeRepository = XMock::of(PhoneContactTypeRepository::class);
        $phoneContactTypeRepository
            ->expects($this->any())->method('getByCode')
            ->willReturn(new PhoneContactType());

        $addressService = new AddressService(
            $entityManager,
            new Hydrator(),
            new AddressValidator(),
            new AddressMapper()
        );

        $contactDetailsService = new ContactDetailsService(
            $entityManager,
            $addressService,
            $phoneContactTypeRepository,
            new ContactDetailsValidator(new AddressValidator())
        );

        return $contactDetailsService;
    }

    /**
     * @return \PHPUnit\Framework\MockObject\MockObject
     */
    protected function createXssFilterMock()
    {
        $xssFilterMock = $this
            ->getMockBuilder(XssFilter::class)
            ->disableOriginalConstructor()
            ->getMock();

        $xssFilterMock
            ->method('filter')
            ->will($this->returnArgument(0));

        return $xssFilterMock;
    }

    private function createMockSiteContactServiceWithMockedUpdateVtsAssertion()
    {
        $siteContactService = new SiteContactService(
            $this->getMockEntityManager(),
            $this->createContactDetailsService(),
            $this->createXssFilterMock(),
            $this->mockUpdateVtsAssertion
        );
        XMock::mockClassField($siteContactService, 'siteContactRepo', $this->mockSiteContactRepo);
        XMock::mockClassField($siteContactService, 'siteContactTypeRepo', $this->mockSiteContactTypeRepo);

        return $siteContactService;
    }

    private function createSiteContact()
    {
        $site = new Site();

        $contactDetails = new ContactDetail();
        $contactDetails->addEmail(
            (new Email())
                ->setIsPrimary(true)
        );
        $contactDetails->addPhone(
            (new Phone())
                ->setIsPrimary(true)
                ->setContactType(
                    (new PhoneContactType())
                        ->setCode(PhoneContactTypeCode::BUSINESS)
                )
        );

        $siteContactType = new SiteContactType();
        $siteContactType->setCode(SiteContactTypeCode::BUSINESS);

        return new SiteContact($contactDetails, $siteContactType, $site);
    }

    /**
     * @dataProvider dataProvideTestPatchContactFromJson
     */
    public function testPatchContactFromJson($data, $expectedAsserts = null, $expectedException = null)
    {
        $this->siteContactSrv = $this->createMockSiteContactServiceWithMockedUpdateVtsAssertion();
        $siteContact = $this->createSiteContact();
        $this->mockSiteContactRepo->expects($this->any())->method('getHydratedByTypeCode')
            ->willReturn($siteContact);

        if (!empty($expectedException)) {
            $this->expectException($expectedException);
        } else {
            $siteContactRepoSpy = new MethodSpy($this->mockSiteContactRepo, 'save');
        }

        if (is_array($expectedAsserts)) {
            $spies = [];
            foreach ($expectedAsserts as $expectedAssert) {
                $spies[] = new MethodSpy($this->mockUpdateVtsAssertion, $expectedAssert);
            }
        }

        $this->siteContactSrv->patchContactFromJson(1, $data);

        if (isset($spies) && is_array($spies)) {
            /** @var MethodSpy $spy */
            foreach ($spies as $spy) {
                $this->assertEquals(1, $spy->invocationCount());
            }
        }

        if (isset($siteContactRepoSpy)) {
            /** @var ContactDetail $savedContact */
            $savedContact = $siteContactRepoSpy->paramsForLastInvocation()[0];

            if (array_key_exists('email', $data)) {
                $this->assertEquals($data['email'], $savedContact->getPrimaryEmail()->getEmail());
                $this->assertCount(1, $savedContact->getEmails());
            }

            if (array_key_exists('phone', $data)) {
                $this->assertEquals($data['phone'], $savedContact->getPrimaryPhone()->getNumber());
                $this->assertCount(1, $savedContact->getPhones());
            }

            if (array_key_exists('address', $data)) {
                $address = $data['address'];
                $addressFields = [
                    'addressLine1' => 'getAddressLine1',
                    'addressLine2' => 'getAddressLine2',
                    'addressLine3' => 'getAddressLine3',
                    'postcode' => 'getPostcode',
                    'town' => 'getTown',
                ];

                foreach ($addressFields as $field => $getter) {
                    if (array_key_exists($field, $address)) {
                        $this->assertEquals($address[$field], $savedContact->getAddress()->$getter());
                    }
                }
            }
        }
    }

    public function dataProvideTestPatchContactFromJson()
    {
        return [
            //Check if correct asserts are runned depending on data
            [
                'data' => [
                    'email' => 'sitecontactservicetest@'.EmailAddressValidator::TEST_DOMAIN,
                ],
                'expectedAsserts' => [
                    'assertUpdateEmail',
                ],
            ],
            [
                'data' => [
                    'phone' => '100200300',
                ],
                'expectedAsserts' => [
                    'assertUpdatePhone',
                ],
            ],
            [
                'data' => [
                    'address' => [
                        'town' => 'New Town',
                        'postcode' => '10-200',
                        'addressLine1' => 'Streeet',
                    ],
                ],
                'expectedAsserts' => [
                    'assertUpdateAddress',
                ],
            ],
            //Check asserts runned for full dataset
            [
                'data' => [
                    'email' => 'sitecontactservicetest@'.EmailAddressValidator::TEST_DOMAIN,
                    'phone' => '100200300',
                    'address' => [
                        'town' => 'New Town',
                        'postcode' => '10-200',
                        'addressLine1' => 'Streeet',
                    ],
                ],
                'expectedAsserts' => [
                    'assertUpdateEmail',
                    'assertUpdatePhone',
                    'assertUpdateAddress',
                ],
            ],
            //Check if exception is thrown if address is incomplete
            [
                'data' => [
                    'address' => [
                        'town' => 'New Town',
                        'postcode' => '10-200',
                    ],
                ],
                'expectedAsserts' => [],
                'expectedException' => 'DvsaCommonApi\Service\Exception\RequiredFieldException',
            ],
        ];
    }
}


text:
describe Facts::Freebsd::Identity::User do
  describe '#call_the_resolver' do
    subject(:fact) { Facts::Freebsd::Identity::User.new }

    let(:value) { 'root' }

    before do
      allow(Facter::Resolvers::PosxIdentity).to receive(:resolve).with(:user).and_return(value)
    end

    it 'calls Facter::Resolvers::PosxIdentity' do
      fact.call_the_resolver
      expect(Facter::Resolvers::PosxIdentity).to have_received(:resolve).with(:user)
    end

    it 'returns id and identity user name' do
      expect(fact.call_the_resolver).to be_an_instance_of(Array).and \
        contain_exactly(an_object_having_attributes(name: 'identity.user', value: value),
                        an_object_having_attributes(name: 'id', value: value, type: :legacy))
    end
  end
end


text:
<?php

namespace RI\RIBundle\Controller\Reportes;

use RI\DBRIBundle\Entity\Internaciones;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Null;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use RI\RIBundle\Utils\RI\RI;
use RI\RIBundle\Utils\RI\RIUtiles;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Filesystem\Filesystem;

use RI\RIBundle\Controller\Reportes\ReportesSET;

/**
 * Internacione controller.
 *
 */
class ReportesController extends Controller
{

    use ReportesSET;

    /**
     * Formulario para reporte.
     *
     * @Route("/central/planilla", name="reportes_index")
     * @Method("GET")
     */
    public function indexAction()
    {

        try {

            $this->get('app.ri.utiles');
            $efectores =
                RI::$doctrine->getRepository
                (RIUtiles::DB_BUNDLE . ':Efectores')
                    ->findByConfiguracionesSistemas();

        } catch (\Exception $e) {

            throw $e;

        }

        return $this->render('@RI/Reportes/reportes.html.twig', array('efectores' => $efectores));

    }

    /**
     * @Route("/ajax/generarArchivo", name="ajax_generarArchivo")
     * @Method({"GET"})
     */
    public function ajaxGenerarArchivo(Request $request)
    {

        $start = $request->query->get('start');

        $length = $request->query->get('length');

        $total = $request->query->get('total');

        $id_efector = $request->query->get('id_efector');

        $fecha_desde = $request->query->get('fecha_desde');

        $fecha_hasta = $request->query->get('fecha_hasta');

        $diagnosticos = $request->query->get('diagnosticos');

        $helper = $this->get('app.ri.helper.algorithmic');

        // Convertimos las fechas a formato DB

        $fecha_desde = $helper->formatoFechaBD($fecha_desde);

        $fecha_hasta = $helper->formatoFechaBD($fecha_hasta);

        $parametros = "";

        if ($id_efector == "")
            $parametros .= "NULL,";
        else {
            $parametros .= "'" . $id_efector . "',";
        }

        if ($fecha_desde == "")
            $parametros .= "NULL,";
        else {
            $parametros .= "'" . $fecha_desde . "',";
        }

        if ($fecha_hasta == "")
            $parametros .= "NULL,";
        else {
            $parametros .= "'" . $fecha_hasta . "',";
        }

        if ($diagnosticos == "")
            $parametros .= "NULL,";
        else {
            $parametros .= "'" . $diagnosticos . "',";
        }

        if ($diagnosticos == "")
            $parametros .= "NULL";
        else {
            $parametros .= "'" . $diagnosticos . "'";
        }

        $fileName = $request->query->get('fileName');

        // TRAEMOS LOS SELECTS QUE LUEGO SE VAN A EJECUTAR

        // CONSULTA

        $consulta = "
        SELECT
        internaciones_get_select_csv(true,".$parametros.") as 'cant',
        internaciones_get_select_csv(false,".$parametros.") as 'select'";

        /// FIN CONSULTA

        $sp = $this->getDoctrine()->getManager('default')->getConnection()->prepare($consulta);

        // Ejecuta sp

        $sp->execute();

        $info = $sp->fetchAll();

        // Creamos el where para todas las consultas

        //$consulta = Self::createWhereFunction($fecha_desde, $diagnosticos, $fecha_hasta, $id_efector);

        // Contamos la cantidad total de internaciones

        if ($total == 0) {

            $sql_cant = $info[0]['cant'];

            $sp2 = $this->getDoctrine()->getManager('default')->getConnection()->prepare($sql_cant);

            $sp2->execute();

            $info2 = $sp2->fetchAll();

            // Calculamos el total de registros encontados solo la primera función ajax que enviamos desde el cliente

            $total = $info2[0]['COUNT(*)'];

            if ($total == 0) {
                $output = array(
                    "start" => 0,
                    "length" => 0,
                    "finish" => true,
                    "total" => 0
                );

                return new JsonResponse($output);

            }

            date_default_timezone_set('America/Argentina/Buenos_Aires');

            $date = date('d-m-Y_h-i-s', time());

            $fileName = $id_efector . "_" . $date . ".csv";

        }

        if (($start + $length) > $total) {

            $length = $total - $start;

        }

        // Seteamos el path de salida

        $pathReportes = $this->getParameter('dir_archivos_reportes');

        $fichero = $pathReportes . '/' . $fileName;

        //ini_set('memory_limit', '-1');

        // Filesystem
        $fs = new Filesystem();
        if ($start == 0) {
            $fs->remove($fichero);
            $fs->dumpFile($fichero, '');
        }

        // Consulta que se ejecuta siempre

        $sql_select = $info[0]['select'];

        $sp2 = $this->getDoctrine()->getManager('default')->getConnection()->prepare($sql_select . " LIMIT " . $start . "," . $length);

        $sp2->execute();

        $internaciones_consulta = $sp2->fetchAll();

        // Fin consulta que se ejecuta siempre

        // Agregamos data al archivo

        $keys = array_keys($internaciones_consulta[0]);

        $texto = "";
        foreach ($keys as $key) {

            /*$find = array(";","\n","/");
            $replace = array(" ");
            $valor = str_replace($find,$replace,$line[$key]);*/

            $valor = preg_replace("/\r\n|\r|\n/", '', $key); // Funciona perfecto.
            $texto .= $valor . ";";
        }
        $texto .= "\n";

        file_put_contents($fichero, $texto, FILE_APPEND | LOCK_EX);

        foreach ($internaciones_consulta as $line) {

            $texto = "";
            foreach ($keys as $key) {

                /*$find = array(";","\n","/");
                $replace = array(" ");
                $valor = str_replace($find,$replace,$line[$key]);*/

                $valor = preg_replace("/\r\n|\r|\n/", '', $line[$key]); // Funciona perfecto.

                $texto .= $valor . ";";
            }
            $texto .= "\n";

            file_put_contents($fichero, $texto, FILE_APPEND | LOCK_EX);
        }

        // Fin agregamos data al archivo

        $start += $length;

        if ($start >= $total) {

            $finish = true;

        } else {

            $finish = false;

        }

        $output = array(
            "start" => $start,
            "length" => $length,
            "finish" => $finish,
            "total" => $total,
            "id_efector" => $id_efector,
            "fecha_desde" => $fecha_desde,
            "fecha_hasta" => $fecha_hasta,
            "diagnosticos" => $diagnosticos,
            "fileName" => $fileName
        );

        return new JsonResponse($output);

    }

    /**
     *
     * Bind parametros de las consultas para crear archivos
     *
     * @param $fecha_desde
     * @param $diagnosticos
     * @param $fecha_hasta
     * @param $id_efector
     * @param $stmt
     */
    private function bind($fecha_desde, $diagnosticos, $fecha_hasta, $id_efector, $stmt)
    {
        if ($fecha_desde != "") {
            $stmt->bindValue("fecha_desde", $fecha_desde);
        }

        /*if ($diagnosticos != "") {
            $stmt->bindValue("id_ciex_4", $diagnosticos);
        }*/

        if ($fecha_hasta != "") {
            $stmt->bindValue("fecha_hasta", $fecha_hasta);
        }

        if ($id_efector != NULL)
            $stmt->bindValue("id_efector", $id_efector);
    }

    /**
     * Arma el where de la consulta para crear archivo.
     *
     * @param $fecha_desde
     * @param $diagnosticos
     * @param $fecha_hasta
     * @param $id_efector
     * @return string
     */
    private function createWhereFunction($fecha_desde, $diagnosticos, $fecha_hasta, $id_efector)
    {

        // Creamos el where para todas las consultas

        $consulta = "AND d.id_internacion = i.id_internacion ";

        /*if ($diagnosticos != "") {
            $consulta .= "AND d.id_ciex_4 = :id_ciex_4 ";
        }*/

        if ($fecha_desde != "") {
            $consulta .= "AND i.ing_fecha_hora >= :fecha_desde ";
        }

        if ($fecha_hasta != "") {
            $consulta .= "AND i.ing_fecha_hora <= :fecha_hasta ";
        }

        if ($id_efector != NULL)
            $consulta .= "AND i.id_efector = :id_efector ";

        return $consulta;
    }

    /**
     * @Route("/ajax/descargarArchivo/{filename}", name="ajax_descargarArchivo")
     */
    public function ajaxDescargarArchivo($filename)
    {

        $pathReportes = $this->getParameter('dir_archivos_reportes');

        $ruta = $pathReportes . "/" . $filename;

        // BinaryFileResponse
        $response = new BinaryFileResponse($ruta);

        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);

        return $response;

    }

    /**
     * @Route("/ajax/cargarDianosticos", name="cargar_dianosticos")
     * @Method({"GET"})
     */
    public function cargar_dianosticos(Request $request)
    {

        $loc = $request->query->get('term');

        $jsonResponse = new Response('{}', 200);

        $jsonResponse->headers->set('Content-Type', 'application/json');

        $sql = "select

                CONCAT(c4.cod_3dig,c4.cod_4dig) AS 'CepsapCodigo',

                replace(c4.descripcion,',','') AS 'Descripcion'

                from ciex_4 c4

                where  (CONCAT(c4.cod_3dig,c4.cod_4dig) like '$loc%' or replace(c4.descripcion,',','') like '$loc%')

                Limit 25 ";

        $stmt = $this->getDoctrine()->getManager('default')->getConnection()->prepare($sql);

        $stmt->execute();

        $diagnosticos = $stmt->fetchAll();

        $data = array();

        foreach ($diagnosticos as $r) {
            //ALMACENA LOS DATOS EN UN ARRAY
            $data[] = array('label' => $r['CepsapCodigo'] . ' - ' . $r['Descripcion'], 'value' => $r['CepsapCodigo'] . ' - ' . $r['Descripcion'], 'id' => $r['CepsapCodigo']);

        }

        $jsonResponse->setContent(json_encode($data));
        return $jsonResponse;

    }

}


text:
<?php

namespace DDDominio\EventSourcing\Snapshotting;

use DDDominio\EventSourcing\Common\EventSourcedAggregateRootInterface;

class Snapshotter
{
    private $snapshotStrategies = [];

    /**
     * @param string $aggregateClass
     * @param ReflectionSnapshotTranslator $snapshotStrategy
     */
    public function addSnapshotTranslator($aggregateClass, $snapshotStrategy)
    {
        $this->snapshotStrategies[$aggregateClass] = $snapshotStrategy;
    }

    /**
     * @param EventSourcedAggregateRootInterface $aggregate
     * @return SnapshotInterface
     */
    public function takeSnapshot($aggregate)
    {
        return $this->snapshotStrategies[get_class($aggregate)]->buildSnapshotFromAggregate($aggregate);
    }

    /**
     * @param SnapshotInterface $snapshot
     * @return EventSourcedAggregateRootInterface
     */
    public function translateSnapshot($snapshot)
    {
        return $this->snapshotStrategies[$snapshot->aggregateClass()]->buildAggregateFromSnapshot($snapshot);
    }
}


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Magento_Reports::report">
                    <resource id="Magento_Reports::salesroot">
                        <resource id="Magento_Braintree::settlement_report" title="Braintree Settlement" sortOrder="80" />
                    </resource>
                </resource>
            </resource>
        </resources>
    </acl>
</config>


text:
package com.snippet.widget;

import com.snippet.R;
import com.snippet.widget.actionbar.ActionBarFragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class Tab2Fragment extends ActionBarFragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
            final Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }
        View view = inflater.inflate(R.layout.fragment_tab2, container, false);

        // Write view customization codes here

        return view;
    }

    @Override
    public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
        // Note: We must inflate main for action bar first, then call super
        // to hide options main for Android 2.x.
        inflater.inflate(R.menu.fragment_tab2, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(final MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.menu_tab2) {
            Toast.makeText(getActivity(), "Menu tab2", Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }
}


text:
package consumer

import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/betchi/tracer"
	logger "github.com/betchi/zapper"
	"github.com/confluentinc/confluent-kafka-go/kafka"
	"github.com/pkg/errors"
	"github.com/swagchat/chat-api/config"
	"github.com/swagchat/chat-api/model"
	"github.com/swagchat/chat-api/service"
	"github.com/swagchat/chat-api/utils"
	scpb "github.com/swagchat/protobuf/protoc-gen-go"
)

var client *kafka.Consumer

type kafkaProvider struct {
	ctx context.Context
}

func (kp *kafkaProvider) SubscribeMessage() error {
	span := tracer.StartSpan(kp.ctx, "SubscribeMessage", "consumer")
	defer tracer.Finish(span)

	cfg := config.Config()

	host := cfg.Consumer.Kafka.Host
	if host == "" {
		err := errors.New("consumer.kafka.host is empty")
		logger.Error(err.Error())
		tracer.SetError(span, err)
		return err
	}

	port := cfg.Consumer.Kafka.Port
	if port == "" {
		err := errors.New("consumer.kafka.port is empty")
		logger.Error(err.Error())
		tracer.SetError(span, err)
		return err
	}

	hostname, err := os.Hostname()
	if err != nil {
		hostname = utils.GenerateUUID()
	}

	sigchan := make(chan os.Signal, 1)
	signal.Notify(sigchan, syscall.SIGINT, syscall.SIGTERM)

	client, err := kafka.NewConsumer(&kafka.ConfigMap{
		"bootstrap.servers": fmt.Sprintf("%s:%s", host, port),
		"group.id":          hostname,
		// "session.timeout.ms":   6000,
		// "default.topic.config": kafka.ConfigMap{"auto.offset.reset": "earliest"}
	})
	if err != nil {
		logger.Error(err.Error())
		tracer.SetError(span, err)
		return err
	}

	topic := cfg.Consumer.Kafka.Topic
	err = client.SubscribeTopics([]string{topic}, nil)
	if err != nil {
		logger.Error(err.Error())
		tracer.SetError(span, err)
		return err
	}
	logger.Info(fmt.Sprintf("%s group.id[%s] topic[%s]", client.String(), hostname, topic))

	run := true

	for run == true {
		select {
		case sig := <-sigchan:
			run = false
			logger.Info(fmt.Sprintf("terminated by %s", sig.String()))
		default:
			ev := client.Poll(100)
			if ev == nil {
				continue
			}

			switch e := ev.(type) {
			case *kafka.Message:
				logger.Info("Receive a message")
				kafkaMsg := e
				if err != nil {
					logger.Error(err.Error())
					tracer.SetError(span, err)
					break
				}

				var pbMsg scpb.Message
				err = json.Unmarshal(kafkaMsg.Value, &pbMsg)
				if err != nil {
					logger.Error(err.Error())
					tracer.SetError(span, err)
					break
				}
				payload := model.JSONText{}
				err := payload.UnmarshalJSON(pbMsg.Payload)
				if err != nil {
					logger.Error(err.Error())
					tracer.SetError(span, err)
					break
				}

				msg := &model.Message{pbMsg, payload}
				req := msg.ConvertToSendMessageRequest()

				ctx := context.Background()
				ctx = context.WithValue(ctx, config.CtxUserID, msg.UserID)

				workspace := cfg.Datastore.Database
				for _, v := range kafkaMsg.Headers {
					logger.Debug(fmt.Sprintf("kafka header %s=%s", v.Key, string(v.Value)))
					if v.Key == config.HeaderWorkspace {
						workspace = string(v.Value)
					}
				}
				ctx = context.WithValue(ctx, config.CtxWorkspace, workspace)

				service.SendMessage(ctx, req)

			case kafka.PartitionEOF:
				logger.Info(e.String())
			case kafka.Error:
				run = false
				err = fmt.Errorf(e.String())
				logger.Error(err.Error())
				tracer.SetError(span, err)
			default:
				logger.Info(e.String())
			}
		}
	}

	client.Close()
	logger.Info("kafka close")

	return nil
}

func (kp *kafkaProvider) UnsubscribeMessage() error {
	span := tracer.StartSpan(kp.ctx, "UnsubscribeMessage", "consumer")
	defer tracer.Finish(span)

	if client == nil {
		return nil
	}

	logger.Info("kafka unsubscribe")
	return client.Unsubscribe()
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

def fill_username(apps, schema_editor):
    TolaUser = apps.get_model('workflow', 'TolaUser')
    for tola_user in TolaUser.objects.filter(name=' ').select_related('user'):
        auth_user = tola_user.user
        tola_user.name = "%s %s" % (auth_user.first_name, auth_user.last_name)
        tola_user.save()

def reverse_migration(apps, schema_editor):
    """Allow the reverse migration to happen"""
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('workflow', '0045_auto_20190425_1109'),
    ]

    operations = [
        migrations.RunPython(fill_username, reverse_code=reverse_migration),
    ]


text:
var Predicates = require("./Predicates")
  , Attributes = require("./Attributes")

function Scan(table, database) {
  this.TableName = table

  Object.defineProperty(
    this, "database",
    {value: database, enumerable: false}
  )
}

Scan.prototype = {
  filter: function(predicates) {
    this.ScanFilter = new Predicates(predicates)

    return this
  },

  get: function() {
    this.AttributesToGet = Array.prototype.concat.apply([], arguments)

    return this
  },

  count: function() {
    this.Count = true

    return this
  },

  limit: function(limit) {
    if(isNaN(limit) || ((limit|0) != limit) || (limit|0) < 1) {
      throw new Error("Limit should be an natural number");
    }

    this.Limit = limit;
    return this;
  },

  fetch: function(cb) {
    var self = this
      , response = []

    !function loop(ExclusiveStartKey) {
      self.database.request(
        "Scan",
        self,
        function fetch(err, data) {
          if (err) return cb(err)

          if (self.Count) return cb(null, data.Count)

          data.Items.forEach(function(item) {
            response.push(Attributes.prototype.parse(item))
          })

          if (data.LastEvaluatedKey) {
            if (self.Limit != null && self.Limit < response.length) {
              loop(data.LastEvaluatedKey)
            } else {
              cb(null, response)
            }
          } else {
            cb(null, response)
          }
        }
      )
    }(this.ExclusiveStartKey)

  }
}

module.exports = Scan


text:
global_foo = 1

def test_outer_function():
    foo = 1
    def bar():
        <weak_warning descr="Shadows name 'foo' from outer scope">foo</weak_warning>, <weak_warning descr="Shadows name 'bar' from outer scope">bar</weak_warning> = 1, 2
    def baz(<weak_warning descr="Shadows name 'foo' from outer scope">foo</weak_warning>, <weak_warning descr="Shadows name 'bar' from outer scope">bar</weak_warning>, <weak_warning descr="Shadows name 'baz' from outer scope">baz</weak_warning>):
        pass
    def nested():
        def <weak_warning descr="Shadows name 'baz' from outer scope">baz</weak_warning>(<weak_warning descr="Shadows name 'foo' from outer scope">foo</weak_warning>):
            <weak_warning descr="Shadows name 'bar' from outer scope">bar</weak_warning> = 1

def test_outer_class():
    baz = 1
    quux = 2
    spam = 3
    class C(object):
        def foo(self):
            def foo():
                def <weak_warning descr="Shadows name 'bar' from outer scope">bar</weak_warning>():
                    class <weak_warning descr="Shadows name 'C' from outer scope">C</weak_warning>:
                        def baz(self):
                            pass
            def bar():
                pass

            <weak_warning descr="Shadows name 'baz' from outer scope">baz</weak_warning> = 2

        def spam(self):
            pass

        quux = 1

def test_outer_global():
    global global_foo
    global_foo = 2

def test_outer_comprehensions():
    print(x for x in range(10))
    print([y for y in range(10)])
    def f(x, <weak_warning descr="Shadows name 'y' from outer scope">y</weak_warning>):
        pass

def test_outer_single_underscore():
    _ = "abc"
    def foo():
        _ = "def"

# PY-3996
def test_outer_underscore_prefixed():
    _a = "abc"
    def foo():
        <weak_warning descr="Shadows name '_a' from outer scope">_a</weak_warning> = "def"

# PY-3996
def test_outer_underscore_prefixed_parameter():
    def foo(_a):
        def bar(_a):
            print(_a)
        print(_a)


text:
#ifndef BSON_TIMEGM_PRIVATE_H
#define BSON_TIMEGM_PRIVATE_H

#include "bson-compat.h"
#include "bson-macros.h"

BSON_BEGIN_DECLS

time_t
_bson_timegm (struct tm *const tmp);

BSON_END_DECLS

#endif /* BSON_TIMEGM_PRIVATE_H */