text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource" class="com.hpe.api.management.prm.login.utils.CustomBasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
	<property name="maxTotal" value="10"/>
	<property name="initialSize" value="5"/>
	<property name="minIdle" value="5"/>
	<property name="maxIdle" value="5"/>
	<property name="connectionProperties" value="defaultNChar=true"></property>
   </bean>

     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
            </props>
        </property>

        <property name="annotatedClasses">
            <list>
                <value>com.hpe.api.management.prm.register.entities.UserEntity</value>
                </list>
             </property>
     </bean>

     <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven/>
</beans>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace EdpSuperluminal\ClassDeclaration;

use Zend\Code\Reflection\FileReflection;

class FileReflectionUseStatementService
{
    /**
     * @param FileReflection $declaringFile
     * @return string
     */
    public function getUseString(FileReflection $declaringFile)
    {
        $useString = '';

        if (!count($uses = $declaringFile->getUses())) {
            return $useString;
        }

        foreach ($uses as $use) {
            $useString .= "use {$use['use']}";

            if ($use['as']) {
                $useString .= " as {$use['as']}";
            }

            $useString .= ";\n";
        }

        return $useString;
    }

    /**
     * @param FileReflection $declaringFile
     * @return array
     */
    public function getUseNames(FileReflection $declaringFile)
    {
        $usesNames = array();

        if (!count($uses = $declaringFile->getUses())) {
            return $usesNames;
        }

        foreach ($uses as $use) {
            $usesNames[$use['use']] = $use['as'];
        }

        return $usesNames;
    }
}


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>
#include <string>

#include "base/test/test_future.h"
#include "chrome/browser/lacros/cert/cert_db_initializer_factory.h"
#include "chrome/browser/net/nss_service.h"
#include "chrome/browser/net/nss_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chromeos/crosapi/cpp/keystore_service_util.h"
#include "chromeos/crosapi/mojom/keystore_service.mojom-shared.h"
#include "chromeos/crosapi/mojom/keystore_service.mojom-test-utils.h"
#include "chromeos/crosapi/mojom/keystore_service.mojom.h"
#include "chromeos/lacros/lacros_service.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/test/browser_test.h"
#include "net/cert/nss_cert_database.h"
#include "net/cert/scoped_nss_types.h"
#include "net/cert/x509_util.h"
#include "net/test/cert_builder.h"

namespace {

namespace is_cert_in_nss {
namespace internal {

void IsCertInNSSDatabaseOnIOThreadWithCertList(
    const std::vector<uint8_t>& expected_cert_der,
    bool* out_cert_found,
    base::OnceClosure done_closure,
    net::ScopedCERTCertificateList certs) {
  for (const net::ScopedCERTCertificate& cert : certs) {
    auto cert_der = base::make_span(cert->derCert.data, cert->derCert.len);
    if (std::equal(cert_der.begin(), cert_der.end(),
                   expected_cert_der.begin())) {
      *out_cert_found = true;
      break;
    }
  }

  std::move(done_closure).Run();
}

void IsCertInNSSDatabaseOnIOThreadWithCertDb(
    const std::vector<uint8_t>& expected_cert_der,
    bool* out_cert_found,
    base::OnceClosure done_closure,
    net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
  cert_db->ListCerts(base::BindOnce(&IsCertInNSSDatabaseOnIOThreadWithCertList,
                                    expected_cert_der, out_cert_found,
                                    std::move(done_closure)));
}

void IsCertInNSSDatabaseOnIOThread(
    NssCertDatabaseGetter database_getter,
    const std::vector<uint8_t>& expected_cert_der,
    bool* out_cert_found,
    base::OnceClosure done_closure) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
  auto did_get_cert_db_split_callback = base::SplitOnceCallback(base::BindOnce(
      &IsCertInNSSDatabaseOnIOThreadWithCertDb, expected_cert_der,
      out_cert_found, std::move(done_closure)));

  net::NSSCertDatabase* cert_db =
      std::move(database_getter)
          .Run(std::move(did_get_cert_db_split_callback.first));
  if (cert_db) {
    std::move(did_get_cert_db_split_callback.second).Run(cert_db);
  }
}
}  // namespace internal

// Returns true if a certificate with subject CommonName `common_name` is
// present in the `NSSCertDatabase` for `profile`.
bool IsCertInNSSDatabase(Profile* profile,
                         const std::vector<uint8_t>& expected_cert_der) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  base::RunLoop run_loop;
  bool cert_found = false;
  content::GetIOThreadTaskRunner({})->PostTask(
      FROM_HERE,
      base::BindOnce(internal::IsCertInNSSDatabaseOnIOThread,
                     NssServiceFactory::GetForContext(profile)
                         ->CreateNSSCertDatabaseGetterForIOThread(),
                     expected_cert_der, &cert_found, run_loop.QuitClosure()));
  run_loop.Run();
  return cert_found;
}

}  // namespace is_cert_in_nss

// Makes a CertBuilder that would return a valid x509 client certificate for the
// `public_key_spki`.
scoped_refptr<net::X509Certificate> MakeCert(
    const std::vector<uint8_t>& public_key_spki) {
  auto issuer = std::make_unique<net::CertBuilder>(/*orig_cert=*/nullptr,
                                                   /*issuer=*/nullptr);
  auto cert_builder =
      net::CertBuilder::FromSubjectPublicKeyInfo(public_key_spki, issuer.get());
  cert_builder->SetSignatureAlgorithmRsaPkca1(net::DigestAlgorithm::Sha256);
  cert_builder->SetValidity(base::Time::Now(),
                            base::Time::Now() + base::Days(30));
  return cert_builder->GetX509Certificate();
}

// Returns x509 client certificate from the `cert_builder` as a DER-encoded
// certificate.
std::vector<uint8_t> CertToDer(scoped_refptr<net::X509Certificate> cert) {
  auto cert_span = net::x509_util::CryptoBufferAsSpan(cert->cert_buffer());
  return std::vector<uint8_t>(cert_span.begin(), cert_span.end());
}

// During ExtensionGenerateKey* call this error means that the key was created,
// but Ash-Chrome failed to tag it properly. It happens because Ash-Chrome is
// trying to work with the real NSS, but in browser tests (i.e. on Linux) it
// doesn't work the same way as on ChromeOS.
const char kFailedToSetAttribute[] = "Setting key attribute value failed.";
// During ExtensionSign call this error means that Ash-Chrome wasn't able to
// find the key in a list of allowed keys.
const char kErrorKeyNotAllowedForSigning[] =
    "This key is not allowed for signing. Either it was used for "
    "signing before or it was not correctly generated.";

// This class provides integration testing for the keystore service crosapi.
// TODO(https://crbug.com/1134340): The logic being tested does not rely on
// //chrome or //content so it would be helpful if this lived in a lower-level
// test suite.
class KeystoreServiceLacrosBrowserTest : public InProcessBrowserTest {
 protected:
  KeystoreServiceLacrosBrowserTest() = default;

  KeystoreServiceLacrosBrowserTest(const KeystoreServiceLacrosBrowserTest&) =
      delete;
  KeystoreServiceLacrosBrowserTest& operator=(
      const KeystoreServiceLacrosBrowserTest&) = delete;

  ~KeystoreServiceLacrosBrowserTest() override = default;

  mojo::Remote<crosapi::mojom::KeystoreService>& keystore_service_remote() {
    return chromeos::LacrosService::Get()
        ->GetRemote<crosapi::mojom::KeystoreService>();
  }

  void SetUp() override {
    CertDbInitializerFactory::GetInstance()
        ->SetCreateWithBrowserContextForTesting(
            /*should_create=*/true);
    InProcessBrowserTest::SetUp();
  }
};

// Tests that providing an incorrectly formatted user keystore challenge returns
// failure.
IN_PROC_BROWSER_TEST_F(KeystoreServiceLacrosBrowserTest, WrongFormattingUser) {
  crosapi::mojom::DEPRECATED_KeystoreStringResultPtr result;
  std::string challenge = "asdf";
  crosapi::mojom::KeystoreServiceAsyncWaiter async_waiter(
      keystore_service_remote().get());
  async_waiter.DEPRECATED_ChallengeAttestationOnlyKeystore(
      challenge, crosapi::mojom::KeystoreType::kUser, /*migrate=*/false,
      &result);
  ASSERT_TRUE(result->is_error_message());

  // TODO(https://crbug.com/1134349): Currently this errors out because remote
  // attestation is disabled. We want this to error out because of a poorly
  // formatted attestation message.
}

// Tests that get certificates works.
IN_PROC_BROWSER_TEST_F(KeystoreServiceLacrosBrowserTest, GetCertificatesEmpty) {
  crosapi::mojom::DEPRECATED_GetCertificatesResultPtr result;
  crosapi::mojom::KeystoreServiceAsyncWaiter async_waiter(
      keystore_service_remote().get());
  async_waiter.DEPRECATED_GetCertificates(crosapi::mojom::KeystoreType::kUser,
                                          &result);
  ASSERT_TRUE(result->is_certificates());
  EXPECT_EQ(0u, result->get_certificates().size());
}

// Tests that extension generate key works.
IN_PROC_BROWSER_TEST_F(KeystoreServiceLacrosBrowserTest,
                       ExtensionGenerateKeyPKCS) {
  crosapi::mojom::DEPRECATED_ExtensionKeystoreBinaryResultPtr result;
  crosapi::mojom::KeystoreServiceAsyncWaiter async_waiter(
      keystore_service_remote().get());
  crosapi::mojom::KeystoreSigningAlgorithmPtr algo =
      crosapi::mojom::KeystoreSigningAlgorithm::New();
  crosapi::mojom::KeystorePKCS115ParamsPtr params =
      crosapi::mojom::KeystorePKCS115Params::New();
  params->modulus_length = 1024;
  algo->set_pkcs115(std::move(params));
  async_waiter.DEPRECATED_ExtensionGenerateKey(
      crosapi::mojom::KeystoreType::kUser, std::move(algo),
      /*extension_id=*/"123", &result);
  // Errors out because Ash-Chrome is not running on ChromeOS.
  ASSERT_TRUE(result->is_error_message());
  EXPECT_EQ(result->get_error_message(), kFailedToSetAttribute);
}

// TODO(https://crbug.com/1134349): After the switch from PlatformKeysService to
// ExtensionPlatformKeysService the test started to crash on cloud builders. The
// current theory is that it is because of the added `AddKeyAttribute` call to
// NSS. In the long term it is not clear if the test should actually try to
// generate/modify keys in non-test NSS database on builders. But there's no
// simple way to prevent this at the moment.
IN_PROC_BROWSER_TEST_F(KeystoreServiceLacrosBrowserTest,
                       DISABLED_ExtensionGenerateKeyECDSA) {
  crosapi::mojom::DEPRECATED_ExtensionKeystoreBinaryResultPtr result;
  crosapi::mojom::KeystoreServiceAsyncWaiter async_waiter(
      keystore_service_remote().get());
  crosapi::mojom::KeystoreSigningAlgorithmPtr algo =
      crosapi::mojom::KeystoreSigningAlgorithm::New();
  crosapi::mojom::KeystoreECDSAParamsPtr params =
      crosapi::mojom::KeystoreECDSAParams::New();
  params->named_curve = "P-256";
  algo->set_ecdsa(std::move(params));
  async_waiter.DEPRECATED_ExtensionGenerateKey(
      crosapi::mojom::KeystoreType::kUser, std::move(algo),
      /*extension_id=*/"123", &result);
  // Errors out because Ash-Chrome is not running on ChromeOS.
  ASSERT_TRUE(result->is_error_message());
  EXPECT_EQ(result->get_error_message(), kFailedToSetAttribute);
}

// Tests that extension sign works.
IN_PROC_BROWSER_TEST_F(KeystoreServiceLacrosBrowserTest, ExtensionSign) {
  crosapi::mojom::DEPRECATED_ExtensionKeystoreBinaryResultPtr result;
  crosapi::mojom::KeystoreServiceAsyncWaiter async_waiter(
      keystore_service_remote().get());
  async_waiter.DEPRECATED_ExtensionSign(
      crosapi::mojom::KeystoreType::kUser,
      /*public_key=*/{1, 2, 3, 4, 5},
      /*scheme=*/crosapi::mojom::KeystoreSigningScheme::kRsassaPkcs1V15Sha256,
      /*data=*/{10, 11, 12, 13, 14, 15},
      /*extension_id=*/"123", &result);
  // Errors out because the public key is not valid. Currently there's no way to
  // create a valid key in Ash-Chrome during browser tests.
  ASSERT_TRUE(result->is_error_message());
  EXPECT_EQ(result->get_error_message(), kErrorKeyNotAllowedForSigning);
}

// Tests that trying to add/remove an incorrectly formatted certificate results
// in failure.
IN_PROC_BROWSER_TEST_F(KeystoreServiceLacrosBrowserTest, CertificateBadFormat) {
  const char expected_error[] = "Certificate is not a valid X.509 certificate.";
  std::string result;
  std::vector<uint8_t> dummy_certificate;
  dummy_certificate.push_back(15);
  crosapi::mojom::KeystoreServiceAsyncWaiter async_waiter(
      keystore_service_remote().get());
  async_waiter.DEPRECATED_AddCertificate(crosapi::mojom::KeystoreType::kUser,
                                         std::move(dummy_certificate), &result);
  EXPECT_EQ(result, expected_error);

  result = "";
  async_waiter.DEPRECATED_RemoveCertificate(crosapi::mojom::KeystoreType::kUser,
                                            std::move(dummy_certificate),
                                            &result);
  EXPECT_EQ(result, expected_error);
}

// TODO(b/219968355): Enable the test when it user directory in Ash is cleaned
// in between tests (otherwise side effects of this test are leaking into the
// other ones).
// Tests that importing a correct certificate works and that it becomes visible
// in both Ash and Lacros.
IN_PROC_BROWSER_TEST_F(KeystoreServiceLacrosBrowserTest,
                       DISABLED_AddCertificate) {
  crosapi::mojom::KeystoreServiceAsyncWaiter async_waiter(
      keystore_service_remote().get());

  // Creating a valid cert using this API requires generating a key for it
  // first.
  crosapi::mojom::KeystoreBinaryResultPtr generate_key_result;
  async_waiter.GenerateKey(
      crosapi::mojom::KeystoreType::kUser,
      crosapi::keystore_service_util::MakeRsaKeystoreSigningAlgorithm(
          /*modulus_length=*/2048, /*sw_backed=*/false),
      &generate_key_result);
  ASSERT_FALSE(generate_key_result->is_error());

  // Generate a client certificate for the generated key.
  scoped_refptr<net::X509Certificate> cert =
      MakeCert(generate_key_result->get_blob());
  std::vector<uint8_t> cert_der = CertToDer(cert);

  // Make Ash import the certificate.
  bool add_cert_is_error = false;
  crosapi::mojom::KeystoreError add_cert_error;
  async_waiter.AddCertificate(crosapi::mojom::KeystoreType::kUser, cert_der,
                              &add_cert_is_error, &add_cert_error);
  ASSERT_FALSE(add_cert_is_error) << "Error: " << add_cert_error;

  // Test that Lacros can see the certificate that was imported by Ash.
  EXPECT_TRUE(
      is_cert_in_nss::IsCertInNSSDatabase(browser()->profile(), cert_der));

  // Test that Ash also returns the imported certificate.
  crosapi::mojom::GetCertificatesResultPtr get_certs_result;
  async_waiter.GetCertificates(crosapi::mojom::KeystoreType::kUser,
                               &get_certs_result);
  ASSERT_FALSE(get_certs_result->is_error());
  EXPECT_TRUE(base::Contains(get_certs_result->get_certificates(), cert_der));
}

}  // namespace


text:
title: Exploring AI
subtitle: Introducing our new friend, Smart Travel Assistant
date: 2020-09-03 00:00:00
description: This piece is about how we developed a strategy for implenting an AI/ML solution to align with the organisation's strategic priorities and to solve immediate problems.
# featured_image: chatbot-1.png
# accent_color: '#222'
# gallery_images:
#   - chatbot-1.png
---

![Exploring AI](/images/projects/chatbot-1.png)

#### Use of AI in the Travel Industry

This emerging technology has been around in the travel space for a number of years now with many recognised brands, such as Qantas, SkyScanner, Expedia, having successfully deployed it across their operations.

#### My Role

For us Product Designers a large part of the job is to design products that are great for the end user but we also need to design for the business too.  In this project I assumed the role as, not only the Product Designer but kind of an acting Product Manager/Owner too.

**What were the problems or opportunities that the organisation were facing?**
Streamlining operations, improve booking experience for customers, dynamic content and increased customer service efficiency.

#### Solution
AI was to play a big part in helping us to alleviate our pain points. We knew we had to automate more and our goal of completing a digital transformation program to include chatbot implementation and dynamically driven content applications driven by AI was to be instrumental in doing so.  Just as SkyScanner had done before us we were looking at a chatbot solution to become our smart travel assistance.

#### Why
As a publicly listed, Travel-Distribution Company providing a diverse range of travel wholesale products and services to markets globally, we could see that such a solution had the potential to help the organisation achieve it's strategic priorities.  In doing so it would improve customer engagement and the booking experience.  The benefits could help to build and maintain better relationships, increase efficiencies, reduce costs, engage customers and improve conversions.  It was a great idea to pitch to the stakeholders.

#### Core Ethical Considerations
If we were going to do this we wanted to do it properly and ethical concerns are big priority in software development especially when artificial intelligence is involved too.  We built a short list of considerations that we felt were important to us as a team and aligned with the organisation's objectives.  I won't talk about it in anygreat length so here's the dot points below:

* Transparency - there should be complete transparency to ensure people are fully aware of when they are being impacted by AI.
Human centred and wellbeing - I believe that AI systems should always respect human rights and diversity and any systems should be the benefit of individuals, society and the environment.
* Fairness - AI systems should be unbiased and not discriminate.
* Privacy and security - AI systems should respect people's privacy and their data and should
practice a high level of security.
* Accountable - those involved at different stages of AI system development should be responsible and accountable for their choices and the outcomes.
* Contestability - in the event that an AI system has had a significant impact on someone, a group, society or the environment they should be permitted to freely challenge the use of the system.

#### Key Performance Indicators
We have chosen to measure the following key performance indicators as they align neatly with the organisation's strategic priorities.

Activity volume | Evaluating the number of interactions from the time the user asks a simple question.
Conversation length | Average length of interactions between chatbot and users.
Comprehension level | This would be continuously evolving. It is a measure of the chatbot's comprehension and knowledge base.
Non-response rates | A measure of the number of times the chatbot fails to respond to a question. Can also be measured against comprehension level metric above.
Retention rate | This is the proportion of users who have consulted the chatbot on repeated occasions.
User engagement | measuring the number of messages exchanged.

#### Wireframing
To support our proposal I began creating wireframes to begin illustrating the main conversation flows and to iron out any usability issues that might arise early on.  The wireframes are also great for getting stakeholders involved in the design process.

To prompt conversation from my working group I first created a wireframes for a desktop view, the conversation types that are currently required and a layout suitable for smaller devices.

![Travel assistant desktop resolution](/images/projects/chatbot-wireframe-desktop.png)

We have identified three main conversation flows below that meet the requirements of the organisation.  Customer Support, Travel Recommendations and Hotel Bookings.

![Chatbot conversation types](/images/projects/chatbot-wireframe-conversation-types.png)

These will also be available on mobile resolutions where the some of clutter will be removed for a cleaner interface.

![Chatbot mobile](/images/projects/chatbot-wireframe-mobile.png)

#### Progress Report
The project is still ongoing although it was put on hold temporarily due to COVID.  We successfully pitched our solution and have a verbal approval to proceed.  I created a high level product road map and the next steps are to continue in the design phase and to build a prototype.  UX research will continue.  We have completed a deep dive analysis on products that exist on the market already to illiminate the need to reinvent the wheel   .


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>React-SASS Template</title>


text:
from oscar.apps.dashboard.catalogue import config

class CatalogueDashboardConfig(config.CatalogueDashboardConfig):
    name = 'oscar_vat_moss.dashboard.catalogue'


text:
namespace Fixtures.MirrorSequences
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using Models;

    /// <summary>
    /// A sample API that uses a petstore as an example to demonstrate
    /// features in the swagger-2.0 specification
    /// </summary>
    public partial class SequenceRequestResponseTest : ServiceClient<SequenceRequestResponseTest>, ISequenceRequestResponseTest
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        public Uri BaseUri { get; set; }

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        public JsonSerializerSettings SerializationSettings { get; private set; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        public JsonSerializerSettings DeserializationSettings { get; private set; }

        /// <summary>
        /// Initializes a new instance of the SequenceRequestResponseTest class.
        /// </summary>
        public SequenceRequestResponseTest() : base()
        {
            this.Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the SequenceRequestResponseTest class.
        /// </summary>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        public SequenceRequestResponseTest(params DelegatingHandler[] handlers) : base(handlers)
        {
            this.Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the SequenceRequestResponseTest class.
        /// </summary>
        /// <param name='rootHandler'>
        /// Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        public SequenceRequestResponseTest(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
        {
            this.Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the SequenceRequestResponseTest class.
        /// </summary>
        /// <param name='baseUri'>
        /// Optional. The base URI of the service.
        /// </param>
        /// <param name='handlers'>
        /// Optional. The delegating handlers to add to the http client pipeline.
        /// </param>
        public SequenceRequestResponseTest(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this.BaseUri = baseUri;
        }

        /// <summary>
        /// Initializes client properties.
        /// </summary>
        private void Initialize()
        {
            this.BaseUri = new Uri("http://petstore.swagger.wordnik.com/api");
            SerializationSettings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                NullValueHandling = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                ContractResolver = new ReadOnlyJsonContractResolver(),
                Converters = new List<JsonConverter>
                    {
                        new Iso8601TimeSpanConverter()
                    }
            };
            DeserializationSettings = new JsonSerializerSettings
            {
                DateFormatHandling = DateFormatHandling.IsoDateFormat,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                NullValueHandling = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                ContractResolver = new ReadOnlyJsonContractResolver(),
                Converters = new List<JsonConverter>
                    {
                        new Iso8601TimeSpanConverter()
                    }
            };
        }
        /// <summary>
        /// Creates a new pet in the store.  Duplicates are allowed
        /// </summary>
        /// <param name='pets'>
        /// Pets to add to the store
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task<HttpOperationResponse<IList<Pet>>> AddPetWithHttpMessagesAsync(IList<Pet> pets, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (pets == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "pets");
            }
            if (pets != null)
            {
                foreach (var element in pets)
                {
                    if (element != null)
                    {
                        element.Validate();
                    }
                }
            }
            // Tracing
            bool shouldTrace = ServiceClientTracing.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("pets", pets);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(invocationId, this, "AddPet", tracingParameters);
            }
            // Construct URL
            var baseUrl = this.BaseUri.AbsoluteUri;
            var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString();
            // Create HTTP transport objects
            HttpRequestMessage httpRequest = new HttpRequestMessage();
            httpRequest.Method = new HttpMethod("POST");
            httpRequest.RequestUri = new Uri(url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach(var header in customHeaders)
                {
                    if (httpRequest.Headers.Contains(header.Key))
                    {
                        httpRequest.Headers.Remove(header.Key);
                    }
                    httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // Serialize Request
            string requestContent = JsonConvert.SerializeObject(pets, this.SerializationSettings);
            httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
            httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }
            HttpStatusCode statusCode = httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                ErrorModel errorBody = JsonConvert.DeserializeObject<ErrorModel>(responseContent, this.DeserializationSettings);
                if (errorBody != null)
                {
                    ex.Body = errorBody;
                }
                ex.Request = httpRequest;
                ex.Response = httpResponse;
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }
                throw ex;
            }
            // Create Result
            var result = new HttpOperationResponse<IList<Pet>>();
            result.Request = httpRequest;
            result.Response = httpResponse;
            // Deserialize Response
            if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
            {
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                result.Body = JsonConvert.DeserializeObject<IList<Pet>>(responseContent, this.DeserializationSettings);
            }
            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }
            return result;
        }

        /// <summary>
        /// Adds new pet stylesin the store.  Duplicates are allowed
        /// </summary>
        /// <param name='petStyle'>
        /// Pet style to add to the store
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task<HttpOperationResponse<IList<int?>>> AddPetStylesWithHttpMessagesAsync(IList<int?> petStyle, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (petStyle == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "petStyle");
            }
            // Tracing
            bool shouldTrace = ServiceClientTracing.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("petStyle", petStyle);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(invocationId, this, "AddPetStyles", tracingParameters);
            }
            // Construct URL
            var baseUrl = this.BaseUri.AbsoluteUri;
            var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString();
            // Create HTTP transport objects
            HttpRequestMessage httpRequest = new HttpRequestMessage();
            httpRequest.Method = new HttpMethod("POST");
            httpRequest.RequestUri = new Uri(url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach(var header in customHeaders)
                {
                    if (httpRequest.Headers.Contains(header.Key))
                    {
                        httpRequest.Headers.Remove(header.Key);
                    }
                    httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // Serialize Request
            string requestContent = JsonConvert.SerializeObject(petStyle, this.SerializationSettings);
            httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
            httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }
            HttpStatusCode statusCode = httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                IList<ErrorModel> errorBody = JsonConvert.DeserializeObject<IList<ErrorModel>>(responseContent, this.DeserializationSettings);
                if (errorBody != null)
                {
                    ex.Body = errorBody;
                }
                ex.Request = httpRequest;
                ex.Response = httpResponse;
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }
                throw ex;
            }
            // Create Result
            var result = new HttpOperationResponse<IList<int?>>();
            result.Request = httpRequest;
            result.Response = httpResponse;
            // Deserialize Response
            if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
            {
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                result.Body = JsonConvert.DeserializeObject<IList<int?>>(responseContent, this.DeserializationSettings);
            }
            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }
            return result;
        }

        /// <summary>
        /// Updates new pet stylesin the store.  Duplicates are allowed
        /// </summary>
        /// <param name='petStyle'>
        /// Pet style to add to the store
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        public async Task<HttpOperationResponse<IList<int?>>> UpdatePetStylesWithHttpMessagesAsync(IList<int?> petStyle, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (petStyle == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "petStyle");
            }
            // Tracing
            bool shouldTrace = ServiceClientTracing.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("petStyle", petStyle);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(invocationId, this, "UpdatePetStyles", tracingParameters);
            }
            // Construct URL
            var baseUrl = this.BaseUri.AbsoluteUri;
            var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString();
            // Create HTTP transport objects
            HttpRequestMessage httpRequest = new HttpRequestMessage();
            httpRequest.Method = new HttpMethod("PUT");
            httpRequest.RequestUri = new Uri(url);
            // Set Headers
            if (customHeaders != null)
            {
                foreach(var header in customHeaders)
                {
                    if (httpRequest.Headers.Contains(header.Key))
                    {
                        httpRequest.Headers.Remove(header.Key);
                    }
                    httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            // Serialize Request
            string requestContent = JsonConvert.SerializeObject(petStyle, this.SerializationSettings);
            httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
            httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }
            HttpStatusCode statusCode = httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
            {
                var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                IList<ErrorModel> errorBody = JsonConvert.DeserializeObject<IList<ErrorModel>>(responseContent, this.DeserializationSettings);
                if (errorBody != null)
                {
                    ex.Body = errorBody;
                }
                ex.Request = httpRequest;
                ex.Response = httpResponse;
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }
                throw ex;
            }
            // Create Result
            var result = new HttpOperationResponse<IList<int?>>();
            result.Request = httpRequest;
            result.Response = httpResponse;
            // Deserialize Response
            if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
            {
                string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                result.Body = JsonConvert.DeserializeObject<IList<int?>>(responseContent, this.DeserializationSettings);
            }
            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }
            return result;
        }

    }
}


text:
/*
 * This file is part of HuDK.
 * ASM and C open source software development kit for the NEC PC Engine.
 * Licensed under the MIT License
 * (c) 2016-2020 MooZ
 */
#define HUDK_USE_CUSTOM_FONT 1

#define FONT_8x8_COUNT 0x1ff
#define FONT_ASCII_FIRST 0x00
#define FONT_ASCII_LAST 0x9e
#define FONT_DIGIT_INDEX 0x30
#define FONT_UPPER_CASE_INDEX 0x41
#define FONT_LOWER_CASE_INDEX 0x61

#include "hudk.h"

#incbin(palette, "data/palette.bin")
#incbin(font_bin, "./data/font.bin")

void main() {
    // load font palette
    vce_load_palette(0, 1, palette);

    // load font gfx
    vdc_load_data(VDC_DEFAULT_TILE_ADDR, font_bin, 4096);

    // set font VRAM address
    font_set_addr(VDC_DEFAULT_TILE_ADDR);

    // set font palette
    font_set_pal(0);

    // Display "Hello world!" on screen.
    // The string will be placed at BAT coordinate [10,8] using the custom font
    print_string(8,10,32,20,"Hello world!");

    // enable IRQ 1.
    irq_enable(INT_IRQ1);

    for(;;) {
        // wait for screen refresh
        vdc_wait_vsync();
    } // and we'll loop indefinitely
}


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

public class QuadMistCardCursor : MonoBehaviour
{
	private void Start()
	{
		this.LoadSprites("EmbeddedAsset/QuadMist/Atlas/quadmist_image0");
		this.gameObjects[0].GetComponent<Renderer>().enabled = true;
		for (Int32 i = 1; i < 7; i++)
		{
			this.gameObjects[i].GetComponent<Renderer>().enabled = false;
		}
		this.SetNormalState();
		this.Hide();
	}

	private void Update()
	{
		if (this.isShow)
		{
			this.timeBeforeNextFrame -= Time.deltaTime;
			if (this.timeBeforeNextFrame <= 0f)
			{
				this.timeBeforeNextFrame = 0.1f - this.timeBeforeNextFrame;
				Int32 num = this.animationIndex;
				if (this.animationIndex < 6)
				{
					this.animationIndex++;
				}
				else
				{
					this.animationIndex = 0;
				}
				this.gameObjects[num].GetComponent<Renderer>().enabled = false;
				this.gameObjects[this.animationIndex].GetComponent<Renderer>().enabled = true;
			}
		}
	}

	public void Hide()
	{
		if (!this.isShow)
		{
			return;
		}
		for (Int32 i = 0; i < 7; i++)
		{
			this.gameObjects[i].GetComponent<Renderer>().enabled = false;
		}
		this.cursorEffect.GetComponent<Renderer>().enabled = false;
		this.isShow = false;
	}

	public void Show()
	{
		if (this.isShow)
		{
			return;
		}
		for (Int32 i = 0; i < 7; i++)
		{
			this.gameObjects[i].GetComponent<Renderer>().enabled = true;
		}
		if (this.state == QuadMistCardCursor.State.Normal)
		{
			this.cursorEffect.GetComponent<Renderer>().enabled = false;
		}
		else if (this.state == QuadMistCardCursor.State.Black)
		{
			this.cursorEffect.GetComponent<Renderer>().enabled = true;
		}
		this.isShow = true;
	}

	public void SetBlackState()
	{
		if (this.cursorEffect == (UnityEngine.Object)null)
		{
			return;
		}
		this.cursorEffect.GetComponent<Renderer>().enabled = true;
		this.state = QuadMistCardCursor.State.Black;
	}

	public void SetNormalState()
	{
		if (this.cursorEffect == (UnityEngine.Object)null)
		{
			return;
		}
		this.cursorEffect.GetComponent<Renderer>().enabled = false;
		this.state = QuadMistCardCursor.State.Normal;
	}

	public void ForceHide()
	{
		this.isShow = true;
		this.Hide();
	}

	private void LoadSprites(String atlasName)
	{
		Sprite[] spriteArray = Resources.LoadAll<Sprite>(atlasName);
		Dictionary<String, Sprite> dictionary = new Dictionary<String, Sprite>();
		List<String> list = new List<String>();
		Texture2D moddedAtlas = null;
		String atlasOnDisc = AssetManager.SearchAssetOnDisc(atlasName, true, false);
		if (!String.IsNullOrEmpty(atlasOnDisc))
		{
			String[] atlasInfo = new String[0];
			moddedAtlas = AssetManager.LoadFromDisc<Texture2D>(atlasOnDisc, ref atlasInfo, "");
		}
		for (Int32 i = 0; i <= 6; i++)
			list.Add("card_cursor_" + i + ".png");
		for (Int32 j = 0; j < spriteArray.Length; j++)
		{
			Sprite sprite = spriteArray[j];
			if (list.Contains(sprite.name))
			{
				Sprite value = Sprite.Create(moddedAtlas != null ? moddedAtlas : sprite.texture, sprite.rect, new Vector2(0f, 0f), 482f);
				dictionary.Add(sprite.name, value);
			}
		}
		for (Int32 k = 0; k < spriteArray.Length; k++)
		{
			Sprite sprite = spriteArray[k];
			if (sprite.name == "card_cursor_0.png")
			{
				Sprite value = Sprite.Create(moddedAtlas != null ? moddedAtlas : sprite.texture, sprite.rect, new Vector2(0f, 0f), 482f);
				dictionary.Add("card_effect", value);
				break;
			}
		}
		this.gameObjects = new GameObject[7];
		for (Int32 l = 0; l < 7; l++)
		{
			GameObject gameObject = new GameObject("CardCursor" + l);
			SpriteRenderer spriteRenderer = gameObject.AddComponent(typeof(SpriteRenderer)) as SpriteRenderer;
			spriteRenderer.sprite = dictionary["card_cursor_" + l + ".png"];
			gameObject.transform.parent = base.transform;
			gameObject.transform.localPosition = default(Vector3);
			this.gameObjects[l] = gameObject;
		}
		this.cursorEffect = new GameObject("CursorEffect");
		SpriteRenderer spriteRenderer2 = this.cursorEffect.AddComponent(typeof(SpriteRenderer)) as SpriteRenderer;
		spriteRenderer2.sprite = dictionary["card_effect"];
		this.cursorEffect.transform.parent = base.transform;
		this.cursorEffect.transform.localPosition = new Vector3(0f, 0f, -0.1f);
		spriteRenderer2.color = new Color(0f, 0f, 0f, 0.5f);
	}

	private const Int32 CURSOR_COUNT = 7;

	private const Single ANIMATION_TIME = 0.1f;

	private GameObject[] gameObjects;

	private Int32 animationIndex;

	private Single timeBeforeNextFrame = 0.1f;

	private GameObject cursorEffect;

	private Boolean isShow = true;

	private QuadMistCardCursor.State state;

	private enum State
	{
		Normal,
		Black
	}
}


text:
{% load i18n %}

        {% include "login_and_password/partials/login_form.html" %}

{% blocktrans %}Are you new to {{ SITE_NAME }}?{% endblocktrans %}
{% trans "Sign up today, it's free!" %}

{% trans "Learn more" %} {% blocktrans %}about how {{ SITE_NAME }} can be your {{ CAN_BE_YOUR }}.{% endblocktrans %}

{% blocktrans %}Don't have a {{ SITE_NAME }} account? Sign up for free and get started today!{% endblocktrans %}

{% trans "Sign Up" %}


text:
NSTimeInterval const ACEDefaultRetryTimeInterval = 5.0;

#if __DDLOG_ENABLED__
    #if DEBUG
        const DDLogLevel ACELogLevel = DDLogLevelDebug;
    #else
        const DDLogLevel ACELogLevel = DDLogLevelInfo;
    #endif
#endif

@interface ACEOAuth2RACManager ()
// managers
@property (nonatomic, strong) AFHTTPSessionManager *networkManager;
@property (nonatomic, strong) AFOAuth2Manager *oauthManager;
@property (nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager;
@property (nonatomic, strong) RACScheduler *scheduler;

// oauth
@property (nonatomic, strong) AFOAuthCredential *oauthCredential;
@property (nonatomic, copy)   RACURLSessionRetryTestBlock oauthTestBlock;
@property (nonatomic, strong) NSString *oauthRedirectURI;

// signals
@property (nonatomic, strong) RACSignal *rac_authenticate;
@property (nonatomic, strong) RACSignal *rac_networkReachabilitySignal;
@property (nonatomic, strong) id<RACSubscriber> pendingSubscriber;

@end

#pragma mark -

@implementation ACEOAuth2RACManager

@synthesize oauthCredential = _oauthCredential;

#pragma mark -

- (instancetype)initWithBaseURL:(NSURL *)baseURL
                       clientID:(NSString *)clientID
                         secret:(NSString *)secret
                    redirectURL:(NSURL *)redirectURL
{
    return [self initWithBaseURL:baseURL clientID:clientID secret:secret redirectURL:redirectURL oauthURLString:nil apiURLString:nil];
}

- (instancetype)initWithBaseURL:(NSURL *)baseURL
                       clientID:(NSString *)clientID
                         secret:(NSString *)secret
                    redirectURL:(NSURL *)redirectURL
                 oauthURLString:(NSString *)oauthURLString
                   apiURLString:(NSString *)apiURLString
{
    self = [super init];
    if (self) {
        NSURL *oauthBaseURL     = oauthURLString ? [baseURL URLByAppendingPathComponent:oauthURLString] : baseURL;
        NSURL *apiBaseURL       = apiURLString ? [baseURL URLByAppendingPathComponent:apiURLString] : baseURL;

        self.oauthManager       = [[AFOAuth2Manager alloc] initWithBaseURL:oauthBaseURL clientID:clientID secret:secret];
        self.oauthManager.useHTTPBasicAuthentication = NO;

        self.networkManager     = [[AFHTTPSessionManager alloc] initWithBaseURL:apiBaseURL];

        self.reachabilityManager= [AFNetworkReachabilityManager managerForDomain:baseURL.host];
        [self.reachabilityManager startMonitoring];

        self.oauthRedirectURI   = [redirectURL absoluteString];
        self.oauthTestBlock = ^BOOL(NSURLResponse *response, id responseObject, NSError *error) {
            // don't retry to call the API if user is not authorized
            NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
            return statusCode >= 401 && statusCode != 422;
        };
    }
    return self;
}

#pragma mark - Properties

- (NSURL *)authenticateURL
{
    NSURL *authenticateURL = [self.oauthManager.baseURL URLByAppendingPathComponent:self.authorizeURLString];
    return [authenticateURL uq_URLByAppendingQueryDictionary:[self authParameters]];
}

- (NSDictionary *)authParameters
{
    return @{
             @"client_id":        self.oauthManager.clientID,
             @"redirect_uri":     self.oauthRedirectURI,
             @"response_type":    @"code"
             };
}

- (RACScheduler *)scheduler
{
    if (_scheduler == nil) {
        dispatch_queue_t queue = dispatch_queue_create("com.onemob.network.queue", DISPATCH_QUEUE_SERIAL);
        _scheduler = [[RACQueueScheduler alloc] initWithName:@"com.onemob.network.scheduler" queue:queue];
    }
    return _scheduler;
}

#pragma mark - Logger

- (void)setLogging:(BOOL)logging
{
    if (_logging != logging) {
        _logging = logging;

        if (logging) {
            [[AFNetworkActivityLogger sharedLogger] startLogging];

        } else {
            [[AFNetworkActivityLogger sharedLogger] stopLogging];
        }
    }
}

#pragma mark - URL Paths

- (NSString *)authorizeURLString
{
    if (_authorizeURLString == nil) {
        _authorizeURLString = @"authorize";
    }
    return _authorizeURLString;
}

- (NSString *)tokenURLString
{
    if (_tokenURLString == nil) {
        _tokenURLString = @"token";
    }
    return _tokenURLString;
}

#pragma mark - Credentials

- (AFOAuthCredential *)oauthCredential
{
    if (_oauthCredential == nil) {
        if ([self.delegate respondsToSelector:@selector(retrieveCodedCredentialForNetworkManager:withIdentifier:)]) {
            // custom implementation
            NSData *data = [self.delegate retrieveCodedCredentialForNetworkManager:self
                                                                    withIdentifier:self.oauthManager.serviceProviderIdentifier];

            _oauthCredential = (data != nil) ? [NSKeyedUnarchiver unarchiveObjectWithData:data] : nil;

        } else {
            // default implementation
            _oauthCredential = [AFOAuthCredential retrieveCredentialWithIdentifier:self.oauthManager.serviceProviderIdentifier];
        }

        // update the request serializer
        [self.networkManager.requestSerializer setAuthorizationHeaderFieldWithCredential:_oauthCredential];
    }
    return _oauthCredential;
}

- (void)setOauthCredential:(AFOAuthCredential *)oauthCredential
{
    if (_oauthCredential != oauthCredential) {
        _oauthCredential = oauthCredential;

        // update the request serializer
        [self.networkManager.requestSerializer setAuthorizationHeaderFieldWithCredential:oauthCredential];

        if (oauthCredential == nil) {

            // delete the credentials from the local store
            if ([self.delegate respondsToSelector:@selector(deleteCodedCredentialForNetworkManager:withIdentifier:)]) {
                [self.delegate deleteCodedCredentialForNetworkManager:self
                                                       withIdentifier:self.oauthManager.serviceProviderIdentifier];

            } else {
                // default implementation
                [AFOAuthCredential deleteCredentialWithIdentifier:self.oauthManager.serviceProviderIdentifier];
            }

        } else {

            // save it
            if ([self.delegate respondsToSelector:@selector(networkManager:storeCodedCredentials:withIdentifier:)]) {
                // custom implementation
                NSData *data = [NSKeyedArchiver archivedDataWithRootObject:oauthCredential];

                [self.delegate networkManager:self
                        storeCodedCredentials:data
                               withIdentifier:self.oauthManager.serviceProviderIdentifier];

            } else {
                // default implementation
                [AFOAuthCredential storeCredential:oauthCredential
                                    withIdentifier:self.oauthManager.serviceProviderIdentifier];
            }
        }
    }
}

#pragma mark - Authentication

- (RACSignal *)rac_authenticate
{
    if (self.oauthCredential != nil && !self.oauthCredential.isExpired) {
        // user credentials are not expired
        return [RACSignal return:self.oauthCredential];

    } else {
        // first login or expired token
        return [RACSignal startLazilyWithScheduler:self.scheduler
                                             block:^(id<RACSubscriber> subscriber) {

                                                 if (self.oauthCredential == nil) {
                                                     ACE_LOG_DEBUG(@"Auth with coordinator");

                                                     [[[[[self rac_authenticateWithCoordinatorSignal] subscribeOn:[RACScheduler mainThreadScheduler]]
                                                        doCompleted:^{

                                                            if ([self.delegate respondsToSelector:@selector(networkManager:authenticatedWithType:)]) {
                                                                [self.delegate networkManager:self authenticatedWithType:[self.coordinator coordinatorType]];
                                                            }

                                                        }] doError:^(NSError *error) {

                                                            if ([self.delegate respondsToSelector:@selector(networkManager:failedAuthenticationWithError:forType:)]) {
                                                                [self.delegate networkManager:self failedAuthenticationWithError:error forType:[self.coordinator coordinatorType]];
                                                            }

                                                        }] subscribe:subscriber];

                                                 } else if (self.oauthCredential.isExpired) {
                                                     ACE_LOG_DEBUG(@"Auth with refresh token");

                                                     NSError *error;
                                                     if ([[[self rac_authenticateWithRefreshToken:self.oauthCredential.refreshToken]
                                                           catch:^RACSignal *(NSError *error) {
                                                               if ([error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey] statusCode] == 401) {
                                                                   return [self rac_authenticateWithCoordinatorSignal];

                                                               } else {
                                                                   return [RACSignal error:error];
                                                               }

                                                           }] waitUntilCompleted:&error]) {
                                                               dispatch_async(dispatch_get_main_queue(), ^{

                                                                   if ([self.delegate respondsToSelector:@selector(networkManager:authenticatedWithType:)]) {
                                                                       [self.delegate networkManager:self authenticatedWithType:@"RefreshToken"];
                                                                   }

                                                                   [subscriber sendNext:self.oauthCredential];
                                                                   [subscriber sendCompleted];
                                                               });

                                                           } else {
                                                               dispatch_async(dispatch_get_main_queue(), ^{

                                                                   if ([self.delegate respondsToSelector:@selector(networkManager:failedAuthenticationWithError:forType:)]) {
                                                                       [self.delegate networkManager:self failedAuthenticationWithError:error forType:@"RefreshToken"];
                                                                   }

                                                                   [subscriber sendError:error];
                                                               });
                                                           }

                                                 } else {
                                                     [[[RACSignal return:self.oauthCredential] deliverOnMainThread] subscribe:subscriber];
                                                 }
                                             }];
    }
}

- (RACSignal *)rac_authenticateWithCoordinatorSignal
{
    @weakify(self)
    return [[RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {

        @strongify(self)

        // start the authentication on the coordinator
        [self.coordinator oauthManagerWillBeginAuthentication:self withURL:[self authenticateURL]];

        // save a reference to the subscriber
        self.pendingSubscriber = subscriber;

        return nil;

    }] setNameWithFormat:@"[%@] -rac_authenticateWithSignal", self.class];
}

- (RACSignal *)rac_authenticateWithCode:(NSString *)oauthCode
{
    @weakify(self)
    return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) {

        @strongify(self)
        NSURLSessionTask *task =
        [self.oauthManager authenticateUsingOAuthWithURLString:self.tokenURLString
                                                          code:oauthCode
                                                   redirectURI:self.oauthRedirectURI
                                                       success:^(AFOAuthCredential *credential) {

                                                           // store the new credentials
                                                           self.oauthCredential = credential;

                                                           // pass the credentials in the chain
                                                           [subscriber sendNext:credential];
                                                           [subscriber sendCompleted];

                                                       } failure:^(NSError *error) {
                                                           [subscriber sendError:error];
                                                       }];

        return [RACDisposable disposableWithBlock:^{
            [task cancel];
        }];

    }] setNameWithFormat:@"[%@] -rac_authenticateWithCode: %@", self.class, oauthCode];
}

- (RACSignal *)rac_authenticateWithRefreshToken:(NSString *)refreshToken
{
    @weakify(self)
    return [[RACSignal createSignal:^(id<RACSubscriber> subscriber) {

        @strongify(self)
        NSURLSessionTask *task =
        [self.oauthManager authenticateUsingOAuthWithURLString:self.tokenURLString
                                                  refreshToken:refreshToken
                                                       success:^(AFOAuthCredential *credential) {

                                                           // store the new credentials
                                                           self.oauthCredential = credential;

                                                           // pass the credentials in the chain
                                                           [subscriber sendNext:credential];
                                                           [subscriber sendCompleted];

                                                       } failure:^(NSError *error) {
                                                           [subscriber sendError:error];
                                                       }];

        return [RACDisposable disposableWithBlock:^{
            [task cancel];
        }];

    }] setNameWithFormat:@"[%@] -rac_authenticateWithRefreshToken: %@", self.class, refreshToken];
}

- (BOOL)handleRedirectURL:(NSURL *)redirectURL
{
    NSString *oauthCode = [redirectURL uq_queryDictionary][@"code"];
    if (oauthCode != nil && self.pendingSubscriber != nil) {

        @weakify(self)
        [[self rac_authenticateWithCode:oauthCode]
         subscribeNext:^(AFOAuthCredential *credential) {

             @strongify(self)

             if ([self.coordinator respondsToSelector:@selector(oauthManagerDidAuthenticate:)]) {
                 [self.coordinator oauthManagerDidAuthenticate:self];
             }

             // pass the credentials in the chain
             [self.pendingSubscriber sendNext:credential];
             [self.pendingSubscriber sendCompleted];

         } error:^(NSError *error) {

             if ([self.coordinator respondsToSelector:@selector(oauthManager:didFailWithError:)]) {
                 [self.coordinator oauthManager:self didFailWithError:error];
             }

             @strongify(self)
             [self.pendingSubscriber sendError:error];
         }];

        return YES;

    } else {
        [self.pendingSubscriber sendError:nil];

        return NO;
    }
}

- (void)handleRedirectError:(NSError *)error
{
    if ([self.coordinator respondsToSelector:@selector(oauthManager:didFailWithError:)]) {
        [self.coordinator oauthManager:self didFailWithError:error];
    }

    [self.pendingSubscriber sendError:error];
}

#pragma mark - HTTP Signals

- (RACSignal *)rac_GET:(NSString *)path parameters:(id)parameters
{
    return [self rac_GET:path parameters:parameters retries:1 interval:ACEDefaultRetryTimeInterval];
}

- (RACSignal *)rac_GET:(NSString *)path parameters:(id)parameters retries:(NSInteger)retries interval:(NSTimeInterval)interval
{
    return [[self rac_authenticate] flattenMap:^__kindof RACSignal *(AFOAuthCredential *credential) {
        return [[self.networkManager rac_GET:path parameters:parameters retries:retries interval:interval test:self.oauthTestBlock]
                map:^id(RACTuple *response) {
                    return [response first];
                }];
    }];
}

- (RACSignal *)rac_HEAD:(NSString *)path parameters:(id)parameters
{
    return [self rac_HEAD:path parameters:parameters retries:1 interval:ACEDefaultRetryTimeInterval];
}

- (RACSignal *)rac_HEAD:(NSString *)path parameters:(id)parameters retries:(NSInteger)retries interval:(NSTimeInterval)interval
{
    return [[self rac_authenticate] flattenMap:^__kindof RACSignal *(AFOAuthCredential *credential) {
        return [[self.networkManager rac_HEAD:path parameters:parameters retries:retries interval:interval test:self.oauthTestBlock]
                map:^id(RACTuple *response) {
                    return [response first];
                }];
    }];
}

- (RACSignal *)rac_POST:(NSString *)path parameters:(id)parameters
{
    return [self rac_POST:path parameters:parameters retries:1 interval:ACEDefaultRetryTimeInterval];
}

- (RACSignal *)rac_POST:(NSString *)path parameters:(id)parameters retries:(NSInteger)retries interval:(NSTimeInterval)interval
{
    return [[self rac_authenticate] flattenMap:^__kindof RACSignal *(AFOAuthCredential *credential) {
        return [[self.networkManager rac_POST:path parameters:parameters retries:retries interval:interval test:self.oauthTestBlock]
                map:^id(RACTuple *response) {
                    return [response first];
                }];
    }];
}

- (RACSignal *)rac_PUT:(NSString *)path parameters:(id)parameters
{
    return [self rac_PUT:path parameters:parameters retries:1 interval:ACEDefaultRetryTimeInterval];
}

- (RACSignal *)rac_PUT:(NSString *)path parameters:(id)parameters retries:(NSInteger)retries interval:(NSTimeInterval)interval
{
    return [[self rac_authenticate] flattenMap:^__kindof RACSignal *(AFOAuthCredential *credential) {
        return [[self.networkManager rac_PUT:path parameters:parameters retries:retries interval:interval test:self.oauthTestBlock]
                map:^id(RACTuple *response) {
                    return [response first];
                }];
    }];
}

- (RACSignal *)rac_PATCH:(NSString *)path parameters:(id)parameters
{
    return [self rac_PATCH:path parameters:parameters retries:1 interval:ACEDefaultRetryTimeInterval];
}

- (RACSignal *)rac_PATCH:(NSString *)path parameters:(id)parameters retries:(NSInteger)retries interval:(NSTimeInterval)interval
{
    return [[self rac_authenticate] flattenMap:^__kindof RACSignal *(AFOAuthCredential *credential) {
        return [[self.networkManager rac_PATCH:path parameters:parameters retries:retries interval:interval test:self.oauthTestBlock]
                map:^id(RACTuple *response) {
                    return [response first];
                }];
    }];
}

- (RACSignal *)rac_DELETE:(NSString *)path parameters:(id)parameters
{
    return [self rac_DELETE:path parameters:parameters retries:1 interval:ACEDefaultRetryTimeInterval];
}

- (RACSignal *)rac_DELETE:(NSString *)path parameters:(id)parameters retries:(NSInteger)retries interval:(NSTimeInterval)interval
{
    return [[self rac_authenticate] flattenMap:^__kindof RACSignal *(AFOAuthCredential *credential) {
        return [[self.networkManager rac_DELETE:path parameters:parameters retries:retries interval:interval test:self.oauthTestBlock]
                map:^id(RACTuple *response) {
                    return [response first];
                }];
    }];
}

#pragma mark - Other Signals

- (RACSignal *)rac_networkReachabilitySignal
{
    if (_rac_networkReachabilitySignal == nil) {
        _rac_networkReachabilitySignal = RACObserve(self.reachabilityManager, reachable);
    }
    return _rac_networkReachabilitySignal;
}

- (RACSignal *)rac_revokeTokenSignal
{
    // inform the server
    return [[[self.oauthManager rac_POST:@"/oauth/revoke"
                              parameters:@{
                                           @"token": self.oauthCredential.accessToken
                                           }
                                 retries:3
                                interval:1]
             initially:^{
                 // add the bearer
                 [self.oauthManager.requestSerializer setAuthorizationHeaderFieldWithCredential:self.oauthCredential];

             }] finally:^{
                 // remove the bearer
                 self.oauthManager.requestSerializer = [AFHTTPRequestSerializer serializer];

                 // clean the oauth credentials
                 self.oauthCredential = nil;
             }];
}

@end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="Description" content="Comparison of JavaScript and TypeScript language support for Typescene applications">
    <meta name="viewport" content="width=device-width, maximum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Typescene - JavaScript vs TypeScript</title>

    <link rel="stylesheet" href="/assets/style.css">
    <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Mono:400,300i|IBM+Plex+Sans:200,300,500,800,200i,300i,500i" rel="stylesheet">
    <link rel="canonical" href="https://typescene.dev/docs/js-ts">

                Typescene

  Docs

Github

<link rel="preload" href="/assets/icons/chevron.svg" as="image" />

          Documentation
           |&nbsp Overview

JavaScript vs TypeScript

The TypeScript language adds a number of enhancements to the JavaScript (or technically, ECMAScript) language. Some of these enhancements have made their way into most modern JavaScript platforms, however some of the features used by Typescene will not be available. There are workarounds for all of these issues.

Note: While it is possible to use Typescene with 'plain' JavaScript code, it is strongly recommended to use TypeScript. All of the examples on this documentation website are written in TypeScript, although they can easily be rewritten to JavaScript using the rules below.

Types

TypeScript includes 'type annotations', which informs the compiler of expected runtime types. When copying examples from TypeScript to JavaScript, these can simply be left out.

// typescript function
function usingTypeScript(p: number): string { /* ... */ }

// this can be rewritten as:
function usingJavaScript(p) { /* ... */ }

However, some editors (e.g. Visual Studio Code) will still use the type information that is available from the typescene module itself for its auto-completion features. This will not affect the resulting JavaScript code.

Class properties

When defining classes, TypeScript allows properties to be listed in the main body of the class, with optional initializers.

// TypeScript class:
class MyComponent extends Component {
  foo = 123;
  bar?: string;
}

The property declarations can be left out in JavaScript, although initializers should be moved to the constructor function:

// JavaScript class:
class MyComponent extends Component {
  constructor() {
    super();
    this.foo = 123;
  }
}

Property decorators

Typescene defines a number of 'decorators', which are used to modify the attributes of a property on all instances of a class. This includes the managed, managedChild, managedDependency, and service decorators.

// TypeScript decorators:
class MyComponent extends Component {
  @managed
  ref = new MyOtherComponent();
}

To achieve the same effect, the decorator functions can be called on their own, passing in the class prototype and property name (option 1 below). However, for cleaner code, these functions can also be called on component instances – albeit at a slight performance loss (option 2 below).

// option 1:
class MyComponent extends Component {
  constructor() {
    super();
    this.ref = new MyOtherComponent();
  }
}
managed(MyComponent.prototype, "ref");

// option 2:
class MyComponent extends Component {
  constructor() {
    super();
    managed(this, "ref");
    this.ref = new MyOtherComponent();
  }
}

Classes

While not recommended (and in most cases, not necessary), it is possible to use Typescene without the use of the class keyword.

You can use pure functions and prototypes instead, but remember to (A) call the original constructor, (B) set the correct prototype, and (C) copy static methods on extended classes as well:

// import Typescene classes:
var UILabel = typescene.UILabel;
var PageViewActivity = typescene.PageViewActivity;
var BrowserApplication = typescene.BrowserApplication;

// define a view (same as TypeScript):
var view = UILabel.withText("Hello, world!");

// create a JavaScript 'class' analog:
var _super = PageViewActivity.with(view).prototype;
function MyActivity() {
  _super.constructor.call(this);  // (A)
  this.path = "/";
}
MyActivity.prototype = Object.create(_super);  // (B)
for (var p in _super.constructor) {
  if (Object.hasOwnProperty.call(_super.constructor, p)) {
    MyActivity[p] = _super.constructor[p];  // (C)
  }
}
BrowserApplication.run(MyActivity);

It is highly recommended to use the modern class syntax, either by targeting modern platforms if possible, or by using a transpiler such as the Babel toolkit. This makes the code above unnecessary.

Overview

Why Typescene?
<link rel="prefetch" href="/docs/goals" as="fetch" />

Introduction
<link rel="prefetch" href="/docs/introduction" as="fetch" />

Installation
<link rel="prefetch" href="/docs/installation" as="fetch" />

JavaScript vs TypeScript

Types

Class properties

Property decorators

Classes

Concepts

Components
<link rel="prefetch" href="/docs/concepts/components" as="fetch" />

Lists and maps
<link rel="prefetch" href="/docs/concepts/lists-maps" as="fetch" />

Views
<link rel="prefetch" href="/docs/concepts/views" as="fetch" />

Activities
<link rel="prefetch" href="/docs/concepts/activities" as="fetch" />

Services
<link rel="prefetch" href="/docs/concepts/services" as="fetch" />

Guides

UI components
<link rel="prefetch" href="/docs/guides/ui/" as="fetch" />

Layout
<link rel="prefetch" href="/docs/guides/layout/" as="fetch" />

                    ↑ Back to top

<link rel="prefetch" href="/docs/" as="fetch" />

                    © Copyright 2021 Typescene contributors

                    Find Typescene on
    Twitter and
    Github


text:
$NetBSD: patch-modules_core_src_parallel__pthreads.cpp,v 1.3 2017/09/04 15:23:49 fhajny Exp $

PTHREAD_RECURSIVE_MUTEX_INITIALIZER doesn't exist on SunOS.

--- modules/core/src/parallel_pthreads.cpp.orig	2017-08-03 23:58:23.000000000 +0000
+++ modules/core/src/parallel_pthreads.cpp
@@ -220,6 +220,10 @@ private:
     ThreadManagerPoolState m_pool_state;
 };

+#ifndef PTHREAD_RECURSIVE_MUTEX_INITIALIZER
+#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
+#endif
+
 const char ThreadManager::m_env_name[] = "OPENCV_FOR_THREADS_NUM";

 ForThread::~ForThread()


text:
package cgeo.geocaching.storage;

import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import cgeo.geocaching.settings.Settings;
import static cgeo.geocaching.storage.Folder.CGEO_PRIVATE_FILES;
import static cgeo.geocaching.storage.Folder.DOCUMENTS_FOLDER_DEPRECATED;
import static cgeo.geocaching.storage.Folder.LEGACY_CGEO_PUBLIC_ROOT;

import android.content.Context;
import android.net.Uri;

import androidx.annotation.AnyRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.util.Consumer;

import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

/**
 * Instances of this enum represent applicaton folders whose state is persisted.
 */
public enum PersistableFolder {

    /** Base directory  */
    BASE (R.string.pref_persistablefolder_basedir, R.string.persistablefolder_base, LEGACY_CGEO_PUBLIC_ROOT, Folder.fromFolder(DOCUMENTS_FOLDER_DEPRECATED, "cgeo")),

    /** Offline Maps folder where cgeo looks for offline map files (also the one where c:geo downloads its own offline maps) */
    //legacy setting: "mapDirectory", a pure file path is stored
    OFFLINE_MAPS(R.string.pref_persistablefolder_offlinemaps, R.string.persistablefolder_offline_maps, Folder.fromPersistableFolder(BASE, "maps")),
    /** Offline Maps: optional folder for map themes (configured in settings) with user-supplied theme data */
    //legacy setting: "renderthemepath", a pure file path is stored
    OFFLINE_MAP_THEMES(R.string.pref_persistablefolder_offlinemapthemes, R.string.persistablefolder_offline_maps_themes, Folder.fromPersistableFolder(OFFLINE_MAPS, "_themes")),
    /** Target folder for written logfiles */
    LOGFILES(R.string.pref_persistablefolder_logfiles, R.string.persistablefolder_logfiles, Folder.fromPersistableFolder(BASE, "logfiles")),
    /** GPX Files */
    GPX(R.string.pref_persistablefolder_gpx, R.string.persistablefolder_gpx, Folder.fromPersistableFolder(BASE, "gpx")),
    /** Backup storage folder */
    BACKUP(R.string.pref_persistablefolder_backup, R.string.persistablefolder_backup, Folder.fromPersistableFolder(BASE, "backup")),
    /** Field Note folder */
    FIELD_NOTES(R.string.pref_persistablefolder_fieldnotes, R.string.persistablefolder_fieldnotes, Folder.fromPersistableFolder(BASE, "field-notes")),
    ///** Spoiler Image folder */
    SPOILER_IMAGES(R.string.pref_persistablefolder_spoilerimages, R.string.persistablefolder_spoilerimages, Folder.fromPersistableFolder(BASE, "GeocachePhotos")),
    /** Routing base & config folder */
    ROUTING_BASE(R.string.pref_persistablefolder_routingbase, R.string.persistablefolder_routingbase, Folder.fromPersistableFolder(BASE, "routing")),
    /** Routing tile files */
    ROUTING_TILES(R.string.pref_persistablefolder_routingtiles, R.string.persistablefolder_routingtiles, Folder.fromPersistableFolder(ROUTING_BASE, "segments4")),

    /** A Folder to use solely for Unit Test */
    TEST_FOLDER(R.string.pref_persistablefolder_testdir, 0, Folder.fromFolder(CGEO_PRIVATE_FILES,  "unittest"));

    @AnyRes
    private final int prefKeyId;
    @AnyRes
    private final int nameKeyId;
    private final boolean needsWrite;

    private final Folder[] defaultFolderCandidates;

    private Folder userDefinedFolder;
    private Folder defaultFolder;

    private final WeakHashMap<Object, List<Consumer<PersistableFolder>>> changeListeners = new WeakHashMap<>();

    @AnyRes
    public int getPrefKeyId() {
        return prefKeyId;
    }

    @StringRes
    public int getNameKeyId() {
        return nameKeyId;
    }

    PersistableFolder(@AnyRes final int prefKeyId, @AnyRes final int nameKeyId, @NonNull final Folder ... defaultFolderCandidates) {
        this.prefKeyId = prefKeyId;
        this.nameKeyId = nameKeyId;
        this.needsWrite = true;

        this.defaultFolderCandidates = defaultFolderCandidates;
        this.defaultFolder = this.defaultFolderCandidates.length == 0 ? null : this.defaultFolderCandidates[0];

        //read current user-defined location from settings.
        this.userDefinedFolder = Folder.fromConfig(Settings.getPersistableFolder(this));

        //if this PersistableFolder's value is based on another PersistableFolder, then we have to notify on  indirect change
        final PersistableFolder rootPersistableFolder = defaultFolder.getRootPersistableFolder();
        if (rootPersistableFolder != null) {
            rootPersistableFolder.registerChangeListener(this, pf -> notifyChanged());
        }
    }

    /** registers a listener which is fired each time the actual location of this folder changes */
    public void registerChangeListener(final Object lifecycleRef, final Consumer<PersistableFolder> listener) {
        List<Consumer<PersistableFolder>> listeners = changeListeners.get(lifecycleRef);
        if (listeners == null) {
            listeners = new ArrayList<>();
            changeListeners.put(lifecycleRef, listeners);
        }
        listeners.add(listener);
    }

    private void notifyChanged() {
        for (List<Consumer<PersistableFolder>> list : this.changeListeners.values()) {
            for (Consumer<PersistableFolder> listener :list) {
                listener.accept(this);
            }
        }
    }

    /** The folder this {@link PersistableFolder} currently points to */
    public Folder getFolder() {
        return this.userDefinedFolder == null ? this.defaultFolder : this.userDefinedFolder;
    }

    /** The (FolderType-specific) Uri this {@link PersistableFolder} currently points to */
    public Uri getUri() {
        return ContentStorage.get().getUriForFolder(getFolder());
    }

    public Uri getUriForFolder(final Folder folder) {
        return ContentStorage.get().getUriForFolder(folder);
    }

    public Folder getDefaultFolder() {
        return this.defaultFolder;
    }

    public boolean isUserDefined() {
        return this.userDefinedFolder != null;
    }

    /** Sets a new user-defined location (or "null" if default shall be used). Should be called ONLY by {@link ContentStorage} */
    protected void setUserDefinedFolder(@Nullable final Folder userDefinedFolder, final boolean setByUser) {
        this.userDefinedFolder = userDefinedFolder;
        Settings.setPersistableFolder(this, userDefinedFolder == null ? null : userDefinedFolder.toConfig(), setByUser);
        notifyChanged();
    }

    /** Sets a new default location (never null!). Should be called ONLY by {@link ContentStorage} */
    protected void setDefaultFolder(@NonNull final Folder defaultFolder) {
        this.defaultFolder = defaultFolder;
    }

    protected Folder[] getDefaultCandidates() {
        return this.defaultFolderCandidates;
    }

    /** Returns an internationalized ID for this folder (e.g. "GPX" or "Offline Maps"). Does not return the actual value/path (see {@link #toUserDisplayableValue()} for that) */
    @NonNull
    public String toUserDisplayableName() {
        if (this.nameKeyId == 0 || CgeoApplication.getInstance() == null) {
            //this codepath is only chosen if no translation is available (e.g. in local unit tests)
            return name();
        }
        return CgeoApplication.getInstance().getApplicationContext().getString(this.nameKeyId);
    }

    /** Returns a representation of this folder's location fit to show to an end user */
    @NonNull
    public String toUserDisplayableValue() {
        return toUserDisplayableValue(false);
    }

    /** Returns a representation of this folder's location fit to show to an end user */
    @NonNull
    public String toUserDisplayableValue(final boolean forceEnglish) {
        String result = getFolder().toUserDisplayableString(true, forceEnglish);

        result += " (";
        if (forceEnglish || CgeoApplication.getInstance() == null) {
            //this codepath is only chosen if no translation is available (e.g. in local unit tests)
            result += isUserDefined() ? "User-Defined" : "Default";
        } else {
            final Context ctx = CgeoApplication.getInstance().getApplicationContext();
            result += isUserDefined() ? ctx.getString(R.string.persistablefolder_usertype_userdefined) : ctx.getString(R.string.persistablefolder_usertype_default);
        }
        result += ")";
        return result;
    }

    /** Returns whether this persistable folder currently points to a legacy (=FILE-based) folder */
    public boolean isLegacy() {
        return getFolder().getBaseType() == Folder.FolderType.FILE;
    }

    public boolean needsWrite() {
        return needsWrite;
    }

    @Override
    public String toString() {
        return name() + ": " + toUserDisplayableValue(true) + "[" + getFolder() + "]";
    }

}


text:
namespace Manisero.DSLExecutor.Parser.SampleDSL.Parsing.Tokens
{
    public interface IFunctionArgumentToken : IToken
    {
    }
}


text:
package org.markysoft.vani.core.javascript;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.markysoft.vani.core.VaniContext;
import org.markysoft.vani.core.annotation.DetectionScript;
import org.markysoft.vani.core.annotation.JavaScript;
import org.markysoft.vani.core.annotation.JsCallFunction;
import org.markysoft.vani.core.util.VaniReflectionUtil;
import org.openqa.selenium.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * This class is responsible for reading source code of declared js-interfaces.
 *

 * The resource path can be a filesystem path or classpath. Both are supported
 * and could be mixed.
 *

 *

 * For details of the source declaration see {@link JavaScript}.
 *

 *
 * @author Thomas
 *
 * @see JavaScript
 * @see DetectionScript
 * @see JsCallFunction
 * @see JavaScriptSource
 */
public class JavaScriptLoader {
	private Log logger = LogFactory.getLog(JavaScriptLoader.class);
	@Autowired
	private VaniReflectionUtil reflectionUtil;

	/**
	 * This method is responsible for loading the javascript code from
	 * filesystem or classpath. Additionally, the detection script and custom
	 * call function will be resolved when declared.
	 *
	 * @param javaScript
	 *            annotation with source declaration
	 * @param jsInterface
	 * @param vaniContext
	 * @return returns a {@link JavaScriptSource} object, which contains the
	 *         source code, custom call function and detection script. If
	 *         resource could not be found, object will have an empty source.
	 * @throws JavaScriptReadException
	 *             will be thrown if an IOException occurs during reading js
	 *             source
	 */
	public <T> JavaScriptSource<T> load(JavaScript javaScript, Class<T> jsInterface, VaniContext vaniContext)
			throws JavaScriptReadException {
		String[] sourcePaths = javaScript.sources();
		if ((sourcePaths == null || sourcePaths.length == 0) && !StringUtils.isEmpty(javaScript.source())) {
			sourcePaths = new String[] { javaScript.source() };
		}

		StringBuilder source = new StringBuilder();
		if (sourcePaths != null) {
			for (String sourcePath : sourcePaths) {
				if (StringUtils.isEmpty(sourcePath)) {
					continue;
				}
				if (sourcePath.startsWith("classpath")) {
					String classpath = sourcePath.replace("classpath:", "");
					source.append(fromClasspath(classpath, vaniContext));
				} else {
					source.append(fromFilesystem(sourcePath, vaniContext));
				}
				source.append("\n");
			}
		}

		JavaScriptSource<T> result = new JavaScriptSource<>(jsInterface, source.toString());
		setDetectedMethod(result);
		setCallFunction(result, vaniContext);
		return result;
	}

	/**
	 * This method will look for method annotated with ({@link DetectionScript}
	 * in taret interface of provided {@link JavaScriptSource}. If a method is
	 * found, the javascript code of the annotation will be set to specified
	 * {@code jsSource} as detection script.
	 *
	 * @param jsSource
	 */
	protected <T> void setDetectedMethod(JavaScriptSource<T> jsSource) {
		Method detectionMethod = reflectionUtil.getAnnotatedMethodWith(jsSource.getJsInterface(), DetectionScript.class,
				null);
		if (detectionMethod != null) {
			DetectionScript detectionAnnotation = detectionMethod.getDeclaredAnnotation(DetectionScript.class);
			jsSource.setDetectionScriptAnnotation(detectionAnnotation);
		}
	}

	/**
	 * This method will look for method annotated with {@link JsCallFunction} in
	 * the target interface of provided {@link JavaScriptSource}. If a method is
	 * found, the corresponding source will be loaded and set to the provided
	 * {@link JavaScriptSource} as custom javascript call function.
	 *

	 * It supports filesystem and classpath declaration.
	 *

	 *
	 * @param jsSource
	 * @param vaniContext
	 */
	protected <T> void setCallFunction(JavaScriptSource<T> jsSource, VaniContext vaniContext) {
		Method callMethod = reflectionUtil.getAnnotatedMethodWith(jsSource.getJsInterface(), JsCallFunction.class,
				null);
		if (callMethod != null) {
			JsCallFunction callFuncAnnotation = callMethod.getDeclaredAnnotation(JsCallFunction.class);
			if (StringUtils.isEmpty(callFuncAnnotation.value())) {
				logger.warn("js-" + jsSource.getJsInterface() + " has callFunction without path!");
				return;
			}

			String source = "";
			String sourcePath = callFuncAnnotation.value();
			if (sourcePath.startsWith("classpath")) {
				String classpath = sourcePath.replace("classpath:", "");
				source = fromClasspath(classpath, vaniContext).toString();
			} else {
				source = fromFilesystem(sourcePath, vaniContext).toString();
			}

			if (!StringUtils.isEmpty(source)) {
				JavaScriptCallFunction callFunction = new JavaScriptCallFunction(callFuncAnnotation, source,
						callMethod);
				jsSource.setJsCallFunction(callFunction);
			}
		}
	}

	/**
	 * method to read javsScript file specified by path from classpath. If
	 * classpath contains a wildcard or there are resources with same name but
	 * paths are different, multiple entries will be returned.
	 *

	 * If you provide resource and path, only matching resources with provided
	 * path will be used.
	 *

	 *
	 * @param sourcePath
	 * @param vaniContext
	 * @return returns {@link StringBuffer} containing only source code of
	 *         specified js-script by {@code sourcePath} or empty
	 *         {@link StringBuilder} if file does not exist
	 * @throws JavaScriptReadException
	 *             will be thrown if an IOException occurs during reading js
	 *             source
	 */
	protected StringBuilder fromClasspath(String classpath, VaniContext vaniContext) throws JavaScriptReadException {
		Set<String> paths = getResourcesPathFromClasspath(classpath, vaniContext);
		if (paths.isEmpty()) {
			logger.warn("no matching js-script files for classpath '" + classpath + "' found!");
		}
		StringBuilder source = new StringBuilder();
		for (String path : paths) {
			if (!path.startsWith("/")) {
				path = "/" + path;
			}
			InputStream is = ClassLoader.class.getResourceAsStream(path);
			if (is != null) {
				try {
					source.append(IOUtils.readFully(is));
					source.append("\n");
				} catch (Exception ex) {
					throw new JavaScriptReadException(
							"cannot read classpath js-file with path '" + path + "': " + ex.getMessage(), ex);
				}
			} else {
				logger.warn("js-script with classpath '" + path + "' not found!");
			}
		}
		return source;
	}

	/**
	 * method to read javsScript file specified by path from file system.
	 *
	 * @param sourcePath
	 * @param vaniContext
	 * @return returns {@link StringBuffer} containing only source code of
	 *         specified js-script by {@code sourcePath} or empty
	 *         {@link StringBuilder} if file does not exist
	 * @throws JavaScriptReadException
	 *             will be thrown if an error occurs during collecting paths to
	 *             specified resources or reading source file
	 */
	protected StringBuilder fromFilesystem(String sourcePath, VaniContext vaniContext) throws JavaScriptReadException {
		StringBuilder result = new StringBuilder();
		List<Path> paths = new ArrayList<>();
		try {
			paths = getResourcesPathFromFilesystem(sourcePath);
		} catch (Throwable ex) {
			throw new JavaScriptReadException(
					"cannot collect paths for property source '" + sourcePath + "': " + ex.getMessage(), ex);
		}

		if (paths.isEmpty()) {
			logger.warn("requested resource '" + sourcePath + "' not found!");
			return result;
		}
		for (Path path : paths) {
			try {
				InputStream is = Files.newInputStream(path);
				if (is != null) {
					try {
						result.append(IOUtils.readFully(is));
					} finally {
						is.close();
					}
					result.append("\n");
				} else {
					logger.warn("resource path '" + path + "' not found!");
				}
			} catch (Exception ex) {
				throw new JavaScriptReadException(
						"cannot read java script source with path '" + path + "' from filesystem: " + ex.getMessage(),
						ex);
			}
		}

		return result;
	}

	/**
	 * method to get paths of resources on filesystem. Regex is NOT
	 * supported.
	 *

	 * If you don't provide an path, it will look in current working path for
	 * it.
	 *

	 *
	 * @param sourceData
	 * @return returns paths for all matching filesystem resources
	 * @throws Throwable
	 *             will be thrown if an error occurs during search for given
	 *             resources on filesystem
	 */
	protected List<Path> getResourcesPathFromFilesystem(String resourcePath) throws Throwable {
		List<Path> result = new ArrayList<>();
		int idx = resourcePath.lastIndexOf("/");
		String path = "";
		if (idx > -1) {
			path = resourcePath.substring(0, idx);
			resourcePath = resourcePath.substring(idx + 1);
		}

		DirectoryStream<Path> stream = null;
		if (StringUtils.isEmpty(path)) {
			path = ".";
		}
		Path dir = Paths.get(path);
		stream = Files.newDirectoryStream(dir, resourcePath);
		stream.forEach(p -> result.add(p));

		return result;
	}

	/**
	 * method to get paths of classpath resources. If classpath contains a
	 * wildcard or there are resources with same name but paths are different,
	 * multiple entries will be returned.
	 *

	 * If you provide resource and path, only matching resources with provided
	 * path will be returned.
	 *

	 *
	 * @param classpath
	 *            name of resource (also path and regex are supported)
	 * @param context
	 * @return returns paths for all matching classpath resources
	 */
	protected Set<String> getResourcesPathFromClasspath(String classpath, VaniContext context) {
		Set<String> result = null;
		boolean isPathUsed = classpath.contains("/");
		String path = "";
		if (isPathUsed) {
			int idx = classpath.lastIndexOf("/");
			path = classpath.substring(0, idx);
			classpath = classpath.substring(idx + 1);
		}
		result = context.getReflections().getResources(Pattern.compile(classpath));

		if (isPathUsed) {
			Set<String> matches = new HashSet<>();
			Pattern fullPattern = Pattern.compile(path + "/" + classpath);
			for (String entry : result) {
				if (fullPattern.matcher(entry).find()) {
					matches.add(entry);
				}
			}
			result = matches;
		}
		return result;
	}

	public void setReflectionUtil(VaniReflectionUtil reflectionUtil) {
		this.reflectionUtil = reflectionUtil;
	}
}