text:
#ifndef INCLUDED_QBtCompareDirsDialog_h
#define INCLUDED_QBtCompareDirsDialog_h

/*------- include files:
-------------------------------------------------------------------*/
#include <QDialog>
#include <QHash>
#include <QMap>
#include <QFileInfo>

/*------- forward declarations:
-------------------------------------------------------------------*/
class QPushButton;
class QTreeWidget;
class QBtInfoLabel;
class QTreeWidgetItem;

/*------- class declaration:
-------------------------------------------------------------------*/
class QBtCompareDirsDialog : public QDialog
{
   Q_OBJECT

//******* TYPES *******
private:
   typedef QHash< QString, QFileInfo > FileMap;
   typedef QHash< QString, FileMap   > DirMap;
   typedef QMap < QString, QString   > AllItems;
   class RowData {
      public:
         RowData()
         : name1_     ( QString() )
         , name2_     ( QString() )
         , path1_     ( QString() )
         , path2_     ( QString() )
         , separator_ ( QString() )
         , is_lft_    ( false )
         , is_rgt_    ( false )
         , is_dir_    ( false )
         {}
         ~RowData() {}
      private:
         RowData( const RowData& );
         RowData& operator=( const RowData& );

      //******* MEMBERS *******
      private:
         QString name1_;
         QString name2_;
         QString path1_;
         QString path2_;
         QString separator_;
         bool    is_lft_;
         bool    is_rgt_;
         bool    is_dir_;
      public:
         const QString& name1    () const { return name1_;     }
         const QString& name2    () const { return name2_;     }
         const QString& path1    () const { return path1_;     }
         const QString& path2    () const { return path2_;     }
         const QString& separator() const { return separator_; }
         bool           is_lft   () const { return is_lft_;    }
         bool           is_rgt   () const { return is_rgt_;    }
         bool           is_dir   () const { return is_dir_;    }
         bool           are_both () const { return ( is_lft_ && is_rgt_ ); }

         void name1    ( const QString& in_text ) { name1_     = in_text; }
         void name2    ( const QString& in_text ) { name2_     = in_text; }
         void path1    ( const QString& in_text ) { path1_     = in_text; }
         void path2    ( const QString& in_text ) { path2_     = in_text; }
         void separator( const QString& in_text ) { separator_ = in_text; }
         void is_lft   ( const bool     in_flag ) { is_lft_    = in_flag; }
         void is_rgt   ( const bool     in_flag ) { is_rgt_    = in_flag; }
         void is_dir   ( const bool     in_flag ) { is_dir_    = in_flag; }

         void reset () {
            name1_ = name2_ = path1_ = path2_ = separator_ = QString();
            is_lft_ = is_rgt_ = is_dir_ = false;
         }
         void set_lft( const QString& in_name, const QString& in_path ) {
            is_lft_ = true;
            name1_  = in_name;
            path1_  = in_path;
         }
         void set_rgt( const QString& in_name, const QString& in_path ) {
            is_rgt_ = true;
            name2_  = in_name;
            path2_  = in_path;
         }
   };

//******* CONSTRUCTION / DESTRUCTION *******
public:
   QBtCompareDirsDialog( QWidget* );
private:
   QBtCompareDirsDialog( const QBtCompareDirsDialog& );
   QBtCompareDirsDialog& operator=( const QBtCompareDirsDialog& );

//******* CONSTANTS *******
private:
   static const char* const Caption;
   static const char* const DirsCaption;
   static const char* const ResultCaption;
   static const char* const LftPanel;
   static const char* const RgtPanel;
   static const char* const Run;
   static const char* const Compare;
   static const char* const Close;
   static const char* const Break;
   static const char* const LeftDir;
   static const char* const RightDir;
   static const char* const NotPresent;
   static const char* const TheSame;
   static const char* const ReadError;
   static const char* const CantOpen;
   static const QString     Dir;
   static const QString     Equal;
   static const QString     NotEqual;
   static const QString     Error;

//******* MEMBERS *******
private:
   QTreeWidget*  const view_;
   QPushButton*  const run_btn_;
   QPushButton*  const close_btn_;
   QBtInfoLabel* const left_dirinfo_;
   QBtInfoLabel* const right_dirinfo_;
   QString             left_path_;
   QString             right_path_;
   bool                runned_;
   bool                continue_;
   bool                ready_;

//******** METHODS *******
public:
   void set_dirs( const QString&, const QString& );
private:
   void    showEvent    ( QShowEvent* );
   void    add_row      ( const RowData& ) const;
   QString check_files  ( const QFileInfo&, const QFileInfo& );
   QString cmp_contents ( const QString&, const QString& );
   void    set_focus    ();
   void    diff         ( const QString& , const QString& ) const;
   void    read_dir     ( const QString& , const QString&, DirMap& ) const;
   void    compare      ( const QString& , const QString&   );
   void    compare_files( const FileMap& , const FileMap&   );
   void    join_dirs    ( AllItems&      , const DirMap&    ) const;
   void    join_files   ( AllItems&      , const FileMap&   ) const;

private slots:
   void start_slot();
   void close_slot();
};

 #endif // INCLUDED_QBtCompareDirsDialog_h


text:
package org.pac4j.jax.rs.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.pac4j.core.profile.ProfileManager;

/**
 *
 * Binds the value(s) of the current Pac4J {@link ProfileManager} to a resource method parameter, resource class field,
 * or resource class bean property.
 *
 * @author Victor Noel - Linagora
 * @since 1.0.0
 *
 */
@Target({ ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Pac4JProfileManager {
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.Prateek.consumerprotectionrights.test">

    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="15" />

    <application>
        <uses-library android:name="android.test.runner" />
    </application>

    <instrumentation android:name="android.test.InstrumentationTestRunner"
                     android:targetPackage="com.Prateek.consumerprotectionrights"
                     android:handleProfiling="false"
                     android:functionalTest="false"
                     android:label="Tests for com.Prateek.consumerprotectionrights"/>
</manifest>


text:
[![npm][version]][npm]
[![npm][downloads]][npm]

[npm]: https://www.npmjs.com/package/cucumber-pretty
[version]: https://img.shields.io/npm/v/cucumber-pretty.svg
[downloads]: https://img.shields.io/npm/dm/cucumber-pretty.svg

Custom Cucumber.js pretty formatter implementing event protocol for versions 3 to 6.

Official Cucumber.js pretty formatter implementing [message protocol](https://github.com/cucumber/common/tree/main/messages) for version 7 and later is at [@cucumber/pretty-formatter](https://www.npmjs.com/package/@cucumber/pretty-formatter).

- For Cucumber.js v1 and v2 use `-f pretty`
- For Cucumber.js v3, v4, and v5 install `cucumber-pretty@1.5` and use `-f node_modules/cucumber-pretty`
- For Cucumber.js v6 install `cucumber-pretty@6` and use `-f node_modules/cucumber-pretty`
- For Cucumber.js v7 install `@cucumber/pretty-formatter` and use `-f @cucumber/pretty-formatter`

Built with 🥒 by [Ilya Kozhevnikov](http://kozhevnikov.com/).

## Use

```bash
npm i cucumber-pretty
cucumber-js -f node_modules/cucumber-pretty
```

## References

- https://github.com/cucumber/cucumber-js/blob/master/docs/cli.md#formats
- https://github.com/cucumber/cucumber-js/blob/master/docs/custom_formatters.md

## Dark

## Light


text:
package mqttclient.impl;

import com.mendix.core.Core;
import com.mendix.logging.ILogNode;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.File;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ako on 1/9/2016.
 */
public class MqttConnector {
    private static Map<String, MqttConnection> mqttHandlers;
    private ILogNode logger;

    public MqttConnector(ILogNode logger) {
        this.logger = logger;
        if (mqttHandlers == null) {
            mqttHandlers = new HashMap();
        }
    }

    public void subscribe(String brokerHost, Long brokerPort, String brokerOrganisation, String topicName, String onMessageMicroflow, String CA, String ClientCertificate, String ClientKey, String CertificatePassword, String username, String password) throws Exception {
        logger.info("MqttConnector.subscribe");
        MqttConnection connection = getMqttConnection(brokerHost, brokerPort, brokerOrganisation, CA, ClientCertificate, ClientKey, CertificatePassword, username, password);
        connection.subscribe(topicName, onMessageMicroflow);
    }

    public void publish(String brokerHost, Long brokerPort, String brokerOrganisation, String topicName, String message, String CA, String ClientCertificate, String ClientKey, String CertificatePassword, String username, String password) throws Exception {
        logger.info("MqttConnector.publish");
        MqttConnection connection = getMqttConnection(brokerHost, brokerPort, brokerOrganisation, CA, ClientCertificate, ClientKey, CertificatePassword, username, password);
        connection.publish(topicName, message);
    }

    private MqttConnection getMqttConnection(String brokerHost, Long brokerPort, String brokerOrganisation, String CA, String ClientCertificate, String ClientKey, String CertificatePassword, String username, String password) throws Exception {
        String key = brokerHost + ":" + brokerPort;
        MqttConnection handler;
        synchronized (mqttHandlers) {
            logger.info("NUmber of objects in mqttHandlers map: " + mqttHandlers.size());

            if (!mqttHandlers.containsKey(key)) {
                logger.info("creating new MqttConnection");
                try {
                    handler = new MqttConnection(logger, brokerHost, brokerPort, brokerOrganisation, CA, ClientCertificate, ClientKey, CertificatePassword, username, password);
                    mqttHandlers.put(key, handler);
                } catch (Exception e) {
                    logger.error(e);
                    throw e;
                }

            } else {
                logger.info("Found existing MqttConnection");
                handler = mqttHandlers.get(key);
            }
            logger.info("Number of objects in mqttHandlers map: " + mqttHandlers.size());
        }

        return handler;
    }

    public void unsubscribe(String brokerHost, Long brokerPort, String topicName) throws Exception {
        MqttConnection connection = getMqttConnection(brokerHost, brokerPort, null, null, null, null, null, null, null);
        connection.unsubscribe(topicName);
    }

    private class MqttConnection {
        private ILogNode logger;
        private MqttClient client;
        private HashMap<String, MqttSubscription> subscriptions = new HashMap<>();
        private String broker;
        private String clientId;
        private MqttConnectOptions connOpts;
        private MemoryPersistence persistence;

        public MqttConnection(ILogNode logger, String brokerHost,  Long brokerPort, String brokerOrganisation, String CA, String ClientCertificate, String ClientKey, String CertificatePassword, String username, String password) throws Exception {
            logger.info("new MqttConnection");

            this.logger = logger;

            String hostname = InetAddress.getLocalHost().getHostName();
            String xasId = Core.getXASId();

            boolean useSsl = (ClientCertificate != null && !ClientCertificate.equals(""));
            connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            connOpts.setAutomaticReconnect(true);

            if(brokerOrganisation != null && !brokerOrganisation.equals("")){
            	broker = String.format("tcp://%1s.%2s:%d",brokerOrganisation, brokerHost, brokerPort);
            	clientId = "a:" + brokerOrganisation + ":" + xasId;
            }else{
            	broker = String.format("tcp://%s:%d", brokerHost, brokerPort);
                clientId = "MxClient_" + xasId + "_" + hostname + "_" + brokerHost + "_" + brokerPort;
            }
            logger.info("new MqttConnection client id " + clientId);

            if (username != null && !username.equals("")) {
                connOpts.setUserName(username);
            }
            if (password != null && !password.equals("")) {
                connOpts.setPassword(password.toCharArray());
            }

            if (useSsl) {
                broker = String.format("ssl://%s:%d", brokerHost, brokerPort);
                //connOpts = new MqttConnectOptions();
                connOpts.setConnectionTimeout(60);
                connOpts.setKeepAliveInterval(60);
                connOpts.setCleanSession(true);

                try {
                    String resourcesPath = null;
                    try {
                        resourcesPath = Core.getConfiguration().getResourcesPath().getPath();
                        resourcesPath += File.separator;

                    } catch (Exception e) {
                        //testing mode?
                        resourcesPath = "";
                    }
                    connOpts.setSocketFactory(SslUtil.getSslSocketFactory(
                            resourcesPath + CA,
                            resourcesPath + ClientCertificate,
                            resourcesPath + ClientKey,
                            CertificatePassword
                    ));
                } catch (Exception e) {
                    logger.error(e);
                    throw e;
                }
            }

            persistence = new MemoryPersistence();

            try {
                this.client = new MqttClient(broker, clientId, persistence);
                logger.info("Connecting to broker: " + broker);
                client.connect(connOpts);
                client.setCallback(new MxMqttCallback(logger, client, subscriptions));
                logger.info("Connected");
            } catch (Exception e) {
                logger.error(e);
                throw e;
            }
        }

        public void finalize() {
            logger.info("finalize MqttConnection");
        }

        public boolean isSubscribed(String topic) {
            return subscriptions.containsKey(topic);

        }

        public void subscribe(String topic, String onMessageMicroflow) throws MqttException {
            logger.info(String.format("MqttConnection.subscribe: %s", client.getClientId()));
            try {
                if(!client.isConnected()){
                    client.reconnect();
                }

                // 0 - at most once
                // 1 - at least once
                // 2 - exactly once

                int subscriptionQos = 1;
                client.subscribe(topic, subscriptionQos);
                subscriptions.put(topic, new MqttSubscription(topic, onMessageMicroflow));
            } catch (Exception e) {
                logger.error(e);
                throw e;
            }

        }

        public void publish(String topic, String message) throws MqttException {
            logger.info(String.format("MqttConnection.publish: %s, %s, %s", topic, message, client.getClientId()));
            try {
                MqttMessage payload = new MqttMessage(message.getBytes());
                int qos = 1;
                payload.setQos(qos);
                client.publish(topic, payload);
                logger.info("Message published");
            } catch (Exception e) {
                logger.error(e);
                throw e;
            }
        }

        public void unsubscribe(String topicName) throws MqttException {
            logger.info(String.format("unsubscribe: %s, %s", topicName, client.getClientId()));
            try {
                client.unsubscribe(topicName);
            } catch (MqttException e) {
                logger.error(e);
                throw e;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.nexuslink.guidecar">

    <!-- 网络权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- 蓝牙权限 -->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
    <!-- 6.0以后需要获取位置权限 -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:name=".app.GuideCarApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/BaseTheme">
        <activity
            android:name=".ui.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/DayTheme">

            <!--
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            -->
        </activity>
        <activity
            android:name=".ui.SettingActivity"
            android:theme="@style/DayTheme" />
        <activity android:name=".ui.DeviceListActivity" />

        <service android:name=".service.BlueToothService" />

        <activity android:name=".ui.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ui.NaviActivity"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/title_activity_navi"
            android:theme="@style/FullscreenTheme"></activity>
    </application>

</manifest>


text:
class Protocol
{
public:
  enum MessageType
  {
    error,
    auth,
    authResponse,
    connect,
    disconnect,
    data,
    suspend,
    resume,
  };

#pragma pack(push, 1)
  struct Header
  {
    uint32 size:24;
    uint8 messageType; // MessageType
  };

  struct AuthMessage : public Header
  {
    char secret[33];
  };

  struct ConnectMessage : public Header
  {
    uint32 connectionId;
    uint16 port;
  };

  struct DisconnectMessage : public Header
  {
    uint32 connectionId;
  };

  struct DataMessage : public Header
  {
    uint32 connectionId;
    uint32 originalSize:24;
  };

  struct SuspendMessage : public Header
  {
    uint32 connectionId;
  };

  struct ResumeMessage : public Header
  {
    uint32 connectionId;
  };
#pragma pack(pop)

  template<size_t N> static void setString(char(&str)[N], const String& value)
  {
    size_t size = value.length() + 1;
    if(size > N - 1)
      size = N - 1;
    Memory::copy(str, (const char*)value, size);
    str[N - 1] = '\0';
  }

  template<size_t N> static String getString(char(&str)[N])
  {
    str[N - 1] = '\0';
    String result;
    result.attach(str, String::length(str));
    return result;
  }
};


text:
require File.expand_path("#{File.dirname(__FILE__)}/test_helper")
require 'json'

module BriteVerify
  describe Email do
    ADDRESS = "john.doe@example.com"
    KEY     = "123-abc-123-abc"

    before do
      stub_email_verification_request(ADDRESS, KEY, valid_email_body)
    end

    it "accepts a key" do
      email = Email.new(ADDRESS, KEY)
      _(email).wont_be_nil
    end

    it "requires a key" do
      ENV['BRITEVERIFY_API_KEY'] = nil
      email = lambda { Email.new(ADDRESS) }
      _(email).must_raise(ArgumentError)
    end

    it "does not accept an empty key" do
      email = lambda { Email.new(ADDRESS, "") }
      _(email).must_raise(ArgumentError)
    end

    it "uses the environment variable the key wasn't given" do
      ENV['BRITEVERIFY_API_KEY'] = "456-def-456-def"
      email = lambda { Email.new(ADDRESS) }
      _(email).must_be_silent
      ENV['BRITEVERIFY_API_KEY'] = nil
    end

    describe :verified? do
      describe "when the response was successful" do
        it "returns true" do
          email = Email.new(ADDRESS, KEY)
          _(email.verified?).must_equal(true)
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns false" do
          email = Email.new(ADDRESS, KEY)
          _(email.verified?).must_equal(false)
        end
      end

      describe "when the response timed out" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, :timeout)
        end

        it "returns false" do
          email = Email.new(ADDRESS, KEY)
          _(email.verified?).must_equal(false)
        end
      end

      describe "when the response is unauthorized" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 401)
        end

        it "returns false" do
          email = Email.new(ADDRESS, KEY)
          _(email.verified?).must_equal(false)
        end
      end
    end

    describe :address do
      describe "when the response was successful" do
        it "returns the verified address returned from BriteVerify" do
          email = Email.new(ADDRESS, KEY)
          _(email.address).must_equal("john.doe@example.com")
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.address).must_be_nil
        end
      end
    end

    describe :account do
      describe "when the response was successful" do
        it "returns the account returned from BriteVerify" do
          email = Email.new(ADDRESS, KEY)
          _(email.account).must_equal("john.doe")
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.account).must_be_nil
        end
      end
    end

    describe :domain do
      describe "when the response was successful" do
        it "returns the domain returned from BriteVerify" do
          email = Email.new(ADDRESS, KEY)
          _(email.domain).must_equal("example.com")
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.domain).must_be_nil
        end
      end
    end

    describe :status do
      describe "when the response was successful" do
        describe "when the address is valid" do
          it "returns the valid status" do
            email = Email.new(ADDRESS, KEY)
            _(email.status).must_equal(:valid)
          end
        end

        describe "when the address is invalid" do
          before do
            stub_email_verification_request(ADDRESS, KEY, invalid_email_body)
          end

          it "returns the invalid status" do
            email = Email.new(ADDRESS, KEY)
            _(email.status).must_equal(:invalid)
          end
        end

        describe "when the address is unknown" do
          before do
            stub_email_verification_request(ADDRESS, KEY, unknown_email_body)
          end

          it "returns the unknown status" do
            email = Email.new(ADDRESS, KEY)
            _(email.status).must_equal(:unknown)
          end
        end

        describe "when the address is an accept all address" do
          before do
            stub_email_verification_request(ADDRESS, KEY, accept_all_email_body)
          end

          it "returns the unknown status" do
            email = Email.new(ADDRESS, KEY)
            _(email.status).must_equal(:accept_all)
          end
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.status).must_be_nil
        end
      end
    end

    describe :connected do
      describe "when the response was successful" do
        describe "when the address is connected" do
          before do
            stub_email_verification_request(ADDRESS, KEY, connected_email_body)
          end

          it "returns true" do
            email = Email.new(ADDRESS, KEY)
            _(email.connected).must_equal(true)
          end
        end

        describe "when it is not known if the address is connected" do
          it "returns nil" do
            email = Email.new(ADDRESS, KEY)
            _(email.connected).must_be_nil
          end
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.connected).must_be_nil
        end
      end
    end

    describe :duration do
      describe "when the response was successful" do
        it "returns the time it took BriteVerify to verify the address" do
          email = Email.new(ADDRESS, KEY)
          _(email.duration).must_equal(0.104516605)
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.duration).must_be_nil
        end
      end
    end

    describe :disposable do
      describe "when the response was successful" do
        describe "the address is disposable" do
          before do
            stub_email_verification_request(ADDRESS, KEY, disposable_email_body)
          end

          it "returns true" do
            email = Email.new(ADDRESS, KEY)
            _(email.disposable).must_equal(true)
          end
        end

        describe "when it is not known if the address is disposable" do
          it "returns nil" do
            email = Email.new(ADDRESS, KEY)
            _(email.disposable).must_be_nil
          end
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.disposable).must_be_nil
        end
      end
    end

    describe :role_address do
      describe "when the response was successful" do
        describe "when the address is a role address" do
          before do
            stub_email_verification_request(ADDRESS, KEY, role_address_email_body)
          end

          it "returns true" do
            email = Email.new(ADDRESS, KEY)
            _(email.role_address).must_equal(true)
          end
        end

        describe "when it is not known if the address is a role address" do
          it "returns nil" do
            email = Email.new(ADDRESS, KEY)
            _(email.role_address).must_be_nil
          end
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.role_address).must_be_nil
        end
      end
    end

    describe :error_code do
      describe "when the response was successful" do
        describe "when the address is valid" do
          it "has no error code" do
            email = Email.new(ADDRESS, KEY)
            _(email.error_code).must_be_nil
          end
        end

        describe "when the address is not valid" do
          before do
            stub_email_verification_request(ADDRESS, KEY, invalid_email_body)
          end

          it "has an error code" do
            email = Email.new(ADDRESS, KEY)
            _(email.error_code).must_equal("email_domain_invalid")
          end
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.error_code).must_be_nil
        end
      end
    end

    describe :error do
      describe "when the response was successful" do
        describe "when the address is valid" do
          it "has no error" do
            email = Email.new(ADDRESS, KEY)
            _(email.error).must_be_nil
          end
        end

        describe "when the address is not valid" do
          before do
            stub_email_verification_request(ADDRESS, KEY, invalid_email_body)
          end

          it "has a more detailed error" do
            email = Email.new(ADDRESS, KEY)
            _(email.error).must_equal("Email domain invalid")
          end
        end
      end

      describe "when the response was not successful" do
        before do
          stub_error_email_verification_request(ADDRESS, KEY, 500)
        end

        it "returns nil" do
          email = Email.new(ADDRESS, KEY)
          _(email.error).must_be_nil
        end
      end
    end
  end
end


text:
/**
 * External dependencies
 */
import { useEffect } from '@googleforcreators/react';

function useWindowResizeHandler(ref) {
  useEffect(() => {
    const handleUpdateMoveable = () => ref.current?.updateRect();
    window.addEventListener('resize', handleUpdateMoveable);
    return () => {
      window.removeEventListener('resize', handleUpdateMoveable);
    };
  }, [ref]);
}

export default useWindowResizeHandler;


text:
from math import sqrt

from python.decorators import euler_timer
from python.functions import sieve

def max_prime_length(digits, primes=[]):
    """
    Returns the length of the longest string of primes
    (starting at 2,3,5,...) that will sum to less 10**digits
    """
    cap = 10 ** digits
    if primes == []:
        primes = sieve(int(4 * sqrt(cap)))
    count = 0
    num_primes = 0
    for prime in primes:
        if count + prime < cap:
            count += prime
            num_primes += 1
        else:
            return num_primes
    raise ValueError("max_prime_length failed logic.")

def all_prime_seqs(length, digits, primes=[]):
    """
    Returns all sequences of primes of

    Assumes length <= max_prime_length(digits)
    """
    cap = 10 ** digits
    if primes == []:
        primes = sieve(cap)

    result = []
    final_index = length - 1
    curr = primes[final_index - length + 1:final_index + 1]
    running_sum = sum(curr)
    while running_sum < cap:
        running_sum -= curr[0]  # remove the smallest value from the sum
        result.append(curr)
        final_index += 1
        curr = primes[final_index - length + 1:final_index + 1]
        running_sum += curr[-1]  # add the new largest
    return result

def prime_sequence_exists(length, digits, primes=[]):
    """
    Returns True if a sequence of length consecutive primes which sums
    to less than 10**digits also sums to a prime number
    """
    cap = 10 ** digits
    if primes == []:
        primes = sieve(cap)
    sums = [sum(seq) for seq in all_prime_seqs(length, digits, primes)]
    return (set(sums).intersection(primes) != set())

def longest_prime_sequence(digits, primes=[]):
    """
    Returns the length of the most consecutive primes which sum
    to a prime and sum to less then 10**digits
    """
    if primes == []:
        primes = sieve(10 ** digits)
    max_length = max_prime_length(digits, primes)
    for length in range(max_length, 0, -1):
        if prime_sequence_exists(length, digits, primes):
            return length
    raise ValueError("Algorithm failed")

def longest_prime(digits):
    primes = sieve(10 ** digits)
    length = longest_prime_sequence(digits, primes)
    sums = [sum(seq) for seq in all_prime_seqs(length, digits, primes)]
    return max(set(sums).intersection(primes))

def main(verbose=False):
    return longest_prime(6)

if __name__ == '__main__':
    print euler_timer(50)(main)(verbose=True)


text:
"""
__init__.py

Created by Keith Fahlgren on Mon Jun 13 16:17:48 PDT 2011
Copyright (c) 2011 Threepress Consulting Inc. All rights reserved.
"""

import logging
import os.path
import subprocess
import tempfile

from lxml import etree, isoschematron

log = logging.getLogger(__name__)

JING_FN = os.path.join(os.path.dirname(__file__),
                       'externals',
                       'jing',
                       'jing.jar')
SAXON_FN = os.path.join(os.path.dirname(__file__),
                        'externals',
                        'saxon',
                        'saxon9he.jar')

SCHEMAS = os.path.join(os.path.dirname(__file__),
                       'externals',
                       'schemas',
                       'epub3')
NAV_RNC = os.path.join(SCHEMAS, 'epub-nav-30.rnc')
NAV_SCH_FN = os.path.join(SCHEMAS, 'epub-nav-30.sch')
NAV_SCHEMATRON = isoschematron.Schematron(etree.parse(NAV_SCH_FN), store_report=True)
NCX_DTD_FN = os.path.join(os.path.dirname(__file__), 'externals', 'schemas', 'ncx-2005-1.dtd')
PACKAGE_RNC = os.path.join(SCHEMAS, 'package-30.rnc')
PACKAGE_SCH_XSL = os.path.join(SCHEMAS, 'package-30.sch.xsl')

NSS={'svrl': "http://purl.oclc.org/dsdl/svrl",
    }

def nav_validate(nav_doc):
    """Validate the supplied EPUB Navigation Document (as etree) against the RELAX NG Compact and Schematron schemas. Returns boolean. Writes warnings
       to this classes' log stream."""
    jing_result = jing_validate(nav_doc, NAV_RNC)
    sch_result = schematron_xslt1_validate(nav_doc, NAV_SCHEMATRON)
    return (jing_result and sch_result)

def ncx_validate(ncx_doc):
    """Validate the supplied NCX Document (as etree) against the NCX 2005-1 DTD Returns boolean. Writes warnings
       to this classes' log stream."""
    dtd = etree.DTD(NCX_DTD_FN)
    result = dtd.validate(ncx_doc)
    for error in dtd.error_log:
        log.warn(error)
    return result

def package_validate(package_doc):
    """Validate the supplied EPUB Navigation Document (as etree) against the RELAX NG Compact and Schematron schemas. Returns boolean. Writes warnings
       to this classes' log stream."""
    jing_result = jing_validate(package_doc, PACKAGE_RNC)
    sch_result = schematron_xslt2_validate(package_doc, PACKAGE_SCH_XSL)
    return (jing_result and sch_result)

def jing_validate(xml, rnc_fn):
    fd, tmp_fn = tempfile.mkstemp()
    f = os.fdopen(fd, 'wb')
    result = False
    try:
        f.write(etree.tostring(xml))
        f.close()

        jing_cmd = ['java', '-jar', JING_FN, '-c', rnc_fn, tmp_fn]
        process = subprocess.Popen(jing_cmd, stdout=subprocess.PIPE)
        output, _ = process.communicate()
        retcode = process.poll()
        if retcode != 0:
            log.warn('Validation errors:\n%s' % output)
        else:
            result = True

    finally:
        os.remove(tmp_fn)
        return result

def schematron_xslt1_validate(xml, validator):
    result = validator.validate(xml)
    if result:
        return True
    else:
        svrl_doc = validator.validation_report
        errors = _collect_svrl_errors(svrl_doc)
        for error in errors:
            log.warn(error)
        return False

def schematron_xslt2_validate(xml, sch_xsl_fn):
    fd, tmp_fn = tempfile.mkstemp()
    f = os.fdopen(fd, 'wb')
    svrl_doc = None
    try:
        f.write(etree.tostring(xml))
        f.close()

        saxon_cmd = ['java', '-jar', SAXON_FN, tmp_fn, sch_xsl_fn]
        log.debug("CS: %s" % saxon_cmd)
        process = subprocess.Popen(saxon_cmd, stdout=subprocess.PIPE)
        output, _ = process.communicate()
        retcode = process.poll()
        if retcode != 0:
            log.warn('Schematron processing errors:\n%s' % output)
        else:
            log.debug("OUT: %s" % output)
            svrl_doc = etree.fromstring(output)

    finally:
        os.remove(tmp_fn)

    errors = _collect_svrl_errors(svrl_doc)
    if len(errors) == 0:
        return True
    else:
        for error in errors:
            log.warn(error)
        return False

def _collect_svrl_errors(svrl_doc):
    errors = []
    for svrl_error in svrl_doc.xpath('//svrl:failed-assert/svrl:text/text()|//svrl:successful-report/svrl:text/text()',
                                     namespaces=NSS):
        errors.append('SVRL Error: %s' % svrl_error)
    return errors


text:
namespace po = boost::program_options;

#include <iostream>
#include <fstream>
#include <iterator>
#include <exception>
using namespace std;

// A helper function to simplify the main part.
template<class T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
    copy(v.begin(), v.end(), ostream_iterator<T>(os, " "));
    return os;
}

int main(int ac, char* av[])
{
    try {
//        int opt;
        string config_file;

        string target_file;
        string input_directory;
        string staging_directory;
        string output_directory;
        string google_maps_api_key;

        // Declare a group of options that will be
        // allowed only on command line
        po::options_description generic("Generic options");
        generic.add_options()
            ("version,v", "print version string")
            ("help,h", "produce help message")
            ("config,c", po::value<string>(&config_file)->default_value(getenv("HOME") + string("/.fby/config.ini")),
                  "name of a file of a configuration.")
            ("scanwikifiles", "scan wiki files and mark changed files changed")
            ("scanimages", "scan image files and mark changed files changed")
            ("scandplfiles", "scan wiki files and mark files with dpl tags changed")
            ("rebuilddirtyfiles", "rebuild all files marked dirty")

            ("getwikifiles", "get a list of all of the wiki files")
            ("getcontentdirty", "get a list of all of the content dirty wiki files")
            ("getreferenceddirty", "get a list of all of the reference dirty wiki files")
            ("rebuildoutputfiles", "rebuild wiki files based on current database status")

            ("writewikifile", po::value<string>(&target_file),
             "wiki file to write to")
            ("writeimagefile", po::value<string>(&target_file),
             "image file to write to")
            ("readwikifile", po::value<string>(&target_file),
             "wiki file to read from")
            ("loadexifdata", po::value<string>(&target_file),
             "load a single image instance data, by filemame")
            ("scanwikifile", po::value<string>(&target_file),
             "scan specified file for links to other files, mark changed files externally changed")
            ("dowikifile", po::value<string>(&target_file),
             "rebuild the specified wiki file")
            ("markcontentdirty", po::value<string>(&target_file),
             "mark the specified wiki page dirty")
            ("markreferencesdirty", po::value<string>(&target_file),
             "mark the specified wiki page dirty")
            ;
        // Declare a group of options that will be
        // allowed both on command line and in
        // config file
        po::options_description config("Configuration");
        config.add_options()
            ( "input_directory", po::value< string >(&input_directory),
              "directory where the .wiki files reside" )
            ( "staging_directory", po::value< string >(&staging_directory),
              "directory where we stage the HTML fiels" )
            ( "html_directory", po::value< string >(&output_directory),
              "final output directory, where the web server serves from" )
            ( "google_maps_api_key", po::value< string >(&google_maps_api_key),
              "Google maps API key" )
            ;

        // Hidden options, will be allowed both on command line and
        // in config file, but will not be shown to the user.
        po::options_description hidden("Hidden options");
        hidden.add_options()
            ("input-file", po::value< vector<string> >(), "input file")
            ;

        po::options_description cmdline_options;
        cmdline_options.add(generic).add(config).add(hidden);

        po::options_description config_file_options;
        config_file_options.add(config).add(hidden);

        po::options_description visible("Allowed options");
        visible.add(generic).add(config);

        po::positional_options_description p;
        po::variables_map vm;
        store(po::command_line_parser(ac, av).
              options(cmdline_options).positional(p).run(), vm);
        notify(vm);

        ifstream ifs(config_file.c_str());
        if (!ifs)
        {
            cout << "can not open config file: " << config_file << "\n";
            return 0;
        }
        else
        {
            store(parse_config_file(ifs, config_file_options), vm);
            notify(vm);
        }

        if (vm.count("help")) {
            cout << visible << "\n";
            return 0;
        }

        if (vm.count("version")) {
            cout << "Multiple sources example, version 1.0\n";
            return 0;
        }

//        cout << "target_file : " << target_file << endl;
//        cout << "input_directory : " << input_directory << endl;
//        cout << "staging_directory : " << staging_directory << endl;
//        cout << "output_directory : " << output_directory << endl;
//        cout << "google_maps_api_key : " << google_maps_api_key << endl;

        WikiPtr wiki(new Wiki(new FbySQLiteDB("../var/fby.sqlite3")));
        wiki->SetInputDirectory(input_directory);
        wiki->SetStagingDirectory(staging_directory);
        wiki->SetOutputDirectory(output_directory);
        wiki->SetGoogleMapsAPIKey(google_maps_api_key);

        if (vm.count("scanwikifiles")) {
            wiki->ScanWikiFiles_NOCHANGES();
        }
        if (vm.count("scanimages")) {
            wiki->ScanImages();
        }
        if (vm.count("scandplfiles")) {
            wiki->ScanDPLFiles_NOCHANGES();
        }
        if (vm.count("rebuilddirtyfiles")) {
            wiki->RebuildDirtyFiles();
        }
        if (vm.count("getwikifiles")) {
            wiki->GetWikiFiles();
        }
        if (vm.count("getcontentdirty")) {
            wiki->GetContentDirty();
        }
        if (vm.count("getreferenceddirty")) {
            wiki->GetReferencedDirty();
        }
        if (vm.count("rebuildoutputfiles")) {
            wiki->RebuildOutputFiles();
        }
        if (vm.count("writewikifile")) {
            wiki->WriteWikiFile(target_file);
        }
        if (vm.count("writeimagefile")) {
            wiki->WriteImageFile(target_file);
        }
        if (vm.count("readwikifile")) {
            wiki->ReadWikiFile(target_file);
        }
        if (vm.count("loadexifdata")) {
            wiki->LoadEXIFData(target_file);
        }
        if (vm.count("scanwikifile")) {
            wiki->ScanWikiFileForLinks(target_file.c_str());
        }
        if (vm.count("markcontentdirty")) {
            wiki->MarkContentDirty(target_file.c_str());
        }
        if (vm.count("markreferencesdirty")) {
            wiki->MarkReferencesDirty(target_file.c_str());
        }

        if (vm.count("dowikifile")) {
            wiki->DoWikiFile(target_file.c_str());
        }
    }
    catch(std::exception& e)
    {
        cout << e.what() << "\n";
        return 1;
    }
    catch(  FbyBaseExceptionPtr e)
    {
        cout << e->file << ":" << e->line << " " << e->Message << endl;
        return 1;
    }

    return  0;
}


text:
package com.deleidos.rtws.master.core.util;

import java.io.InputStream;
import java.io.InputStreamReader;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.exolab.castor.xml.Unmarshaller;

import com.deleidos.rtws.commons.config.RtwsConfig;
import com.deleidos.rtws.commons.config.UserDataProperties;
import com.deleidos.rtws.commons.jersey.config.JerseyClientConfig;
import com.deleidos.rtws.commons.nat.NatIPRuleConfig;
import com.deleidos.rtws.commons.net.listener.client.target.UpdateNatIPTableRulesClient;
import com.deleidos.rtws.master.core.net.dns.query.dao.DNSAnchorThreadListener;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

public class NatUtil {

	private static final Logger logger = Logger.getLogger(NatUtil.class);

	private static NatIPRuleConfig ipConfig =null;

	private static String natIP = null;

	private static String publicNatIP = null;

	private static String subnetCIDR = null;

	private static void initialize(){
		try{
			InputStream is = null;
			is = NatUtil.class.getResourceAsStream("/nat/nat-ip-rule-config.xml");

			ipConfig = (NatIPRuleConfig) Unmarshaller.unmarshal(NatIPRuleConfig.class, new InputStreamReader(is));

			//get nat ip for system
			Client client = Client.create(JerseyClientConfig.getInstance().getInternalConfig(60000, 120000));

			WebResource resource = client.resource(String.format("%s/json/system/nat/%s",
												RtwsConfig.getInstance().getString("webapp.gatewayapi.url.path"),
												UserDataProperties.getInstance().getString(UserDataProperties.RTWS_DOMAIN)));

			String jsonString = resource.get(String.class);

			natIP = JSONObject.fromObject(jsonString).getString("privateIpAddress");
			publicNatIP = JSONObject.fromObject(jsonString).getString("publicIpAddress");

			resource = client.resource(String.format("%s/json/system/subnet_mapping/%s",
					RtwsConfig.getInstance().getString("webapp.gatewayapi.url.path"),
					UserDataProperties.getInstance().getString(UserDataProperties.RTWS_DOMAIN)));

			jsonString = resource.get(String.class);

			subnetCIDR = JSONObject.fromObject(jsonString).getString("cidrBlock");
		}catch(Exception e){
			logger.error(e.toString(), e);
		}
	}

	public static DNSAnchorThreadListener performProcessGroupOperations(String groupName, String ip, boolean allocateInternetAddress,
														String fqdn){
		NatUtil.sendCommand(groupName, ip);

		DNSAnchorThreadListener dnsListener = null;

		// Assign the Internet address to the public DNS, if user did not request one,
		// for systems configured to use NAT, any instance that modifies IP tables needs a DNS entry
		if(allocateInternetAddress == false){
			dnsListener = new DNSAnchorThreadListener(publicNatIP, fqdn, true);
		}

		return dnsListener;
	}

	public static void sendCommand(String groupName, String ip){
		try{
			if(ipConfig == null){
				initialize();
			}

			//if process group needs to modify ip table
			if(ipConfig.findRule(groupName) != null){
				for(String port : ipConfig.findRule(groupName).getPorts()){
					String [] args = {ip, port, subnetCIDR};
					logger.info("Sending to IP:  " + natIP + "\targs:" + args[0] +", " + args[1]);
					UpdateNatIPTableRulesClient client = UpdateNatIPTableRulesClient.newInstance(natIP, args);
					client.sendCommand();
				}
			}
		}catch(Exception e){
			logger.error(e.toString(), e);
		}
	}

	public static String getNatIp(){
		return publicNatIP;
	}

}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System;
using System.Threading.Tasks;
using FakeItEasy;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.EventSourcing;
using Squidex.Infrastructure.Log;
using Squidex.Infrastructure.States;

namespace Squidex.Infrastructure.TestHelpers
{
    public sealed class MyDomainObject : DomainObjectGrain<MyDomainState>
    {
        public sealed class ValueChanged : IEvent
        {
            public int Value { get; set; }
        }

        public sealed class CreateAuto : MyCommand
        {
            public int Value { get; set; }
        }

        public sealed class CreateCustom : MyCommand
        {
            public int Value { get; set; }
        }

        public sealed class UpdateAuto : MyCommand
        {
            public int Value { get; set; }
        }

        public sealed class UpdateCustom : MyCommand
        {
            public int Value { get; set; }
        }

        public MyDomainObject(IStore<Guid> store)
           : base(store, A.Dummy<ISemanticLog>())
        {
        }

        protected override Task<object> ExecuteAsync(IAggregateCommand command)
        {
            switch (command)
            {
                case CreateAuto createAuto:
                    return CreateAsync(createAuto, c =>
                    {
                        RaiseEvent(new ValueChanged { Value = c.Value });
                    });

                case CreateCustom createCustom:
                    return CreateReturnAsync(createCustom, c =>
                    {
                        RaiseEvent(new ValueChanged { Value = c.Value });

                        return "CREATED";
                    });

                case UpdateAuto updateAuto:
                    return UpdateAsync(updateAuto, c =>
                    {
                        RaiseEvent(new ValueChanged { Value = c.Value });
                    });

                case UpdateCustom updateCustom:
                    return UpdateAsync(updateCustom, c =>
                    {
                        RaiseEvent(new ValueChanged { Value = c.Value });

                        return "UPDATED";
                    });
            }

            return Task.FromResult<object>(null);
        }

        protected override MyDomainState OnEvent(Envelope<IEvent> @event)
        {
            return new MyDomainState { Value = ((ValueChanged)@event.Payload).Value };
        }
    }
}


text:
'use strict';
angular.module('eehNavigation').directive('eehNavigationActiveMenuItem', ActiveMenuItemDirective);

function isMenuItemActive(menuItem, $state) {
    if (!menuItem.hasChildren()) {
        // Return whether or not the leaf is active.
        return angular.isDefined(menuItem.state) && $state.includes(menuItem.state);
    }
    var children = menuItem.children();
    for (var i = 0; i < children.length; i++) {
        if (angular.isDefined(children[i].state) && $state.includes(children[i].state)) {
            // Return true if the child menu item is active.
            return true;
        }
        if (isMenuItemActive(children[i], $state)) {
            // Return true if the child has at least one active child of its own.
            return true;
        }
    }
    // Return false if the menu item has no active children.
    return false;
}

/** @ngInject */
function ActiveMenuItemDirective($state) {
    return {
        restrict: 'A',
        scope: {
            menuItem: '=eehNavigationActiveMenuItem'
        },
        link: function (scope, element) {
            var checkIsActive = function () {
                var isActive = isMenuItemActive(scope.menuItem, $state);
                element.toggleClass('active', isActive);
            };
            scope.$on('$stateChangeSuccess', checkIsActive);
            checkIsActive();
        }
    };
}


text:
/*
 * 源程序名称: SessionMainCookieStore.java
 * 软件著作权: 恒生电子股份有限公司 版权所有
 * 模块名称:TODO(这里注明模块名称)
 *
 */

package com.hundsun.jresplus.web.nosession.cookie;

import java.util.HashSet;
import java.util.Set;

public class SessionToken implements AttributeCookieStore {

	public static final String CREATION_TIME = "creationTime";
	public static final String LAST_ACCESSED_TIME = "lastAccessedTime";
	public static final String SESSION_ID = "jsessionId";
	public static final String KEYS = "sessionKeys";
	public static Set<String> keyNames = new HashSet<String>();
	static {
		keyNames.add(CREATION_TIME);
		keyNames.add(SESSION_ID);
		keyNames.add(LAST_ACCESSED_TIME);
		keyNames.add(KEYS);
	}

	private String metaDomain;
	private String metaCookieName;
	private int maxInactiveInterval = -1;
	private Encode encode;

	public void setEncode(Encode encode) {
		this.encode = encode;
	}

	public void setMetaDomain(String metaDomain) {
		this.metaDomain = metaDomain;
	}

	public String getMetaDomain() {
		return this.metaDomain;
	}

	public void setMetaCookieName(String metaCookieName) {
		this.metaCookieName = metaCookieName;
	}

	public int getOrder() {
		return 0;
	}

	public boolean isMatch(String key) {
		return keyNames.contains(key);
	}

	public String getCookieName() {
		return metaCookieName;
	}

	public Encode getEncode() {
		return encode;
	}

	public void setMaxInactiveInterval(int maxInactiveInterval) {
		this.maxInactiveInterval = maxInactiveInterval;
	}

	public int getMaxInactiveInterval() {
		return this.maxInactiveInterval;
	}

	public String getPath() {
		return "/";
	}

	public Set<String> getAttributeNames() {
		return keyNames;
	}

	public String getDomain() {
		return metaDomain;
	}

}


text:
{-# htermination intersect :: [Bool] -> [Bool] -> [Bool] #-}
import List


text:
@class CCPBVActionPath;
@class CCPBVContentWriter;
@class CCPBVFHIRFHIRUtils_MedicalCode;
@class CCPBVHttpHeaders;
@class JavaIoWriter;
@class JavaUtilDate;
@class JavaUtilHashMap;
@class RAREUTCharArray;
@class RAREUTJSONArray;
@class RAREUTJSONObject;
@class RAREUTJSONWriter;
@protocol JavaUtilSet;

#import "JreEmulation.h"

@interface CCPBVFHIRFHIRUtils : NSObject {
}

+ (JavaUtilHashMap *)interpretationColors;
- (id)init;
+ (NSString *)cleanAndEncodeStringWithNSString:(NSString *)value;
+ (RAREUTCharArray *)concatBestMedicalTextWithRAREUTJSONArray:(RAREUTJSONArray *)a
                                                 withNSString:(NSString *)key
                                          withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (RAREUTCharArray *)concatStringWithRAREUTJSONArray:(RAREUTJSONArray *)a
                                        withNSString:(NSString *)key
                                 withRAREUTCharArray:(RAREUTCharArray *)sb;
+ (RAREUTCharArray *)concatStringWithRAREUTJSONArray:(RAREUTJSONArray *)a
                                        withNSString:(NSString *)key
                                 withRAREUTCharArray:(RAREUTCharArray *)sb
                                        withNSString:(NSString *)sep;
+ (NSString *)convertIfFractionWithNSString:(NSString *)stringValue
                                  withFloat:(float)value;
+ (id)createWriterWithCCPBVActionPath:(CCPBVActionPath *)path
               withCCPBVContentWriter:(CCPBVContentWriter *)w
                 withCCPBVHttpHeaders:(CCPBVHttpHeaders *)headers
                          withBoolean:(BOOL)row;
+ (void)escapeContolSequencesIfNecessaryWithJavaIoWriter:(JavaIoWriter *)w
                                            withNSString:(NSString *)value;
+ (NSString *)getActorWithRAREUTJSONObject:(RAREUTJSONObject *)o
                       withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (NSString *)getBestMedicalCodeWithRAREUTJSONArray:(RAREUTJSONArray *)a;
+ (NSString *)getBestMedicalCodeWithRAREUTJSONObject:(RAREUTJSONObject *)o;
+ (NSString *)getBestMedicalTextWithRAREUTJSONArray:(RAREUTJSONArray *)a;
+ (NSString *)getBestMedicalTextWithRAREUTJSONObject:(RAREUTJSONObject *)o;
+ (NSString *)getCodableConceptWithRAREUTJSONArray:(RAREUTJSONArray *)a
                                      withNSString:(NSString *)field
                               withJavaUtilHashMap:(JavaUtilHashMap *)map;
+ (NSString *)getCodeableConceptOrReferenceTextWithRAREUTJSONObject:(RAREUTJSONObject *)o
                                                       withNSString:(NSString *)prefix
                                                withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (int)getDaysBetweenInSameYearWithJavaUtilDate:(JavaUtilDate *)date1
                               withJavaUtilDate:(JavaUtilDate *)date2;
+ (NSString *)getHL7FHIRCodeWithRAREUTJSONArray:(RAREUTJSONArray *)a;
+ (NSString *)getInterpretationColorWithNSString:(NSString *)code;
+ (CCPBVFHIRFHIRUtils_MedicalCode *)getMedicalCodeWithRAREUTJSONArray:(RAREUTJSONArray *)a;
+ (CCPBVFHIRFHIRUtils_MedicalCode *)getMedicalCodeWithRAREUTJSONObject:(RAREUTJSONObject *)o;
+ (NSString *)getQuantityWithRAREUTJSONObject:(RAREUTJSONObject *)qty
                          withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (NSString *)getRangeWithRAREUTJSONArray:(RAREUTJSONArray *)ranges
                              withBoolean:(BOOL)includeUnits
                      withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (NSString *)getRangeWithRAREUTJSONObject:(RAREUTJSONObject *)range
                               withBoolean:(BOOL)includeUnits
                       withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (NSString *)getRangeOrRatioWithRAREUTJSONObject:(RAREUTJSONObject *)rate
                                     withNSString:(NSString *)firstKey
                                     withNSString:(NSString *)secondKey
                                     withNSString:(NSString *)sep
                                      withBoolean:(BOOL)includeUnits
                              withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (NSString *)getRatioWithRAREUTJSONObject:(RAREUTJSONObject *)rate
                       withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (NSString *)getPeriodWithRAREUTJSONObject:(RAREUTJSONObject *)period
                        withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (NSString *)getReferenceTextWithRAREUTJSONObject:(RAREUTJSONObject *)o;
+ (NSString *)getTimingWithRAREUTJSONObject:(RAREUTJSONObject *)o
                        withRAREUTCharArray:(RAREUTCharArray *)sb;
+ (NSString *)getTimingWithRAREUTJSONObject:(RAREUTJSONObject *)o
                               withNSString:(NSString *)dose
                               withNSString:(NSString *)route
                                withBoolean:(BOOL)appendBounds
                        withRAREUTCharArray:(RAREUTCharArray *)sb;
+ (NSString *)getDataAsStringWithNSString:(NSString *)url
                             withNSString:(NSString *)type;
+ (NSString *)getDataAsBase64StringWithNSString:(NSString *)url
                                   withNSString:(NSString *)type;
+ (void)writeAttachmentWithRAREUTJSONObject:(RAREUTJSONObject *)attachment
                           withJavaIoWriter:(JavaIoWriter *)w
                                withBoolean:(BOOL)child;
+ (NSString *)getValueWithRAREUTJSONObject:(RAREUTJSONObject *)value
                               withBoolean:(BOOL)includeUnits
                       withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (BOOL)isHTMLFormatRequestedWithCCPBVActionPath:(CCPBVActionPath *)path;
+ (BOOL)isJSONFormatRequestedWithCCPBVActionPath:(CCPBVActionPath *)path;
+ (void)populateAddressWithRAREUTJSONObject:(RAREUTJSONObject *)src
                       withRAREUTJSONObject:(RAREUTJSONObject *)dst;
+ (void)populateTelcomWithRAREUTJSONArray:(RAREUTJSONArray *)src
                     withRAREUTJSONObject:(RAREUTJSONObject *)dst;
+ (void)writeActorListWithJavaIoWriter:(JavaIoWriter *)w
                   withRAREUTJSONArray:(RAREUTJSONArray *)list
                   withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (void)writeCodableConceptWithRAREUTJSONWriter:(RAREUTJSONWriter *)jw
                            withRAREUTJSONArray:(RAREUTJSONArray *)a
                            withJavaUtilHashMap:(JavaUtilHashMap *)map;
+ (void)writeCodeableConceptListWithJavaIoWriter:(JavaIoWriter *)w
                             withRAREUTJSONArray:(RAREUTJSONArray *)list;
+ (void)writeDocumentTitleWithJavaIoWriter:(JavaIoWriter *)w
                              withNSString:(NSString *)title;
+ (void)writeEventWithJavaIoWriter:(JavaIoWriter *)w
              withRAREUTJSONObject:(RAREUTJSONObject *)event;
+ (void)writeEventsWithJavaIoWriter:(JavaIoWriter *)w
                withRAREUTJSONArray:(RAREUTJSONArray *)events;
+ (void)writeHTMLDocumentFinishWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeHTMLDocumentStartWithJavaIoWriter:(JavaIoWriter *)w
                                  withNSString:(NSString *)title;
+ (void)writeMultipartSubDocumentStartWithJavaIoWriter:(JavaIoWriter *)w
                                          withNSString:(NSString *)title;
+ (void)writeMultipartDocumentFinishWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeMultipartSubDocumentFinishWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeMultipartDocumentIndexWithNSString:(NSString *)type
                                   withNSString:(NSString *)date
                                   withNSString:(NSString *)title
                                   withNSString:(NSString *)url
                               withJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeHTMLTagWithJavaIoWriter:(JavaIoWriter *)w
                        withNSString:(NSString *)tag
                        withNSString:(NSString *)text
                         withBoolean:(BOOL)lf;
+ (void)writeListFinishWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeListStartWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeListValueWithJavaIoWriter:(JavaIoWriter *)w
                          withNSString:(NSString *)value;
+ (void)writeNameWithId:(id)writer
    withRAREUTJSONArray:(RAREUTJSONArray *)a;
+ (void)writeNoteWithJavaIoWriter:(JavaIoWriter *)w
             withRAREUTJSONObject:(RAREUTJSONObject *)note;
+ (void)writeNotesWithJavaIoWriter:(JavaIoWriter *)w
               withRAREUTJSONArray:(RAREUTJSONArray *)notes;
+ (BOOL)writeTextWithJavaIoWriter:(JavaIoWriter *)w
             withRAREUTJSONObject:(RAREUTJSONObject *)text
                      withBoolean:(BOOL)writeHeader
                      withBoolean:(BOOL)writeGenerated;
+ (void)writeQuotedStringIfNecessaryWithJavaIoWriter:(JavaIoWriter *)w
                                        withNSString:(NSString *)value
                                 withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (void)writeReferenceListWithJavaIoWriter:(JavaIoWriter *)w
                       withRAREUTJSONArray:(RAREUTJSONArray *)list;
+ (void)writeSectionEndWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeSectionStartWithJavaIoWriter:(JavaIoWriter *)w
                             withNSString:(NSString *)title;
+ (void)writeSubDivEndWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeSubDivStartWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeSubSectionStartWithJavaIoWriter:(JavaIoWriter *)w
                                withNSString:(NSString *)title;
+ (void)writeSubSubSectionStartWithJavaIoWriter:(JavaIoWriter *)w
                                   withNSString:(NSString *)title;
+ (void)writeTableFinishWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeTableSectionFinishWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeTableSectionStartWithJavaIoWriter:(JavaIoWriter *)w
                                  withNSString:(NSString *)title;
+ (void)writeTableStartWithJavaIoWriter:(JavaIoWriter *)w;
+ (void)writeTableValueWithJavaIoWriter:(JavaIoWriter *)w
                           withNSString:(NSString *)name
                           withNSString:(NSString *)value;
+ (void)writeTableValueStartWithJavaIoWriter:(JavaIoWriter *)w
                                withNSString:(NSString *)name;
+ (void)writeTableValueActorWithJavaIoWriter:(JavaIoWriter *)w
                                withNSString:(NSString *)name
                         withRAREUTJSONArray:(RAREUTJSONArray *)list
                         withRAREUTCharArray:(RAREUTCharArray *)ca;
+ (NSString *)htmlWithNSString:(NSString *)value;
+ (void)writeTableValueCodeableConceptWithJavaIoWriter:(JavaIoWriter *)w
                                          withNSString:(NSString *)name
                                   withRAREUTJSONArray:(RAREUTJSONArray *)list;
+ (void)writeTableValueReferenceWithJavaIoWriter:(JavaIoWriter *)w
                                    withNSString:(NSString *)name
                             withRAREUTJSONArray:(RAREUTJSONArray *)list;
+ (NSString *)getResourceAsStringWithNSString:(NSString *)name;
@end

typedef CCPBVFHIRFHIRUtils ComSparsewareBellavistaExternalFhirFHIRUtils;

@interface CCPBVFHIRFHIRUtils_MedicalCode : NSObject {
 @public
  NSString *hl7Code_;
  NSString *snomedCode_;
  NSString *loincCode_;
  NSString *hl7Display_;
  NSString *loincDisplay_;
  NSString *snomedDisplay_;
  NSString *text_;
}

- (id)initWithNSString:(NSString *)loincCode
          withNSString:(NSString *)snomedCode;
- (id)initWithNSString:(NSString *)loincCode
          withNSString:(NSString *)snomedCode
          withNSString:(NSString *)loincDisplay
          withNSString:(NSString *)snomedDisplay;
- (id)initWithNSString:(NSString *)hl7Code
          withNSString:(NSString *)snomedCode
          withNSString:(NSString *)loincCode
          withNSString:(NSString *)hl7Display
          withNSString:(NSString *)loincDisplay
          withNSString:(NSString *)snomedDisplay;
- (NSString *)getBestCode;
- (NSString *)getBestText;
- (BOOL)isOneOfWithJavaUtilSet:(id<JavaUtilSet>)codes;
- (BOOL)isSNOMEDOnlyCode;
- (void)resolveHL7DisplayWithJavaUtilHashMap:(JavaUtilHashMap *)codeMap;
- (void)copyAllFieldsTo:(CCPBVFHIRFHIRUtils_MedicalCode *)other;
@end

J2OBJC_FIELD_SETTER(CCPBVFHIRFHIRUtils_MedicalCode, hl7Code_, NSString *)
J2OBJC_FIELD_SETTER(CCPBVFHIRFHIRUtils_MedicalCode, snomedCode_, NSString *)
J2OBJC_FIELD_SETTER(CCPBVFHIRFHIRUtils_MedicalCode, loincCode_, NSString *)
J2OBJC_FIELD_SETTER(CCPBVFHIRFHIRUtils_MedicalCode, hl7Display_, NSString *)
J2OBJC_FIELD_SETTER(CCPBVFHIRFHIRUtils_MedicalCode, loincDisplay_, NSString *)
J2OBJC_FIELD_SETTER(CCPBVFHIRFHIRUtils_MedicalCode, snomedDisplay_, NSString *)
J2OBJC_FIELD_SETTER(CCPBVFHIRFHIRUtils_MedicalCode, text_, NSString *)

#endif // _CCPBVFHIRFHIRUtils_H_


text:
import { HitPayload } from "./models/Analytics";
import { NativeModules, EventSubscriptionVendor } from "react-native";
import DataLayerEvent from "./models/DataLayerEvent";
const {
  GoogleTagManagerBridge,
  GoogleAnalyticsBridge,
  GoogleAnalyticsSettings
} = NativeModules;

if (
  !GoogleTagManagerBridge ||
  !GoogleAnalyticsBridge ||
  !GoogleAnalyticsSettings
) {
  console.error(
    "Something went wrong initializing the native react-native-google-analytics-bridge module.\nPlease check your configuration.\nDid you forget to run 'react-native link' or install your node_modules?"
  );
}

export interface IGoogleAnalyticsBridge {
  trackScreenView(
    trackerId: string,
    screenName: string,
    payload: HitPayload
  ): void;
  trackEvent(
    trackerId: string,
    category: string,
    action: string,
    label: string,
    value: string,
    payload: HitPayload
  ): void;
  trackTiming(
    trackerId: string,
    category: string,
    interval: number,
    name: string,
    label: string,
    payload: HitPayload
  ): void;
  trackException(
    trackerId: string,
    error: string,
    fatal: boolean,
    payload: HitPayload
  ): void;
  trackSocialInteraction(
    trackerId: string,
    network: string,
    action: string,
    targetUrl: string,
    payload: HitPayload
  ): void;
  setUser(trackerId: string, userId: string): void;
  setClient(trackerId: string, clientId: string): void;
  getClientId(trackerId: string): Promise<string>;
  allowIDFA(trackerId: string, enabled: boolean): void;
  setSamplingRate(trackerId: string, sampleRate: number): void;
  setAnonymizeIp(trackerId: string, enabled: boolean): void;
  setAppName(trackerId: string, appName: string): void;
  setAppVersion(trackerId: string, appVersion: string): void;
  setCurrency(trackerId: string, currencyCode: string): void;
  setTrackUncaughtExceptions(trackerId: string, enabled: boolean): void;
  dispatch(): Promise<boolean>;
}

export interface IGoogleTagManagerBridge extends EventSubscriptionVendor {
  openContainerWithId(containerId: string): Promise<boolean>;
  refreshContainer(): Promise<boolean>;
  booleanForKey(key: string): Promise<boolean>;
  stringForKey(key: string): Promise<string>;
  doubleForKey(key: any): Promise<number>;
  pushDataLayerEvent(event: DataLayerEvent): Promise<boolean>;
  registerFunctionCallTagHandler(functionName: string): Promise<boolean>;
  setVerboseLoggingEnabled(enabled: boolean): Promise<boolean>;
}

export interface IGoogleAnalyticsSettings {
  setOptOut(enabled): void;
  setDispatchInterval(intervalInSeconds): void;
  setDryRun(enabled): void;
}

const AnalyticsBridge = GoogleAnalyticsBridge as IGoogleAnalyticsBridge;
const TagManagerBridge = GoogleTagManagerBridge as IGoogleTagManagerBridge;
const AnalyticsSettings = GoogleAnalyticsSettings as IGoogleAnalyticsSettings;

export { TagManagerBridge };
export { AnalyticsBridge };
export { AnalyticsSettings };


text:
require 'stockboy/translator'

module Stockboy::Translations

  # Convert numeric strings to +BigDecimal+
  #
  # == Job template DSL
  #
  # Registered as +:decimal+. Use with:
  #
  #   attributes do
  #     check_in as: :decimal
  #   end
  #
  # @example
  #   dec = Stockboy::Translator::Date.new
  #
  #   record.cost = "256.99"
  #   dec.translate(record, :cost) # => #<BigDecimal 256.99>
  #
  class Decimal < Stockboy::Translator

    # @return [BigDecimal]
    #
    def translate(context)
      value = field_value(context, field_key)
      return nil if value.blank?

      BigDecimal.new(value, 10)
    end

  end
end


text:
<?php

namespace BolPartnerPlugin\Widgets\Renderer;

use BolOpenApi\Model\Product;

class ProductRenderer
{
    /**
     * @var array
     */
    protected $standardOptions = array(
        'show_sub_title' => true,
    );

    /**
     * @var BolOpenApi\Model\Product
     */
    protected $product;
    /**
     * @var array
     */
    protected $options;
    /**
     * @var string
     */
    protected $standardImage;

    /**
     * @var string
     */
    protected $prefix;

    /**
     * @param array $options
     * @return ProductRenderer
     */
    public function setOptions($options)
    {
        $this->options = array_merge($this->standardOptions, $options);
        return $this;
    }

    /**
     * @param \BolOpenApi\Model\Product $product
     * @return ProductRenderer
     */
    public function setProduct(Product $product)
    {
        $this->product = $product;
        return $this;
    }

    /**
     * @param string $standardImage
     * @return ProductRenderer
     */
    public function setStandardImage($standardImage)
    {
        $this->standardImage = $standardImage;
        return $this;
    }

    public function __construct(Product $product = null, array $options = null)
    {
        if ($product) {
            $this->setProduct($product);
        }

        if ($options) {
            $this->setOptions($options);
        }
        $this->prefix = is_ssl() ? 'https' : 'http';
        $this->standardImage = $this->prefix . '://www.bol.com/nl/static/images/main/noimage_48x48default.gif';
    }

    public function render()
    {
        $html = $this->getHtmlBody();

        $link = $this->getLink();
        $target = isset($this->options['link_target']) && $this->options['link_target']
            ? '_blank' : '_self';

        $title = $this->getTitle();

        $factor = 3.6;
        $width  = $this->options['element_width'] - $this->options['image_width'] - 20;
        $chars  = floor($width / $factor);

        $abbrTitle = mb_strlen($title) > $chars ? substr($title, 0, $chars - 3) . '...' : $title;

        return sprintf(
            $html,

            $this->getElementStyle(),
            $this->product->getId(),

            $target, $link, $this->getTitle(),
            $this->getImageHtml(),

            $this->getDetailsStyle(),

            $target, $link, $this->getTitle(), $this->getLinkCss(), $abbrTitle,
            $this->getSubtitle(),
            $this->getPrice(),
            $this->getRatingHtml(),
            $this->getImpressionImage(),
            $this->getAvailabilityDescription()
        );
    }

    public function __toString()
    {
        return $this->render();
    }

    protected function getHtmlBody()
    {
        return '
' .
            '
' .
            '    %s' .
            '
' .
            '
' .
            '       ' .
            '        %s' .
            '        %s' .
            '       ' .
            '        %s' .
            '        %s' .
            '        %s' .
            '        %s' .
            '
' .
            '
';
    }

    protected function getCss($cssOptions)
    {
        $css = '';

        foreach ($cssOptions as $id => $cssElem) {
            if (! isset($this->options[$id])) {
                continue;
            }
            $css .= sprintf($cssElem, $this->options[$id]);
        }
        return $css;

    }

    protected function getElementStyle()
    {
        $cssOptions = array(
            'element_width'             => 'width: %spx;'
        );

        return $this->getCss($cssOptions);
    }

    protected function getDetailsStyle()
    {
        $this->options['details_width'] = $this->options['element_width'] - $this->options['image_width'] - 20;

        $cssOptions = array(
            'details_width' => 'width: %spx',
        );

        return $this->getCss($cssOptions);
    }

    protected function getLinkCss()
    {
        $cssOptions = array(
            'link_color' => 'color: #%s;',
        );

        return $this->getCss($cssOptions);

    }

    protected function getSubTitleCss()
    {
        $cssOptions = array(
            'subtitle_color' => 'color: #%s;',
        );

        return $this->getCss($cssOptions);
    }

    protected function getPriceTypeCss()
    {
        $cssOptions = array(
            'pricetype_color' => 'color: #%s;',
        );

        return $this->getCss($cssOptions);
    }

    protected function getPriceCss()
    {
        $cssOptions = array(
            'price_color' => 'color: #%s;',
        );

        return $this->getCss($cssOptions);
    }

    protected function getDeliveryTimeCss()
    {
        $cssOptions = array(
            'deliverytime_color' => 'color: #%s',
        );

        return $this->getCss($cssOptions);
    }

    protected function getBestPrice()
    {
        if (! isset($this->options['show_price']) || ! $this->options['show_price']) {
            return '';
        }

        $offers = $this->product->getOffers()->getOffers();

        uasort($offers, array($this, 'sortOffers'));

        /* @var $bestOffer \BolOpenApi\Model\Offer */
        $bestOffer  = reset($offers);

        if (! is_object($bestOffer) || ! $bestOffer->getSecondHand()) {
            return '';
        }

        $price = number_format((double) $bestOffer->getPrice(), 2, '.', '');

        $priceText = __('Best price', 'bolcom-partnerprogramma-wordpress-plugin');
        return $price > 0 ? sprintf(' %s: € %s', $priceText, $$price) : '';
    }

    protected function getPrice()
    {
        if (! isset($this->options['show_price']) || ! $this->options['show_price']) {
            return '';
        }

        $offers = $this->product->getOffers();
        $offers = $offers ? $offers->getOffers() : array();

        if (!count($offers)) {
            return '';
        }

        $bolOffers = $this->getBolOffers($offers);
        $resellerOffers = $this->getResellerOffers($offers);
        $secondHand = $this->getSecondHandOffers($offers);

        uasort($offers, array($this, 'sortOffers'));

        $normal = count($bolOffers) ? reset($bolOffers) : null;
        $hasResellerOffers = count($resellerOffers) ? reset($resellerOffers) : false;
        $hasSecondHand = count($secondHand) ? reset($secondHand) : false;

        // Standard show the normal offer
        $offer = $normal;

        // When no normal offers are found then show another offer
        if (is_null($offer) || ($offer->getAvailabilityDescription() == 'Niet leverbaar.')) {
            // When a valid resellerOffer is found show this one
            if ($hasResellerOffers !== false) {

                $offer = $hasResellerOffers;

            } else if ($hasSecondHand !== false) {
                // When no normal offers or resellerOffers are found then show secondHand offer
                $offer = $hasSecondHand;
            }
        }

        if (! is_object($offer) || (! $offer->getPrice() && ! $offer->getListPrice())) {
            return '';
        }

        $price = $offer->getPrice() == '' ? $offer->getListPrice() : $offer->getPrice();

        /* @var $offer \BolOpenApi\Model\Offer */
        $price = number_format((double) $price, 2, '.', '');

        if ($offer == $hasResellerOffers || $offer == $hasSecondHand) {
            $priceTitle = __('From', 'bolcom-partnerprogramma-wordpress-plugin');
        } else {
            $priceTitle = __('Price', 'bolcom-partnerprogramma-wordpress-plugin');
        }

        $priceTitle = sprintf('%s', $this->getPriceTypeCss() , $priceTitle);

        $html = '' . $priceTitle . ' € %s';
        return ($price > 0) ? sprintf($html, $this->getPriceCss(), $price) : '';
    }

    protected function getAvailabilityDescription()
    {
        if (! isset($this->options['show_deliverytime']) || ! $this->options['show_deliverytime']) {
            return '';
        }

        $offers = $this->product->getOffers();
        $offers = $offers ? $offers->getOffers() : array();

        if (!count($offers)) {
            return '';
        }

        // Get the different offers
        $bolOffers = $this->getBolOffers($offers);
        $resellerOffers = $this->getResellerOffers($offers);
        $secondHand = $this->getSecondHandOffers($offers);

        // Sort the offers
        uasort($offers, array($this, 'sortOffers'));

        $normal = count($bolOffers) ? reset($bolOffers) : null;
        $hasResellerOffers = count($resellerOffers) ? reset($resellerOffers) : false;
        $hasSecondHand = count($secondHand) ? reset($secondHand) : false;

        // Standard show the normal offer
        $offer = $normal;

        // When no normal offers are found then show another offer
        if (is_null($offer) || ($offer->getAvailabilityDescription() == 'Niet leverbaar.')) {

            // When a valid resellerOffer is found show this one
            if ($hasResellerOffers !== false) {
                $availability = $hasResellerOffers->getAvailabilityDescription();

            } else if ($hasSecondHand !== false) {
                // When no normal offers or resellerOffers are found then show secondHand offer
                $availability = '2<super>e</super> hands beschikbaar';
            }
        } else {
            // Initialize the availability description
            $availability = $offer->getAvailabilityDescription();
        }

        return sprintf('%s', $this->getDeliveryTimeCss(), $availability);
    }

    protected function getBolOffers(array $offers)
    {
        $bolOffers = array();
        foreach ($offers as $offer) {
            if ($offer->getSeller()->getId() === '0') {
                $bolOffers[] = $offer;
            }
        }

        if (count($bolOffers) > 1) {
            uasort($bolOffers, array($this, 'sortOffers'));
        }

        return $bolOffers;
    }

    protected function getResellerOffers(array $offers)
    {
        $resellerOffers = array();
        foreach ($offers as $offer) {
            if ($offer->getSeller()->getId() !== '0' && ($offer->getSecondHand() === 'false' || $offer->getSecondHand() == '')) {
                $resellerOffers[] = $offer;
            }
        }

        if (count($resellerOffers) > 1) {
            uasort($resellerOffers, array($this, 'sortOffers'));
        }

        return $resellerOffers;
    }

    protected function getSecondHandOffers(array $offers)
    {
        $secondHandOffers = array();
        foreach ($offers as $offer) {
            if ($offer->getSecondHand() === 'true') {
                $secondHandOffers[] = $offer;
            }
        }

        if (count($secondHandOffers) > 1) {
            uasort($secondHandOffers, array($this, 'sortOffers'));
        }

        return $secondHandOffers;
    }

    protected function sortOffers($a, $b)
    {
        $priceA = $a->getPrice();
        $priceB = $b->getPrice();
        if ($priceA == $priceB) {
            return 0;
        }

        return $priceA < $priceB ? -1 : 1;
    }

    protected function getTitle()
    {
        return $this->product->getTitle();
    }

    protected function getSubTitle()
    {
        if (! isset($this->options['show_sub_title']) || ! $this->options['show_sub_title']) {
            return '';
        }

        $typeArray = explode('\\', get_class($this->product));
        $type = end($typeArray);

        $method = 'get' . ucfirst($type) . 'SubTitle';

        $subTitle = method_exists($this, $method) ? $this->$method() : $this->product->getSubtitle();
        return empty($subTitle) ? '' : sprintf('%s', $this->getSubTitleCss(), $subTitle);
    }

    protected function getBookSubTitle()
    {
        $result = $this->product->getAuthors();

        if (empty($result)) {
            return '';
        }

        $authors = array();

        foreach ($result as $author) {
            $authors[] = $author->getName();
        }

        return implode(' / ', $authors);
    }

    protected function getMusicSubTitle()
    {
        $result = $this->product->getArtists();
        if (empty($result)) {
            return '';
        }

        $artists = array();

        foreach ($result as $artist) {
            $artists[] = $artist->getName();
        }

        return implode(' / ', $artists);
    }

    protected function getDvdSubTitle()
    {
        return $this->product->getPublisher();
    }

    protected function getGameSubTitle()
    {
        return $this->product->getPublisher();
    }

    protected function getToySubTitle()
    {
        return $this->product->getPublisher();
    }

    protected function getElectronicDeviceSubTitle()
    {
        return $this->product->getPublisher();
    }

    protected function getComputerSubTitle()
    {
        return $this->product->getPublisher();
    }

    protected function getProductSubTitle()
    {
        return $this->product->getPublisher();
    }

    protected function getLink()
    {
        $link = $this->getUrl();

        return $this->prefix. '://partnerprogramma.bol.com/click/click?' . $link;
    }

    protected function getImageHtml()
    {
        $str = '';

        $images = $this->product->getImages();

        $image = $images ? $images->getMedium() : null;
        $image = $image ? $image : $this->standardImage;

        if (is_ssl() && substr($image, 0, 5) !== 'https' && substr($image, 0, 4) === 'http') {
            $image = preg_replace("/^http:/i", "https:", $image);
        }

        return sprintf($str, $image, $this->product->getTitle(), $this->options['image_width']);
    }

    protected function getRatingHtml()
    {
        if (! isset($this->options['show_rating']) || ! $this->options['show_rating']) {
            return '';
        }

        $html = '';
        if ($this->product->getRating()) {
            $nicerating = substr($this->product->getRating(), 0, 1);
            $nicerating .= '_'.substr($this->product->getRating(), -1);
            $altrating = str_replace("_", ".", $nicerating);

            $str = '' .
                'prefix.'://review.bol.com/7628-nl_nl/%s/5/rating.gif">' .
                '';

            $html = sprintf($str, $nicerating, $altrating);
        }

        return empty($html) ? '' : $html;
    }

    public function getImpressionImage()
    {
        $link = $this->getUrl();

        return 'prefix.'://partnerprogramma.bol.com/click/impression?' . $link . '" alt="">';
    }

    private function getUrl()
    {
        // Determine the type of widget
        switch($this->options['widget_type']) {
            case 'search-form':
                $type = 'WP_SBX';

                break;
            case 'product-link':
                $type = 'WP_PDL';

                break;
            case 'bestellers':
                $type = 'WP_BSL';

                break;
            default:
                $type = 'API';
        }

        $str = 'p=1&t=url&s=%s&url=%s&f=' . $type . '&subid=%s&name=%s';

        $urls = $this->product->getUrls();

        $link = sprintf(
            $str,
            $this->options['partnerId'],
            $urls ? urlencode($this->product->getUrls()->getMain()) : '#',
            $this->options['sub_id'],
            urlencode($this->options['name'])
        );

        return $link;
    }
}


text:
#pragma once
#include <appbase/application.hpp>

namespace eosio {

using namespace appbase;

/**
 *  This is a template plugin, intended to serve as a starting point for making new plugins
 */
class template_plugin : public appbase::plugin<template_plugin> {
public:
   template_plugin();
   virtual ~template_plugin();

   APPBASE_PLUGIN_REQUIRES()
   virtual void set_program_options(options_description&, options_description& cfg) override;

   void plugin_initialize(const variables_map& options);
   void plugin_startup();
   void plugin_shutdown();

private:
   std::unique_ptr<class template_plugin_impl> my;
};

}


text:
package org.locationtech.geogig.plumbing;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.locationtech.geogig.model.Ref;
import org.locationtech.geogig.model.RevCommit;
import org.locationtech.geogig.porcelain.BranchCreateOp;
import org.locationtech.geogig.porcelain.CommitOp;
import org.locationtech.geogig.test.integration.RepositoryTestCase;

import com.google.common.base.Optional;

public class UpdateRefTest extends RepositoryTestCase {
    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Override
    protected void setUpInternal() throws Exception {
        injector.configDatabase().put("user.name", "groldan");
        injector.configDatabase().put("user.email", "groldan@boundlessgeo.com");
    }

    @Test
    public void testConstructorAndMutators() throws Exception {
        insertAndAdd(points1);
        RevCommit commit1 = geogig.command(CommitOp.class).call();
        geogig.command(BranchCreateOp.class).setName("branch1").call();

        insertAndAdd(points2);
        RevCommit commit2 = geogig.command(CommitOp.class).call();
        Optional<Ref> newBranch = geogig.command(UpdateRef.class).setName("refs/heads/branch1")
                .setNewValue(commit2.getId()).setOldValue(commit1.getId()).setReason("Testing")
                .call();

        assertTrue(newBranch.get().getObjectId().equals(commit2.getId()));
        assertFalse(newBranch.get().getObjectId().equals(commit1.getId()));
    }

    @Test
    public void testNoName() {
        exception.expect(IllegalStateException.class);
        geogig.command(UpdateRef.class).call();
    }

    @Test
    public void testNoValue() {
        exception.expect(IllegalStateException.class);
        geogig.command(UpdateRef.class).setName(Ref.MASTER).call();
    }

    @Test
    public void testDeleteRefThatWasASymRef() throws Exception {
        insertAndAdd(points1);
        RevCommit commit1 = geogig.command(CommitOp.class).call();
        geogig.command(BranchCreateOp.class).setName("branch1").call();

        insertAndAdd(points2);
        RevCommit commit2 = geogig.command(CommitOp.class).call();

        geogig.command(UpdateSymRef.class).setName("refs/heads/branch1")
                .setOldValue(commit1.getId().toString()).setNewValue(Ref.MASTER)
                .setReason("this is a test").call();

        geogig.command(UpdateRef.class).setName("refs/heads/branch1").setNewValue(commit2.getId())
                .setOldValue(Ref.MASTER).call();

        Optional<Ref> branchId = geogig.command(RefParse.class).setName("refs/heads/branch1")
                .call();

        assertTrue(branchId.get().getObjectId().equals(commit2.getId()));

        geogig.command(UpdateRef.class).setDelete(true).setName("refs/heads/branch1").call();
    }

    @Test
    public void testDeleteWithNonexistentName() {
        Optional<Ref> ref = geogig.command(UpdateRef.class).setDelete(true).setName("NoRef").call();
        assertFalse(ref.isPresent());
    }
}


text: <!DOCTYPE html>


text:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
        <property name="order" value="2" />
    </bean>

</beans>


text:
<?php declare(strict_types=1);
echo "<?php\n"; ?>

namespace <?php echo $namespace; ?>;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;

class <?php echo $class_name; ?> implements ProviderInterface
{
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
    {
        // Retrieve the state from somewhere
    }
}


text:
<!DOCTYPE html>

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

Static content 2


text:
v2.0.1 2021-03-23
  * Route all URI and file requests through `resync/url_or_file_open.py` so that settings such as authentication headers can be consistently applied
  * Do not exclude any directories from sync by default, specify with --exclude
  * Fix comparison of using possibly multiple checksums
  * Improve test coverage
  * Remove Python 2 cruft

v2.0.0 2020-12-16
  * Supports ResourceSync v1.1 ANSI/NISO Z39.99-2017 <http://www.openarchives.org/rs/1.1/toc> as default
  * Support for the prior v1.0 ANSI/NISO Z39.99-2014 <http://www.openarchives.org/rs/1.0/toc> is retained with `spec-version='1.0'` option in scripts and `spec_version='1.0'` in various classes
  * Split old `resync` script into `resync-sync` and `resync-build`
  * Move scripts from `bin` dir to base dir for easier testing/development (now that there is no conflict with the module name)
  * Switch from optparse to argparse, use exclusive argument group for commands
  * Add --access_token option to pass bearer token with web requests
  * Add --delay option to pause between successive web requests
  * Drop Python 2.7, 3.3 & 3.4 from tests, add 3.7 & 3.8
  * Fix various depracation warnings and errors for 3.7 & 3.8
  * Switch from pep8 to pycodestyle in tests
  * Change README from RDS to github flavored Markdown
  * Move libraries to support tests into test/testlib

v1.0.9 2018-10-23
  * Add -t/--tries and -T/--timeout options (https://github.com/resync/resync/issues/34)
  * Includes partial replacement of urllib.request with requests

v1.0.8 2017-08-30
  * Fix support for explicitly writing ResourceList objects as indexes (https://github.com/resync/resync/issues/31)
  * Change argument names for local modes to have `--write-` prefix, e.g. --write-resourcelist
  * Improve modes to detect capabilities
  * Abandon support for Python 2.6 (https://github.com/resync/resync/issues/23)

v1.0.7 2017-03-27
  * Fixed silly error in `resync-explorer` introduced in 1.0.6

v1.0.6 2017-03-20
  * Fixed md5 hash format (https://github.com/resync/resync/issues/25)
  * Added support for sha-1 and sha-256 hashes

v1.0.5 2017-01-30
  * Fixed to support non-ASCII URIs/filenames (https://github.com/resync/resync/issues/22)
  * Added tests for Python 3.6
  * Temporarily disabled tests for Python 2.6 due to problems with coverage (https://github.com/resync/resync/issues/23)

v1.0.4 2017-01-27
  * pep8 formatting
  * Added contributing note

v1.0.2 2016-05-06
  * Python 3 fixes in resync-explorer
  * Improved test coverage
  * pep257 formatting

v1.0.1 2016-03-22
  * Work with Python 2 (2.6/2.7) and Python 3 (3.3/3.4/3.5)
  * Improved test coverage
  * Use defusedxml for safer XML parsing
  * Changed parameter str to str_data in ListBase.parse(), str still supported
    but deprecated. Issue pointed out by @uweschmitt

v1.0.0 2014-06-18
  * Update for v1.0, Z39.99-2014 specification (http://www.openarchives.org/rs/1.0/)
  * Partial implementation of dump output (no read yet)

v0.9.5 2013-11-06
  * Still working toward v0.9.1 specification (http://www.openarchives.org/rs/0.9.1/)
  * Set up for Travis-CI working from github
  * Use /usr/bin/env to find python in executables
  * Fix timezone handling in w3c_datetime.py
  * Fix a number of documentation inconsistencies

v0.9.4 2013-09-06
  * Work toward v0.9.1 specification (http://www.openarchives.org/rs/0.9.1/)
  * ResourceSync Description becomes Source Description

v0.9.3 2013-07-31
  * Add dependencies and tests to setup, no code changes

v0.9.2 2013-07-04
  * Cosmetic only

v0.9.1 2013-07-04
  * First release working toward v0.9 specification
  * Use test examples from v0.9 specification, add code to build them too
  * Added ResourceSync Description document
  * Improved resync-explore binary replaces --explore mode
  * Relax default notion of URL authority, add --strictauth

v0.6.3 2013-05...
  * Improved --explore mode

v0.6.2 2013-05-14
  * Fixed example code in README!
  * Added --version flag
  * Added --paths option to specify local paths to search rather than mappings

v0.6.1 2013-05-09
  * First release working toward v0.6 specification
  * Changed test examples to be those from v0.6 specification
  * Added first stab at ResourceDump and ResourceDumpManifest objects

v0.5.3 2013-05-08
  * Final release working with v0.5 specification
  * Improved handling of assumed mappings for testing client on a local filesystem
  * Fixed sitemapindex support for large resource lists, add rel="up" for component sitemaps

v0.5.2 2013-03-26
  * Fixed setup.py

v0.5.1 2013-03-22
  * Code reworked for 0.5 specification (http://www.openarchives.org/rs/0.5/)
  * Client code handles --baseline, --audit and --incremental sync against the simulator


text: Contains the code shared between babel and typescript transforms.


text:
package io.github.benas.randombeans.validation;

import io.github.benas.randombeans.api.Randomizer;
import io.github.benas.randombeans.randomizers.text.CharacterRandomizer;

import javax.validation.constraints.Size;
import java.lang.reflect.Field;
import java.nio.charset.Charset;

import static io.github.benas.randombeans.randomizers.range.IntegerRangeRandomizer.aNewIntegerRangeRandomizer;
import static io.github.benas.randombeans.randomizers.text.CharacterRandomizer.aNewCharacterRandomizer;

class SizeAnnotationHandler implements BeanValidationAnnotationHandler {

    private long seed;

    private Charset charset;

    public SizeAnnotationHandler(long seed, Charset charset) {
        this.seed = seed;
        this.charset = charset;
    }

    public Randomizer<?> getRandomizer(Field field) {
        Class<?> fieldType = field.getType();
        Size sizeAnnotation = field.getAnnotation(Size.class);

        final int min = sizeAnnotation.min();
        final int max = sizeAnnotation.max();
        if (fieldType.equals(String.class)) {
            final int randomLength = aNewIntegerRangeRandomizer(min, max).getRandomValue();
            return new Randomizer<String>() {
                private final CharacterRandomizer characterRandomizer = aNewCharacterRandomizer(charset, seed);

                @Override
                public String getRandomValue() {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < randomLength; i++) {
                        stringBuilder.append(characterRandomizer.getRandomValue());
                    }
                    return stringBuilder.toString();
                }
            };
        }
        return null;
    }
}


text:
using System.Threading;
using System.Threading.Tasks;

namespace DvachBrowser4.Core.Lifetime
{
    /// <summary>
    /// Прокси-объект для отслеживания времени жизни объекта.
    /// </summary>
    public sealed class LifetimeProxy : LifetimeStateBase, ILifetimeBound
    {
        /// <summary>
        /// Установить состояние.
        /// </summary>
        /// <param name="newState">Новое состояние.</param>
        /// <returns>Таск.</returns>
        public ValueTask<Nothing> SetLifetimeState(LifetimeState newState)
        {
            return UpdateLifetimeState(newState);
        }

        private ILifetimeBinding _binding;

        /// <summary>
        /// Текущая привязка.
        /// </summary>
        public ILifetimeBinding Binding
        {
            get { return Interlocked.CompareExchange(ref _binding, null, null); }
            set { Interlocked.Exchange(ref _binding, value); }
        }
    }
}


text:
Modulo by 1 always returns 0. This may be a typo or a logic issue.

## Rule Details

Examples of **incorrect** code for this rule:

```js
x % 1
```

Examples of **correct** code for this rule:

```js
x % 2
```