text:
<?xml version="1.0" encoding="UTF-8"?>

<sect1 id="zend.controller.quickstart">
    <title>Zend_Controller - Быстрый старт</title>

    <sect2 id="zend.controller.quickstart.introduction">
        <title>Введение</title>
        <para>
            <classname>Zend_Controller</classname> является ядром системы MVC в Zend
            Framework. Аббревиатура MVC - сокращение от
            <ulink url="http://en.wikipedia.org/wiki/Model-view-controller">Model-View-Controller</ulink>
            (модель-вид-контроллер), это паттерн проектирования, предназначенный
            для отделения логики приложения от логики представления.
            <classname>Zend_Controller_Front</classname> реализует паттерн
            <ulink url="http://www.martinfowler.com/eaaCatalog/frontController.html">Front
            Controller</ulink>, в котором все запросы перехватываются
            фронт-контроллером (front controller) и перенаправляются отдельным
            контроллерам действий (action controllers), выбор которых
            производится по запрошенному URL.
        </para>
        <para>
            Система <classname>Zend_Controller</classname> построена с расчетом на
            расширяемость как через наследование от уже существующих классов
            и написание новых классов, реализующих различные интерфейсы и
            абстрактные классы, образующих основу семейства классов
            контроллеров, так и через написание плагинов или помощников действий
            для наращивания функциональности системы или управления ею.
        </para>
    </sect2>

    <sect2 id="zend.controller.quickstart.go">
        <title>Быстрый старт</title>

        <para>
            Если вам нужна более подробная информация, то сразу переходите к
            следующим разделам. Если хотите быстро начать работать с
            <classname>Zend_Controller</classname>, то читайте далее.
        </para>

        <sect3 id="zend.controller.quickstart.go.directory">
            <title>Создайте файловую структуру</title>

            <para>
                Первый шаг состоит в том, чтобы создать файловую
                структуру приложения. Ниже приведено типовое решение:
            </para>

            <programlisting language="php"><![CDATA[
application/
    controllers/
        IndexController.php
    models/
    views/
        scripts/
            index/
                index.phtml
        helpers/
        filters/
html/
    .htaccess
    index.php
]]>
            </programlisting>

        </sect3>

        <sect3 id="zend.controller.quickstart.go.docroot">
            <title>Установите корневую директорию для документов</title>

            <para>
                В своем веб-сервере установите директорию html из
                приведенной выше структуры в качестве корневой для
                веб-документов.
            </para>
        </sect3>

        <sect3 id="zend.controller.quickstart.go.rewrite">
            <title>Создайте свои правила перезаписи</title>

            <para>
                Отредактируйте файл html/.htaccess из
                приведенной выше структуры следующим образом:
            </para>

            <programlisting language="php"><![CDATA[
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
]]>
            </programlisting>

            <note>
                <title>Узнайте больше о mod_rewrite</title>

                <para>
                    Приведенные выше правила перезаписи позволяют получить
                    доступ к любому файлу в корневой для веб-документов
                    директории вашего виртуального хоста. Если
                    в ней есть файлы, которые нужно скрыть от посторонних глаз,
                    то вы наверное захотите установить более строгие правила.
                    Перейдите на сайт Apache, чтобы
                    <ulink
                        url="http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html">узнать больше о mod_rewrite</ulink>.
                </para>
            </note>

            <para>
                Если у вас IIS 7.0, то используйте следующую
                конфигурацию перезаписи:
            </para>

            <programlisting language="xml"><![CDATA[
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
     <system.webServer>
         <rewrite>
             <rules>
                 <rule name="Imported Rule 1" stopProcessing="true">
                     <match url="^.*$" />
                     <conditions logicalGrouping="MatchAny">
                         <add input="{REQUEST_FILENAME}"
                             matchType="IsFile" pattern=""
                             ignoreCase="false" />
                         <add input="{REQUEST_FILENAME}"
                             matchType="IsDirectory"
                             pattern="" ignoreCase="false" />
                     </conditions>
                     <action type="None" />
                 </rule>
                 <rule name="Imported Rule 2" stopProcessing="true">
                     <match url="^.*$" />
                     <action type="Rewrite" url="index.php" />
                 </rule>
             </rules>
         </rewrite>
     </system.webServer>
</configuration>
]]></programlisting>

            <para>
                Эти правила перезаписи пропускают запросы к
                существующим ресурсам (существующие символьные
                ссылки, непустые файлы и директории), все остальные запросы
                перенаправляются к фронт-контроллеру.
            </para>

            <note>
                <para>
                    Вышеприведенные правила перезаписи предназначены для
                    веб-сервера Apache. За примерами правил перезаписи для
                    других веб-серверов см. <link linkend="zend.controller.router.introduction">документацию
                    по маршрутизаторам</link>.
                </para>
            </note>
        </sect3>

        <sect3 id="zend.controller.quickstart.go.bootstrap">
            <title>Создайте файл загрузки</title>

            <para>
                Файл загрузки - это страница, на которую направляются все
                запросы, в нашем случае это html/index.php.
                Откройте html/index.php в любом текстовом редакторе
                и добавьте следующие строки:
            </para>

            <programlisting language="php"><![CDATA[
Zend_Controller_Front::run('/path/to/app/controllers');
]]></programlisting>

            <para>
                Этот код выполняет инстанцирование и запуск фронт-контроллера,
                который будет направлять запросы к контроллерам действий.
            </para>
        </sect3>

        <sect3 id="zend.controller.quickstart.go.controller">
            <title>Создайте свой контроллер действий, используемый по умолчанию</title>

            <para>
                До того, как начать обсуждение контроллеров действий, нужно
                сначала понять, как обрабатываются запросы в Zend Framework. По
                умолчанию первая часть пути в URL соответствует контроллеру, а
                вторая - действию. Например, дан URL
                http://framework.zend.com/roadmap/components. В нем
                путь /roadmap/components будет соответствовать
                контроллеру roadmap и действию
                components. Если не передано имя действия, то
                предполагается действие index; если не передано имя
                контроллера, то предполагается контроллер index (по
                соглашению Apache это соответствует
                DirectoryIndex).
            </para>

            <para>
                Диспетчер <classname>Zend_Controller</classname>-а принимает значение
                контроллера и находит соответствующий ему класс. По умолчанию
                это имя контроллера, начинающееся с заглавной буквы и со словом
                Controller в конце. Таким образом, контроллер
                roadmap будет соответствовать классу
                RoadmapController.
            </para>

            <para>
                Аналогичным образом устанавливается соответствие значения
                действия методу класса контроллера. По умолчанию значение
                приводится к нижнему регистру и к нему присоединяется слово
                Action. Таким образом, в нашем примере выше
                действие components будет методом с именем
                componentsAction, и в итоге вызов метода
                будет выглядеть следующим образом:
                RoadmapController::componentsAction().
            </para>

            <para>
                Итак, двигаемся дальше. Теперь приступим к созданию контроллера
                и действия, используемых по умолчанию. Как было замечено ранее,
                эти контроллер и действие должны оба называться
                index. Откройте файл
                application/controllers/IndexController.php и
                введите следующее:
            </para>

            <programlisting language="php"><![CDATA[
/** Zend_Controller_Action */
class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
    }
}
]]></programlisting>

            <para>
                По умолчанию включен помощник действий <link
                    linkend="zend.controller.actionhelpers.viewrenderer">ViewRenderer</link>.
                Это означает, что, просто определив метод действия и
                соответствующий скрипт вида, вы получите рендеринг контента.
                По умолчанию в MVC в качестве "вида" используется
                <classname>Zend_View</classname>. render() использует имя
                контроллера (например, index) и имя текущего
                действия (например, index) для определения того,
                какой шаблон тянуть. По умолчанию шаблоны имеют расширение
                .phtml, это значит, что в нашем примере будет
                использоваться шаблон index/index.phtml. Кроме
                этого, ViewRenderer автоматически
                предполагает, что директория views, находящаяся на
                том же уровне, что и директория контроллера, будет базовой
                директорией видов, и что действующие скрипты вида будут в
                поддиректории views/scripts/.
                Таким образом, шаблон для рендеринга будет находится в
                application/views/scripts/index/index.phtml.
            </para>
        </sect3>

        <sect3 id="zend.controller.quickstart.go.view">
            <title>Создайте скрипт вида</title>

            <para>
                Как было упомянуто в <link linkend="zend.controller.quickstart.go.controller">предыдущем
                разделе</link>, скрипты вида находятся в
                application/views/scripts/. Скриптом вида для
                контроллера и действия, используемых по умолчанию, является
                application/views/scripts/index/index.phtml.
                Создайте этот файл и добавьте в него какой-либо HTML-код:
            </para>

            <programlisting language="php"><![CDATA[
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>My first Zend Framework App</title>

Hello, World!

]]></programlisting>
        </sect3>

        <sect3 id="zend.controller.quickstart.go.errorhandler">
            <title>Создайте контроллер ошибок</title>

            <para>
                По умолчанию зарегистрирован <link
                linkend="zend.controller.plugins.standard.errorhandler">плагин-обработчик
                ошибок</link>. Этот плагин ожидает, что есть контроллер для
                обработки ошибок. По умолчанию он предполагает, что в модуле,
                используемом по умолчанию, имеется контроллер
                ErrorController с методом errorAction.
            </para>

            <programlisting language="php"><![CDATA[
class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
    }
}
]]></programlisting>

            <para>
                Согласно уже обсуждаемой выше структуре директорий этот файл
                будет находиться по пути
                application/controllers/ErrorController.php. Нужно
                также создать скрипт вида
                application/views/scripts/error/error.phtml, пример
                его содержимого:
            </para>

            <programlisting language="php"><![CDATA[
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Error</title>

An error occurred

An error occurred; please try again later.

]]></programlisting>
        </sect3>

        <sect3 id="zend.controller.quickstart.go.finish">
            <title>Смотрим сайт!</title>

            <para>
                Теперь, имея свои первые контроллер и вид, вы можете
                запустить свой броузер и просматривать сайт. Если ваш домен -
                example.com, то любой из следующих URL-ов будет
                возвращать ту страницу, которую вы только что создали:
            </para>

            <itemizedlist>
                <listitem><para>http://example.com/</para></listitem>
                <listitem><para>http://example.com/index</para></listitem>
                <listitem><para>http://example.com/index/index</para></listitem>
            </itemizedlist>

            <para>
                Теперь вы можете приступить к созданию других контроллеров и
                методы действий. Поздравляем!
            </para>
        </sect3>
    </sect2>
</sect1>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Madroño 22:68. 1973

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
/*global requireSocket */
"use strict";

const Room = requireSocket("controllers/room");

module.exports = app => {
    const room = Room(app);

    room.join("general");

    app.route("room.join", room.join)
       .route("room.leave", room.leave)
       .route("room.current", room.current)
       .route("room.getUserlist", room.getUserlist)

    return app;
};


text:
/**
 * Created by bmf on 11/2/13.
 */
var should = require('should');
var crypto = require('crypto');

var Key = require('../lib/keys/keypair');
if (process.env.COVERAGE) {
    Key = require('../lib-cov/keys/keypair');
}

describe("KeyPair", function () {
    it('generate should throw', function(done) {
        var key = new Key();
        (function() {
            key.init();
        }).should.throw();
        done();
    });

    it('generate should throw', function(done) {
        var key = new Key();
        (function() {
            key.generate();
        }).should.throw();
        done();
    });

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/ExampleParallaxRecycler.iml" filepath="$PROJECT_DIR$/ExampleParallaxRecycler.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/parallaxrecyclerview/parallaxrecyclerview.iml" filepath="$PROJECT_DIR$/parallaxrecyclerview/parallaxrecyclerview.iml" />
    </modules>
  </component>
</project>


text:
package es.polgomez.domain.interactors.poinofinterest;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import es.polgomez.domain.PointOfInterestDetail;
import es.polgomez.domain.PointsOfInterest;
import es.polgomez.domain.executor.MainThread;
import es.polgomez.domain.executor.ThreadExecutor;
import es.polgomez.domain.interactors.pointofinterest.GetPointOfInterestDetail;
import es.polgomez.domain.repository.PointOfInterestRepository;
import rx.Observable;
import rx.observers.TestSubscriber;

public class GetPointOfInterestDetailTest {

    private static final int FAKE_POI_ID = 4;

    @Mock
    PointOfInterestRepository pointOfInterestRepository;
    @Mock
    ThreadExecutor threadExecutor;

    @Mock
    MainThread mainThread;

    private GetPointOfInterestDetail getPointsOfInterestDetail;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        Mockito.when(pointOfInterestRepository.getPointsOfInterest(FAKE_POI_ID))
                .thenReturn(Observable.just(Mockito.mock(PointOfInterestDetail.class)));

        getPointsOfInterestDetail = new GetPointOfInterestDetail(FAKE_POI_ID, pointOfInterestRepository,
                threadExecutor, mainThread);
    }

    @Test
    public void testGetPointsOfInterestRequestExecution() {
        TestSubscriber<PointsOfInterest> testSubscriber = TestSubscriber.create();
        getPointsOfInterestDetail.execute(testSubscriber);

        // Test if the method is called one time
        Mockito.verify(pointOfInterestRepository, Mockito.times(1)).getPointsOfInterest(FAKE_POI_ID);
    }
}


text:
class StochasticTransparency;

enum class StochasticTransparencyOptimization { NoOptimization, AlphaCorrection, AlphaCorrectionAndDepthBased };

class StochasticTransparencyOptions
{
public:
    StochasticTransparencyOptions(StochasticTransparency & painter);
    ~StochasticTransparencyOptions();

    void initGL();

    unsigned char transparency() const;
    void setTransparency(unsigned char transparency);

    StochasticTransparencyOptimization optimization() const;
    void setOptimization(StochasticTransparencyOptimization optimization);

    bool backFaceCulling() const;
    void setBackFaceCulling(bool b);

    uint16_t numSamples() const;
    void setNumSamples(uint16_t numSamples);

    bool numSamplesChanged() const;

private:
    StochasticTransparency & m_painter;

    unsigned char m_transparency;
    StochasticTransparencyOptimization m_optimization;
    bool m_backFaceCulling;
    uint16_t m_numSamples;
    mutable bool m_numSamplesChanged;
};


text:
package gov.nih.nci.cagrid.fqp.service;

import gov.nih.nci.cagrid.common.FaultHelper;
import gov.nih.nci.cagrid.dcql.DCQLQuery;
import gov.nih.nci.cagrid.fqp.common.FQPConstants;
import gov.nih.nci.cagrid.fqp.processor.exceptions.FederatedQueryProcessingException;
import gov.nih.nci.cagrid.fqp.results.service.globus.resource.FederatedQueryResultsResource;
import gov.nih.nci.cagrid.fqp.results.service.globus.resource.FederatedQueryResultsResourceHome;
import gov.nih.nci.cagrid.fqp.results.stubs.types.FederatedQueryResultsReference;
import gov.nih.nci.cagrid.fqp.results.stubs.types.InternalErrorFault;
import gov.nih.nci.cagrid.introduce.servicetools.security.SecurityUtils;

import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import java.util.concurrent.ExecutorService;

import org.apache.axis.MessageContext;
import org.apache.axis.message.addressing.AttributedURI;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.fqp.execution.QueryExecutionParameters;
import org.cagrid.gaards.cds.client.DelegatedCredentialUserClient;
import org.cagrid.gaards.cds.delegated.stubs.types.DelegatedCredentialReference;
import org.globus.gsi.GlobusCredential;
import org.globus.wsrf.ResourceKey;
import org.globus.wsrf.container.ServiceHost;
import org.globus.wsrf.security.SecurityManager;
import org.globus.wsrf.utils.AddressingUtils;

/**
 * FQPAsynchronousExecutionUtil
 * Performs asynchronous execution of a federated query in the context of
 * a federated query results resource.
 *
 * @deprecated Replaced by FQPAsynchronousQueryUtil for DCQL 2 support
 * @author ervin
 */
public class FQPAsynchronousExecutionUtil {

    private static final int DEFAULT_RESULT_LEASE_MINS = 30;

    private static Log LOG = LogFactory.getLog(FQPAsynchronousExecutionUtil.class);

    private FederatedQueryResultsResourceHome resourceHome;
    private int leaseDurration = DEFAULT_RESULT_LEASE_MINS;
    private ExecutorService workExecutor = null;

    public FQPAsynchronousExecutionUtil(FederatedQueryResultsResourceHome resourceHome, ExecutorService workExecutor) {
        this(resourceHome, workExecutor, DEFAULT_RESULT_LEASE_MINS);
    }

    public FQPAsynchronousExecutionUtil(FederatedQueryResultsResourceHome resourceHome, ExecutorService workExecutor, int leaseDurration) {
        this.resourceHome = resourceHome;
        this.workExecutor = workExecutor;
        this.leaseDurration = leaseDurration;
    }

    public synchronized FederatedQueryResultsReference executeAsynchronousQuery(
        DCQLQuery query, DelegatedCredentialReference delegatedCredential, QueryExecutionParameters executionParameters)
        throws InternalErrorFault, FederatedQueryProcessingException {
        // use the resource home to create an FQP result resource
        FederatedQueryResultsResource fqpResultResource = null;
        ResourceKey key = null;
        try {
            key = resourceHome.createResource();
            fqpResultResource = (FederatedQueryResultsResource) resourceHome.find(key);
        } catch (Exception e) {
            String message = "Problem creating and accessing resource:" + e.getMessage();
            LOG.error(message, e);
            InternalErrorFault fault = new InternalErrorFault();
            fault.setFaultString(message);
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            throw (InternalErrorFault) helper.getFault();
        }

        // configure security on the resource so only the creator of the
        // resource (whoever is executing this method) can operate on it
        try {
            // may be null if no current caller
            fqpResultResource.setSecurityDescriptor(SecurityUtils.createCreatorOnlyResourceSecurityDescriptor());
        } catch (Exception e) {
            String message = "Problem configuring caller-only security on resource: " + e.getMessage();
            LOG.error(message, e);
            InternalErrorFault fault = new InternalErrorFault();
            fault.setFaultString(message);
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            throw (InternalErrorFault) helper.getFault();
        }

        LOG.info("Resource created for, and owned by: " + SecurityManager.getManager().getCaller());

        // set to terminate after lease expires
        Calendar termTime = Calendar.getInstance();
        termTime.add(Calendar.MINUTE, leaseDurration);
        fqpResultResource.setTerminationTime(termTime);

        // set the query
        fqpResultResource.setQuery(query);

        // set the credential (if any)
        if (delegatedCredential != null) {
            GlobusCredential clientCredential = validateAndRetrieveDelegatedCredential(delegatedCredential);
            fqpResultResource.setDelegatedCredential(clientCredential);
        }

        // set the query execution parameters
        fqpResultResource.setQueryExecutionParameters(executionParameters);

        // set the work manager for tasks the resource needs to do
        fqpResultResource.setWorkExecutor(workExecutor);

        // start the resource working on the query
        fqpResultResource.beginQueryProcessing();

        // return handle to resource
        FederatedQueryResultsReference resultsReference = createEPR(key);
        return resultsReference;
    }

    private synchronized GlobusCredential validateAndRetrieveDelegatedCredential(DelegatedCredentialReference reference) throws InternalErrorFault {
        // get the caller's ID
        String callerID = null;
        try {
            callerID = SecurityUtils.getCallerIdentity();
        } catch (Exception ex) {
            LOG.error("Error obtaining caller identity: " + ex.getMessage(), ex);
            FaultHelper helper = new FaultHelper(new InternalErrorFault());
            helper.addDescription("Error obtaining caller identity");
            helper.addDescription(ex.getMessage());
            helper.addFaultCause(ex);
            throw (InternalErrorFault) helper.getFault();
        }
        if (callerID == null) {
            // no null IDs with delegated credentials!
            FaultHelper helper = new FaultHelper(new InternalErrorFault());
            helper.setDescription("Caller identity found to be null while using a delegated credential!");
            throw (InternalErrorFault) helper.getFault();
        }
        GlobusCredential clientCredential = getDelegatedCredential(reference);
        // validate the caller's ID is the same as the credential they've delegated
        boolean valid = clientCredential.getIdentity().equals(callerID);
        if (!valid) {
            FaultHelper helper = new FaultHelper(new InternalErrorFault());
            helper.addDescription("Caller's identity and delegated credential identity did not match");
            throw (InternalErrorFault) helper.getFault();
        }
        return clientCredential;
    }

    private GlobusCredential getDelegatedCredential(DelegatedCredentialReference reference) throws InternalErrorFault {
        GlobusCredential userCredential = null;
        LOG.info("Retrieving delegated credential");
        try {
            DelegatedCredentialUserClient credentialClient =
                new DelegatedCredentialUserClient(reference);
            userCredential = credentialClient.getDelegatedCredential();
        } catch (Exception ex) {
            String message = "Error obtaining delegated credential from CDS";
            LOG.error(message, ex);
            FaultHelper helper = new FaultHelper(new InternalErrorFault());
            helper.addDescription(message);
            helper.addDescription(ex.getMessage());
            helper.addFaultCause(ex);
            throw (InternalErrorFault) helper.getFault();
        }
        return userCredential;
    }

    private FederatedQueryResultsReference createEPR(ResourceKey key) throws InternalErrorFault {
        MessageContext ctx = MessageContext.getCurrentContext();
        String transportURL = (String) ctx.getProperty(org.apache.axis.MessageContext.TRANS_URL);
        // modify URL to fix a bug https://gforge.nci.nih.gov/tracker/?func=detail&aid=22308&group_id=25&atid=174
        try {
            AttributedURI uri = new AttributedURI(transportURL);
            URL baseURL = ServiceHost.getBaseURL();
            String correctHost = baseURL.getHost();
            uri.setHost(correctHost);
            transportURL = uri.toString();
        } catch (IOException ex) {
            LOG.error("Problem returning reference to result:" + ex.getMessage(), ex);
            InternalErrorFault fault = new InternalErrorFault();
            fault.setFaultString("Problem returning reference to result:" + ex.getMessage());
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(ex);
            throw (InternalErrorFault) helper.getFault();
        }
        transportURL = transportURL.substring(0, transportURL.lastIndexOf('/') + 1);
        transportURL += FQPConstants.RESULTS_SERVICE_NAME;
        try {
            EndpointReferenceType epr = AddressingUtils.createEndpointReference(transportURL, key);
            return new FederatedQueryResultsReference(epr);
        } catch (Exception e) {
            LOG.error("Problem returning reference to result:" + e.getMessage(), e);
            InternalErrorFault fault = new InternalErrorFault();
            fault.setFaultString("Problem returning reference to result:" + e.getMessage());
            FaultHelper helper = new FaultHelper(fault);
            helper.addFaultCause(e);
            throw (InternalErrorFault) helper.getFault();
        }
    }
}


text:
from django.db import models
from django.core.exceptions import ValidationError
# abstract models with common fields to be
# used as mix-ins

class Named(models.Model):
    '''Abstract model with a 'name' field; by default, name is used as
    the string display.'''

    #: unique name (required)
    name = models.CharField(max_length=255, unique=True)

    class Meta:
        abstract = True
        ordering = ['name']

    def __str__(self):
        return self.name

class Notable(models.Model):
    '''Abstract model with an optional notes text field'''

    #: optional notes
    notes = models.TextField(blank=True)

    class Meta:
        abstract = True

    def has_notes(self):
        '''boolean flag indicating if notes are present, for display
        in admin lists'''
        return bool(self.notes)
    has_notes.boolean = True

class DateRange(models.Model):
    '''Abstract model with optional start and end years, and a
    custom dates property to display the date range nicely.  Includes
    validation that requires end year falls after start year.'''

    #: start year (optional)
    start_year = models.SmallIntegerField(null=True, blank=True)
    #: end year (optional)
    end_year = models.SmallIntegerField(null=True, blank=True)

    class Meta:
        abstract = True

    @property
    def dates(self):
        '''Date or date range as a string for display'''

        # if no dates are set, return an empty string
        if not self.start_year and not self.end_year:
            return ''

        # if start and end year are the same just return one year
        if self.start_year == self.end_year:
            return self.start_year

        date_parts = [self.start_year, '-', self.end_year]
        return ''.join([str(dp) for dp in date_parts if dp is not None])

    def clean_fields(self, exclude=None):
        '''Override to clean fields to make sure start/end year are sensical'''
        if exclude is None:
            exclude = []
        if 'start_year' in exclude or 'end_year' in exclude:
            return
        # require end year to be greater than or equal to start year
        # (allowing equal to support single-year ranges)
        if self.start_year and self.end_year and \
                self.end_year < self.start_year:
            raise ValidationError('End year must be after start year')


text:
var customLabel = {
    restaurant: {
        label: 'R'
    },
    bar: {
        label: 'A'
    }
};

function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
        center: new google.maps.LatLng(6.902431,79.861326),
        zoom: 16
    });
    var infoWindow = new google.maps.InfoWindow;

    // Change this depending on the name of your PHP or XML file
    downloadUrl('http://localhost/Projects/ciproject/index.php/Markers/', function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName('marker');
        Array.prototype.forEach.call(markers, function(markerElem) {
            var id = markerElem.getAttribute('id');
            var name = markerElem.getAttribute('name');
            var address = markerElem.getAttribute('address');
            var type = markerElem.getAttribute('type');
            var description =markerElem.getAttribute('description');
            var point = new google.maps.LatLng(
                parseFloat(markerElem.getAttribute('lat')),
                parseFloat(markerElem.getAttribute('lng')));
            var infowincontent = document.createElement('div');
            var strong = document.createElement('strong');
            strong.textContent = name;
            infowincontent.appendChild(strong);
            infowincontent.appendChild(document.createElement('br'));
            var text = document.createElement('text');
            text.textContent = address;
            infowincontent.appendChild(text);
            var icon = customLabel[type] || {};
            var marker = new google.maps.Marker({
                map: map,
                position: point,
                label: icon.label
            });
            marker.addListener('click', function() {
                infoWindow.setContent(infowincontent);
                infoWindow.open(map, marker);
            });
        });
    });
}

function downloadUrl(url, callback) {
    var request = window.ActiveXObject ?
        new ActiveXObject('Microsoft.XMLHTTP') :
        new XMLHttpRequest;

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
        }
    };

    request.open('GET', url, true);
    request.send(null);
}

function doNothing() {}


text:
from django import template
from canvas.details_models import ContentDetails
from canvas.models import Visibility
register = template.Library()

def _wh(content_data, ratio):
    return dict((dimension, int(content_data[dimension] / ratio),)
                for dimension in ['width', 'height'])

def _fit_inside(fit_w, fit_h, content_data):
    rw = float(content_data['width'])  / fit_w
    rh = content_data['height'] / fit_h
    ratio = max(1, rw, rh)
    return _wh(content_data, ratio)

def _fit_height(fit_h, content_data):
    ratio = float(content_data['height']) / fit_h
    return _wh(content_data, ratio)

def _fit_width(fit_w, content_data):
    ratio = float(content_data['width']) / fit_w
    return _wh(content_data, ratio)

def _size_attrs(content_data, fit_w=None, fit_h=None):
    if fit_w is None and fit_h is None:
        # Do nothing
        return {'width': content_data['width'], 'height': content_data['height']}
    elif fit_w is None:
        return _fit_height(fit_h, content_data)
    elif fit_h is None:
        return _fit_width(fit_w, content_data)
    else:
        return _fit_inside(fit_w, fit_h, content_data)

@register.inclusion_tag('content/tag.django.html')
def content(comment, content_details, image_type):
    """ Renders an html snippet (includes an img tag) for @content_details.
        param @image_type: Could be "column"
    """
    details = content_details
    if not isinstance(details, ContentDetails):
        details = ContentDetails(details)

    data = details[image_type]
    wh = _size_attrs(data)

    return {
        'url': details.get_absolute_url_for_image_type(image_type),
        'width': wh['width'],
        'height': wh['height'],
        # @TODO: Note the @comment here is a dict. The current version of the details does not store
        # is_visbile. Hence, we're duplicating the is_visibile code here.
        'alt': details.get("remix_text") if comment.get("visibility") == Visibility.PUBLIC else ""
    }


text:
SportsrocketQA Automation Test Report

Herewith attached the Test Report for the executed script in nightwatch.js.

Summary Information

            Report Generated Time
            Duration
            Tests Executed count
            Title

            Sat, 10 Jun 2017 11:47:38 GMT
            1063.1300000000003 sec
            15
            Fullscreen / Endslate / Autoplay / VideoplayerUI / Player-Playpause / Playthrough / Share_Facebook / Share / Share_Linkedin / Share_Google / Share_Pinterest / Share_Twitter / Share_Tumblr / Player-Progressbar / Player-Volume /

Test Statistics

            Total count of Pass
            Total count of Failures
            Total count of Errors
            Total count of Skipped

            8
            12
            23
            0


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="@deveshbinjola" />
    <meta name="twitter:site" content="@thtravelstudent" />
    <meta name="twitter:creator" content="@deveshbinjola" />
    <meta property="og:url" content="http://thetravelstudent.com/youngdriver" />
    <meta property="og:title" content="How to waive the Young Driver Fee" />
    <meta property="og:description" content= "Car rental companies charge drivers under age of 25 with a Young Driver Fee worth $15 - $25 per day. Most of the students are under 25 and it costs them a lot for renting card for daily purposes or vacations. So how to avoid these useless fees?"/>
    <meta property="og:image" content="http://thetravelstudent.com/Image/hertzgold.jpg" />
  <link rel="icon" href="/favicon.ico" type="image/x-icon" />

    <title>How to waive the Young Driver Fee</title>

  <link href="posts/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

  <link href="posts/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
  <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

  <link href="posts/css/clean-blog.min.css" rel="stylesheet">

      THE TRAVEL STUDENT
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        Menu

      </button>

            STUDENTS

            CREDIT CARDS

            BLOG

            DEALS

            ABOUT

How to waive the Young Driver Fee?

Waiving the extra fee.

            Posted by
              The Travel Student
              on August 31, 2016

Tweet

  Car rental companies charge drivers under age of 25 with a Young Driver Fee worth $15 - $25 per day. Most of the students are under 25 also many of th readers are under 25. It costs them a lot for a renting car for daily purposes or vacations. So how to avoid these useless fees?

  The best way to avoid the Young Driver fee is by taking the USAA Membership. It is reserved for Military people and their families but it allows other people to take membership and it is free of cost as well for using certain products and Car rentals is one of them.

    Taking USAA membership allows you (people under 25) save $15 - $25 per day. This is best way to save money on car rentals. You can save on Hertz, Enterprise, AVIS, Budget from USAA membership. Though i have only used it on Hertz and Enterprise. I have saved over $500 in this useless fee. I hope you guys can also take advantage to this membership and save money. Steps to sign up for USAA Membership and book rental cars(Hertz):

Just go to USAA and sign up for a membership.

After you are all set, search for auto car rentals.

            Benefits of Renting through USAA.

You can book/check here or link you account to Hertz account or even use the promo ode to book cars.

            Money you will be saving each day for rental.

Now book the cards through the links or through Hertz.

            Here's how my Hertz booking page looks like.

            My Hertz Account. You can see USAA membership.

I have been renting cars from when I was 19 (Only Hertz allows you to book cars from 19). You even get more discounts booking cars from USAA. I get 11% extra discount while booking from USAA. I have seen students book cars for insanely high prices. Car rentals can be really cheap if you just know how to make them and I am here to help you with. Read my post on how to avoid paying for insurance while renting cars.

The Travel Student © 2019


text:
@echo off
attrib -r %windir%\Prefetch\Layout.ini
IF %ERRORLEVEL% NEQ 0 (
ECHO ERROR: Cannot access the layout.ini file!
ECHO If you have UAC enabled give permission for the current user to access
ECHO the layout.ini file or the %windir%\Prefetch folder.
GOTO:END
)
echo Updating the prefetched files list, the layout.ini file..
echo This can take a while..
start /wait Rundll32.exe advapi32.dll, ProcessIdleTasks & echo Updated.
attrib +r %windir%\Prefetch\Layout.ini & echo Layout.ini file attribute set to read only.
:END
timeout /t 5
exit


text:
/**
 * Provides access to server events.
 * @author Johannes Donath <johannesd@evil-co.com>
 * @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.com>
 */
package org.evilco.network.rcon.server.event;


text:
<?xml version="1.0" encoding="utf-8"?>
<animation-list android:oneshot="false"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman01" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman02" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman03" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman04" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman05" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman06" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman07" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman08" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman09" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman10" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman11" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman12" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman13" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman14" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman15" />
    <item android:duration="@integer/peak" android:drawable="@drawable/droidman16" />
</animation-list>


text:
import os

(basepath, _) = os.path.split(os.path.abspath(__file__))

try:
    from distutils.core import run_setup

    # Run the setup script in the sandbox, so that it doesn't complain about unknown args when launched through nose
    run_setup(basepath + "/compile.py")

    from topo.sparse import sparse, sparsecf # pyflakes:ignore (try/except import)
except ImportError:
    print "WARNING: Install distutils and Cython to build sparse extension."


text:
<?php

namespace salyangoz\pazaryeriparasut;

use Parasut\Client as ParasutClient;
use Illuminate\Support\Facades\App;
use Mail;

class ParasutAdapter
{
    public $parasut;
    protected $localStorage;
    protected $invoice  =   [];
    protected $eInvoiceDefaults;
    protected $paymentPlatforms;

    public function __construct(array $config)
    {
        // create a new client instance
        $this->parasut = new ParasutClient([
            'client_id'     => array_get($config, 'parasut_client_id'),
            'client_secret' => array_get($config, 'parasut_client_secret'),
            'username'      => array_get($config, 'parasut_username'),
            'password'      => array_get($config, 'parasut_password'),
            'company_id'    => array_get($config, 'parasut_company_id'),
            'grant_type'    => 'password',
            'redirect_uri'  => 'urn:ietf:wg:oauth:2.0:oob',
        ]);

        $this->parasut->authorize();

        $this->localStorage =   new LocalStorage();

        $paymentPlatforms   =   [
            "HB"    =>  "Hepsiburada",
            "GG"    =>  "Gittigidiyor",
            "N11"   =>  "N11"
        ];

        $this->paymentPlatforms =   $paymentPlatforms;

        $this->eInvoiceDefaults =   [
            'internet_sale'         =>[
                "payment_type"      => config("pazaryeri-parasut.einvoice_payment_type"),
            ],
            'vat_withholding_code'  =>config("pazaryeri-parasut.einvoice_vat_withholding_code")
        ];

    }

    /**
     * Yeni müşteri kaydı oluşturur
     * @param $customerDetails
     * @return mixed
     */
    private function createContact($customerDetails)
    {
        return $this->parasut->make('contact')->create(
            $customerDetails
        );
    }

    /**
     * Paraşütte yeni ürün kaydı oluşturur
     * @param $productData
     * @return mixed
     */
    private function createProduct($productData)
    {
        return $this->parasut->make('product')->create(
            $productData
        );
    }

    /**
     * Faturaya ürün ekler
     * @param $productName
     * @param $productID
     * @return bool|mixed
     */
    private function setProduct($productName,$productID)
    {
        if(!$parasutProductID = $this->localStorage->get("product.{$this->marketplace}_".$productID))
        {
            $product = $this->createProduct(["name"=>$productName, "code"=>"{$this->marketplace}_".$productID]);

            $parasutProductID = $product['product']['id'];
            $this->localStorage->set('product',"{$this->marketplace}_{$productID}", $parasutProductID);
            $this->localStorage->save();
        }

        return $parasutProductID;
    }

    /**
     * Müşteri oluşturur ve faturaya ekler
     * @param $buyerID
     * @param $fullName
     * @param $address
     * @param $taxID
     * @param $taxOffice
     * @param $city
     * @param $district
     * @param $phone
     * @param $email
     * @return bool|mixed
     */
    public function setContact($contactType,$buyerID,$fullName,$address,$taxID,$taxOffice,$city,$district,$phone,$email)
    {

        $parasutContactID = $this->localStorage->get("customer.{$this->marketplace}_".$buyerID);

        if(!$parasutContactID){

            $parasutCustomer    =   [
                'contact_type'  =>  $contactType,
                'name' => $fullName,
                'email' => $email,
                'tax_number' => $taxID,
                'tax_office' => $taxOffice,
                'category_id' => null,
                'address_attributes' => [
                    'address' => $address,
                    'phone' => $phone,
                    'fax' => null,
                ],
                'city'     =>$city,
                'district' =>$district
            ];

            $contact            =   $this->createContact($parasutCustomer);
            $parasutContactID   =   $contact['contact']['id'];

            $this->localStorage->set('customer',"{$this->marketplace}_".$buyerID,$parasutContactID);
            $this->localStorage->save();
        }

        $this->invoice['contact_id']    =   $parasutContactID;

        return $parasutContactID;
    }

    /**
     * Ürün oluşturur ve faturaya ekler
     * @param $productName
     * @param $productID
     * @param $quantity
     * @param $amount
     */
    public function addProduct($productName,$productID,$quantity,$amount)
    {

        $parasutProductID   =   $this->setProduct($productName,$productID);

        $this->invoice['details_attributes'][] =
            [
                'product_id'        => $parasutProductID,
                'quantity'          => $quantity,
                'discount_value'    => 0,
                'discount_type'     => 'amount',
                'unit_price'        => ($amount) / (1 + 0.18),
                'vat_rate'          => 0.18 * 100,
            ];

    }

    /**
     * Bilgileri girilen faturayı kayıt eder
     * @param $saleID
     * @param $total
     * @param $invoiceDescription
     * @param $invoiceDate
     */
    public function saveInvoice($saleID,$total,$invoiceDescription,$invoiceDate,$taxNumber)
    {

        $this->invoice      =  array_merge($this->invoice,[
            'item_type'     => 'invoice',
            'description'   => $invoiceDescription,
            'issue_date'    => $invoiceDate,
            'invoice_series'=> $this->marketplace,
            'category_id'   => config("pazaryeri-parasut.parasut_category_id"),
            'payment_status'=> 'paid',
        ]);

        /**
         * Sipariş daha önce işlendiyse atlıyor
         */
        if($this->localStorage->get("order.{$this->marketplace}_{$saleID}"))
            return;

        try{

            /**
             * Fatura kaydı oluşturuluyor
             */
            $response = $this->parasut->make('sale')->create($this->invoice);

            /**
             * Fatura ödendi yapılıyor ve ödeme belirlenen hesap kasasına kaydediliyor
             */
            $this->parasut->make('sale')->paid(
                $response['sales_invoice']['id'],
                [   "amount"    =>  $total,
                    "date"      =>  date('Y-m-d'),
                    "account_id"=>  Config('pazaryeri-parasut.parasut_account_id')]
            );

            $this->localStorage->set('order',"{$this->marketplace}_".$saleID,$response['sales_invoice']['id']);
			$this->localStorage->save();

            $this->makeEInvoice("{$this->marketplace}_".$saleID, $response['sales_invoice']['id'], $taxNumber);

        }catch (\Exception $e)
        {
            echo $e->getMessage()."\n";
        }

    }

    private function makeEInvoice($saleID,$invoiceID,$taxNumber)
    {
		$this->localStorage->set('waiting_einvoice',$saleID,$invoiceID);
		$this->localStorage->save();

        /** İstek yapmadan önce daha önce istek yapılmış mı kontrol ediliyor */
        $eInvoiceStatus	=	$this->parasut->make('sale')->getEInvoiceStatus($invoiceID);

        if($eInvoiceStatus['status']!="done")
        {

            $eInvoiceTypeData	=	$this->parasut->make('sale')->getEInvoiceType($invoiceID);

            if($eInvoiceTypeData['e_document_type'] == 'e_archive' )
            {

                $this->eArchiveRequest($invoiceID);

            }
            elseif($eInvoiceTypeData['e_document_type'] == 'e_invoice' )
            {

                $this->eInvoiceRequest($invoiceID,$taxNumber);
            }
        }
        else
        {
            $this->localStorage->delete('waiting_einvoice',$saleID);
            $this->localStorage->save();
        }
    }

    private function eArchiveRequest($invoiceID)
    {
        $eArchiveResponse = $this->parasut->make('sale')->createEArchive($invoiceID,
            ["internet_sale"=>array_merge(
                $this->eInvoiceDefaults,["internet_sale"=>['payment_date'=>strtotime("now")]]
            )]);

        if(isset($eArchiveResponse['success'])) {

            if ($eArchiveResponse['success'] == 'OK') {

                return true;
            }
        }

        return false;
    }

    /** E-fatura isteği yapar
     * @param $saleToken
     * @param $invoice
     * @param $tax
     */
    private function eInvoiceRequest($invoiceID,$tax)
    {
        //Get customer inboxes
        $eInvoiceInboxes =  $this->parasut->make('sale')->getEInvoiceInboxes($tax);
        if($eInvoiceInboxes['e_invoice_inboxes'] !== null)
        {

            $inboxes        =   $eInvoiceInboxes['e_invoice_inboxes'];
            $inboxAddress	=   $inboxes[0]['e_invoice_address'];

            try{

                $eInvoiceResponse =  $this->parasut->make('sale')->createEInvoice($invoiceID,
                    array_merge(
                        [
                            'scenario'=>'commercial',
                            'to'=>$inboxAddress
                        ],
                        $this->eInvoiceDefaults
                    ));

                if($eInvoiceResponse['success'] !== null)
                {

                    if($eInvoiceResponse['success'] == 'OK')
                    {
                        return true;
                    }
                }

            }catch(Exception $e)
            {
                Log::error("Fatura isteği hatası (eInvoice) ({Fatura: $invoiceID}):".$e->getMessage());
            }
        }

    }

    /**
     * S3'e aktarılmamış veya emaili gönderilmemiş e-faturaları s3'e aktarır ve emailini iletir
     */
    public function transferEInvoices()
    {

        //E faturası bekleyen faturalar
        $eInvoiceRequestedInvoices = (array)$this->localStorage->get('waiting_einvoice');

        foreach ($eInvoiceRequestedInvoices as $orderID=>$invoice)
        {

            $eInvoiceStatus	=	$this->parasut->make('sale')->getEInvoiceStatus($invoice);
            $saleInvoice 	=	$this->parasut->make('sale')->find($invoice);

            if(isset($saleInvoice['error']))
            {
                continue;
            }

            if($eInvoiceStatus['status'] == "done" && $saleInvoice['sales_invoice']['item_type'] == 'invoice')
            {
                $saleInvoice = $this->parasut->make('sale')->find($invoice);
                $customer    = $saleInvoice['sales_invoice']['contact'];

                $eInvoicePath   =   $this->replaceTr(date('Y-m-d')."/{$customer['name']}-{$invoice}.pdf");

                $s3Transfer =   $this->s3Transfer($eInvoicePath, $eInvoiceStatus['pdf']['url']);

                if($s3Transfer)
                {

                    list($marketplace,$orderNumber)  =   explode('_',$orderID);
                    $marketplaceProvider =  $this->paymentPlatforms[$marketplace];

                    $emailSent = $this->sendEInvoiceMail($customer['name'], $customer['email'],
                                config('pazaryeri-parasut.aws.invoice_bucket_url').$eInvoicePath, $orderNumber,
                                "$marketplaceProvider"." ".config('pazaryeri-parasut.marketplace.name'));

                    /**
                     * Email de başarıyla gönderildiyse fatura e-faturası bekleyenler arasından siliniyor.
                     */
                    if($emailSent)
                    {
                        $this->localStorage->delete('waiting_einvoice',$orderID);
			$this->localStorage->save();
                    }
                }

            }
        }
    }

    /**
     * Metindeki türkçeye has karekterleri ingilizce alternatifleriyle değiştirir.
     * @param $text
     * @return string
     */
    public static function replaceTr($text) {
        $text = trim($text);
        $search = array('Ç','ç','Ğ','ğ','ı','İ','Ö','ö','Ş','ş','Ü','ü',' ', 'â', 'Â');
        $replace = array('c','c','g','g','i','i','o','o','s','s','u','u','_','a','a,');
        $new_text = str_replace($search,$replace,$text);
        return strtolower($new_text);
    }
}


text:
<!DOCTYPE html>

	<title>Integration with calendar</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/fonts/font_roboto/roboto.css"/>
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>


text:
1.2.0 (2015-03-12)
—
* Feature: add dashboard statistics widget
* Bugfix: parent folder images are now compressed too

1.1.0 (2015-02-09)
--
* Code refactoring and general cleanup
* Individual TinyPNG API class file
* Check files if they're already compressed (hash checksum)
* Better error handling (e.g. wrong API key)
* Removed Fork CMS license from files
* Default action is now Settings

1.0.0 (2015-02-07)
--
First public release


text:
#ifndef _PIPED_SIGNAL_H
#define _PIPED_SIGNAL_H

// #include "mace-macros.h"
#include "SockUtil.h"
#include "SysUtil.h"
#include "FileUtil.h"
#include "Log.h"
#include "maceConfig.h"

#ifndef HAVE_PIPE
#include "Util.h"
#include "Exception.h"
#include "ThreadCreate.h"
#include "NumberGen.h"
#include "m_net.h"
#endif

/**
 * \file PipedSignal.h
 * \brief defines the PipedSignal class
 */

/**
 * \brief Used for lock-free signalling of threads, and to allow a select thread to be awoken by signal.
 *
 * Two common uses for PipedSignal.  First, as a basic mutex/condition variable
 * style signal, and later as a second as a way to awaken threads in select.
 *
 * First (condition variable style signal):
 * \code
 * PipedSignal p;
 *
 * // thread 1:
 * p.wait();
 *
 * // thread 2:
 * p.signal();
 * \endcode
 *
 * Second (used for select):
 * \code
 * PipedSignal p;
 *
 * // thread 1:
 * fd_set rset;
 * int selectMax = 0;
 * // add any number of other sockets to select for reading on.
 * p.addToSet(rset, selectMax);
 * SysUtil::select(selectMax, rset);
 * p.clear(rset);
 *
 * // thread 2:
 * p.signal();
 * \endcode
 *
 * PipedSignal provides challenges for portability.  On Linux, you can select
 * on a pipe, allowing a simple version which in the constructor creates a pipe
 * and uses it for signalling and waiting.
 *
 * However, on Windows, you cannot select on a pipe.  To overcome this, the
 * Windows implementation spawns a new thread, waits for it to connect a socket
 * over localhost, and then the new thread dies.  Additionally, a new port
 * number series must be used to allocate the PipedSignal server sockets.
 *
 * A separate implemenation was briefly devised on Windows (kept in a compiled
 * out version here) which supports only the first model.  It does so by
 * actually using a mutex and condition variable with pthread_cond_timed_wait.
 * The primary use of the select version is in the Transport scheduler, to wake
 * the scheduler thread.  This can be worked around with a smaller timeout on
 * select.
 */
class PipedSignal
#ifdef HAVE_PIPE
{
#else
: public RunThreadClass {
  friend void _runNewThread(pthread_t* t, func f, void* arg,
			    pthread_attr_t* attr, const char* fname, bool joinThread);
  friend void _runNewThreadClass(pthread_t* t, RunThreadClass* c, classfunc f,
				 void* arg, pthread_attr_t* attr,
				 const char* fname, bool joinThread);
  friend void* connectSignal(void* vfa);
private:
  int16_t port;

  void* connectSignal(void* arg) {
    w = ::socket(AF_INET, SOCK_STREAM, 0);
    ASSERT(w >= 0);
    struct sockaddr_in sa;
    uint32_t bindaddr = ntohl(INADDR_LOOPBACK);
    SockUtil::fillSockAddr(bindaddr, port, sa);
    if (::connect(w, (struct sockaddr*)&sa, sizeof(sa)) < 0) {
      Log::perror("connect");
      ABORT("connect");
    }
    return NULL;
  }
#endif

public:
  PipedSignal() {
    #ifdef HAVE_PIPE
    int des[2];
    if(pipe(des) < 0) {
      Log::perror("pipe");
      ASSERT(0);
    }
    r = des[0];
    w = des[1];
    #else
    SockUtil::init();
    socket_t sv = socket(AF_INET, SOCK_STREAM, 0);
    if (sv < 0) {
      Log::perror("socket");
      ABORT("socket");
    }

    int n = 1;
    if (setsockopt(sv, SOL_SOCKET, SO_REUSEADDR, (char*)&n, sizeof(n)) < 0) {
      Log::perror("setsockopt");
      ABORT("setsockopt");
    }

    struct sockaddr_in sa;
    uint32_t bindaddr = ntohl(INADDR_LOOPBACK);
    ASSERT(params::containsKey("PIPED_SIGNAL_SOCKET_PORT"));
    port = NumberGen::Instance("PIPED_SIGNAL_SOCKET_PORT")->GetVal();
    SockUtil::fillSockAddr(bindaddr, port, sa);

    if (bind(sv, (struct sockaddr*)&sa, sizeof(sa)) < 0) {
      Log::perror("bind");
      ::close(sv);
    }
    if (listen(sv, 1) < 0) {
      Log::perror("listen");
      ABORT("listen");
    }

    sockaddr_in sin;
    socklen_t sinlen = sizeof(sin);
    memset(&sin, 0, sinlen);
    pthread_t pt;
    _runNewThreadClass(&pt, this, (classfunc)&PipedSignal::connectSignal, 0, 0, "PipedSignal::constructor", false);
    r = ::accept(sv, (struct sockaddr*)&sin, &sinlen);
    ASSERT(r > 0);
    pthread_join(pt, NULL);
    ::close(sv);

    #endif
    SockUtil::setNonblock(r);
    SockUtil::setNonblock(w);
    FD_ZERO(&rset);
  }

  virtual ~PipedSignal() {
    close();
  }

  /// adds the PipedSignal read fd to the fd_set \c s, and updates selectMax if needed.
  void addToSet(fd_set& s, socket_t& selectMax) const {
    //     Log::log("PipedSignal::addToSet") << "Adding socket " << r << " to fdset" << Log::endl;
    FD_SET(r, &s);
    selectMax = std::max(selectMax, r);
  }

  /// if using addToSet, after select call clear with the resulting read set to read bytes from it.
  bool clear(fd_set& s) {
    bool ret = FD_ISSET(r, &s);
    if (ret) {
      read(s);
    }
    FD_CLR(r, &s);
    return ret;
  }

  /// used to awaken a piped signal thread
  /**
   * an interesting side effect of using PipedSignal is that the signal() can
   * be called before wait(), and then wait() will return immediately as there
   * should be bytes to read.
   */
  void signal() {
    #ifdef HAVE_PIPE
    if (::write(w, " ", 1) < 0) {
      if (!SockUtil::errorWouldBlock()) {
        Log::perror("PipedSignal::signal");
      }
    }
    #else
    ::send(w, " ", 1, 0);
    #endif
  }

  /// wait for the read fd to be signalled, with an optional timeout (0 means sleep forever)
  int wait(uint64_t usec = 0) {
    //     Log::log("PipedSignal::wait") << "Waiting for " << usec << Log::endl;
    FD_SET(r, &rset);
    int n = SysUtil::select(r + 1, &rset, 0, 0, usec);
    if (n) {
      read(rset);
    }
    //     Log::log("PipedSignal::wait") << "Done waiting for " << usec << Log::endl;
    return n;
  }

  /// cleans up the state from the PipedSignal
  void close() {
    ::close(r);
    ::close(w);
  }

private:
  inline void read(fd_set& rs) {
    #ifdef HAVE_PIPE
    ASSERT(FD_ISSET(r, &rs));
    FileUtil::read(r);
    #else
    int ret = 0;
    char buf[1024];
    do {
      ret = ::recv(r, buf, 1024, 0);
    } while (ret > 0);
    #endif
  }

private:
  socket_t r;
  socket_t w;
  fd_set rset;
}; // PipedSignal

#if 0

// Using Windows CreatePipe and WaitForObject
#include "ScopedLock.h"
#include "TimeUtil.h"

class PipedSignal {
public:
  PipedSignal() : waiting(false), signalled(false), mutex(PTHREAD_MUTEX_INITIALIZER), cond(PTHREAD_COND_INITIALIZER) {

  }

  virtual ~PipedSignal() {
  }

  void signal() {
    ScopedLock sl(mutex);
    if (!signalled) {
      signalled = true;
      if (waiting) {
        pthread_cond_signal(&cond);
      }
    }
  }

  int wait(uint64_t usec = 0) {
    struct timeval t;
    struct timespec ts;
    uint64_t fintime = TimeUtil::timeu() + usec;
    TimeUtil::fillTimeval(fintime, t);
    ts.tv_sec = t.tv_sec;
    ts.tv_nsec = t.tv_usec * 1000;
    ScopedLock sl(mutex);
    if (!signalled ) {
      waiting = true;
      pthread_cond_timedwait(&cond, &mutex, &ts);
    }
    waiting = false;
    signalled = false;
    return 0;
  }

private:
  bool waiting;
  bool signalled;
  pthread_mutex_t mutex;
  pthread_cond_t cond;
}; // PipedSignal

#endif

#endif // _PIPED_SIGNAL_H


text:
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { run } from '@ember/runloop';

export default Component.extend({
  resizeableColumns: service(),
  classNames: ['row', 'twiddle-panes'],
  classNameBindings: ['fileTreeShown'],

  init() {
    this._super(...arguments);
    this.resizeableColumns; // ensure service created
  },

  didRender() {
    this._super(...arguments);
    run.schedule('afterRender', this, this.setupHandles);
  },

  setupHandles() {
    if (!this.get('media.isMobile')) {
      this.$('.twiddle-pane').after('

');
      this.$('.handle').last().remove();
      this.$('.handle').drags({ pane: '.twiddle-pane', min: 20 });
    }
  },

  willUpdate() {
    this.cleanupDrags();
  },

  willDestroyElement() {
    this._super(...arguments);

    this.cleanupDrags();
  },

  cleanupDrags() {
    this.$('.handle').drags("destroy");
    this.$('.handle').remove();
  }
});


text:
<?php

require_once('common.inc');
startpage(UNRESTRICTED);
?>
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="theme.css" />
<link rel="icon" type="image/png" href="shcicon.png" />
<title>SHC Manager</title>

Welcome to the Summer Hiatus Challenge 2017 homepage!

The Summer Hiatus Challenge is a competition on
jboard.tv (and, previously, the official Sony Jeopardy!
message boards).  Now in its thirteenth iteration, the Summer Hiatus Challenge
gives Jeopardy! fans and contestant hopefuls the opportunity
to participate in a fun trivia challenge with clues in the style of
the clues featured on Jeopardy!.

Use the navigation links at the bottom of this page to access all the
information available on this site, including current standings and
the clues in use for this competition.  If you have permission, you can
also perform administrative actions like grading and adding new clues
and users to the database.

<?php footer();?>


text:
package com.qtt.tool.util;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//==========================================================================
/**This class contains various number manipulation methods. */
//==========================================================================
public class NumberUtil
{
  private static Pattern m_notIntegerPattern = Pattern.compile("[^0-9\\-]");
  private static Pattern m_notDecimalPattern = Pattern.compile("[^0-9\\.\\-]");
  private static Pattern m_endWithDot = Pattern.compile("\\.$");
  public static NumberFormat m_currencyFormat;
  public static NumberFormat m_integerFormat;
  public static NumberFormat m_percentFormat;
  public static DecimalFormat m_decimalFormat;
  public static DecimalFormat m_decimalFormatPrecise;
  public static DecimalFormat m_currencyFormatTax;

  static
  {
    m_currencyFormat = NumberFormat.getCurrencyInstance();
    m_integerFormat = NumberFormat.getIntegerInstance();
    m_percentFormat = NumberFormat.getPercentInstance();
    m_decimalFormat = new DecimalFormat("0.00");
    m_decimalFormatPrecise = new DecimalFormat("0.00000");
    m_currencyFormatTax = new DecimalFormat("###,##0.00");
    m_currencyFormatTax.setNegativePrefix("(");
    m_currencyFormatTax.setNegativeSuffix(")");
  }

  public static String toMillion(double value)
  {
    value /= 1000000;
    return m_currencyFormat.format(value);
  }

  public static String toCurrencyFormat(double value)
  {
    return m_currencyFormat.format(value);
  }

  public static String toCurrencyFormat(Object value)
  {
    return m_currencyFormat.format(value);
  }

  public static String toIntegerFormat(Object value)
  {
    return m_integerFormat.format(value);
  }

  public static String toTaxCurrency(double number)
  {
    return m_currencyFormatTax.format(number);
  }

  public static String toTaxCurrency(String numberStr)
  {
    return toTaxCurrency(Double.parseDouble(numberStr));
  }

  public static String toPercentFormat(String value)
  {
    return toPercentFormat(Double.parseDouble(value));
  }

  public static String toPercentFormat(double value)
  {
    return m_percentFormat.format(value);
  }

  public static String toDecimalFormat(Object value)
  {
    return m_decimalFormat.format(value);
  }

  public static String toPreciseDecimalFormat(Object value)
  {
    return m_decimalFormatPrecise.format(value);
  }

  public static String parseDecimal(String number)
  {
    // Get rid of non decimal characters.
    String newNumber = parseNumber(number, m_notDecimalPattern);

    // "1." will be replaced with "1.0"
    Matcher matcher = m_endWithDot.matcher(newNumber);
    if (matcher.find())
      return newNumber + "0";

    return newNumber;
  }

  public static String parseInteger(String number)
  {
    // Get rid of non integer characters.
    return parseNumber(number, m_notIntegerPattern);
  }

  private static String parseNumber(String number, Pattern pattern)
  {
    Matcher matcher = pattern.matcher(number);
    number = matcher.replaceAll("");

    if (number.length() <= 0)
      return "0";
    return number;
  }

  //-----------------------------------------------------------------------
  /**Found out how many digits a number takes.
   *
   * @param number  The number we want to find the # of digits.
   * @return  The # of digits of 'number'. */
  //-----------------------------------------------------------------------
  public static int digitCount(int number)
  {
    int digit=0;

    if (number==0) return 1;

    if (number<0) number=-number;

    while ( number >= 1 )
    {
      number/=10;
      digit++;
    }

    return digit;
  }

  //-----------------------------------------------------------------------
  /**Calculate the # of bytes need to according to the  width and bitcount.
   *
   * @param width   The the width of an image.
   * @param bitCount  The # of bits used.
   * @return  Returns the # of bytes. */
  //-----------------------------------------------------------------------
  public static int byteWidth(int width, int bitCount)
  {
    int n=width*bitCount;
    return n/8 + ((n%8==0)?0:1);
  }

  //-----------------------------------------------------------------------
  /**Round the number up to fit multiple of blocks. This is good for
   * calculating the actually disk space a file really takes.
   * Ex: (511,512)=512, (512,512)=512, (513,512)=1024.
   *
   * @param number  The number.
   * @param block   The block for 'number' to fit in.
   * @return The number that fit in multiple 'block'. */
  //-----------------------------------------------------------------------
  public static long upperNumber(int number, int block)
  {
    if (number<=0) return 0;
    if (block<=0) return number;

    return number/block*block+((number%block)==0?0:1)*block;
  }

  //-----------------------------------------------------------------------
  /**Extract a digit from an integer.
   *
   * @param number  The integer.
   * @param position  The decimal place of the digit from right to left.
   *                  0 is the first digit.
   * @return On success, will return the digit.
   *         On failure, will return 0. */
  //-----------------------------------------------------------------------
  public static int getDigit(int number, int position)
  {
    int n=number;
    while(position>0)
    {
      n/=10;
      if (n==0) return 0;
      position--;
    }

    return n % 10;
  }

  //-----------------------------------------------------------------------
  /**Delete a digit from an integer.  If digit is in the middle
   * position, it will be turned to 0.
   *
   * @param number  The number.
   * @param position  The decimal place of the digit from right to left.
   *                  0 is the first digit.
   * @return  Returns a new integer that has the specified digit deleted.*/
  //-----------------------------------------------------------------------
  public static long ridDigit(int number, int position)
  {
    int i;
    int digit=getDigit(number,position);

    // No change since digit is 0.
    if (digit==0) return number;

    for(i=0; i<position; i++)
      digit*=10;

    number-=digit;
    return number;
  }

  //-----------------------------------------------------------------------
  /**Convert a byte to unsigned byte.
   *
   * @param number  The byte to convert to an unsigned number.
   * @return  The unsigned byte number. */
  //-----------------------------------------------------------------------
  public static int toUnsignedByte(byte number)
  {
    return number & 0xff;
  }

  //-----------------------------------------------------------------------
  /**Convert a short to unsigned short.
   *
   * @param number  The short to convert to an unsigned number.
   * @return  The unsigned short number. */
  //-----------------------------------------------------------------------
  public static int toUnsignedShort(short number)
  {
    return number & 0xffff;
  }

  //-----------------------------------------------------------------------
  /** Convert an int to unsigned int.
   *
   * @param number  The int to convert to an unsigned number.
   * @return  The unsigned int number. */
  //-----------------------------------------------------------------------
  public static long toUnsignedInt(int number)
  {
    return number & 0xffffffffL;
  }

  public static short toShort(String number)
  {
    if (number != null && number.trim().length() != 0)
    {
      try
      {
        return Short.parseShort(number);
      }
      catch(NumberFormatException e){}
    }

    return 0;
  }

  public static int toInt(String number)
  {
    if (number != null && number.trim().length() != 0)
    {
      try
      {
        return Integer.parseInt(number);
      }
      catch(NumberFormatException e){}
    }

    return 0;
  }

  public static long toLong(String number)
  {
    if (number != null && number.trim().length() != 0)
    {
      try
      {
        return Long.parseLong(number);
      }
      catch(NumberFormatException e){}
    }

    return 0L;
  }

  public static float toFloat(String number)
  {
    if (number != null && number.trim().length() != 0)
    {
      try
      {
        return Float.parseFloat(number);
      }
      catch(NumberFormatException e){}
    }

    return 0.0f;
  }

  public static double toDouble(String number)
  {
    if (number != null && number.trim().length() != 0)
    {
      try
      {
        return Double.parseDouble(number);
      }
      catch(NumberFormatException e){}
    }

    return 0.0;
  }

  public static boolean toBoolean(String number)
  {
    if (number != null && number.trim().length() != 0)
    {
      try
      {
        return Boolean.parseBoolean(number);
      }
      catch(NumberFormatException e){}
    }

    return false;
  }
}


text:
<?php

namespace Sonata\NewsBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SonataNewsBundle extends Bundle
{

}


text:
<?php

namespace Bundle\KidskulaBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AccountFileUploadType extends AbstractType{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('file', 'file', array(
            'label' => 'Profile Image',
            'label_attr' => array('class' => 'col-md-4 control-label'),
            'required' => true,
            'data_class' => null,
            'attr' => array(
                'class' => 'form-control'
            ),
            //...
        )) ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
			'data_class' => 'Bundle\AdminBundle\Entity\KidskulaUsersProfile'
        ));
    }

    /**
     * @return string
     */
    public function getName() {
        //return 'vet_adminbundle_vetcommusers_Account_Profilefic';
		return 'bundle_adminbundle_kidskulausersprofile';
    }

	//put your code here
}


text:
<?php

namespace GEMA\gemaBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ColaboradorType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('nombre')
            ->add('ubicacion')
            ->add('datos')
            ->add('guid',null,array(
                'label_attr'=>array(
                    'style'=>'display:none'
                ),
                'attr'=>array(
                    'style'=>'display:none'
                )
            ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'GEMA\gemaBundle\Entity\Colaborador'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'gema_gemabundle_colaborador';
    }
}


text:
<?php

namespace Kint;

class CallFinder
{
    private static $ignore = [
        T_CLOSE_TAG => true,
        T_COMMENT => true,
        T_DOC_COMMENT => true,
        T_INLINE_HTML => true,
        T_OPEN_TAG => true,
        T_OPEN_TAG_WITH_ECHO => true,
        T_WHITESPACE => true,
    ];

    /**
     * Things we need to do specially for operator tokens:
     * - Refuse to strip spaces around them
     * - Wrap the access path in parentheses if there
     *   are any of these in the final short parameter.
     */
    private static $operator = [
        T_AND_EQUAL => true,
        T_BOOLEAN_AND => true,
        T_BOOLEAN_OR => true,
        T_ARRAY_CAST => true,
        T_BOOL_CAST => true,
        T_CLASS => true,
        T_CLONE => true,
        T_CONCAT_EQUAL => true,
        T_DEC => true,
        T_DIV_EQUAL => true,
        T_DOUBLE_CAST => true,
        T_FUNCTION => true,
        T_INC => true,
        T_INCLUDE => true,
        T_INCLUDE_ONCE => true,
        T_INSTANCEOF => true,
        T_INT_CAST => true,
        T_IS_EQUAL => true,
        T_IS_GREATER_OR_EQUAL => true,
        T_IS_IDENTICAL => true,
        T_IS_NOT_EQUAL => true,
        T_IS_NOT_IDENTICAL => true,
        T_IS_SMALLER_OR_EQUAL => true,
        T_LOGICAL_AND => true,
        T_LOGICAL_OR => true,
        T_LOGICAL_XOR => true,
        T_MINUS_EQUAL => true,
        T_MOD_EQUAL => true,
        T_MUL_EQUAL => true,
        T_NEW => true,
        T_OBJECT_CAST => true,
        T_OR_EQUAL => true,
        T_PLUS_EQUAL => true,
        T_REQUIRE => true,
        T_REQUIRE_ONCE => true,
        T_SL => true,
        T_SL_EQUAL => true,
        T_SR => true,
        T_SR_EQUAL => true,
        T_STRING_CAST => true,
        T_UNSET_CAST => true,
        T_XOR_EQUAL => true,
        T_POW => true,
        T_POW_EQUAL => true,
        T_DOUBLE_ARROW => true,
        '!' => true,
        '%' => true,
        '&' => true,
        '*' => true,
        '+' => true,
        '-' => true,
        '.' => true,
        '/' => true,
        ':' => true,
        '<' => true,
        '=' => true,
        '>' => true,
        '?' => true,
        '^' => true,
        '|' => true,
        '~' => true,
    ];

    private static $strip = [
        '(' => true,
        ')' => true,
        '[' => true,
        ']' => true,
        '{' => true,
        '}' => true,
        T_OBJECT_OPERATOR => true,
        T_DOUBLE_COLON => true,
        T_NS_SEPARATOR => true,
    ];

    private static $classcalls = [
        T_DOUBLE_COLON => true,
        T_OBJECT_OPERATOR => true,
    ];

    private static $namespace = [
        T_STRING => true,
    ];

    public static function getFunctionCalls($source, $line, $function)
    {
        static $up = [
            '(' => true,
            '[' => true,
            '{' => true,
            T_CURLY_OPEN => true,
            T_DOLLAR_OPEN_CURLY_BRACES => true,
        ];
        static $down = [
            ')' => true,
            ']' => true,
            '}' => true,
        ];
        static $modifiers = [
            '!' => true,
            '@' => true,
            '~' => true,
            '+' => true,
            '-' => true,
        ];
        static $identifier = [
            T_DOUBLE_COLON => true,
            T_STRING => true,
            T_NS_SEPARATOR => true,
        ];

        if (KINT_PHP70) {
            self::$operator[T_SPACESHIP] = true;
        }

        if (KINT_PHP74) {
            self::$operator[T_COALESCE_EQUAL] = true;
        }

        if (KINT_PHP80) {
            $up[T_ATTRIBUTE] = true;
            self::$operator[T_MATCH] = true;
            self::$strip[T_NULLSAFE_OBJECT_OPERATOR] = true;
            self::$classcalls[T_NULLSAFE_OBJECT_OPERATOR] = true;
            self::$namespace[T_NAME_FULLY_QUALIFIED] = true;
            self::$namespace[T_NAME_QUALIFIED] = true;
            self::$namespace[T_NAME_RELATIVE] = true;
            $identifier[T_NAME_FULLY_QUALIFIED] = true;
            $identifier[T_NAME_QUALIFIED] = true;
            $identifier[T_NAME_RELATIVE] = true;
        }

        $tokens = \token_get_all($source);
        $cursor = 1;
        $function_calls = [];
        // Performance optimization preventing backwards loops
        $prev_tokens = [null, null, null];

        if (\is_array($function)) {
            $class = \explode('\\', $function[0]);
            $class = \strtolower(\end($class));
            $function = \strtolower($function[1]);
        } else {
            $class = null;
            $function = \strtolower($function);
        }

        // Loop through tokens
        foreach ($tokens as $index => $token) {
            if (!\is_array($token)) {
                continue;
            }

            // Count newlines for line number instead of using $token[2]
            // since certain situations (String tokens after whitespace) may
            // not have the correct line number unless you do this manually
            $cursor += \substr_count($token[1], "\n");
            if ($cursor > $line) {
                break;
            }

            // Store the last real tokens for later
            if (isset(self::$ignore[$token[0]])) {
                continue;
            }

            $prev_tokens = [$prev_tokens[1], $prev_tokens[2], $token];

            // Check if it's the right type to be the function we're looking for
            if (!isset(self::$namespace[$token[0]])) {
                continue;
            }

            $ns = \explode('\\', \strtolower($token[1]));

            if (\end($ns) !== $function) {
                continue;
            }

            // Check if it's a function call
            $nextReal = self::realTokenIndex($tokens, $index);
            if (!isset($nextReal, $tokens[$nextReal]) || '(' !== $tokens[$nextReal]) {
                continue;
            }

            // Check if it matches the signature
            if (null === $class) {
                if ($prev_tokens[1] && isset(self::$classcalls[$prev_tokens[1][0]])) {
                    continue;
                }
            } else {
                if (!$prev_tokens[1] || T_DOUBLE_COLON !== $prev_tokens[1][0]) {
                    continue;
                }

                if (!$prev_tokens[0] || !isset(self::$namespace[$prev_tokens[0][0]])) {
                    continue;
                }

                /** @var array{int, string, int} $prev_tokens[0] */
                // All self::$namespace tokens are T_ constants
                $ns = \explode('\\', \strtolower($prev_tokens[0][1]));

                if (\end($ns) !== $class) {
                    continue;
                }
            }

            $inner_cursor = $cursor;
            $depth = 1; // The depth respective to the function call
            $offset = $nextReal + 1; // The start of the function call
            $instring = false; // Whether we're in a string or not
            $realtokens = false; // Whether the current scope contains anything meaningful or not
            $paramrealtokens = false; // Whether the current parameter contains anything meaningful
            $params = []; // All our collected parameters
            $shortparam = []; // The short version of the parameter
            $param_start = $offset; // The distance to the start of the parameter

            // Loop through the following tokens until the function call ends
            while (isset($tokens[$offset])) {
                $token = $tokens[$offset];

                // Ensure that the $inner_cursor is correct and
                // that $token is either a T_ constant or a string
                if (\is_array($token)) {
                    $inner_cursor += \substr_count($token[1], "\n");
                }

                if (!isset(self::$ignore[$token[0]]) && !isset($down[$token[0]])) {
                    $paramrealtokens = $realtokens = true;
                }

                // If it's a token that makes us to up a level, increase the depth
                if (isset($up[$token[0]])) {
                    if (1 === $depth) {
                        $shortparam[] = $token;
                        $realtokens = false;
                    }

                    ++$depth;
                } elseif (isset($down[$token[0]])) {
                    --$depth;

                    // If this brings us down to the parameter level, and we've had
                    // real tokens since going up, fill the $shortparam with an ellipsis
                    if (1 === $depth) {
                        if ($realtokens) {
                            $shortparam[] = '...';
                        }
                        $shortparam[] = $token;
                    }
                } elseif ('"' === $token[0]) {
                    // Strings use the same symbol for up and down, but we can
                    // only ever be inside one string, so just use a bool for that
                    if ($instring) {
                        --$depth;
                        if (1 === $depth) {
                            $shortparam[] = '...';
                        }
                    } else {
                        ++$depth;
                    }

                    $instring = !$instring;

                    $shortparam[] = '"';
                } elseif (1 === $depth) {
                    if (',' === $token[0]) {
                        $params[] = [
                            'full' => \array_slice($tokens, $param_start, $offset - $param_start),
                            'short' => $shortparam,
                        ];
                        $shortparam = [];
                        $paramrealtokens = false;
                        $param_start = $offset + 1;
                    } elseif (T_CONSTANT_ENCAPSED_STRING === $token[0] && \strlen($token[1]) > 2) {
                        $shortparam[] = $token[1][0].'...'.$token[1][0];
                    } else {
                        $shortparam[] = $token;
                    }
                }

                // Depth has dropped to 0 (So we've hit the closing paren)
                if ($depth <= 0) {
                    if ($paramrealtokens) {
                        $params[] = [
                            'full' => \array_slice($tokens, $param_start, $offset - $param_start),
                            'short' => $shortparam,
                        ];
                    }

                    break;
                }

                ++$offset;
            }

            // If we're not passed (or at) the line at the end
            // of the function call, we're too early so skip it
            if ($inner_cursor < $line) {
                continue;
            }

            // Format the final output parameters
            foreach ($params as &$param) {
                $name = self::tokensFormatted($param['short']);
                $expression = false;
                foreach ($name as $token) {
                    if (self::tokenIsOperator($token)) {
                        $expression = true;
                        break;
                    }
                }

                $param = [
                    'name' => self::tokensToString($name),
                    'path' => self::tokensToString(self::tokensTrim($param['full'])),
                    'expression' => $expression,
                ];
            }

            // Get the modifiers
            --$index;

            while (isset($tokens[$index])) {
                if (!isset(self::$ignore[$tokens[$index][0]]) && !isset($identifier[$tokens[$index][0]])) {
                    break;
                }

                --$index;
            }

            $mods = [];

            while (isset($tokens[$index])) {
                if (isset(self::$ignore[$tokens[$index][0]])) {
                    --$index;
                    continue;
                }

                if (isset($modifiers[$tokens[$index][0]])) {
                    $mods[] = $tokens[$index];
                    --$index;
                    continue;
                }

                break;
            }

            $function_calls[] = [
                'parameters' => $params,
                'modifiers' => $mods,
            ];
        }

        return $function_calls;
    }

    private static function realTokenIndex(array $tokens, $index)
    {
        ++$index;

        while (isset($tokens[$index])) {
            if (!isset(self::$ignore[$tokens[$index][0]])) {
                return $index;
            }

            ++$index;
        }

        return null;
    }

    /**
     * We need a separate method to check if tokens are operators because we
     * occasionally add "..." to short parameter versions. If we simply check
     * for `$token[0]` then "..." will incorrectly match the "." operator.
     *
     * @param array|string $token The token to check
     *
     * @return bool
     */
    private static function tokenIsOperator($token)
    {
        return '...' !== $token && isset(self::$operator[$token[0]]);
    }

    private static function tokensToString(array $tokens)
    {
        $out = '';

        foreach ($tokens as $token) {
            if (\is_string($token)) {
                $out .= $token;
            } elseif (\is_array($token)) {
                $out .= $token[1];
            }
        }

        return $out;
    }

    private static function tokensTrim(array $tokens)
    {
        foreach ($tokens as $index => $token) {
            if (isset(self::$ignore[$token[0]])) {
                unset($tokens[$index]);
            } else {
                break;
            }
        }

        $tokens = \array_reverse($tokens);

        foreach ($tokens as $index => $token) {
            if (isset(self::$ignore[$token[0]])) {
                unset($tokens[$index]);
            } else {
                break;
            }
        }

        return \array_reverse($tokens);
    }

    private static function tokensFormatted(array $tokens)
    {
        $space = false;
        $attribute = false;

        $tokens = self::tokensTrim($tokens);

        $output = [];
        $last = null;

        foreach ($tokens as $index => $token) {
            if (isset(self::$ignore[$token[0]])) {
                if ($space) {
                    continue;
                }

                $next = $tokens[self::realTokenIndex($tokens, $index)];

                /** @var array|string $last */
                if ($attribute && ']' === $last[0]) {
                    $attribute = false;
                } elseif (isset(self::$strip[$last[0]]) && !self::tokenIsOperator($next)) {
                    continue;
                }

                if (isset(self::$strip[$next[0]]) && $last && !self::tokenIsOperator($last)) {
                    continue;
                }

                $token = ' ';
                $space = true;
            } else {
                if (KINT_PHP80 && $last && T_ATTRIBUTE == $last[0]) {
                    $attribute = true;
                }

                $space = false;
                $last = $token;
            }

            $output[] = $token;
        }

        return $output;
    }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**`class`** | **String** |  |  [optional]
**links** | [**ExtensionClassContainerImpl1links**](ExtensionClassContainerImpl1links.md) |  |  [optional]
**map** | [**ExtensionClassContainerImpl1map**](ExtensionClassContainerImpl1map.md) |  |  [optional]


text:
export declare class SomeClass {
    constructor();
}


text:
package com.zzzmode.appopsx.ui.core;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import androidx.appcompat.app.AppCompatDelegate;

/**
 * Created by zl on 2017/4/19.
 */

public class SpHelper {

  public static SharedPreferences getSharedPreferences(Context context) {
    return PreferenceManager.getDefaultSharedPreferences(context);
  }

  public static int getThemeMode(Context context) {
    if (getSharedPreferences(context).getBoolean("pref_app_daynight_mode", false)) {
      return AppCompatDelegate.MODE_NIGHT_YES;
    }
    return AppCompatDelegate.MODE_NIGHT_NO;
  }

  public static boolean isIgnoredNetOps(Context context,int op){
    return getSharedPreferences(context).getBoolean("pref_ignore_op_code_"+op,false);
  }

  public static void ignoredNetOps(Context context,int op){
    getSharedPreferences(context).edit().putBoolean("pref_ignore_op_code_"+op,true).apply();
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/home/konrad2/AndroidstudioProjects/GoProHERO4Controller/app/src/main/res/values-v14/colors.xml -->
    <eat-comment/>
    <color name="action_bar">#002233</color>
    <color name="text_color">#FFFFFF</color>
    <!-- From: file:/home/konrad2/AndroidstudioProjects/GoProHERO4Controller/app/src/main/res/values-v14/dimens.xml -->
    <eat-comment/>
    <dimen name="widget_margin">8dp</dimen>
    <!-- From: file:/home/konrad2/AndroidstudioProjects/GoProHERO4Controller/app/src/main/res/values-v14/ids.xml -->
    <eat-comment/>
    <item name="action_calc" type="id">Timelapse calculator</item>
    <item name="action_profilesettings" type="id">Profile configuration</item>
    <item name="action_settings_three" type="id">Configure older cameras</item>
    <item name="btnCancelNotification" type="id">Cancel</item>
    <item name="btnShowNotification" type="id">Show Notification</item>
    <!-- From: file:/home/konrad2/AndroidstudioProjects/GoProHERO4Controller/app/src/main/res/values-v14/strings.xml -->
    <eat-comment/>
    <string name="action_calc">Timelapse Calculator</string>
    <string name="permdesc_flashlight">Ayy lmao</string>
    <string name="permlab_flashlight">Ayy lmao shrek republic reddit</string>
    <string name="wifi">Open WiFi settings</string>
    <!-- From: file:/home/konrad2/AndroidstudioProjects/GoProHERO4Controller/app/src/main/res/values-v14/styles.xml -->
    <eat-comment/>
    <style name="ActionBarTheme" parent="android:Theme.Holo">
        <item name="android:gravity">center_horizontal</item>
        <item name="android:background">@color/action_bar</item>

        <item name="android:textColor">@color/text_color</item>
    </style>
    <style name="AppBaseTheme" parent="android:Theme.Material">
        <!--
            Theme customizations available in newer API levels can go in
            res/values-vXX/styles.xml, while customizations related to
            backward-compatibility can go here.
        -->
        <item name="android:actionBarStyle">@style/ActionBarTheme</item>
    </style>
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>
    <style name="Buttons" parent="android:Theme.Material.Light">

    </style>
</resources>


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

ENV['RACK_ENV'] = 'test'

require 'coveralls'
require 'simplecov'
require 'rack/test'
require 'webmock/rspec'

SimpleCov.formatters = [SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter]

SimpleCov.start do
  add_filter 'spec'
  coverage_dir 'docs/coverage'
end

require 'omniauth'
require 'omniauth-pge'

Dir['spec/support/**/*.rb'].each { |f| require f }

RSpec.configure do |config|
  config.pattern = '**/*_spec.rb'
  config.mock_framework = :rspec
  config.include WebMock::API
  config.include Rack::Test::Methods
  config.extend  OmniAuth::Test::StrategyMacros, type: :strategy
end