text:
define('employee-forms-auth/components/my-application', ['exports', 'ember'], function (exports, _ember) {
  'use strict';
  exports['default'] = _ember['default'].Component.extend({
    auth: _ember['default'].inject.service(),

    user: _ember['default'].computed.alias('auth.credentials.email'),
    isAuthenticated: _ember['default'].computed.alias('auth.isAuthenticated'),

    actions: {
      signOut: function signOut() {
        this.sendAction('signOut');
      }
    }
  });
});


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150715_112525_raiting_tables extends Migration {

    public function up() {
        $this->createTable('{{%raiting}}', [
            'id' => Schema::TYPE_PK,
            'nid' => Schema::TYPE_INTEGER . ' NOT NULL',
            'model' => Schema::TYPE_STRING . '(50) NOT NULL',
                ], 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=MyISAM');
        $this->createIndex('nid', '{{%raiting}}', 'nid', false);

        $this->createTable('{{%rating_votes}}', [
            'id' => Schema::TYPE_PK,
            'rid' => Schema::TYPE_INTEGER . ' NOT NULL',
            'uid' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
            'vote' => Schema::TYPE_FLOAT . ' NOT NULL',
            'name' => Schema::TYPE_STRING . '(50) NOT NULL',
            'ip' => Schema::TYPE_STRING . '(20) NOT NULL',
                ], 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=MyISAM');

        $this->createIndex('uid', '{{%rating_votes}}', 'uid', false);
        $this->createIndex('rid', '{{%rating_votes}}', 'rid', false);

        $this->createTable('{{%rating_total}}', [
            'id' => Schema::TYPE_PK,
            'rid' => Schema::TYPE_INTEGER . ' NOT NULL',
            'nid' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
            'name' => Schema::TYPE_STRING . '(50) NOT NULL',
            'votes' => Schema::TYPE_INTEGER . ' NOT NULL DEFAULT "0"',
            'rating' => Schema::TYPE_FLOAT . ' NOT NULL',
                ], 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=MyISAM');

        $this->createIndex('nid', '{{%rating_total}}', 'nid', false);
        $this->createIndex('rid', '{{%rating_total}}', 'rid', false);
    }

    public function down() {
        $this->dropTable('{{%raiting}}');
        $this->dropTable('{{%rating_votes}}');
        $this->dropTable('{{%rating_total}}');
        return false;
    }

    /*
      // Use safeUp/safeDown to run migration code within a transaction
      public function safeUp()
      {
      }

      public function safeDown()
      {
      }
     */
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace app\components\widgets\v3;

use Yii;
use app\components\widgets\Label;
use app\models\Result3;
use app\models\Rule3;
use yii\base\Widget;

final class Result extends Widget
{
    public ?Result3 $result = null;
    public ?Rule3 $rule = null;
    public ?bool $isKnockout = null;
    public string $separator = ' ';

    public function run(): ?string
    {
        $result = $this->result;
        if ($result === null) {
            return null;
        }

        if ($result->key === 'draw') {
            return $this->renderResult($result);
        }

        return \implode($this->separator, array_filter([
            $this->renderResult($result),
            $this->renderTimeKO($result, $this->isKnockout, $this->rule),
        ]));
    }

    private function renderResult(Result3 $result): string
    {
        return Label::widget([
            'content' => Yii::t('app', $result->name),
            'color' => $result->label_color,
        ]);
    }

    private function renderTimeKO(Result3 $result, ?bool $isKnockout, ?Rule3 $rule): ?string
    {
        if (
            $isKnockout === null ||
            ($rule && $rule->key === 'nawabari')
        ) {
            return null;
        }

        if ($isKnockout) {
            return Label::widget([
                'content' => Yii::t('app', 'Knockout'),
                'color' => 'info',
            ]);
        }

        return Label::widget([
            'content' => Yii::t('app', 'Time is up'),
            'color' => 'warning',
        ]);
    }
}


text:
using System;
using System.IO;
using Newtonsoft.Json.Linq;
using Skybrud.Umbraco.GridData.Models;
using Skybrud.Umbraco.GridData.Models.Config;
using Skybrud.Umbraco.GridData.Models.Values;
using Umbraco.Cms.Core.Models.PublishedContent;

namespace Skybrud.Umbraco.GridData.Converters {

    /// <summary>
    /// Interface describing a Grid converter.
    /// </summary>
    public interface IGridConverter {

        bool GetConfigType(GridEditor editor, out Type type);

        bool GetValueType(GridControl control, out Type type);

        /// <summary>
        /// Converts the specified <paramref name="token"/> into an instance of <see cref="IGridControlValue"/>.
        /// </summary>
        /// <param name="control">The parent control.</param>
        /// <param name="token">The instance of <see cref="JToken"/> representing the control value.</param>
        /// <param name="value">The converted value.</param>
        bool ConvertControlValue(GridControl control, JToken token, out IGridControlValue value);

        /// <summary>
        /// Converts the specified <paramref name="token"/> into an instance of <see cref="IGridEditorConfig"/>.
        /// </summary>
        /// <param name="editor"></param>
        /// <param name="token">The instance of <see cref="JToken"/> representing the editor config.</param>
        /// <param name="config">The converted config.</param>
        bool ConvertEditorConfig(GridEditor editor, JToken token, out IGridEditorConfig config);

        bool WriteSearchableText(GridContext context, IPublishedElement element, TextWriter writer);

        bool IsValid(IGridControlValue value, out bool result);

        bool IsValid(IPublishedElement element, out bool result);

    }

}


text:
static constexpr uint16_t ZCL_DESCRIPTOR_CLUSTER_REVISION              = 1;
static constexpr uint16_t ZCL_BRIDGED_DEVICE_BASIC_CLUSTER_REVISION    = 1;
static constexpr uint16_t ZCL_FIXED_LABEL_CLUSTER_REVISION             = 1;
static constexpr uint16_t ZCL_ON_OFF_CLUSTER_REVISION                  = 4;
static constexpr uint16_t ZCL_SWITCH_CLUSTER_REVISION                  = 1;
static constexpr uint16_t ZCL_LEVEL_CONTROL_CLUSTER_REVISION           = 1;
static constexpr uint16_t ZCL_TEMPERATURE_MEASUREMENT_CLUSTER_REVISION = 1;

class GeneratedCluster
{
public:
    virtual ~GeneratedCluster() = default;
    // Get the ID for this cluster.
    virtual chip::ClusterId GetClusterId() = 0;
    // Gets the list of available attributes for this cluster.
    virtual std::vector<AttributeInterface *> GetAttributes() = 0;
};


text:
(function () {
    'use strict';

    AudioNetwork.Injector
        .registerService('Common.AverageValueCollectorBuilder', _AverageValueCollectorBuilder);

    _AverageValueCollectorBuilder.$inject = [
        'Common.AverageValueCollector'
    ];

    function _AverageValueCollectorBuilder(
        AverageValueCollector
    ) {

        function build() {
            return new AverageValueCollector();
        }

        return {
            build: build
        };
    }

})();


text:
class RnaseqStats < ActiveRecord::Base
  belongs_to :rnaseq_pipeline
end


text:
package com.amazonaws.services.appflow.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeConnectorsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     */
    private java.util.List<String> connectorTypes;
    /**
     *

     * The maximum number of items that should be returned in the result set. The default is 20.
     *

     */
    private Integer maxResults;
    /**
     *

     * The pagination token for the next page of data.
     *

     */
    private String nextToken;

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     *
     * @return The type of connector, such as Salesforce, Amplitude, and so on.
     * @see ConnectorType
     */

    public java.util.List<String> getConnectorTypes() {
        return connectorTypes;
    }

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     *
     * @param connectorTypes
     *        The type of connector, such as Salesforce, Amplitude, and so on.
     * @see ConnectorType
     */

    public void setConnectorTypes(java.util.Collection<String> connectorTypes) {
        if (connectorTypes == null) {
            this.connectorTypes = null;
            return;
        }

        this.connectorTypes = new java.util.ArrayList<String>(connectorTypes);
    }

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setConnectorTypes(java.util.Collection)} or {@link #withConnectorTypes(java.util.Collection)} if you want
     * to override the existing values.
     *

     *
     * @param connectorTypes
     *        The type of connector, such as Salesforce, Amplitude, and so on.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ConnectorType
     */

    public DescribeConnectorsRequest withConnectorTypes(String... connectorTypes) {
        if (this.connectorTypes == null) {
            setConnectorTypes(new java.util.ArrayList<String>(connectorTypes.length));
        }
        for (String ele : connectorTypes) {
            this.connectorTypes.add(ele);
        }
        return this;
    }

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     *
     * @param connectorTypes
     *        The type of connector, such as Salesforce, Amplitude, and so on.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ConnectorType
     */

    public DescribeConnectorsRequest withConnectorTypes(java.util.Collection<String> connectorTypes) {
        setConnectorTypes(connectorTypes);
        return this;
    }

    /**
     *

     * The type of connector, such as Salesforce, Amplitude, and so on.
     *

     *
     * @param connectorTypes
     *        The type of connector, such as Salesforce, Amplitude, and so on.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ConnectorType
     */

    public DescribeConnectorsRequest withConnectorTypes(ConnectorType... connectorTypes) {
        java.util.ArrayList<String> connectorTypesCopy = new java.util.ArrayList<String>(connectorTypes.length);
        for (ConnectorType value : connectorTypes) {
            connectorTypesCopy.add(value.toString());
        }
        if (getConnectorTypes() == null) {
            setConnectorTypes(connectorTypesCopy);
        } else {
            getConnectorTypes().addAll(connectorTypesCopy);
        }
        return this;
    }

    /**
     *

     * The maximum number of items that should be returned in the result set. The default is 20.
     *

     *
     * @param maxResults
     *        The maximum number of items that should be returned in the result set. The default is 20.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The maximum number of items that should be returned in the result set. The default is 20.
     *

     *
     * @return The maximum number of items that should be returned in the result set. The default is 20.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The maximum number of items that should be returned in the result set. The default is 20.
     *

     *
     * @param maxResults
     *        The maximum number of items that should be returned in the result set. The default is 20.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeConnectorsRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     *

     * The pagination token for the next page of data.
     *

     *
     * @param nextToken
     *        The pagination token for the next page of data.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The pagination token for the next page of data.
     *

     *
     * @return The pagination token for the next page of data.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The pagination token for the next page of data.
     *

     *
     * @param nextToken
     *        The pagination token for the next page of data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeConnectorsRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getConnectorTypes() != null)
            sb.append("ConnectorTypes: ").append(getConnectorTypes()).append(",");
        if (getMaxResults() != null)
            sb.append("MaxResults: ").append(getMaxResults()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeConnectorsRequest == false)
            return false;
        DescribeConnectorsRequest other = (DescribeConnectorsRequest) obj;
        if (other.getConnectorTypes() == null ^ this.getConnectorTypes() == null)
            return false;
        if (other.getConnectorTypes() != null && other.getConnectorTypes().equals(this.getConnectorTypes()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getConnectorTypes() == null) ? 0 : getConnectorTypes().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public DescribeConnectorsRequest clone() {
        return (DescribeConnectorsRequest) super.clone();
    }

}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2017 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#include <ctype.h>
#include <errno.h>
#include <evutil.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <string>

#include <folly/portability/GTest.h>
#include <platform/dirutils.h>

#include "memcached/openssl.h"
#include "testapp.h"

/**
 * This test suite tests the various settings for authenticating over SSL
 * with client certificates. It does not test all of the various paths one
 * may configure as that is tested in the unit tests for the parsing of the
 * configuration.
 */

class SslCertTest : public TestappTest {
};

/**
 * Setting the control to "disable" simply means that the server don't
 * even ask the client to provide a certificate, and if it end up providing
 * one it'll be ignored.
 *
 * Setting the control to "enable" means that we ask the client to provide
 * a certificate, and if it does it must be:
 *   * valid
 *   * contain a user-mapping which maps to a user defined in the system
 *
 * Setting the control to "mandatory" means that the client _MUST_ provide
 * a valid certificate and it must contain a user mapping which maps to a
 * user defined in the system.
 *
 * Connections which is authenticated via certificate cannot perform SASL
 * to change their identity, and they are not automatically connected to
 * a bucket with the same name as the user.
 */

/**
 * When disabled we don't look at the certificate so it should be possible
 * to connect without one
 */
TEST_F(SslCertTest, LoginWhenDiabledWithoutCert) {
    reconfigure_client_cert_auth("disable", "", "", "");

    MemcachedConnection connection("127.0.0.1", ssl_port, AF_INET, true);
    connection.connect();
    connection.authenticate("@admin", "password", "PLAIN");
}

/**
 * When disabled we don't look at the certificate so it should be possible
 * to connect with one even if it doesn't map to a user (we've not defined
 * a user mapping).
 */
TEST_F(SslCertTest, LoginWhenDiabledWithCert) {
    reconfigure_client_cert_auth("disable", "", "", "");

    MemcachedConnection connection("127.0.0.1", ssl_port, AF_INET, true);
    setClientCertData(connection);
    connection.connect();
    connection.authenticate("@admin", "password", "PLAIN");
}

/**
 * When set to enabled we allow the user to connect even if it no certificate
 * is provided
 */
TEST_F(SslCertTest, LoginEnabledWithoutCert) {
    reconfigure_client_cert_auth("enable", "subject.cn", "", " ");

    MemcachedConnection connection("127.0.0.1", ssl_port, AF_INET, true);
    connection.connect();
    connection.authenticate("@admin", "password", "PLAIN");
}

/**
 * It should be possible to connect with a certificate when there is no
 * mapping defined on the system (only the client certificate is validated)
 */
TEST_F(SslCertTest, LoginEnabledWithCertNoMapping) {
    reconfigure_client_cert_auth("enable", "", "", " ");

    MemcachedConnection connection("127.0.0.1", ssl_port, AF_INET, true);
    setClientCertData(connection);
    connection.connect();
    connection.authenticate("@admin", "password", "PLAIN");
}

/**
 * It should be possible to connect with a certificate which maps to a user.
 * The connection is not bound to a bucket so the client needs to explicitly
 * run select bucket to in order to perform operations.
 */
TEST_F(SslCertTest, LoginEnabledWithCert) {
    reconfigure_client_cert_auth("enable", "subject.cn", "", " ");

    MemcachedConnection connection("127.0.0.1", ssl_port, AF_INET, true);
    setClientCertData(connection);
    connection.connect();
    connection.setXerrorSupport(true);

    try {
        connection.get("foo", Vbid(0));
        FAIL() << "Should not be associated with a bucket";
    } catch (const ConnectionError& error) {
        EXPECT_TRUE(error.isAccessDenied())
                << "Received: " << to_string(error.getReason());
    }

    connection.selectBucket("default");
    try {
        connection.get("foo", Vbid(0));
        FAIL() << "document should not exists";
    } catch (const ConnectionError& error) {
        EXPECT_TRUE(error.isNotFound())
                << "Received: " << to_string(error.getReason());
    }
}

/**
 * When the setting is set to mandatory a client certificate _HAS_ to be
 * provided in order to allow the connection to succeed.
 */
TEST_F(SslCertTest, LoginWhenMandatoryWithoutCert) {
    reconfigure_client_cert_auth("mandatory", "subject.cn", "", " ");

    MemcachedConnection connection("127.0.0.1", ssl_port, AF_INET, true);
    try {
        connection.connect();
        connection.execute(BinprotGenericCommand{cb::mcbp::ClientOpcode::Noop});
        FAIL() << "It should not be possible to connect without certificate";
    } catch (const std::runtime_error&) {
    }
}

/**
 * Verify that we may log into the system when we provide a certificate,
 * and that we're not automatically bound to a bucket (an explicit select
 * bucket is needed).
 */
TEST_F(SslCertTest, LoginWhenMandatoryWithCert) {
    reconfigure_client_cert_auth("mandatory", "subject.cn", "", " ");

    MemcachedConnection connection("127.0.0.1", ssl_port, AF_INET, true);
    setClientCertData(connection);
    connection.connect();
    connection.setXerrorSupport(true);

    try {
        connection.get("foo", Vbid(0));
        FAIL() << "Should not be associated with a bucket";
    } catch (const ConnectionError& error) {
        EXPECT_TRUE(error.isAccessDenied())
                << "Received: " << to_string(error.getReason());
    }

    connection.selectBucket("default");
    try {
        connection.get("foo", Vbid(0));
        FAIL() << "document should not exists";
    } catch (const ConnectionError& error) {
        EXPECT_TRUE(error.isNotFound())
                << "Received: " << to_string(error.getReason());
    }
}

/**
 * The system should _only_ allow users into the system where the information
 * in the certificate map to a user defined in the system.
 */
TEST_F(SslCertTest, LoginWhenMandatoryWithCertIncorrectMapping) {
    reconfigure_client_cert_auth("mandatory", "subject.cn", "Tr", "");

    MemcachedConnection connection("127.0.0.1", ssl_port, AF_INET, true);
    setClientCertData(connection);

    // The certificate will be accepted, so the connection is established
    // but the server will disconnect the client immediately
    connection.connect();

    // Try to run a hello (should NOT work)
    try {
        connection.setXerrorSupport(true);
        FAIL() << "The server should disconnect the client due to missing RBAC lookup";
    } catch (const std::exception&) {

    }
}

/**
 * A client who authenticated itself by using a certificate should not
 * be able to change it's identity by running SASL.
 */
TEST_F(SslCertTest, LoginWhenMandatoryWithCertShouldNotSupportSASL) {
    reconfigure_client_cert_auth("mandatory", "subject.cn", "", " ");

    MemcachedConnection connection("127.0.0.1", ssl_port, AF_INET, true);
    setClientCertData(connection);
    connection.connect();
    connection.setXerrorSupport(true);

    try {
        connection.authenticate("@admin", "password", "PLAIN");
        FAIL() << "SASL Auth should be disabled for cert auth'd connections";
    } catch (const ConnectionError& error) {
        EXPECT_TRUE(error.isNotSupported())
                << "Received: " << to_string(error.getReason());
    }
}


text:
#include <stdlib.h>

#include "telescope/station/private_station.h"
#include "telescope/station/oskar_station.h"

#ifdef __cplusplus
extern "C" {
#endif

void oskar_station_set_element_coords(oskar_Station* station, int feed,
        int index, const double measured_enu[3], const double true_enu[3],
        int* status)
{
    int dim = 0, num_dim = 2;
    if (*status || !station) return;

    /* Check range. */
    if (index >= station->num_elements || feed > 1)
    {
        *status = OSKAR_ERR_OUT_OF_RANGE;
        return;
    }

    /* Check if any z component is nonzero, and set 3D flag if so. */
    if (measured_enu[2] != 0.0 || true_enu[2] != 0.0)
    {
        station->array_is_3d = OSKAR_TRUE;
        num_dim = 3;
    }

    const int type = station->precision;
    const int loc = station->mem_location;
    for (dim = 0; dim < num_dim; dim++)
    {
        oskar_Mem *ptr_meas = 0, *ptr_true = 0;
        ptr_meas = station->element_measured_enu_metres[feed][dim];
        ptr_true = station->element_true_enu_metres[feed][dim];
        if (!ptr_meas)
        {
            station->element_measured_enu_metres[feed][dim] =
                    oskar_mem_create(type, loc, station->num_elements, status);
            ptr_meas = station->element_measured_enu_metres[feed][dim];
        }
        if (!ptr_true)
        {
            station->element_true_enu_metres[feed][dim] =
                    oskar_mem_create(type, loc, station->num_elements, status);
            ptr_true = station->element_true_enu_metres[feed][dim];
        }
        if (loc == OSKAR_CPU)
        {
            if (type == OSKAR_DOUBLE)
            {
                ((double*)oskar_mem_void(ptr_meas))[index] = measured_enu[dim];
                ((double*)oskar_mem_void(ptr_true))[index] = true_enu[dim];
            }
            else if (type == OSKAR_SINGLE)
            {
                const float meas_enu_f = (float)(measured_enu[dim]);
                const float true_enu_f = (float)(true_enu[dim]);
                ((float*)oskar_mem_void(ptr_meas))[index] = meas_enu_f;
                ((float*)oskar_mem_void(ptr_true))[index] = true_enu_f;
            }
            else
            {
                *status = OSKAR_ERR_BAD_DATA_TYPE;
            }
        }
        else
        {
            oskar_mem_set_element_real(ptr_meas,
                    index, measured_enu[dim], status);
            oskar_mem_set_element_real(ptr_true,
                    index, true_enu[dim], status);
        }
    }
}

#ifdef __cplusplus
}
#endif


text:
require 'unlocalize/ruby_ext'
require 'unlocalize/localized_date_time_parser'
require 'unlocalize/unlocalize_params'

if defined?(Rails::Railtie)
  require 'unlocalize/railtie'
elsif defined?(Rails::Initializer)
  raise "This version of unlocalize is only compatible with Rails 3.0 or newer"
end


text:
from swgpy.object import *

def create(kernel):
	result = Creature()

	result.template = "object/mobile/shared_thune_herd_leader.iff"
	result.attribute_template_id = 9
	result.stfName("monster_name","thune")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
<?php

namespace App\Http\Controllers\Admin;

use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    public function index(Request $request){

        // Get Sort, OrderBy, Limit.
        $sort = $request->get('sort') ? $request->get('sort') : 'id';
        $order = $request->get('order') ? $request->get('order') : 'desc';
        $limit = $request->get('limit') ? $request->get('limit') : 10;

        $this->data['breadcrumbs'][] = array(
            'text' => trans('categories.browse'),
            'href' => '#',
        );

        // Get Selected
        $this->data['selected'] = $request->input('selected') ? $request->input('selected') : [];

        $this->data['objects'] = Category::orderBy($sort, $order)
            ->paginate($limit)
            ->appends(\Input::except('page'));

        return view('admin.categories.index', $this->data);
    }

}


text:
L'objectif de ce processus est d'optimiser le traitement des demandes d'habilitation informatique qui concernent plusieurs départements de l'entreprise.

Le superviseur de l'employé pour lequel la demande est soumise sélectionne les applications pour lesquelles il requiert l'habilitation. Le directeur du département valide la demande et une fois approuvée, les divers services en charge des applications demandées peuvent transmettre leurs décisions en parallèle. WorkflowGen synchronise les réponses des services et selon les décisions, la demande est envoyée au département d'informatique qui ensuite créera les comptes nécessaires.

### Participants impliqués

* Demandeur
* Superviseur
* Directeur du département
* Service commercial
* Comptabilité
* Ressources humaines
* Département d'informatique

### Bénéfices

* Suivi du traitement de la demande par le demandeur en temps réel.
* Qualité de service améliorée et réduction des délais.
* Actions des participants parallélisées et synchronisées par WorkflowGen réduisant considérablement les délais de traitement.
* Applications des standards informatiques et meilleurs pratiques (ex. : ITIL).
* Traçabilité des demandes et archivage automatique des demandes clôturées.

### Exemples d'intégrations à valeur ajoutée

* Liaison des données des listes déroulantes avec un référentiel comprenant les modules d'applications, les sous-modules et les profils d'utilisateurs, ou aux listes globales gérées dans WorkflowGen.
* Sélection depuis des listes d'applications générées selon les fonctions des demandeurs.
* Les approbations des participants impliqués lancent une action système qui crée les comptes utilisateurs directement dans les applications et transmet les informations aux demandeur sans nécessiter une intervention humaine du département informatique.
* Les demandes d'habilitation informatique alimentent un référentiel d'applications qui gère les permissions des utilisateurs, et qui peut également gérer les modifications des comptes utilisateurs ou les processus de suppression.
* Les demandes d'habilitation informatique peuvent être intégrées en tant que sous-processus des processus de gestion des nouveaux employés.
* Les dates d'expiration peuvent être associées aux comptes, permettant à WorkflowGen de lancer automatiquement des processus d'extension ou de suppression des comptes utilisateurs.

### Workflow

![Workflow habilitation informatique](assets/habilitation-informatique-workflow.png)

### Formulaire

![Formulaire habilitation informatique 1](assets/habilitation-informatique-form-1.png)

![Formulaire habilitation informatique 2](assets/habilitation-informatique-form-2.png)

![Formulaire habilitation informatique 3](assets/habilitation-informatique-form-3.png)

### Télécharger

[Téléchargez ce processus](dist/habilitation-informatiquev1.xml.zip) et importez-le dans votre environnement WorkflowGen existant. Exécutez le processus tel quel ou personnalisez le formulaire ainsi que la définition du workflow selon vos besoins spécifiques.


text:
using System;

namespace JSONClientSampleCore
{
    public enum Gender
    {
        Male,
        Female,
        None
    }

    public class Patient
    {
        public int PatientId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public Gender Gender { get; set; }
        public string Street { get; set; }
        public string StreetNumber { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string ExternalId { get; set; }
        public DateTime Created { get; set; }
    }
}


text:
package com.facebook.buck.rules.modern.impl;

import com.facebook.buck.core.rulekey.AddsToRuleKey;
import com.facebook.buck.log.Logger;
import com.facebook.buck.rules.modern.ClassInfo;
import com.facebook.buck.rules.modern.ModernBuildRule;
import com.facebook.buck.util.exceptions.BuckUncheckedExecutionException;
import com.google.common.base.Preconditions;
import java.lang.reflect.Modifier;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/** Creates and caches the default ClassInfo implementations. */
public class DefaultClassInfoFactory {
  private static final Logger LOG = Logger.get(DefaultClassInfo.class);

  /** Returns the ClassInfo for the object based on its runtime type. */
  public static <T extends AddsToRuleKey> ClassInfo<T> forInstance(T value) {
    @SuppressWarnings("unchecked")
    ClassInfo<T> classInfo = (ClassInfo<T>) getClassInfo(value.getClass());
    return classInfo;
  }

  private static final ConcurrentHashMap<Class<?>, ClassInfo<? extends AddsToRuleKey>> classesInfo =
      new ConcurrentHashMap<>();

  private static ClassInfo<?> getClassInfo(Class<?> clazz) {
    ClassInfo<?> info = classesInfo.get(clazz);
    if (info != null) {
      return info;
    }
    try {
      Preconditions.checkArgument(
          AddsToRuleKey.class.isAssignableFrom(clazz),
          "%s is not assignable to AddsToRuleKey.",
          clazz.getName());
      Class<?> superClazz = clazz.getSuperclass();
      if (isIgnoredBaseClass(superClazz)) {
        // This ensures that classesInfo holds an entry for the super class and computeClassInfo
        // can get it without having to modify the map.
        LOG.verbose(
            String.format(
                "Getting superclass %s info for %s.", clazz.getName(), superClazz.getName()));
        getClassInfo(superClazz);
      }
      info = classesInfo.computeIfAbsent(clazz, DefaultClassInfoFactory::computeClassInfo);
      return info;
    } catch (Exception e) {
      throw new BuckUncheckedExecutionException(
          e, "When getting class info for %s: %s", clazz.getName(), e.getMessage());
    }
  }

  private static <T extends AddsToRuleKey> ClassInfo<T> computeClassInfo(Class<?> clazz) {
    // Lambdas, anonymous and local classes can easily access variables that we can't find via
    // reflection.
    Preconditions.checkArgument(
        !clazz.isAnonymousClass(), "ModernBuildRules cannot be or reference anonymous classes.");
    Preconditions.checkArgument(
        !clazz.isLocalClass(), "ModernBuildRules cannot be or reference local classes.");
    Preconditions.checkArgument(
        !clazz.isSynthetic(), "ModernBuildRules cannot be or reference synthetic classes.");
    // We don't want to have to deal with inner non-static classes (and verifying usage of state
    // from the outer class).
    Preconditions.checkArgument(
        !clazz.isMemberClass() || Modifier.isStatic(clazz.getModifiers()),
        "ModernBuildRules cannot be or reference inner non-static classes.");

    Optional<ClassInfo<? super T>> superInfo = Optional.empty();
    Class<?> superClazz = clazz.getSuperclass();
    if (isIgnoredBaseClass(superClazz)) {
      // It's guaranteed that the superclass's info is already computed.
      @SuppressWarnings("unchecked")
      ClassInfo<? super T> superClazzInfo = (ClassInfo<? super T>) classesInfo.get(superClazz);
      superInfo = Optional.of(superClazzInfo);
    }
    return new DefaultClassInfo<>(clazz, superInfo);
  }

  private static boolean isIgnoredBaseClass(Class<?> superClazz) {
    return !superClazz.equals(Object.class) && !superClazz.equals(ModernBuildRule.class);
  }
}


text:
package com.oneops.cms.exceptions;

public class ResourceNotFoundException extends CmsBaseException {
  private static final long serialVersionUID = 1L;
}


text:
namespace ArmyOfCreatures.Extended.Specialties
{
    using System;
    using System.Globalization;
    using ArmyOfCreatures.Logic.Battles;
    using ArmyOfCreatures.Logic.Specialties;

    public class AddAttackWhenSkip : Specialty
    {
        private readonly int attackToAdd;

        public AddAttackWhenSkip(int attackToAdd)
        {
            if (attackToAdd <= 0 || attackToAdd > 10)
            {
                throw new ArgumentOutOfRangeException("attackAdding", "The number of attack to add should be between 1 and 10 inclusive");
            }
            this.attackToAdd = attackToAdd;
        }

        public override void ApplyOnSkip(ICreaturesInBattle skipCreature)
        {
            if (skipCreature == null)
            {
                throw new ArgumentNullException("skipCreature cannot be null");
            }

            skipCreature.PermanentAttack += this.attackToAdd;
        }

        public override string ToString()
        {
            return string.Format(CultureInfo.InvariantCulture, "{0}({1})", this.GetType().Name, this.attackToAdd);
        }
    }
}


text:
package org.wso2.carbon.business.rules.core.deployer;

import feign.Response;
import feign.RetryableException;
import org.json.JSONObject;
import org.wso2.carbon.business.rules.core.datasource.configreader.ConfigReader;
import org.wso2.carbon.business.rules.core.deployer.api.SiddhiAppApiHelperService;
import org.wso2.carbon.business.rules.core.deployer.util.HTTPSClientUtil;
import org.wso2.carbon.business.rules.core.exceptions.SiddhiAppDeployerServiceStubException;
import org.wso2.carbon.business.rules.core.exceptions.SiddhiAppsApiHelperException;

/**
 * Consists of methods for additional features for the exposed Siddhi App Api
 */
public class SiddhiAppApiHelper implements SiddhiAppApiHelperService {
    private ConfigReader configReader;
    private String username;
    private String password;

    public SiddhiAppApiHelper() {
        configReader = new ConfigReader();
        username = configReader.getUserName();
        password = configReader.getPassword();
    }

    @Override
    public boolean deploySiddhiApp(String hostAndPort, String siddhiApp) throws SiddhiAppsApiHelperException {
        Response response = null;
        try {
            response = HTTPSClientUtil.doPostRequest(hostAndPort, username, password, siddhiApp);
            int status = response.status();
            switch (status) {
                case 201:
                    return true;
                case 400:
                    throw new SiddhiAppsApiHelperException("A validation error occurred during " +
                            "saving the siddhi app '" + siddhiApp + "' on the node '" + hostAndPort + "'", status);
                case 409:
                    throw new SiddhiAppsApiHelperException("A Siddhi Application with " +
                            "the given name already exists in the node '" + hostAndPort + "'", status);
                case 500:
                    throw new SiddhiAppsApiHelperException("Unexpected error occurred during " +
                            "saving the siddhi app '" + siddhiApp + "' on the node '" + hostAndPort + "'", status);
                default:
                    throw new SiddhiAppsApiHelperException("Unexpected status code '" + status + "' received when " +
                            "trying to deploy the siddhi app '" + siddhiApp + "' on node '" + hostAndPort + "'", status);
            }
        } catch (SiddhiAppDeployerServiceStubException e) {
            throw new SiddhiAppsApiHelperException("Failed to deploy siddhi app '" + siddhiApp + "' on the node '" +
                    hostAndPort + "'. ", e);
        } catch (RetryableException e) {
            throw new SiddhiAppsApiHelperException("Cannot connect to the worker node (" + hostAndPort + ") for " +
                    "retrieving status of the siddhi app " + siddhiApp + ".", e);
        } finally {
            closeResponse(response);
        }
    }

    @Override
    public String getStatus(String hostAndPort, String siddhiAppName) throws SiddhiAppsApiHelperException {
        Response response = null;
        try {
            response = HTTPSClientUtil.doGetRequest(hostAndPort, username, password, siddhiAppName);
            int status = response.status();
            JSONObject statusMessage;
            switch (status) {
                case 200:
                    statusMessage = new JSONObject(response.body().toString());
                    return statusMessage.getString(SiddhiAppApiConstants.STATUS);
                case 404:
                    throw new SiddhiAppsApiHelperException("Specified siddhi app '" + siddhiAppName + "' " +
                            "is not found on the node '" + hostAndPort + "'", status);
                default:
                    throw new SiddhiAppsApiHelperException("Unexpected status code '" + status + "' received when " +
                            "requesting the status of siddhi app '" + siddhiAppName + "' from the node '" +
                            hostAndPort + "'", status);
            }
        } catch (SiddhiAppDeployerServiceStubException e) {
            throw new SiddhiAppsApiHelperException("URI generated for node url '" + hostAndPort + "' is invalid.", e);
        } catch (RetryableException e) {
            throw new SiddhiAppsApiHelperException("Cannot connect to the worker node (" + hostAndPort + ") for " +
                    "retrieving status of the siddhi app " + siddhiAppName + ".", e);
        } finally {
            closeResponse(response);
        }
    }

    @Override
    public boolean delete(String hostAndPort, String siddhiAppName) throws SiddhiAppsApiHelperException {
        Response response = null;
        try {
            response = HTTPSClientUtil.doDeleteRequest(hostAndPort, username, password, siddhiAppName);
            int status = response.status();
            switch (status) {
                case 200:
                    return true;
                case 404:
                    throw new SiddhiAppsApiHelperException("Specified siddhi app '" + siddhiAppName +
                            "' is not found on the node '" + hostAndPort + "'", status);
                default:
                    throw new SiddhiAppsApiHelperException("Unexpected status code '" + status + "' received when " +
                            "trying to delete the siddhi app '" + siddhiAppName + "' from the node '" +
                            hostAndPort + "'", status);
            }
        } catch (SiddhiAppDeployerServiceStubException e) {
            throw new SiddhiAppsApiHelperException("Failed to delete siddhi app '" + siddhiAppName +
                    "' from the node '" + hostAndPort + "'. ", e);
        } catch (RetryableException e) {
            throw new SiddhiAppsApiHelperException("Cannot connect to the worker node (" + hostAndPort + ") for " +
                    "retrieving status of the siddhi app " + siddhiAppName + ".", e);
        } finally {
            closeResponse(response);
        }
    }

    @Override
    public void update(String hostAndPort, String siddhiApp) throws SiddhiAppsApiHelperException {
        Response response = null;
        try {
            response = HTTPSClientUtil.doPutRequest(hostAndPort, username, password, siddhiApp);
            int status = response.status();
            switch (status) {
                case 400:
                    throw new SiddhiAppsApiHelperException("Failed to update the siddhi app '" + siddhiApp +
                            "' on node '" + hostAndPort + "' due to a validation error occurred " +
                            "when updating the siddhi app", status);
                case 500:
                    throw new SiddhiAppsApiHelperException("Failed to update the siddhi app '" + siddhiApp +
                            "' on node '" + hostAndPort + "' due to an unexpected error occurred during updating the " +
                            "siddhi app", status);
            }
        } catch (SiddhiAppDeployerServiceStubException e) {
            throw new SiddhiAppsApiHelperException("Failed to update the siddhi app '" + siddhiApp + "' on node '"
                    + hostAndPort + "'. ", e);
        } catch (RetryableException e) {
            throw new SiddhiAppsApiHelperException("Cannot connect to the worker node (" + hostAndPort + ") for " +
                    "retrieving status of the siddhi app " + siddhiApp + ".", e);
        } finally {
            closeResponse(response);
        }
    }

    private void closeResponse(Response response) {
        if (response != null) {
            response.close();
        }
    }
}


text:
CKEDITOR.editorConfig = function( config ) {
	// Define changes to default configuration here. For example:
	// config.language = 'fr';
	// config.uiColor = '#AADC6E';

	config.language = 'ru';
	config.bodyClass = 'content';
	//        config.skin = 'office2003',
	config.toolbar_Yii =
		[
			['Source', 'Maximize', '-', 'RemoveFormat', '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord',
				'-', 'Find', 'Replace', '-', 'Undo', 'Redo', '-', 'Link', 'Unlink', 'Anchor', '-',
				'Image', 'Table', 'HorizontalRule', 'SpecialChar', '-', 'SpellCheck', 'Abbr'
				/*'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'HiddenField'*/
			],
			['Styles', 'Format'/*,'Font','FontSize'*/],
			['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
			['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript', '-',
				'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote', /*'CreateDiv', '-', 'TextColor', */'ShowBlocks'],

		];

	config.toolbar_Basic =
		[
			['Source', 'RemoveFormat', '-', 'PasteText', 'PasteFromWord',
				'-', 'Undo', 'Redo', '-', 'Link', 'Unlink', '-',
				'SpecialChar'/*, '-',
			 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'HiddenField'*/
			],
			['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
			['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript', '-',
				'ShowBlocks', 'SpellCheck'],
		]

	config.contentsCss =
		[
			//			CKEDITOR.basePath.replace('vendors/ckeditor/', '') + 'themes/myriad/css/style.css',
			//			CKEDITOR.basePath.replace('vendors/ckeditor/', '') + 'themes/myriad/css/content.css',
//			CKEDITOR.basePath + 'content.css'
		];

	config.toolbarCanCollapse = false;
	config.toolbar = 'Yii';
	config.AutoParagraph = false;

	config.resize_minWidth = '100%';
	config.resize_maxWidth = '100%';

//	config.stylesSet =
//		[
//			//{ name : 'Красный заголовок', element : 'h2', styles : { 'color' : 'Red', 'font-size' : '1.3em' } },
//			//{ name : 'Заголовок страницы', element : 'h1', attributes : { 'class' : 'h' } },
//			//{ name : 'Синий текст', element: 'span',  styles : { 'color' : '#000080', 'font-weight' : 'bold'} },
//			//			{ name:'Текст 10px', element:'span', styles:{'font-size':'10px'} },
//			//			{ name:'Текст 12px', element:'span', styles:{'font-size':'12px'} },
//			//			{ name:'Текст 14px', element:'span', styles:{'font-size':'14px'} },
//			//			{ name:'Текст 16px', element:'p', styles:{'font-size':'16px'} },
//			//			{ name:'Текст 18px', element:'span', styles:{'font-size':'18px'} },
////			{ name: 'Изображение слева', element: 'img', attributes: {'class': 'img-left'}},
////			{ name: 'Изображение справа', element: 'img', attributes: {'class': 'img-right'}},
//
//
//			{ name: 'Стандартная таблица', element: 'table', attributes: {'class': 'table-style'} } ,
//			{ name: 'Альтернативный ряд', element: 'tr', attributes: {'class': 'table-style-row'} } ,
//			{ name: 'Заголовочный ряд', element: 'tr', attributes: {'class': 'table-style-header'} } ,
//			{ name: 'Обычный ряд', element: 'tr', attributes: {'class': ''} },
//		];
//
	var _FileBrowserLanguage = 'php';	// asp | aspx | cfm | lasso | perl | php | py
	var _QuickUploadLanguage = 'php';	// asp | aspx | cfm | lasso | php

	var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage;

	config.format_tags = 'p;h2;h3;h4;h5;h6;pre;address;div';
	config.allowedContent = true;
//	config.extraPlugins += (config.extraPlugins ? ',aspell' : 'aspell' );
	//	config.toolbar_Yii[2] = { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellCheck'] };
	config.disableNativeSpellChecker = false;

//	config.extraPlugins += (config.extraPlugins ? ',onchange' : 'onchange');

//	config.extraPlugins += (config.extraPlugins ? ',abbr' : 'abbr');

	//	config.extraPlugins = 'autogrow';
};


text:
import React, { useState } from 'react';
import { registerComponent, Components } from '../../lib/vulcan-lib';
import { useUpdateCurrentUser } from '../hooks/useUpdateCurrentUser';
import { useCurrentUser } from '../common/withUser';
import Geosuggest from 'react-geosuggest';
import DialogContent from '@material-ui/core/DialogContent';
import DialogActions from '@material-ui/core/DialogActions';
import DialogTitle from '@material-ui/core/DialogTitle';
import Slider from '@material-ui/lab/Slider';
import Input from '@material-ui/core/Input';
import InputAdornment from '@material-ui/core/InputAdornment';
import FormLabel from '@material-ui/core/FormLabel';
import Checkbox from '@material-ui/core/Checkbox';
import { geoSuggestStyles, useGoogleMaps } from '../form-components/LocationFormComponent'
import { MAX_NOTIFICATION_RADIUS } from '../../lib/collections/users/custom_fields'
import { forumTypeSetting } from '../../lib/instanceSettings';

const suggestionToGoogleMapsLocation = (suggestion) => {
  return suggestion ? suggestion.gmaps : null
}

export const sharedStyles = (theme: ThemeType): JssStyles => ({
  removeButton: {
    color: theme.palette.error.main,
    marginRight: 'auto',
    marginLeft: -4
  },
  submitButton: {
    color: theme.palette.secondary.main,
    textTransform: 'uppercase'
  },
  actions: {
    marginTop: 24
  },
  geoSuggest: {
    marginTop: 16,
    marginBottom: 16,
    width: 400,
    ...geoSuggestStyles(theme),
    "& .geosuggest__suggests": {
      top: "100%",
      left: 0,
      right: 0,
      maxHeight: "25em",
      padding: 0,
      marginTop: -1,
      background: "#fff",
      borderTopWidth: 0,
      overflowX: "hidden",
      overflowY: "auto",
      listStyle: "none",
      zIndex: 5,
      transition: "max-height 0.2s, border 0.2s",
    },
    "& .geosuggest__input": {
      border: "2px solid transparent",
      borderBottom: "1px solid rgba(0,0,0,.87)",
      padding: ".5em 1em 0.5em 0em !important",
      width: '100%',
      fontSize: 13,
      [theme.breakpoints.down('sm')]: {
        width: "100%"
      },
    },
  },
})

const styles = (theme: ThemeType): JssStyles => ({
  ...sharedStyles(theme),
  distanceSection: {
    marginTop: 30,
    display: 'flex'
  },
  input: {
    width: '15%',
    marginLeft: '5%',
    position: 'relative',
    top: -12
  },
  slider: {
    width: '80%',
  },
  inputAdornment: {
    marginLeft: 0,
  },
  distanceHeader: {
    marginTop: 20
  },
  peopleThreshold: {
    display: 'flex'
  },
  peopleThresholdText: {
    alignSelf: 'center',
    position: 'relative',
    top: 2
  },
  peopleInput: {
    width: 20
  },
  peopleThresholdCheckbox: {
    marginLeft: -12
  }
})

const MAX_NOTIFICATION_RADIUS_STEPSIZE = 5
const EventNotificationsDialog = ({ onClose, classes }: {
  onClose: ()=>void,
  classes: ClassesType,
}) => {
  const currentUser = useCurrentUser();
  const { Loading, Typography, LWDialog } = Components
  const { nearbyEventsNotificationsLocation, mapLocation, googleLocation, nearbyEventsNotificationsRadius, nearbyPeopleNotificationThreshold } = currentUser || {}

  const [ mapsLoaded ] = useGoogleMaps("EventNotificationsDialog")
  const [ location, setLocation ] = useState(nearbyEventsNotificationsLocation || mapLocation || googleLocation)
  const [ label, setLabel ] = useState(nearbyEventsNotificationsLocation?.formatted_address || mapLocation?.formatted_address || googleLocation?.formatted_address)
  const [ distance, setDistance ] = useState(nearbyEventsNotificationsRadius || 50)
  const [ notifyPeopleThreshold, setNotifyPeopleThreshold ] = useState(nearbyPeopleNotificationThreshold || 10)
  const [ notifyPeopleCheckboxState, setNotifyPeopleCheckboxState ] = useState(!!nearbyPeopleNotificationThreshold)

  const updateCurrentUser = useUpdateCurrentUser()

  const peopleThresholdInput = <Input
    className={classes.peopleInput}
    value={notifyPeopleThreshold}
    margin="dense"
    onChange={(e) => setNotifyPeopleThreshold(parseFloat(e.target.value))}
  />

  const isEAForum = forumTypeSetting.get() === 'EAForum';

  return (
    <LWDialog
      open={true}
      onClose={onClose}
    >
      <DialogTitle>
        I wish to be notified of nearby events and new groups
      </DialogTitle>
      <DialogContent>
        <Typography variant="body2">

            Notify me for events and new groups in this location

        </Typography>

          {mapsLoaded ? <Geosuggest
            placeholder="Location"
            onSuggestSelect={(suggestion) => {
              setLocation(suggestionToGoogleMapsLocation(suggestion))
              setLabel(suggestion?.label)
            }}
            initialValue={label}
          /> : <Loading/>}

        <FormLabel className={classes.distanceHeader} component={"legend" as any}>Notification Radius</FormLabel>

          <Slider
            className={classes.slider}
            value={distance}
            step={MAX_NOTIFICATION_RADIUS_STEPSIZE}
            min={0}
            max={MAX_NOTIFICATION_RADIUS}
            onChange={(e, value) => setDistance(value)}
            aria-labelledby="input-slider"
          />
          <Input
            className={classes.input}
            value={distance}
            margin="dense"
            onChange={(e) => setDistance(parseFloat(e.target.value))}
            endAdornment={<InputAdornment disableTypography className={classes.inputAdornment} position="end">km</InputAdornment>}
            onBlur={() => setDistance(distance > MAX_NOTIFICATION_RADIUS ? MAX_NOTIFICATION_RADIUS : (distance < 0 ? 0 : distance))}
            inputProps={{
              step: MAX_NOTIFICATION_RADIUS_STEPSIZE,
              min: 0,
              max: MAX_NOTIFICATION_RADIUS,
              type: 'number',
              'aria-labelledby': 'input-slider',
            }}
          />

        {!isEAForum &&

            <Checkbox
              className={classes.peopleThresholdCheckbox}
              checked={notifyPeopleCheckboxState}
              onChange={(e) => setNotifyPeopleCheckboxState(!!e.target.checked)}
            />

            Notify me when there are {peopleThresholdInput} or more people in my area

}
        <DialogActions className={classes.actions}>
          {currentUser?.nearbyEventsNotifications && {
            void updateCurrentUser({
              nearbyEventsNotifications: false,
              nearbyEventsNotificationsLocation: null,
              nearbyEventsNotificationsRadius: null,
              nearbyPeopleNotificationThreshold: null,
            })
            onClose()
          }}>
            Stop notifying me
          }
          {
            void updateCurrentUser({
              nearbyEventsNotifications: true,
              nearbyEventsNotificationsLocation: location,
              nearbyEventsNotificationsRadius: distance,
              nearbyPeopleNotificationThreshold: notifyPeopleCheckboxState ? notifyPeopleThreshold : null,
            })
            onClose()
          }}>
            Submit

        </DialogActions>
      </DialogContent>
    </LWDialog>
  )
}

const EventNotificationsDialogComponent = registerComponent('EventNotificationsDialog', EventNotificationsDialog, {styles});

declare global {
  interface ComponentTypes {
    EventNotificationsDialog: typeof EventNotificationsDialogComponent
  }
}