text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2014 Thomas Bouron
  ~
  ~ 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.
  -->

<resources>

    <string name="app_name">ShakeDetector</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="sensibility">Sensibility</string>
    <string name="shake_number">Number of shakes to trigger</string>
    <string name="label_sensibility">Sensibility: %sG</string>
    <string name="label_shake_number">Number of shakes: %s</string>
    <string name="shake_detector_created">Shake detector created and started!</string>
    <string name="shake_detector_error">ERROR: Cannot create and start shake detector!</string>
    <string name="shake_detector_restarted">Listener restarted successfully.</string>
    <string name="shake_detector_stopped">Listener stopped.</string>
    <string name="shake_detector_destroyed">Listener Destroyed.</string>
    <string name="shake_detected">Shake detected. Send toast</string>
    <string name="device_shaken">Device shaken!</string>
    <string name="update_sensibility">Update \"sensibility\" to: %.1fG</string>
    <string name="update_shake_number">Update \"number of shakes to trigger\" to: %d</string>

</resources>


text:
from _IECoreUSD import *

__import__( "IECore" ).loadConfig( "CORTEX_STARTUP_PATHS", subdirectory = "IECoreUSD" )

redpajama_set_name: RedPajamaGithub


text:
import { GenericAst } from "./GenericAst";
export class TypeOfExportsKeyword extends GenericAst { }


text:
<?php

namespace SymfonyId\AdminBundle\Configuration;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\Form\FormFactory;
use SymfonyId\AdminBundle\Annotation\Crud;
use SymfonyId\AdminBundle\Exception\RuntimeException;
use SymfonyId\AdminBundle\Model\ModelInterface;
use SymfonyId\AdminBundle\SymfonyIdAdminConstrants as Constants;

/**
 * @author Muhammad Surya Ihsanuddin <surya.kejawen@gmail.com>
 */
class CrudConfigurator implements ContainerAwareInterface, ConfiguratorInterface
{
    use ContainerAwareTrait;

    /**
     * @var FormFactory
     */
    private $formFactory;

    /**
     * @var Crud
     */
    private $crud;

    public function __construct(FormFactory $formFactory)
    {
        $this->formFactory = $formFactory;
    }

    /**
     * @return Crud
     */
    public function getCrud()
    {
        return $this->crud;
    }

    /**
     * @param Crud $crud
     */
    public function setCrud(Crud $crud)
    {
        $this->crud = $crud;
    }

    /**
     * @return \SymfonyId\AdminBundle\Annotation\Template
     */
    public function getTemplate()
    {
        return $this->crud->getTemplate();
    }

    /**
     * @param ModelInterface|null $formData
     * @param string              $method
     *
     * @return \Symfony\Component\Form\FormInterface
     *
     * @throws RuntimeException
     */
    public function getForm(ModelInterface $formData = null, $method = 'POST')
    {
        if (!$this->crud) {
            throw new RuntimeException(sprintf('You must call "setCrud()" before call this method'));
        }

        $formClass = $this->crud->getForm();

        if (class_exists($formClass)) {
            $formObject = new $formClass();
        } else {
            $formObject = $this->container->get($formClass);
        }

        $builder = $this->formFactory->createBuilder(get_class($formObject));
        $builder->setMethod($method);

        $form = $builder->getForm();
        $form->setData($formData);

        return $form;
    }

    /**
     * @return array
     */
    public function getGridAction()
    {
        $action = array();

        if ($this->crud->isAllowEdit()) {
            $action[] = Constants::GRID_ACTION_EDIT;
        }
        if ($this->crud->isAllowShow()) {
            $action[] = Constants::GRID_ACTION_SHOW;
        }
        if ($this->crud->isAllowDelete()) {
            $action[] = Constants::GRID_ACTION_DELETE;
        }

        return $action;
    }
}


text:
import {
  isArray,
  isString,
  isUndefined,
} from './common/utils'

import Helper, { typeTag, prepareAddress } from './common/helpers'

import AtomicBlob from './atomic/blob'
import AtomicFloat32 from './atomic/float32'
import AtomicFloat64 from './atomic/float64'
import AtomicInt32 from './atomic/int32'
import AtomicInt64 from './atomic/int64'
import AtomicUInt64 from './atomic/uint64'
import AtomicString from './atomic/string'
import {
  VALUE_NONE, VALUE_TRUE, VALUE_FALSE, VALUE_INFINITY,
} from './atomic/constant'

/**
 * A TypedMessage consists of an OSC address and an optional array of typed OSC arguments.
 *
 * ## Supported types
 *
 * - `i` - int32
 * - `f` - float32
 * - `s` - string
 * - `b` - blob
 * - `h` - int64
 * - `t` - uint64
 * - `d` - double
 * - `T` - True (no argument data)
 * - `F` - False (no argument data)
 * - `N` - Nil (no argument data)
 * - `I` - Infinitum (no argument data)
 *
 */
export class TypedMessage {
  /**
   * Create a TypedMessage instance
   * @param {array|string} address Address
   * @param {array} args Arguments
   *
   * @example
   * const message = new TypedMessage(['test', 'path'])
   * message.add('d', 123.123456789)
   * message.add('s', 'hello')
   *
   * @example
   * const message = new TypedMessage('/test/path', [
   *   { type: 'i', value: 123 },
   *   { type: 'd', value: 123.123 },
   *   { type: 'h', value: 0xFFFFFFn },
   *   { type: 'T', value: null },
   * ])
   */
  constructor(address, args) {
    /**
     * @type {number} offset
     * @private
     */
    this.offset = 0
    /** @type {string} address */
    this.address = ''
    /** @type {string} types */
    this.types = ''
    /** @type {array} args */
    this.args = []

    if (!isUndefined(address)) {
      if (!(isString(address) || isArray(address))) {
        throw new Error('OSC Message constructor first argument (address) must be a string or array')
      }
      this.address = prepareAddress(address)
    }

    if (!isUndefined(args)) {
      if (!isArray(args)) {
        throw new Error('OSC Message constructor second argument (args) must be an array')
      }
      args.forEach((item) => this.add(item.type, item.value))
    }
  }

  /**
   * Add an OSC Atomic Data Type to the list of elements
   * @param {string} type
   * @param {*} item
   */
  add(type, item) {
    if (isUndefined(type)) {
      throw new Error('OSC Message needs a valid OSC Atomic Data Type')
    }

    if (type === 'N') {
      this.args.push(VALUE_NONE)
    } else if (type === 'T') {
      this.args.push(VALUE_TRUE)
    } else if (type === 'F') {
      this.args.push(VALUE_FALSE)
    } else if (type === 'I') {
      this.args.push(VALUE_INFINITY)
    } else {
      this.args.push(item)
    }

    this.types += type
  }

  /**
   * Interpret the Message as packed binary data
   * @return {Uint8Array} Packed binary data
   */
  pack() {
    if (this.address.length === 0 || this.address[0] !== '/') {
      throw new Error('OSC Message has an invalid address')
    }

    const encoder = new Helper()

    // OSC Address Pattern and Type string
    encoder.add(new AtomicString(this.address))
    encoder.add(new AtomicString(`,${this.types}`))

    // followed by zero or more OSC Arguments
    if (this.args.length > 0) {
      let argument

      if (this.args.length > this.types.length) {
        throw new Error('OSC Message argument and type tag mismatch')
      }

      this.args.forEach((value, index) => {
        const type = this.types[index]
        if (type === 'i') {
          argument = new AtomicInt32(value)
        } else if (type === 'h') {
          argument = new AtomicInt64(value)
        } else if (type === 't') {
          argument = new AtomicUInt64(value)
        } else if (type === 'f') {
          argument = new AtomicFloat32(value)
        } else if (type === 'd') {
          argument = new AtomicFloat64(value)
        } else if (type === 's') {
          argument = new AtomicString(value)
        } else if (type === 'b') {
          argument = new AtomicBlob(value)
        } else if (type === 'T') {
          argument = VALUE_TRUE
        } else if (type === 'F') {
          argument = VALUE_FALSE
        } else if (type === 'N') {
          argument = VALUE_NONE
        } else if (type === 'I') {
          argument = VALUE_INFINITY
        } else {
          throw new Error('OSC Message found unknown argument type')
        }

        encoder.add(argument)
      })
    }

    return encoder.merge()
  }

  /**
   * Unpack binary data to read a Message
   * @param {DataView} dataView The DataView holding the binary representation of a Message
   * @param {number} [initialOffset=0] Offset of DataView before unpacking
   * @return {number} Offset after unpacking
   */
  unpack(dataView, initialOffset = 0) {
    if (!(dataView instanceof DataView)) {
      throw new Error('OSC Message expects an instance of type DataView.')
    }

    // read address pattern
    const address = new AtomicString()
    address.unpack(dataView, initialOffset)

    // read type string
    const types = new AtomicString()
    types.unpack(dataView, address.offset)

    if (address.value.length === 0 || address.value[0] !== '/') {
      throw new Error('OSC Message found malformed or missing address string')
    }

    if (types.value.length === 0 && types.value[0] !== ',') {
      throw new Error('OSC Message found malformed or missing type string')
    }

    let { offset } = types
    let next
    let type

    const args = []

    // read message arguments (OSC Atomic Data Types)
    for (let i = 1; i < types.value.length; i += 1) {
      type = types.value[i]
      next = null

      if (type === 'i') {
        next = new AtomicInt32()
      } else if (type === 'h') {
        next = new AtomicInt64()
      } else if (type === 't') {
        next = new AtomicUInt64()
      } else if (type === 'f') {
        next = new AtomicFloat32()
      } else if (type === 'd') {
        next = new AtomicFloat64()
      } else if (type === 's') {
        next = new AtomicString()
      } else if (type === 'b') {
        next = new AtomicBlob()
      } else if (type === 'T') {
        args.push(VALUE_TRUE)
      } else if (type === 'F') {
        args.push(VALUE_FALSE)
      } else if (type === 'N') {
        args.push(VALUE_NONE)
      } else if (type === 'I') {
        args.push(VALUE_INFINITY)
      } else {
        throw new Error('OSC Message found unsupported argument type')
      }

      if (next) {
        offset = next.unpack(dataView, offset)
        args.push(next.value)
      }
    }

    this.offset = offset
    this.address = address.value
    this.types = types.value
    this.args = args

    return this.offset
  }
}

/**
 * An OSC message consists of an OSC Address Pattern followed
 * by an OSC Type Tag String followed by zero or more OSC Arguments
 */
export default class Message extends TypedMessage {
  /**
   * Create a Message instance
   * @param {array|string} args Address
   * @param {...*} args OSC Atomic Data Types
   *
   * @example
   * const message = new Message(['test', 'path'], 50, 100.52, 'test')
   *
   * @example
   * const message = new Message('/test/path', 51.2)
   */
  constructor(...args) {
    let address
    if (args.length > 0) {
      address = args.shift()
    }

    let oscArgs
    if (args.length > 0) {
      if (args[0] instanceof Array) {
        oscArgs = args.shift()
      }
    }

    super(address, oscArgs)

    if (args.length > 0) {
      this.types = args.map((item) => typeTag(item)).join('')
      this.args = args
    }
  }

  /**
   * Add an OSC Atomic Data Type to the list of elements
   * @param {*} item
   */
  add(item) {
    super.add(typeTag(item), item)
  }
}


text:
/**
 * Lorem Ipsum plug-in for TinyMCE version 3.x
 * -------------------------------------------
 * $Id: editor_plugin_src.js 10 2009-04-30 23:20:50Z scholzj $
 *
 * @author     JAkub Scholz
 * @version    $Rev: 10 $
 * @package    LoremIpsum
 * @link       http://www.assembla.com/spaces/lorem-ipsum
 */

(function() {
	// Load plugin specific language pack
	tinymce.PluginManager.requireLangPack('loremipsum');

	tinymce.create('tinymce.plugins.LoremIpsum', {
		/**
		 * Initializes the plugin, this will be executed after the plugin has been created.
		 * This call is done before the editor instance has finished it's initialization so use the onInit event
		 * of the editor instance to intercept that event.
		 *
		 * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
		 * @param {string} url Absolute URL to where the plugin is located.
		 */
		init : function(ed, url) {
			// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
			ed.addCommand('mceLoremIpsum', function() {
				ed.windowManager.open({
					file : url + '/loremipsum.html',
					width : 320 + ed.getLang('loremipsum.delta_width', 0),
					height : 120 + ed.getLang('loremipsum.delta_height', 0),
					inline : 1
				}, {
					plugin_url : url // Plugin absolute URL
				});
			});

			// Register LoremIpsum button
			ed.addButton('loremipsum', {
				title : 'loremipsum.desc',
				cmd : 'mceLoremIpsum',
				image : url + '/img/loremipsum.gif'
			});

		},

		/**
		 * Creates control instances based in the incomming name. This method is normally not
		 * needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons
		 * but you sometimes need to create more complex controls like listboxes, split buttons etc then this
		 * method can be used to create those.
		 *
		 * @param {String} n Name of the control to create.
		 * @param {tinymce.ControlManager} cm Control manager to use inorder to create new control.
		 * @return {tinymce.ui.Control} New control instance or null if no control was created.
		 */
		createControl : function(n, cm) {
			return null;
		},

		/**
		 * Returns information about the plugin as a name/value array.
		 * The current keys are longname, author, authorurl, infourl and version.
		 *
		 * @return {Object} Name/value array containing information about the plugin.
		 */
		getInfo : function() {
			return {
				longname : 'Lorem Ipsum plugin',
				author : 'Jakub Scholz (based on similar plugin from Guszt�v P�lv�lgyi)',
				authorurl : 'http://www.assembla.com/spaces/lorem-ipsum',
				infourl : 'http://www.assembla.com/spaces/lorem-ipsum',
				version : "0.1.2"
			};
		}
	});

	// Register plugin
	tinymce.PluginManager.add('loremipsum', tinymce.plugins.LoremIpsum);
})();


text:
/*
 * Zed Attack Proxy (ZAP) and its related class files.
 *
 * ZAP is an HTTP/HTTPS proxy for assessing web application security.
 *
 * 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.
 */
package org.zaproxy.zap.extension.httppanel.view.paramtable;

import java.util.Iterator;
import java.util.TreeSet;

import javax.swing.JComboBox;

import org.parosproxy.paros.Constant;
import org.parosproxy.paros.extension.ExtensionAdaptor;
import org.parosproxy.paros.extension.ExtensionHook;
import org.parosproxy.paros.network.HtmlParameter;
import org.zaproxy.zap.extension.httppanel.component.split.request.RequestSplitComponent;
import org.zaproxy.zap.extension.httppanel.view.DefaultHttpPanelViewModel;
import org.zaproxy.zap.extension.httppanel.view.HttpPanelView;
import org.zaproxy.zap.extension.httppanel.view.HttpPanelViewModel;
import org.zaproxy.zap.view.HttpPanelManager;
import org.zaproxy.zap.view.HttpPanelManager.HttpPanelViewFactory;

public class ExtensionHttpPanelRequestQueryCookieTableView extends ExtensionAdaptor {

	public static final String NAME = "ExtensionHttpPanelRequestQueryCookieTableView";

	public ExtensionHttpPanelRequestQueryCookieTableView() {
		super(NAME);
	}

	@Override
	public void hook(ExtensionHook extensionHook) {
	    super.hook(extensionHook);
		if (getView() != null) {
			HttpPanelManager.getInstance().addRequestViewFactory(RequestSplitComponent.NAME, new HttpPanelQueryCookieParamTableViewFactory());
		}
	}

	@Override
	public boolean canUnload() {
		// Do not allow the unload until moved to an add-on.
		return false;
	}

	@Override
	public void unload() {
		if (getView() != null) {
			HttpPanelManager panelManager = HttpPanelManager.getInstance();
			panelManager.removeRequestViewFactory(RequestSplitComponent.NAME, HttpPanelQueryCookieParamTableViewFactory.NAME);
			panelManager.removeRequestViews(RequestSplitComponent.NAME, HttpPanelQueryCookieParamTableView.NAME, RequestSplitComponent.ViewComponent.HEADER);
		}
	}

	private static final class HttpPanelQueryCookieParamTableViewFactory implements HttpPanelViewFactory {

		public static final String NAME = "HttpPanelQueryCookieParamTableViewFactory";

		@Override
		public String getName() {
			return NAME;
		}

		@Override
		public HttpPanelView getNewView() {
			return new HttpPanelQueryCookieParamTableView(new DefaultHttpPanelViewModel(), new HttpPanelQueryCookieParamTableModel());
		}

		@Override
		public Object getOptions() {
			return RequestSplitComponent.ViewComponent.HEADER;
		}
	}

	private static class HttpPanelQueryCookieParamTableView extends HttpPanelParamTableView {

		public HttpPanelQueryCookieParamTableView(HttpPanelViewModel model, HttpPanelParamTableModel tableModel) {
			super(model, tableModel);
		}

		@Override
		public String getTargetViewName() {
			return "";
		}

		@Override
		public JComboBox<HtmlParameter.Type> getComboBoxTypes() {
			JComboBox<HtmlParameter.Type> comboBoxTypes = new JComboBox<>();

			comboBoxTypes.addItem(HtmlParameter.Type.url);
			comboBoxTypes.addItem(HtmlParameter.Type.cookie);

			return comboBoxTypes;
		}
	}

	private static class HttpPanelQueryCookieParamTableModel extends HttpPanelParamTableModel {

		private static final long serialVersionUID = 869819957109403800L;

		@Override
		protected void loadAllParams() {
			allParams.addAll(httpMessage.getUrlParams());
			allParams.addAll(httpMessage.getRequestHeader().getCookieParams());
		}

		@Override
		public void saveAllParams() {
			TreeSet<HtmlParameter> get = new TreeSet<>();
			TreeSet<HtmlParameter> cookies = new TreeSet<>();

			Iterator<HtmlParameter> it = allParams.iterator();
			while (it.hasNext()) {
				HtmlParameter htmlParameter = it.next();
				if(!htmlParameter.getName().isEmpty()) {
					switch (htmlParameter.getType()) {
					case url:
						get.add(htmlParameter);
						break;
					case cookie:
						cookies.add(htmlParameter);
						break;
					case form:
						break;
					default:
						break;
					}
				}
			}

			httpMessage.setGetParams(get);
			httpMessage.setCookieParams(cookies);
		}

		@Override
		protected HtmlParameter getDefaultHtmlParameter() {
			return new HtmlParameter(HtmlParameter.Type.url, "", "");
		}
	}
	@Override
	public String getAuthor() {
		return Constant.ZAP_TEAM;
	}

	/**
	 * No database tables used, so all supported
	 */
	@Override
	public boolean supportsDb(String type) {
		return true;
	}
}


text: Open source Blog Management System


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><%= htmlWebpackPlugin.options.title %></title>


text:
package com.sejelli;

import com.sejelli.messaging.domain.application.SmsSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by aibano on 10/16/2016.
 */
@Component
public class ScheduledTasks {
    @Autowired
    private SmsSender smsSender;

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000, initialDelay = 3000)
    public void reportCurrentTime() {
        log.info("Sending Pending Messages", dateFormat.format(new Date()));
        this.smsSender.sendPendingMessages();
    }

    @Scheduled(fixedRate = 60000)
    public void reloadSettings() {
        log.info("Reloading the settings...", dateFormat.format(new Date()));
        this.smsSender.reloadSetting();
    }
}


text:
BASE_INSTALL_PATH=/var/www/orbital-src
APP_PATH=/var/www/orbital
UPLOAD_PATH=/var/www/orbital-uploads

VERSION=$(echo $1 | sed 's/.*web-\([a-f0-9]*\)\.tar\.gz/\1/');
INSTALL_PATH="$BASE_INSTALL_PATH/$VERSION"

# extract package
echo "Extracting package to $INSTALL_PATH"

mkdir -p $INSTALL_PATH
tar xjf $1 -C $INSTALL_PATH
chown -R www-data:www-data $INSTALL_PATH

# update symlinks -- uploads
echo "Linking uploads folder"

mkdir -p $UPLOAD_PATH
chown www-data:www-data $UPLOAD_PATH
ln -s $UPLOAD_PATH $INSTALL_PATH/web/uploads

pushd $INSTALL_PATH > /dev/null
export SYMFONY_ENV=prod

# setup parameters.yml
if [ ! -f $BASE_INSTALL_PATH/parameters.yml ]; then
  echo "Creating $BASE_INSTALL_PATH/parameters.yml"
  touch $BASE_INSTALL_PATH/parameters.yml
fi

ln -s $BASE_INSTALL_PATH/parameters.yml $INSTALL_PATH/app/config/parameters.yml

# install composer deps
echo "Installing dependencies"

curl -sS https://getcomposer.org/installer | php
php composer.phar install --no-dev --optimize-autoloader

# warmup cache
echo "Warming up cache"

php app/console cache:clear --env=prod --no-debug
chown -R www-data:www-data $INSTALL_PATH/app/cache/prod $INSTALL_PATH/app/logs/
chmod -R +w $INSTALL_PATH/app/cache/prod $INSTALL_PATH/app/logs/

# update symlinks -- offline
echo "Taking Orbital offline"

OFFLINE_PATH="$BASE_INSTALL_PATH/offline"

rm -R $OFFLINE_PATH
mkdir -p $OFFLINE_PATH/web
echo "<!doctype html><title>Orbital Offline</title>
Orbital is updating...
" > $OFFLINE_PATH/web/app.php
chown -R www-data:www-data $OFFLINE_PATH

rm $APP_PATH
ln -s $OFFLINE_PATH $APP_PATH

service php5-fpm restart

echo "Orbital offline"

# migrate DB
echo "Migrating database"

php app/console doctrine:migrations:migrate

popd > /dev/null

# update symlinks -- app
echo "Putting new version live"

rm $APP_PATH
ln -s $INSTALL_PATH $APP_PATH
chown www-data:www-data $APP_PATH

service php5-fpm restart

echo "Setup complete -- check $BASE_INSTALL_PATH/parameters.yml";


text:
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>OAuth Popup Callback</title>
  <style type="text/css">
    html,
    body {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px;
      font-family: Lucida Sans, Lucida Grande, Arial !important;
      font-size: 14px;
    }
  </style>
  <script type="text/javascript" src="https://js.arcgis.com/3.35"></script>
  <script type="text/javascript">
    require(["esri/urlUtils", "dojo/domReady!"], function (urlUtils) {
      var url = document.location.href;
      var urlObject = urlUtils.urlToObject(url);
      urlObject.query = urlObject.query || {};
      var redirect = urlObject.query.redirect;
      if (redirect) {
        location.href = redirect + location.hash;
      } else {
        window.opener.instagramCallback(location.hash);
        window.close();
      }
    });
  </script>
</head>

<body>
  <!--OAuth Popup Callback-->
</body>

</html>


text:
<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );

/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files.  Please see the user guide for info:
|
|	http://codeigniter.com/user_guide/general/hooks.html
|
*/


text:
Template.bitmask.helpers({
  matrix : function() {
    return Matrix.findOne();
  },

  pixels : function() {
    var pixels = [];

    this.bitmask.forEach(function(r, i) {
      r.split('').forEach(function(val, j) {
        pixels.push({
        row: i,
        column: j,
        x: j*32,
        y: i*32,
        pixel: !!+val
        });
      });
    });
    return pixels;
  },

  columns : function() {
    return this.row.split('').map(function(val, i){ return { pixel: !!+val, index: i }; });
  }
});

Template.bitmask.events({
  'click .pixel' : function(evt) {

  var el = evt.currentTarget;
  var row = el.getAttribute('data-row');
  var column = el.getAttribute('data-column');
  var bitmask = Matrix.findOne('42').bitmask.map(function(line) { return line.split(''); } );
  var pixel = !!+bitmask[row][column];
  // console.log('click pixel', row, column, pixel);
  bitmask[row][column] = +!pixel;
  bitmask = bitmask.map(function(line) { return line.join(''); } );
  Matrix.update('42', { $set:
    { bitmask: bitmask }
  });
  // console.log('bitmask', bitmask);
  },

  'click [data-action=clear]' : function() {
    Matrix.update('42', { $set:
      { bitmask: _.range(8).map( function(el) { return '00000000';} ) }
    });
  }
});

Template.bitmask.events({
  'change input[type=color]' : _.throttle(function(evt) {
  // console.log(evt.currentTarget.value);
    Matrix.update('42', { $set:
      { color: hex2rgb(evt.currentTarget.value) }
    });
  },50)
});

Template.bitmask.helpers({
  hexColor : function(c) {
    return rgbToHex(c[0], c[1], c[2]);
  }
});

function hex2rgb(h){return [hexToR(h),hexToG(h),hexToB(h)]; };
function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}


text:
import os

from flask import Flask
from flask import jsonify
from flask import render_template
from flask import request

from lib.tweet_locator import determinate_tweet_location

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    """Return the home page or map if tweet_id is send"""
    tweet_ids = request.form.get('tweetId')
    if tweet_ids:
        tweet_ids = tweet_ids.split(',')
    else:
        tweet_ids = []

    weight_text = request.form.get('weightText')
    weight_timezone = request.form.get('weightTimezone')
    weight_location_field = request.form.get('weightLocationField')
    weight_language = request.form.get('weightLanguage')
    weight_url = request.form.get('weightURL')
    weight_geolocalization = request.form.get('weightGeolocalization')
    aggregate = not bool(request.form.get('aggregate'))

    polys = []
    for tweet_id in tweet_ids:
        polys.append(determinate_tweet_location(tweet_id, weight_text=weight_text, weight_timezone=weight_timezone,
                                                weight_location_field=weight_location_field,
                                                weight_language=weight_language, weight_url=weight_url,
                                                weight_geolocalization=weight_geolocalization,
                                                aggregate=aggregate))
    return render_template('map.html', polys=polys, maps_key=os.environ['GOOGLE_MAPS_KEY'])

@app.route('/api', methods=['GET'])
def api():
    """API"""
    if request.args.get('tweetIds'):
        tweet_ids = request.args.get('tweetIds').split(',')
        polys = []
        for tweet_id in tweet_ids:
            polys.append(determinate_tweet_location(tweet_id))
        return jsonify({'results': [{'tweet': p[1], 'geojson': {'type': 'MultiPolygon', 'coordinates': p[0]}} for p in polys]})
    return (jsonify({'error': 'no tweet ids specified'}), 400)

if __name__ == "__main__":
    app.run()


text:
title: Gatsby Cloud Content Sync
---

## Try Content Sync with Contentful on Gatsby Cloud

To get setup quickly with a new site and have Gatsby Cloud do the heavy lifting, [deploy a new Gatsby Contentful site with just a few clicks on gatsbyjs.com](https://www.gatsbyjs.com/dashboard/deploynow?url=https://github.com/contentful/starter-gatsby-blog).

## What is Content Sync?

Content Sync is a Gatsby Cloud feature for improving the Preview experience for content authors.

When content authors press "Open Preview" in their CMS, Content Sync routes them to the correct URL. It helps them understand the status of previews, so they know when their content is ready to view and otherwise if there were any build errors. It does this by redirecting to a "waiting room" page which displays a loading state while the content preview builds. Once the build is complete, the author is redirected to the correct page on the frontend of the Gatsby Preview site automatically.

Content Sync will route users to the correct page even when pressing "Open Preview" from within a nested node which has no associated top-level page.

![Screenshot of Gatsbyjs.com Content Sync UI loading state. On the very left vertically centered is a widget with three icons: Gatsby Icon, a Link Icon, and an Information Icon. In the center of the screen a loading indicator says "Polishing your site".](../images/content-sync-loading.png)

If the build for the preview fails or if no page is created that contains the content being previewed, Content Sync UI will display an error message.

![Screenshot of Gatsbyjs.com Content Sync UI error state. Now the center of the screen says "Oh no! We've run into an error previewing your site". You can click a "View Error Logs" link below that text.](../images/content-sync-error.png)

## Finding the right page for Content Previews

In the case that your content lives on multiple pages, for example a blog post page and a blog listing page, and you find you're being routed to the page you don't want to view your preview on, you can specify which node owns which page using the [`ownerNodeId` setting in the `createPage` API][createpage]. Set the `ownerNodeId` to the Gatsby `node.id` of the node you want to preview for the page. Note that the `ownerNodeId` must correspond to the `node.id` of a node which is queried on that page via a GraphQL query.

You will not need to do this if you're building pages using the [File System Route API][fsroutesapi], or if your page context includes a matching `id` property. See the next section for more info on this.

## Node to Page Mapping Hierarchy

Content Sync uses the [`unstable_createNodeManifest`][createnodemanifest] API via source plugins to allow source plugins to tell Gatsby which nodes are being previewed. When this public action is called, Gatsby uses an internal hierarchy to determine which page the content author intends to preview.

The hierarchy is as follows, from most specific to least specific:

1. [The`ownerNodeId` property in the `createPage` action][createpage]. (This is set manually by the Gatsby site developer)
2. Nodes associated with pages created from the [File System Route API][fsroutesapi]. (automatic)
3. An `id` property in the [page `context` passed to the `createPage` API][createpage] with a node id which matches the previewed node id. (automatic)
4. The first matching node id found in Gatsby's [GraphQL query tracking][querytracking] which maps node id's to pages that query them. This allows nodes which have no direct top-level page correlated with them to be previewed throughout the site. (automatic)

## Source Plugin Authors

If you're a source plugin author, you can find instructions on adding Content Sync support to your source plugin and CMS extension in the [source plugin author docs](https://www.gatsbyjs.com/docs/how-to/plugins-and-themes/creating-a-source-plugin/).

## Diagram

![Diagram of Content Sync on Gatsby Cloud. When a user clicks "Open Preview" the manifest id is created from the CMS and sent to Gatsby Cloud. The Content Sync UI then displays a loading state while it checks for a matching manifest id in Gatsby build public directory. At the same time a request is send to the preview webhook and Gatsby Cloud starts a build. If it finds a matching manifest id created from the CMS Gatsby maps data to correct page for preview and adds the manifest file to the build public directory. Now the Gatsby Cloud Preview Runner detects a node manifest to preview and redirects to the preview itself.](../images/content-sync-diagram.png)

[authordocs]: /docs/how-to/plugins-and-themes/creating-a-source-plugin/#enabling-content-sync
[createnodemanifest]: /docs/reference/config-files/actions#unstable_createNodeManifest
[createpage]: /docs/reference/config-files/actions#createPage
[querytracking]: /docs/page-node-dependencies/
[fsroutesapi]: /docs/reference/routing/file-system-route-api/


text:
"""Provide info to system health."""
from __future__ import annotations

from typing import Any

from pyisy import ISY

from homeassistant.components import system_health
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant, callback

from .const import DOMAIN, ISY994_ISY, ISY_URL_POSTFIX

@callback
def async_register(
    hass: HomeAssistant, register: system_health.SystemHealthRegistration
) -> None:
    """Register system health callbacks."""
    register.async_register_info(system_health_info)

async def system_health_info(hass: HomeAssistant) -> dict[str, Any]:
    """Get info for the info page."""

    health_info = {}
    config_entry_id = next(
        iter(hass.data[DOMAIN])
    )  # Only first ISY is supported for now
    isy: ISY = hass.data[DOMAIN][config_entry_id][ISY994_ISY]

    entry = hass.config_entries.async_get_entry(config_entry_id)
    assert isinstance(entry, ConfigEntry)
    health_info["host_reachable"] = await system_health.async_check_can_reach_url(
        hass, f"{entry.data[CONF_HOST]}{ISY_URL_POSTFIX}"
    )
    health_info["device_connected"] = isy.connected
    health_info["last_heartbeat"] = isy.websocket.last_heartbeat
    health_info["websocket_status"] = isy.websocket.status

    return health_info


text:
import java.awt.*;
import java.awt.event.*;
import org.apache.cassandra.locator.TokenMetadata;

public class CassandraTest{

	public static void main(String[] args){
		test();
	}

	/**
	 * Test takes an option and runs the selected test case
	 */

	static void test() {

	    TokenMetadata token = new TokenMetadata();
	    token.getRingVersion();
            token.invalidateCachedRings();
	    System.out.println("Hello");
	}
}


text:
#ifndef OPTIONS_H
#define OPTIONS_H
#include "wx/wx.h"
#include "wx/propdlg.h"

class OptionsDlg : public wxDialog
{
public:
    OptionsDlg(wxWindow* parent, wxWindowID id, const wxString& title,
            const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize,
            long style = wxDEFAULT_DIALOG_STYLE, const wxString& name = "dialogBox");
    void OnButtonHandler(wxCommandEvent &evt);
    //void OnPage(wxNotebookEvent &evt);

private:
    wxNotebook *m_pages;
    //wxWindow *m_current;

private:
    DECLARE_EVENT_TABLE()
};

#endif


text:
namespace IsolationForest
{
	/// Constructor.
	Node::Node() :
		m_splitValue(0),
		m_left(NULL),
		m_right(NULL)
	{
	}

	/// Constructor.
	Node::Node(const std::string& featureName, uint64_t splitValue) :
		m_featureName(featureName),
		m_splitValue(splitValue),
		m_left(NULL),
		m_right(NULL)
	{
	}

	/// Destructor.
	Node::~Node()
	{
		DestroyLeftSubtree();
		DestroyRightSubtree();
	}

	void Node::SetLeftSubTree(Node* subtree)
	{
		DestroyLeftSubtree();
		m_left = subtree;
	}

	void Node::SetRightSubTree(Node* subtree)
	{
		DestroyRightSubtree();
		m_right = subtree;
	}

	void Node::DestroyLeftSubtree()
	{
		if (m_left)
		{
			delete m_left;
			m_left = NULL;
		}
	}

	void Node::DestroyRightSubtree()
	{
		if (m_right)
		{
			delete m_right;
			m_right = NULL;
		}
	}

	/// Returns the node as a JSON string.
	std::string Node::Dump() const
	{
		std::string data = "{";

		data.append("'Feature Name': '");
		data.append(this->m_featureName);
		data.append("', 'Split Value': ");
		data.append(std::to_string(m_splitValue));
		data.append(", 'Left': ");
		if (this->m_left)
			data.append(this->m_left->Dump());
		else
			data.append("{}");
		data.append(", 'Right': ");
		if (this->m_right)
			data.append(this->m_right->Dump());
		else
			data.append("{}");
		data.append("}");
		return data;
	}

	/// Constructor.
	Forest::Forest() :
		m_randomizer(new Randomizer()),
		m_numTreesToCreate(10),
		m_subSamplingSize(0)
	{
	}

	/// Constructor.
	Forest::Forest(uint32_t numTrees, uint32_t subSamplingSize) :
		m_randomizer(new Randomizer()),
		m_numTreesToCreate(numTrees),
		m_subSamplingSize(subSamplingSize)
	{
	}

	/// Destructor.
	Forest::~Forest()
	{
		DestroyRandomizer();
		Destroy();
	}

	void Forest::SetRandomizer(Randomizer* newRandomizer)
	{
		DestroyRandomizer();
		m_randomizer = newRandomizer;
	}

	/// Adds each of the sample's features to the list of known features
	/// with the corresponding set of unique values.
	void Forest::AddSample(const Sample& sample)
	{
        // We don't store the sample directly, just the features.
		const FeaturePtrList& features = sample.Features();
		FeaturePtrList::const_iterator featureIter = features.begin();
		while (featureIter != features.end())
		{
			const FeaturePtr feature = (*featureIter);
			const std::string& featureName = feature->Name();
			uint64_t featureValue = feature->Value();

			// Either create or update the feature values count.
			if (m_featureValues.count(featureName) == 0)
			{
				Uint64Set featureValueSet;
				featureValueSet.insert(featureValue);
				m_featureValues.insert(std::make_pair(featureName, featureValueSet));
			}
			else
			{
				Uint64Set& featureValueSet = m_featureValues.at(featureName);
				featureValueSet.insert(featureValue);
			}

			++featureIter;
		}
	}

	/// Creates and returns a single tree. As this is a recursive function,
	/// depth indicates the current depth of the recursion.
	NodePtr Forest::CreateTree(const FeatureNameToValuesMap& featureValues, size_t depth)
	{
		// Sanity check.
		size_t featureValuesLen = featureValues.size();
		if (featureValuesLen <= 1)
		{
			return NULL;
		}

		// If we've exceeded the maximum desired depth, then stop.
		if ((m_subSamplingSize > 0) && (depth >= m_subSamplingSize))
		{
			return NULL;
		}

		// Randomly select a feature.
		size_t selectedFeatureIndex = (size_t)m_randomizer->RandUInt64(0, featureValuesLen - 1);
		FeatureNameToValuesMap::const_iterator featureIter = featureValues.begin();
		std::advance(featureIter, selectedFeatureIndex);
		const std::string& selectedFeatureName = (*featureIter).first;

		// Get the value list to split on.
		const Uint64Set& featureValueSet = (*featureIter).second;
		if (featureValueSet.size() == 0)
		{
			return NULL;
		}

		// Randomly select a split value.
		size_t splitValueIndex = 0;
		if (featureValueSet.size() > 1)
		{
			splitValueIndex = (size_t)m_randomizer->RandUInt64(0, featureValueSet.size() - 1);
		}
		Uint64Set::const_iterator splitValueIter = featureValueSet.begin();
		std::advance(splitValueIter, splitValueIndex);
		uint64_t splitValue = (*splitValueIter);

		// Create a tree node to hold the split value.
		NodePtr tree = new Node(selectedFeatureName, splitValue);
		if (tree)
		{
			// Create two versions of the feature value set that we just used,
			// one for the left side of the tree and one for the right.
			FeatureNameToValuesMap tempFeatureValues = featureValues;

			// Create the left subtree.
			Uint64Set leftFeatureValueSet = featureValueSet;
			splitValueIter = leftFeatureValueSet.begin();
			std::advance(splitValueIter, splitValueIndex);
			leftFeatureValueSet.erase(splitValueIter, leftFeatureValueSet.end());
			tempFeatureValues[selectedFeatureName] = leftFeatureValueSet;
			tree->SetLeftSubTree(CreateTree(tempFeatureValues, depth + 1));

			// Create the right subtree.
			if (splitValueIndex < featureValueSet.size() - 1)
			{
				Uint64Set rightFeatureValueSet = featureValueSet;
				splitValueIter = rightFeatureValueSet.begin();
				std::advance(splitValueIter, splitValueIndex + 1);
				rightFeatureValueSet.erase(rightFeatureValueSet.begin(), splitValueIter);
				tempFeatureValues[selectedFeatureName] = rightFeatureValueSet;
				tree->SetRightSubTree(CreateTree(tempFeatureValues, depth + 1));
			}
		}

		return tree;
	}

	/// Creates a forest containing the number of trees specified to the constructor.
	void Forest::Create()
	{
		m_trees.reserve(m_numTreesToCreate);

		for (size_t i = 0; i < m_numTreesToCreate; ++i)
		{
			NodePtr tree = CreateTree(m_featureValues, 0);
			if (tree)
			{
				m_trees.push_back(tree);
			}
		}
	}

    /// Scores the sample against the specified tree.
	double Forest::Score(const Sample& sample, const NodePtr tree)
	{
		double depth = (double)0.0;

		const FeaturePtrList& features = sample.Features();

		NodePtr currentNode = tree;
		while (currentNode)
		{
			bool foundFeature = false;

			// Find the next feature in the sample.
			FeaturePtrList::const_iterator featureIter = features.begin();
			while (featureIter != features.end() && !foundFeature)
			{
				const FeaturePtr currentFeature = (*featureIter);
				if (currentFeature->Name().compare(currentNode->FeatureName()) == 0)
				{
					if (currentFeature->Value() < currentNode->SplitValue())
					{
						currentNode = currentNode->Left();
					}
					else
					{
						currentNode = currentNode->Right();
					}
					++depth;
					foundFeature = true;
				}
				++featureIter;
			}

			// If the tree contained a feature not in the sample then take
			// both sides of the tree and average the scores together.
			if (!foundFeature)
			{
				double leftDepth = depth + Score(sample, currentNode->Left());
				double rightDepth = depth + Score(sample, currentNode->Right());
				return (leftDepth + rightDepth) / (double)2.0;
			}
		}
		return depth;
	}

	/// Scores the sample against the entire forest of trees. Result is the average path length.
	double Forest::Score(const Sample& sample)
	{
		double avgPathLen = (double)0.0;

		if (m_trees.size() > 0)
		{
			NodePtrList::const_iterator treeIter = m_trees.begin();
			while (treeIter != m_trees.end())
			{
				avgPathLen += (double)Score(sample, (*treeIter));
				++treeIter;
			}
			avgPathLen /= (double)m_trees.size();
		}
		return avgPathLen;
	}

	#define H(i) (log(i) + 0.5772156649)
	#define C(n) (2 * H(n - 1) - (2 * (n - 1) / n))

	/// Scores the sample against the entire forest of trees. Result is normalized so that values
    /// close to 1 indicate anomalies and values close to zero indicate normal values.
	double Forest::NormalizedScore(const Sample& sample)
    {
		double score = (double)0.0;
		size_t numTrees = m_trees.size();

		if (numTrees > 0)
		{
			double avgPathLen = (double)0.0;

			NodePtrList::const_iterator treeIter = m_trees.begin();
			while (treeIter != m_trees.end())
			{
				avgPathLen += (double)Score(sample, (*treeIter));
				++treeIter;
			}
			avgPathLen /= (double)numTrees;

			if (numTrees > 1)
			{
				double exponent = -1.0 * (avgPathLen / C(numTrees));
				score = pow(2, exponent);
			}
		}
		return score;
    }

	/// Destroys the entire forest of trees.
	void Forest::Destroy()
	{
		std::vector<NodePtr>::iterator iter = m_trees.begin();
		while (iter != m_trees.end())
		{
			NodePtr tree = (*iter);
			if (tree)
			{
				delete tree;
			}
			++iter;
		}
		m_trees.clear();
	}

	/// Frees the custom randomizer object (if any).
	void Forest::DestroyRandomizer()
	{
		if (m_randomizer)
		{
			delete m_randomizer;
			m_randomizer = NULL;
		}
	}

	/// Returns the forest as a JSON object.
	std::string Forest::Dump() const
	{
		std::string data = "{";
		auto featureValuesIter = m_featureValues.begin();
		auto treeIter = m_trees.begin();

		data.append("'Sub Sampling Size': ");
		data.append(std::to_string(this->m_subSamplingSize));
		data.append(", 'Feature Values': [");
		while (featureValuesIter != m_featureValues.end())
		{
			data.append("'");
			data.append((*featureValuesIter).first);
			data.append("': [");

			auto valuesIter = (*featureValuesIter).second.begin();
			while (valuesIter != (*featureValuesIter).second.end())
			{
				data.append(std::to_string(*valuesIter));
				++valuesIter;

				// Last item?
				if (valuesIter != (*featureValuesIter).second.end())
					data.append(", ");
			}
			++featureValuesIter;

			data.append("]");

			// Last item?
			if (featureValuesIter != m_featureValues.end())
				data.append(", ");
		}
		data.append("], 'Trees': [");
		while (treeIter != m_trees.end())
		{
			data.append((*treeIter)->Dump());
			++treeIter;

			// Last item?
			if (treeIter != m_trees.end())
				data.append(", ");
		}
		data.append("]");
		data.append("}");
		return data;
	}
}


text:
* Status: implemented

## Context and Problem Statement

To enable portability and reproducibility of building the container application, a buildtool is of utmost importance.
It simplifies the buildprocess and should preferrably allow a minimal configuration effort for IDEs.

## Decision Drivers

* Core Concern is management of building the container, preferrably in a single command invocation
* Support for dependency management is optional, but highly appreciated
* The tool should also support deployment of the finished web application to an application server
* Cross Platform tooling, Automation and support for Running a Test suite are also necessary

## Considered Options

* Maven
* Gradle
* Ant

## Decision Outcome

Maven was chosen both for it's maturity and integration with established IDEs.
It also was previously used to automate the container build when the container was still deployed as an OSGI application.
Additionally maven dependencies are the de-facto standard distribution mechanism in the java ecosystem.

## Pros and Cons of the Options

### Maven

* Mature and tested ecosystem
* De-Facto standard for dependency distribution
* Existing maven structure for previous incarnation of container allows code reuse
* Strong support for testing, automation and known cross-platform usability

### Gradle

* Not quite as mature ecosystem as maven
* Dependency management is possible, but doesn't open new avenues over maven
* Cross-Platform compatibility for gradle is present, but often requires additional support through gradle-wrapper
* Support for testing and automation is present

### Ant

* Ecosystem is mature, but configuration over convention paradigm
* No builtin support for dependency management
* Cross-Platform compatibility is not builtin
* Support for testing is incomplete, automation with current CI providers may require additional support


text:
title: What to Do if You Speak a Language not Yet Supported by Free Code Camp
localeTitle: O que fazer se você falar um idioma ainda não suportado pelo Free Code Camp
---
Tradução é uma proposta de tudo ou nada.

Não poderemos adicionar novos idiomas ao Free Code Camp até que todos os nossos
desafios são traduzidos para esse idioma.

Além de traduzi-las inicialmente, também precisaremos manter
a tradução como os desafios são gradualmente atualizados (usamos o
sistema de emissão do github para manter registro).

Se você puder nos ajudar, junte-se ao [canal do gitter](https://gitter.im/FreeCodeCamp/Translators)
e leia o [Guia de Tradução](http://forum.freecodecamp.com/t/guidelines-for-translating-free-code-camp-to-any-language/19111)


text:
<?php
/**
 * View: Month View - Multiday Event
 *
 * Override this template in your own theme by creating a file at:
 * [your-theme]/tribe/events/v2/month/calendar-body/day/multiday-events/multiday-event.php
 *
 * See more documentation about our views templating system.
 *
 * @link {INSERT_ARTCILE_LINK_HERE}
 *
 * @version 5.0.0
 *
 * @var string $day_date        The `Y-m-d` date of the day currently being displayed.
 * @var string $today_date      Today's date in the `Y-m-d` format.
 * @var string $grid_start_date The `Y-m-d` date of the day where the grid starts.
 * @var WP_Post $event          An event post object with event-specific properties added from the the `tribe_get_event`
 *                              function.
 * @var bool $is_start_of_week  Whether the current grid day being rendered is the first day of the week or not.
 *
 * @see tribe_get_event() For the format of the event object and its properties.
 *
 */

use Tribe__Date_Utils as Dates;

/*
 * To keep the calendar accessible, in the context of a week, we'll print the event only on either its first day
 * or the first day of the week.
 */
$should_display = in_array( $day_date, $event->displays_on, true )
                  || $is_start_of_week;

$classes = tribe_get_post_class( [ 'tribe-events-calendar-month__multiday-event' ], $event->ID );

// @todo @fe move class configuration to template tag

if ( $event->featured ) {
	$classes[] = 'tribe-events-calendar-month__multiday-event--featured';
}

// If the event started on a previous month.
$started_previous_month = $event->dates->start_display->format( 'Y-m-d' ) < $grid_start_date;
$is_first_appearance    = ( $event->dates->start_display->format( 'Y-m-d' ) === $day_date )
                          || ( $started_previous_month && $grid_start_date === $day_date );

// If it starts today and this week, let's add the left border and set the width.
if ( $should_display ) {

	/*
	 * The "duration" here is how many days the event will take this week, not in total.
	 * The two values might be the same but they will differ for events that last more than one week.
	 */
	$classes[] = 'tribe-events-calendar-month__multiday-event--width-' . $event->this_week_duration;
	$classes[] = 'tribe-events-calendar-month__multiday-event--display';

	// If it ends this week, let's add the start class (left border).
	if ( $event->starts_this_week ) {
		$classes[] = 'tribe-events-calendar-month__multiday-event--start';
	}

	// If it ends this week, let's add the end class (right border).
	if ( $event->ends_this_week ) {
		$classes[] = 'tribe-events-calendar-month__multiday-event--end';
	}

	if ( $event->dates->end->format( 'Y-m-d' ) < $today_date ) {
		$classes[] = 'tribe-events-calendar-month__multiday-event--past';
	}
}
?>

	<article <?php tribe_classes( $classes ); ?> data-event-id="<?php echo esc_attr( $event->ID ); ?>">

			<time
				datetime="<?php echo esc_attr( $event->dates->start->format( Dates::DBDATEFORMAT ) ); ?>"
				class="tribe-common-a11y-visual-hide"
			>
				<?php echo esc_attr( $event->dates->start->format( Dates::DBDATEFORMAT ) ); ?>
			</time>
			<a
				href="<?php echo esc_url( $event->permalink ); ?>"
				class="tribe-events-calendar-month__multiday-event-hidden-link"
				data-js="tribe-events-tooltip"
				data-tooltip-content="#tribe-events-tooltip-content-<?php echo esc_attr( $event->ID ); ?>"
				aria-describedby="tribe-events-tooltip-content-<?php echo esc_attr( $event->ID ); ?>"
			>
				<?php if ( $event->featured ) : ?>
					<em
						class="tribe-events-calendar-month__multiday-event-hidden-featured-icon tribe-common-svgicon tribe-common-svgicon--featured"
						aria-label="<?php esc_attr_e( 'Featured', 'the-events-calendar' ); ?>"
						title="<?php esc_attr_e( 'Featured', 'the-events-calendar' ); ?>"
					>
				<?php endif; ?>

					<?php
					// phpcs:ignore
					echo $event->title;
					?>

		<?php if ( $should_display ) : ?>

					<?php if ( $event->featured ) : ?>
						<em
							class="tribe-events-calendar-month__multiday-event-bar-featured-icon tribe-common-svgicon tribe-common-svgicon--featured"
							aria-label="<?php esc_attr_e( 'Featured', 'the-events-calendar' ); ?>"
							title="<?php esc_attr_e( 'Featured', 'the-events-calendar' ); ?>"
						>
					<?php endif; ?>

						<?php
						// phpcs:ignore
						echo $event->title;
						?>

			<?php if ( $is_first_appearance ) : ?>
				<?php $this->template( 'month/calendar-body/day/calendar-events/calendar-event/tooltip', [ 'event' => $event ] ); ?>
			<?php endif; ?>
		<?php endif; ?>