text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.anarres.ipmi.protocol.packet.ipmi.security.impl.authentication;

import java.security.NoSuchAlgorithmException;
import org.anarres.ipmi.protocol.packet.ipmi.security.IpmiAuthenticationAlgorithm;

/**
 * [IPMI2] Section 13.28.3, page 158.
 *
 * @author shevek
 */
public class RAKP_HMAC_MD5 extends AbstractJCEHash {

    public RAKP_HMAC_MD5() throws NoSuchAlgorithmException {
        super("HmacMD5");
    }

    @Override
    public IpmiAuthenticationAlgorithm getName() {
        return IpmiAuthenticationAlgorithm.RAKP_HMAC_MD5;
    }
}


text:
'use strict';

var assert = require('chai').assert;
var rule = require('../../../lib/rules/type.js');

describe('type', function () {
  it('should have a message', function () {
    assert.equal(rule.message, 'expected {0}');
  });

  it('should validate strings only as strings', function () {
    assert.isTrue(rule('abc', 'string'));
    assert.isFalse(rule('abc', 'number'));
    assert.isFalse(rule('abc', 'object'));
    assert.isFalse(rule('abc', 'array'));
    assert.isFalse(rule('abc', 'date'));
    assert.isFalse(rule('abc', 'json'));
  });

  it('should validate numbers as numbers (but also dates and json because technically)', function () {
    assert.isFalse(rule(1, 'string'));
    assert.isTrue(rule(1, 'number'));
    assert.isFalse(rule(1, 'object'));
    assert.isFalse(rule(1, 'array'));
    assert.isTrue(rule(1, 'date'));
    assert.isTrue(rule(1, 'json'));
  });

  it('should validate objects as objects and as json', function () {
    assert.isFalse(rule({field: 'value'}, 'string'));
    assert.isFalse(rule({field: 'value'}, 'number'));
    assert.isTrue(rule({field: 'value'}, 'object'));
    assert.isFalse(rule({field: 'value'}, 'array'));
    assert.isFalse(rule({field: 'value'}, 'date'));
    assert.isTrue(rule({field: 'value'}, 'json'));
  });

  it('should validate arrays only as arrays', function () {
    assert.isFalse(rule(['abc'], 'string'));
    assert.isFalse(rule(['abc'], 'number'));
    assert.isFalse(rule(['abc'], 'object'));
    assert.isTrue(rule(['abc'], 'array'));
    assert.isFalse(rule(['abc'], 'date'));
    assert.isFalse(rule(['abc'], 'json'));
  });

  it('should validate dates as dates (but also objects because technically)', function () {
    assert.isFalse(rule(new Date(), 'string'));
    assert.isFalse(rule(new Date(), 'number'));
    assert.isTrue(rule(new Date(), 'object'));
    assert.isFalse(rule(new Date(), 'array'));
    assert.isTrue(rule(new Date(), 'date'));
    assert.isFalse(rule(new Date(), 'json'));
  });

  it('should validate stringified json as json (and also strings)', function () {
    assert.isTrue(rule('{"field": "value"}', 'string'));
    assert.isFalse(rule('{"field": "value"}', 'number'));
    assert.isFalse(rule('{"field": "value"}', 'object'));
    assert.isFalse(rule('{"field": "value"}', 'array'));
    assert.isFalse(rule('{"field": "value"}', 'date'));
    assert.isTrue(rule('{"field": "value"}', 'json'));
  });
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Drupal\rp_repo\Controller\oldVersion;

use Drupal\Core\Controller\ControllerBase;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\node\Entity\Node;
use Drupal\rp_api\RPAPIClient;
use Drupal\taxonomy\Entity\Term;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use Drupal\rp_repo\Controller\entities\Taxonomies\taxonomySteveTimeZone;
use Drupal\rp_repo\Controller\entities\Taxonomies\taxonomyTournament;
use Drupal\rp_repo\Controller\entities\Taxonomies\taxonomyParticipan;

/**
 * Class CreateClientData.
 */
class CreateClientData extends ControllerBase {

  //------------------------------------------------------------ NODE CREATION ----------------------------

  /**
   * function createStreamPages ()
   *
   * - $streams - Array of stream from Steve API
   *   streamprovider: [{
   * id: 1,
   * meta: [
   * { channel: 1},
   * {channel: 2},
   * {channel: 3},
   * {channel: 4}
   * ]
   * }...]
   * - $sport_tags - Taxonomy ID to sport  (Example. 2145)
   */
  public function createStreamPages($streams, $sport_tags) {
    $tags_array = [];
    $getInfoObj = new RepoGeneralGetInfo();
    $rpClient = RPAPIClient::getClient();
    foreach ($streams as $stream) {
      $actualStream = $getInfoObj->getTaxonomyByCriterio($stream['id'], 'field_stream_provider_api_id');
      if (empty($actualStream)) {
        $streamObj = $rpClient->getStreamprovidersbyID(['id' => $stream['id']]);
        $streamType = $streamObj['type'];
        $requestType = [
          'field_stream_provider_type_apiid' => $streamType['id'],
          'name' => $streamType['name'],
        ];
        $taxonomyStreamType = $getInfoObj->getTaxonomyByCriterioMultiple($requestType);
        if (empty($taxonomyStreamType)) {
          $obj = [
            'name' => $streamType['name'],
            'vid' => 'stream_provider',
            //'field_streamprovider_logo'=>'',
            //'field_streamprovider_logo_date'=>'',
            'field_stream_provider_api_id' => '',
            'field_stream_provider_type_apiid' => $streamType['id'],
            'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
              'vid' => 'jsonld_',
              'name' => 'Streams',
            ]))->id(),
          ];
          $this->createGenericTaxonomy($obj);
          $parent = $getInfoObj->getTaxonomyByCriterioMultiple($requestType);
        }
        $requestStream = [
          'field_stream_provider_api_id' => $streamObj['id'],
          'name' => $streamObj['name'],
        ];
        $taxonomyStream = $getInfoObj->getTaxonomyByCriterioMultiple($requestStream);
        if (empty($taxonomyStream)) {
          $parent = $getInfoObj->getTaxonomyByCriterioMultiple($requestType);
          $data = $getInfoObj->getClearUrl(strtolower($streamObj['name']));
          //   $alias = $getInfoObj->getMultiplesAlias($data);
          $obj = [
            'name' => $streamObj['name'],
            'vid' => 'stream_provider',
            'parent' => $parent,
            'field_stream_provider_api_id' => $streamObj['id'],
            'field_stream_provider_type_apiid' => $streamType['id'],
            'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
              'vid' => 'jsonld_',
              'name' => 'Streams',
            ]))->id(),
            //  'path' => '/'.$data,
          ];
          $taxonomystream = $this->createGenericTaxonomy($obj, FALSE);
          $taxonomystreamId = $taxonomystream->id();
          $tags_array [] = ['target_id' => $taxonomystreamId];
        }
      }
      else {
        $tags_array [] = ['target_id' => $actualStream->id()];
      }
    }
    return $tags_array;
  }

  /**
   * function createGenericTaxonomy ( )
   * - $obj (array of fields an data)
   * $obj = [
   * 'parent' => [],
   * 'name' => $name,
   * 'vid' => $voc,
   * 'field_participant_api_id' => $idApi,
   * ]
   * return an object or an array if $reset is true
   */
  public function createGenericTaxonomy($obj, $reset = TRUE) {
    $term = Term::create($obj);
    $term->save();
    if ($reset) {
      $term = reset($term);
    }
    return $term;
  }

  /**
   * function createStreamPages ()
   * - $competition - Array  from Steve API
   *   competition: {
   * id: 153,
   * meta: [ {channel: 1},
   * {channel: 2},
   * {channel: 3},
   * {channel: 4}
   * ]
   *              }
   *
   *
   * - $sport_tags - Taxonomy ID to sport  (Example. 2145)
   * - $sportName - Sport name (Example. Tennis )
   */
  public function createTournamentPages($competition, $sport_tags, $sportName, $langId) {
    $getInfoObj = new RepoGeneralGetInfo();
    $taxonomyCompetition = $getInfoObj->getTaxonomyByCriterio($competition['id'], 'field_competition_id');
    if (empty($taxonomyCompetition)) {
      $rpClient = RPAPIClient::getClient();
      $parameters = [
        'id' => $competition['id'],
        'include_locales' => 1,
      ];
      $competition = $rpClient->getCompetitionsbyID($parameters);
      $taxonomy = new  taxonomySteveTimeZone();
      $sportName = $taxonomy->getLocaleName($competition["locales"], $langId);
      $competitionName = $sportName;
      $logo_path = $competition["logo"];
      $logo_modified = $competition["modified"];
      $locale = json_encode($competition["locales"]);
      $logo = $getInfoObj->getImg($logo_path, $getInfoObj->getClearUrl($competitionName . '_logo'));
      $competition_array[0] = $competition;
      $NewTax = $this->createTournametTaxonomy($competition_array, 'sport', $sport_tags, $sportName, $logo, $logo_modified, $locale);
      return $NewTax;
    }
    else {
      $node = $taxonomyCompetition->id();
      /* $updateObj = new UpdateClienetData();
       $updateObj->updateTournament($competition['id']);*/
    }
    return $node;

  }

  /**
   * function createTournametTaxonomy ( )
   * - $tournament (array from Steve API)
   * - $voc (vocavulary id)
   * - $sport_tags (name of item)
   * - $sport_id (sport taxonomy id)
   * - $logo (img id)
   * - $logo_modified (date of modified logo)
   * return taxonomy id
   */
  public function createTournametTaxonomy($tournament, $voc, $sport_tags, $sport_id, $logo, $logo_modified, $locale = []) {
    $getInfoObj = new RepoGeneralGetInfo();
    $tournamentId = $tournament[0]["id"];
    $tournamentName = $tournament[0]["name"];
    $tournamentParent = $tournament[0]["parent"];
    $tournamentSport = $tournament[0]["sport"];
    $taxonomy = $getInfoObj->getTaxonomyByAPIID($tournamentId);
    if (isset($taxonomy) or $taxonomy == FALSE) {
      if ($tournamentParent == NULL) {
        $data = $getInfoObj->getClearUrl(strtolower($tournamentName));
        $taxonomySport = $getInfoObj->getTaxonomyByAPIID('sport_' . 'sport_' . $tournamentSport);
        $obj = [
          'parent' => [$sport_tags],
          'name' => $tournamentName,
          'vid' => $voc,
          'field_api_id' => $tournamentId,
          'field_api_parent' => '',
          // 'field_sport_api_id' => $sport_id,
          'field_competition_id' => $tournamentId,
          'field_content' => '',
          'field_locales' => $locale,
          'field_logo' => $logo,
          'field_logo_date' => $logo_modified,
          'field_weight' => rand(1, 1000),
          'field_sport_api_id' => $taxonomySport->id(),
          'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
            'vid' => 'jsonld_',
            'name' => 'Leages',
          ]))->id(),

        ];
        $tournamentTaxonomy = $this->createGenericTaxonomy($obj, FALSE);
        return $tournamentTaxonomy->id();
      }
      else {
        $competition = $getInfoObj->getTaxonomyParent($tournament);
        $index = count($competition) - 2;
        if ($index < 0) {
          $index = 0;
        }
        for ($i = $index; $i >= 0; $i--) {
          $id = $competition[$i]["id"];
          $name = $competition[$i]["name"];
          $tournamentId = $competition[$i]["id"];
          $parent_id = $competition[$i]["parent"];
          $parent_locale = json_encode($competition[$i]["locales"]);
          $taxonomy = $getInfoObj->getTaxonomyByAPIID($id);
          if (empty($taxonomy) or $taxonomy == FALSE) {
            if ($parent_id != NULL) {
              $parentTaxonomyId = $competition[$i + 1]["id"];
              $parentTaxonomyId = $getInfoObj->getTaxonomyByAPIID($parentTaxonomyId);
              $parentTaxonomyId = $parentTaxonomyId->id();
              $obj = [
                'parent' => [$parentTaxonomyId],
                'name' => $name,
                'vid' => $voc,
                'field_api_id' => $tournamentId,
                'field_api_parent' => $parentTaxonomyId,
                'field_sport_api_id' => $sport_id,
                'field_competition_id' => $tournamentId,
                'field_content' => '',
                'field_logo' => $logo,
                'field_locales' => $parent_locale,
                'field_logo_date' => $logo_modified,
                'field_weight' => rand(1, 1000),
                'field_sport_api_id' => $sport_tags,
                'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
                  'vid' => 'jsonld_',
                  'name' => 'Leages',
                ]))->id(),

              ];
              $this->createGenericTaxonomy($obj);
            }
            else {
              $data = $getInfoObj->getClearUrl(strtolower($name));
              $obj = [
                'parent' => [$sport_tags],
                'name' => $name,
                'vid' => $voc,
                'field_api_id' => $tournamentId,
                'field_api_parent' => 'Sport id: ' . $sport_id,
                'field_sport_api_id' => $sport_id,
                'field_competition_id' => $tournamentId,
                'field_content' => '',
                'field_logo' => $logo,
                'field_locales' => $parent_locale,
                'field_weight' => rand(1, 1000),
                'field_logo_date' => $logo_modified,
                'field_sport_api_id' => $sport_tags,
                'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
                  'vid' => 'jsonld_',
                  'name' => 'Sport',
                ]))->id(),
              ];
              $this->createGenericTaxonomy($obj);
            }
          }
        }
      }
    }
    $tournamentID = $competition[0]["id"];
    $tournamentTaxonomy = $getInfoObj->getTaxonomyByAPIID($tournamentID);
    $id = $tournamentTaxonomy->id();
    print ' Creating Tournament Taxonomy - ' . $tournamentName . '  -  ' . $id . ' - at ' . date("h:i:s") . "\n";
    return $id;
  }

  /**
   * function createChannelsPages (Import all channels )
   *
   */
  public function createChannelsPages() {
    $rpClient = RPAPIClient::getClient();
    $AllChannel = $rpClient->getChannel();
    $getInfoObj = new RepoGeneralGetInfo();
    foreach ($AllChannel as $channel) {
      $oldChanel = $getInfoObj->getTaxonomyByCriterio($channel['id'], 'field_channel_api_id');
      if (empty($oldChanel)) {
        $newChanel = [
          'vid' => 'channels',
          'name' => $channel['name'],
          'field_channel_api_id' => $channel['id'],
          'field_channel_name' => $channel['name'],
          'field_channel_code' => $channel['name'],
          'field_channel_des' => $channel['description'],
          'field_channel_notes' => $channel['notes'],
        ];
        $this->createGenericTaxonomy($newChanel);
        print ' Creating node (Channels) "' . $channel['name'] . ' - at ' . date("h:i:s") . "\n";
      }
      /*  else {
          $nodeId = reset($oldChanel)->id();
          $updateObj = new UpdateClienetData();
          $updateObj->updateChanel($nodeId, $oldChanel);
        }*/
    }
    return TRUE;
  }

  /**
   * function createGamePage ( Create Events page on events content type)
   * - $sport_tags ( Sport Taxonomy id )
   * - $event (Array from Steve API)
   * - $stream (Stream Array Taxonomies ids  )
   * - $defautltText (text by default)
   * - $Tags_Team (Teams Array Taxonomies ids )
   * - $ChannelByNode (Channel Array Taxonomies ids )
   * - $region  ( Steve API region - Example. en_EG)
   */
  public function createGamePage($sport_tags = '', $event, $stream = '', $defautltText, $Tags_Team, $ChannelByNode = '', $region, $tournamentID) {
    $getInfoObj = new RepoGeneralGetInfo();
    $sport = $getInfoObj->getTaxonomyByAPIID($sport_tags);
    if (isset($event)) {
      $metaSportArray = $event['sport'];
      $metaCompetitionArray = $event['competition'];
      $metaEventArray = $event['meta'];
      $metaParticipantsArray = $event['participants'];
      $metaStreamproviderArray = $event['streamprovider'];
      $data[$region] = [
        "sport" => $metaSportArray,
        "competition" => $metaCompetitionArray,
        "event" => $metaEventArray,
        "participants" => $metaParticipantsArray,
        "streamers" => $metaStreamproviderArray,
      ];
      $properties = json_encode($data);
      $node = [
        'type' => 'events',
        'body' => [
          'value' => $defautltText,
          'summary' => $defautltText,
          'format ' => 'full_html',
        ],
        'field_event_channels' => $ChannelByNode,
        'field_event_date' => strtotime($event['start']),
        'field_event_api_id' => $event['id'],
        'field_event_participants' => $Tags_Team,
        'field_events_sport' => $sport->id(),
        'field_events_properties' => $properties,
        'field_event_stream_provider' => $stream,
        'field_event_tournament' => $tournamentID,
        'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
          'vid' => 'jsonld_',
          'name' => 'Events',
        ]))->id(),
        'title' => $event['name'],
      ];
      $node = $this->createNodeGeneric($node);
    }
    print ' Creating Game Page   - ' . $event['name'] . "\n";
    print ' Event API ID         - ' . $event['id'] . "\n";
    print "\n";
    return $node;
  }

  /**
   * function createParticipantPages ( )
   * - $partArray ( Participants array from Steve - API )
   *    participants: [{
   * id: 687,
   * meta: [
   * {channel: 1},
   * {channel: 2},
   * {channel: 3},
   * {channel: 4}
   * ],
   * name: "Trelleborgs FF",
   * running_order: 2
   * },{
   * id: 864,
   * meta: [
   * {channel: 1},
   * {channel: 2},
   * {channel: 3},
   * {channel: 4}
   * ],
   * name: "Örgryte IS",
   * running_order: 1
   * }
   * ]
   * -  $sport_tags ( Sport Taxonomy id )
   */
  public function createParticipantPages($partArray, $sport_tags, $langId) {

    $tags_team_array = [];
    $getInfoObj = new RepoGeneralGetInfo();
    foreach ($partArray as $team) {
      $id = $team['id'];
      $opc = 'field_participant_api_id';
      //$taxonomyCompetition = $getInfoObj->getTaxonomyByCriterio($id, $opc);
      $tParticipan = new  taxonomyParticipan();
      $taxonomyCompetition = $tParticipan->getTaxonomyByOBj([
        'vid' => 'sport','field_participant_api_id' => $id,
      ], 1);
      if (empty($taxonomyCompetition)) {
        $parameters = ['id' => $team ['id'], 'include_locales' => 1];
        $rpClient = RPAPIClient::getClient();
        $Participants = $rpClient->getParticipantsbyID($parameters);
        $logo_path = $Participants["logo"];
        $logo_modified = $Participants["modified"];
        $locales = json_encode($Participants["locales"]);
        $taxonomy = new  taxonomySteveTimeZone();
        $name = $taxonomy->getLocaleName($Participants["locales"], $langId);
        $logo = $getInfoObj->getImg($logo_path, $getInfoObj->getClearUrl($name . '_logo'), 'team');
        $obj = [
          'parent' => [],
          'name' => $name == null ? $Participants["name"]:$name ,
          'vid' => 'participant',
          'field_participant_api_id' => $team ['id'],
          'field_participant_content' => '',
          'field_participant_logo' => $logo,
          'field_participant_logo_date' => $logo_modified,
          'field_participant_sport' => $sport_tags,
          'field_locales' => $locales,
          'field_weight' => rand(1, 1000),
          'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
            'vid' => 'jsonld_',
            'name' => 'Participants',
          ]))->id(),
        ];
        $this->createGenericTaxonomy($obj);
        $taxonomyCompetition = $getInfoObj->getTaxonomyByCriterio($id, $opc);
        $team_tax = $taxonomyCompetition->id();
        print ' Creating Participant - ' . $name . "\n";
      }
      else {
        $team_tax = $taxonomyCompetition->id();
      }
        $tags_team_array [] = ['target_id' => $team_tax];
    }
    return $tags_team_array;
  }

  /**
   * function createMeta ( )
   * - $event (Event Array from Steve API)
   */
  public function createMeta($event) {

    //General Variable
    $eventID = $event['id'];
    $eventName = $event['id'] . '/' . $event['name'];
    $eventName = substr($eventName, 0, 25);
    // Sport Variable
    $metaSportArray = $event['sport'];
    $metaCompetitionArray = $event['competition'];
    $metaEventArray = $event['meta'];
    $metaParticipantsArray = $event['participants'];
    $metaStreamproviderArray = $event['streamprovider'];
    $data = [
      "sport" => $metaSportArray,
      "competition" => $metaCompetitionArray,
      "event" => $metaEventArray,
      "participants" => $metaParticipantsArray,
      "streamers" => $metaStreamproviderArray,
    ];
    $this->createSimpleMeta($eventName, $eventID, $data);
    print "\n Insert Metas";
    //---------------------------------------------------------------------------------------------------------------------------------//
    return TRUE;
  }

  //---------------------------------------------------------- ENTITY "META" CREATION ----------------------------

  /**
   * function createParticipantTaxonomy ( )
   * - $name (name of item)
   * - $voc (vocavulary id)
   * - $idApi (Participant API id)
   * return taxonomy id
   */
  public function createParticipantTaxonomy($name, $voc, $idApi, $locale) {
    $getInfoObj = new RepoGeneralGetInfo();
    $taxonomy = $getInfoObj->getTaxonomyByParticipantAPIID($idApi);

    if (!$taxonomy or empty($taxonomy)) {
      $term = Term::create([
        'parent' => [],
        'name' => $name,
        'vid' => $voc,
        'field_locales' => $locale,
        'field_participant_api_id' => $idApi,
        'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
          'vid' => 'jsonld_',
          'name' => 'Participants',
        ]))->id(),
      ]);
      $term->save();
      $taxonomy = $getInfoObj->getTaxonomyByParticipantAPIID($idApi);
    }
    print ' Creating Participant Taxonomy -' . $name . ' - at ' . date("h:i:s") . "\n";
    return $taxonomy->id();

  }

  /**
   * function createParticipantPages ( )
   * - $partArray ( Participants array from Steve - API )
   *    participants: [{
   * id: 687,
   * meta: [
   * {channel: 1},
   * {channel: 2},
   * {channel: 3},
   * {channel: 4}
   * ],
   * name: "Trelleborgs FF",
   * running_order: 2
   * },{
   * id: 864,
   * meta: [
   * {channel: 1},
   * {channel: 2},
   * {channel: 3},
   * {channel: 4}
   * ],
   * name: "Örgryte IS",
   * running_order: 1
   * }
   * ]
   * -  $sport_tags ( Sport Taxonomy id )
   *
   * public function createParticipantPages($partArray, $sport_tags)
   * {
   * $tags_team_array = [];
   * $getInfoObj = new RepoGeneralGetInfo();
   * foreach ($partArray as $team) {
   * $id = $team['id'];
   * $name = $team['name'];
   * $opc = 'field_participant_api_id';
   * $taxonomyCompetition = $getInfoObj->getTaxonomyByCriterio($id, $opc);
   * if (empty($taxonomyCompetition)) {
   * $parameters = ['id' => $team ['id'], 'include_locales' => 1];
   * $rpClient = RPAPIClient::getClient();
   * $Participants = $rpClient->getParticipantsbyID($parameters);
   * $logo_path = $Participants["logo"];
   * $logo_modified = $Participants["modified"];
   * $locales = json_encode($Participants["locales"]);
   * $logo = $getInfoObj->getImg($logo_path, $getInfoObj->getClearUrl($name .
   * '_logo'), 'team');
   * $data = $getInfoObj->getClearUrl(strtolower($name));
   * $alias = $getInfoObj->getMultiplesAlias($data);
   * $obj = [
   * 'parent' => [],
   * 'name' => $name,
   * 'vid' => 'participant',
   * 'field_participant_api_id' => $team ['id'],
   * 'field_participant_content' => '',
   * 'field_participant_logo' => $logo,
   * 'field_participant_logo_date' => $logo_modified,
   * 'field_participant_sport' => $sport_tags,
   * 'field_locales' => $locales,
   * 'field_weight' => rand(1, 500),
   * 'field_jsonld_struct' =>
   * ($getInfoObj->getTaxonomyByCriterioMultiple(array('vid' => 'jsonld_',
   * 'name' => 'Participants')))->id(),
   * ];
   * $this->createGenericTaxonomy($obj);
   * $taxonomyCompetition = $getInfoObj->getTaxonomyByCriterio($id, $opc);
   * $team_tax = $taxonomyCompetition->id();
   * print ' Creating Participant - ' . $team ['name'] . '- at ' .
   * date("h:i:s") . "\n";
   * } else {
   * $team_tax = $taxonomyCompetition->id();
   *
   * }
   * $tags_team_array [] = ['target_id' => $team_tax];
   *
   *
   * return $tags_team_array;
   * }
   * }
   *
   *
   * /**
   * function createChannelsPages ( )
   *
   *
   * public function createSimpleMeta($eventName, $eventID, $data) {
   *
   * $data = [
   * 'name' => $eventName,
   * 'field_events_apiid' => $eventID,
   * 'field_properties' => json_encode($data),
   * ];
   * $node = \Drupal::entityTypeManager()
   * ->getStorage('channels_by_contenttype')
   * ->create($data);
   * $node->save();
   * }
   * /**
   * function createChannelsPages ( )
   *
   *
   * public function createMultipleMeta($eventID, $metaDescriptionArray,
   * $metaName, $nodeGPID, $token) { foreach ($metaDescriptionArray as
   * $metaArray) { foreach ($metaArray["meta"] as $array) {
   * $data = [
   * 'name' => $metaName . $metaArray['id'] . ' - channel/' .
   * $array['channel'],
   * 'field_cannel_apiid' => $array['channel'],
   * 'field_order_priority' => $metaArray['running_order'],
   * 'field_events_apiid' => $eventID,
   * 'field_meta_type_event_sport_part' => $metaName,
   * 'field_meta_type_api_id_event_id' => $metaArray['id'],
   * 'field_properties' => json_encode($array['properties']),
   * 'field_game_page_taxonomy' => $nodeGPID,
   * 'field_token' => $token,
   * ];
   * $node = \Drupal::entityTypeManager()
   * ->getStorage('channels_by_contenttype')
   * ->create($data);
   * $node->save();
   * }
   * }
   * }
   */

  //-------------------------------------------------------- TAXONOMY CREATION ----------------------------

  /**
   * function createVocabulary
   *
   */
  public function createVocabulary() {
    $vocabularys = ['sport', 'stream_provider', 'participant', 'tournament'];
    foreach ($vocabularys as $vocal) {
      $vocabulary = \Drupal\taxonomy\Entity\Vocabulary::create([
        'vid' => $vocal,
        'description' => '',
        'name' => $vocal,
      ]);
      print ' Creating Vocabulary -' . $vocal . ' - at ' . date("h:i:s") . "\n";
      $vocabulary->save();
    }
    return TRUE;
  }

  /**
   * function createChannelsPages ( )
   *
   */
  public function createSportPages_multiplesMenu($sport_id) {
    $rpClient = RPAPIClient::getClient();
    $para = ['id' => $sport_id];
    $getInfoObj = new RepoGeneralGetInfo();
    $node_id = $getInfoObj->getNode($sport_id, 'sport_pages', 'field_sport_api_id');
    if (empty($node_id)) {
      $competition = $rpClient->getSportbyID($para);
      $name = $competition["name"];
      $id_api = $competition["id"];
      $node = [
        'type' => 'sport_pages',
        'title' => $name,
        'field_sport_name' => $name,
        'field_sport_api_id' => $id_api,
        'field_sport_theme_descrption' => $getInfoObj->getDefaultSportPage($name),
        'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
          'vid' => 'jsonld_',
          'name' => 'Site',
        ]))->id(),
        'body' => [
          'value' => $getInfoObj->getDefaultSportPage($name),
          'summary' => 'Live stream ' . $name . ' | Online ' . $name . ' i dag ',
          'format ' => 'full_html',
        ],
      ];
      $new_node = $this->createNodeGeneric($node);

      $menu_name = [
        'TopSportMenu',
        'FrontTopSportMenu',
        'FrontButtomSportMenu',
      ];
      $description = [
        'General Top Sport Menu',
        'Front Page Top Sport Menu',
        'Front Page Buttom Sport Menu',
      ];

      $term = $this->createTaxonomy($name, 'sport');
      $sport_tags = $term->id();
      $this->createMenu($menu_name, $description, $new_node, $name);
      $this->createSportPages($sport_id);
      print ' Creating Sport Pages -' . $name . '- at ' . date("h:i:s") . "\n";
    }
    else {
      $competition = $rpClient->getSportbyID($para);
      $name_sport = $competition["name"];
      $term = $getInfoObj->getTaxonomy($name_sport);
      $sport_tags = reset($term)->id();
      print 'Get Sport Pages Taxonomy-' . $name_sport . '- at ' . date("h:i:s") . "\n";
    }
    return $sport_tags;
  }

  /**
   * function createTaxonomy ( )
   * - $name (name of item)
   * - $voc (vocavulary id)
   * return an array
   */
  public function createTaxonomy($name, $voc) {
    $getInfoObj = new RepoGeneralGetInfo();
    $taxonomy = $getInfoObj->getTaxonomy($name);
    if (!$taxonomy) {
      $term = Term::create([
        'parent' => [],
        'name' => $name,
        'vid' => $voc,
      ]);
      $term->save();
      $taxonomy = $getInfoObj->getTaxonomy($name);
    }
    // print_r( ' Creating Taxonomy -' . $name . ' - at ' . date("h:i:s") . "\n");
    $term = reset($taxonomy);
    return $term;

  }

  /**
   * function createChannelsPages ( )
   *
   */
  public function createMenu($menu_name, $description, $node, $sport) {
    for ($i = 0; $i < count($menu_name); $i++) {
      $menuid = $menu_name[$i] . '_id';
      $id_node = \Drupal::entityTypeManager()
        ->getStorage('menu')
        ->loadByProperties(['id' => $menuid]);
      if (!$id_node) {
        $menu = \Drupal::entityTypeManager()->getStorage('menu')
          ->create([
            'id' => $menuid,
            'label' => $menu_name[$i],
            'menu_name' => $menu_name[$i],
            'description' => $description[$i],
          ])->save();
        print " Creating Menu $menu_name[$i]" . ' - at ' . date("h:i:s") . "\n";
      }

      $menu_link = \Drupal::entityTypeManager()
        ->getStorage('menu_link_content')
        ->loadByProperties(['menu_name' => $menuid, 'title' => $sport]);

      if (empty($menu_link)) {
        $menu_link = MenuLinkContent::create([
          'title' => $sport,
          'link' => ['uri' => 'internal:/node/' . $node],
          'menu_name' => $menuid,
          'expanded' => TRUE,
        ])->save();
        print " Creating menu item $sport on Menu $menu_name[$i]" . ' - at ' . date("h:i:s") . "\n";
      }
    }
    return TRUE;
  }

  /**
   * Funtion createSportPages ( create a Taxonomy,sport pagas to a specify
   * sport )
   * - $sportDrupalId (drupal specify id for sports - Example. sport_1 )
   * - $sportApiId ( Steve API Sport id -  Example. 1 )
   * - $region ( Steve API region - Example. en_EG)
   */
  public function createSportPages($array) {
    $sportName = $array["sportName"];
    $taxonomySportId = $array["taxonomySportId"];
    $region = $array["region"];
    $json = $array["json"];
    $sportDrupalId= $array["sportDrupalId"];
      $node = [
        'type' => 'sport',
        'title' => $sportName,
        'field_sport_sport' => $taxonomySportId,
        'field_sport_theme_properties' => '',
        'langcode' => $region,
        'field_jsonld_struct' =>  $json,
        'body' => [
          'value' => '',
          'summary' => '',
          'format ' => 'full_html',
        ],
      ];
      print 'Creating Sport Pages -' . $sportName . ' - at ' . date("h:i:s") . "\n";
      $newNode = $this->createNodeGeneric($node);
      $this->createItemMenu('main', '', $newNode, $sportName, $taxonomySportId, $sportDrupalId, $region);

   // }
    /*else {
            $updateOBJ = new UpdateClienetData();
            $competitionName = $TaxonomyObj->name->value;
            $taxonomySportId = $TaxonomyObj->id();
            $sportNode = reset($getInfoObj->getNode($taxonomySportId, 'sport', 'field_sport_sport'));
            $updateOBJ->createTranslation($sportNode, $region, [], '/' . $region . '/' . $sportNode->getTitle());

            $sportNode = reset($getInfoObj->getNode($taxonomySportId, 'sport_blogs', 'field_sport_blogs_sport'));
            $updateOBJ->createTranslation($sportNode, $region, [], '/' . $region . '/' . $sportNode->getTitle());

            $sportNode = reset($getInfoObj->getNode($taxonomySportId, 'sport_stream_reviews', 'field_sport_stream_reviews_sport'));
            $updateOBJ->createTranslation($sportNode, $region, [], '/' . $region . '/' . $sportNode->getTitle());

            print "\n";
            print ' Using Sport - ' . $competitionName . ' ( ' . $region . ' ) - at ' . date("h:i:s") . "\n";
        }*/
    return $taxonomySportId;
  }

  /**
   * function createChannelsPages ( )
   *
   */
  public function defaultTournamentTaxonomy($parentId, $name, $voc, $tournamentId, $tournamentParents, $sport_id, $jsonld = 'Leages', $color, $locales = []) {
    $getInfoObj = new RepoGeneralGetInfo();
    $taxonomy = $getInfoObj->getTaxonomyByCriterioMultiple(['vid' => 'sport','field_api_id'=>$tournamentId]);
    if ($taxonomy == FALSE) {
      if ($voc = 'sport') {
        $term = Term::create([
          'parent' => [$parentId],
          'name' => $name,
          'vid' => $voc,
          'field_api_id' => $tournamentId,
          'field_api_parent' => $tournamentParents,
          'field_sport_api_id' => $sport_id,
          'field_base_color' => $color,
          'field_locales' => $locales,
          'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
            'vid' => 'jsonld_',
            'name' => $jsonld,
          ]))->id(),
        ]);
      }
      else {
        $term = Term::create([
          'parent' => [$parentId],
          'name' => $name,
          'vid' => $voc,
          'field_api_id' => $tournamentId,
          'field_api_parent' => $tournamentParents,
          'field_sport_api_id' => $sport_id,
          'field_base_color' => $color,
          'field_base_color' => $color,
          'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
            'vid' => 'jsonld_',
            'name' => $jsonld,
          ]))->id(),
        ]);
      }

      $term->save();
      print ' Creating Taxonomy -' . $name . ' - at ' . date("h:i:s") . "\n";
      print ' Creating Tournament Taxonomy -' . $name . ' - at ' . date("h:i:s") . "\n";
      $taxonomy = $getInfoObj->getTaxonomyByAPIID($tournamentId);
    }
    return $taxonomy->id();

  }

  public function createJsonLdTaxonomy($voc = 'jsonld_', $data = [
    'Events',
    'Leages',
    'Participants',
    'Personal',
    'Place',
    'Site',
    'Streams',
    'Sport',
    'Reviews',
    'Blog',
  ]) {
    foreach ($data as $tName) {
      $this->createTaxonomy($tName, $voc);
    }
    return TRUE;
  }

  //-------------------------------------------------------- Generic CREATION ----------------------------

  /**
   * function createChannelsPages ( )
   *
   */
  public function createItemMenu($menu_name, $description, $nodeId, $sport, $sport_tags, $sport_id, $region) {

    /*---------- new menu----------- */
    $id_node = \Drupal::entityTypeManager()->getStorage('menu')->loadByProperties(['id' => $menu_name]);
    if (!$id_node) {
      $menu = \Drupal::entityTypeManager()->getStorage('menu')->create([
        'id' => $menu_name,
        'label' => $menu_name,
        'menu_name' => $menu_name,
        'description' => $description,
      ])->save();
      print " Creating Menu $menu_name" . ' - at ' . date("h:i:s") . "\n";
    }
   /*--------------------- */

    $menu_link = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(['menu_name' => $menu_name, 'title' => $sport]);
    if (empty($menu_link)) {
       MenuLinkContent::create([
        'title' => $sport,
        'link' => ['uri' => 'internal:/node/' . $nodeId],
        'description' => $sport_tags,
        'menu_name' => $menu_name,
        'parent' => 'null',
        'expanded' => TRUE,
      ])->save();

      $menu_link_SportObj = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(['description' => $sport_tags]);
      $uuid = reset($menu_link_SportObj)->uuid->value;

      if ($uuid) {
        $menuID = 'main';
        $forside = $sport . ' Forside';
        $this->createGenericItemMenu($menuID, $forside, $nodeId, $uuid, -99);

        $LiveStream = 'Live Stream ' . $sport;
        $url = 'Live Stream ' . $sport;
        $id = 'liveStream';
        $LiveStream_id = $this->createSportInternPages($sport_tags, $sport, $LiveStream, $id, $url, $sport_id, 'sport_stream_reviews', $region);
        $this->createGenericItemMenu($menuID, $LiveStream, $LiveStream_id, $uuid, -98);

        $Blog = 'Blog ' . $sport;
        $url = 'Blog';
        $id = 'blog';
        $Blog_id = $this->createSportInternBlog($sport_tags, $sport, $Blog, $id, $url, $sport_id, 'sport_blogs', $region);
        $this->createGenericItemMenu($menuID, $Blog, $Blog_id, $uuid, -97);
      }
      print " Creating menuitem $sport on Menu $menu_name" . ' - at ' . date("h:i:s") . "\n";
    }
    return TRUE;
  }

  /**
   * function createChannelsPages ( )
   *
   */
  public function createGenericItemMenu($menuID, $title, $nodeID, $parent, $weight) {
    MenuLinkContent::create([
      'title' => $title,
      'link' => ['uri' => 'internal:/node/' . $nodeID],
      'menu_name' => $menuID,
      'expanded' => TRUE,
      'parent' => 'menu_link_content:' . $parent,
      'weight' => $weight,
    ])->save();
    print " Creating menu item '. $title . ' on Menu" . ' - at ' . date("h:i:s") . "\n";
    return TRUE;
  }

  /**
   * function createSportInternPages ()
   * - $sportTags - Taxonomy ID to sport  (Example. 2145)
   * - $sportName - Sport name (Example. Tennis )
   * - $PageTitle - Page Title (Example. Live Stream Tennis)
   * - $id - Page id (Example. Live Stream)
   * - $url - Page last part alias url (Example. Tennis )
   * - $sportApiId - sport id  (Example. 5)
   * - $type - content type. (Example.sport_blogs)
   * - $region -  ( Steve API region - Example. en_EG)
   */

  public function createSportInternPages($sportTags, $sportName, $PageTitle, $id, $url, $sportApiId, $type, $region) {
    if ($type) {
      $getInfoObj = new RepoGeneralGetInfo();
      $Aliasdata = $region . '/' . $getInfoObj->getClearUrl($sportName) . '/' . $getInfoObj->getClearUrl($url);
      //  $alias = $getInfoObj->getMultiplesAlias($Aliasdata);
      $createStreamPages = [
        'type' => $type,
        'title' => $PageTitle,
        'field_sport_stream_reviews_sport' => $sportTags,
        'field_sport_review_properties' => '',
        'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
          'vid' => 'jsonld_',
          'name' => 'Reviews',
        ]))->id(),
        'body' => [
          'value' => '',
          'summary' => '',
          'format ' => 'full_html',
        ],
        //'path' => '/'.$getInfoObj->getClearUrl($PageTitle),
      ];
      $id = $this->createNodeGeneric($createStreamPages);
      print ' Creating Sport Intern Pages - ' . $PageTitle . ' - at ' . date("h:i:s") . "\n";
    }
    return $id;

  }

  /**
   * function createNodeGeneric
   *
   */

  public function createNodeGeneric($data) {
    $node = Node::create($data);
    $node->save();
    return $node->id();
  }

  /**
   * function createSportInternPages ()
   * - $sportTags - Taxonomy ID to sport  (Example. 2145)
   * - $sportName - Sport name (Example. Tennis )
   * - $PageTitle - Page Title (Example. Live Stream Tennis)
   * - $id - Page id (Example. Live Stream)
   * - $url - Page last part alias url (Example. Tennis )
   * - $sportApiId - sport id  (Example. 5)
   * - $type - content type. (Example.sport_blogs)
   * - $region -  ( Steve API region - Example. en_EG)
   */

  public function createSportInternBlog($sportTags, $sportName, $name, $id, $url, $sportApiId, $type, $region) {
    $getInfoObj = new RepoGeneralGetInfo();
    if ($type) {
      $getInfoObj = new RepoGeneralGetInfo();
      $Aliasdata = $getInfoObj->getClearUrl($sportName) . '/' . $getInfoObj->getClearUrl($url);
      // $alias = $getInfoObj->getMultiplesAlias($Aliasdata);
      $createStreamPages = [
        'type' => $type,
        'title' => $name,
        'field_sport_blogs_sport' => $sportTags,
        'field_sport_theme_blog_propertie' => '',
        'field_jsonld_struct' => ($getInfoObj->getTaxonomyByCriterioMultiple([
          'vid' => 'jsonld_',
          'name' => 'Blog',
        ]))->id(),
        'body' => [
          'value' => '',
          'summary' => '',
          'format ' => 'full_html',
        ],
        // 'path' => '/'.$getInfoObj->getClearUrl($name),
      ];
      $id = $this->createNodeGeneric($createStreamPages);
      print ' Creating Sport Internal Blog Page - ' . $name . '- at ' . date("h:i:s") . "\n";
    }
    return $id;

  }

  /**
   * function createChannelsPages ( )
   *
   */
  public function CreateClientData() {
    return TRUE;
  }

}


text:
package com.cloudTop.starshare.bean;//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import com.cloudTop.starshare.utils.JsonUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class User {
    private String email;
    private String name;
    private String avatar;

    public String getEmail() {
        return this.email;
    }

    public String getName() {
        return this.name;
    }

    public String getAvatarUrl() {
        return this.avatar;
    }

    public User(String var1, String var2, String var3) {
        this.email = var1;
        this.name = var2;
        this.avatar = var3;
    }

    public static List fromJsonArray(JSONArray var0) {
        ArrayList var1 = new ArrayList();
        if(var0 == null) {
            return var1;
        } else {
            for(int var2 = 0; var2 < var0.length(); ++var2) {
                JSONObject var3 = var0.optJSONObject(var2);
                var1.add(fromJSONObject(var3));
            }

            return var1;
        }
    }

    public static User fromString(String var0) {
        try {
            return fromJSONObject(new JSONObject(var0));
        } catch (JSONException var2) {
            return new User("", "", "");
        }
    }

    public static User fromJSONObject(JSONObject var0) {
        if(var0 == null) {
            return new User("", "", "");
        } else {
            String var1 = var0.optString("email");
            String var2 = var0.optString("name");
            String var3 = var0.optString("avatar");
            return new User(var1, var2, var3);
        }
    }

    public JSONObject toJSONObject() {
        JSONObject var1 = new JSONObject();
        JsonUtils.safePut(var1, "email", this.email);
        JsonUtils.safePut(var1, "name", this.name);
        JsonUtils.safePut(var1, "avatar", this.avatar);
        return var1;
    }

    public static JSONArray toJson(List var0) {
        JSONArray var1 = new JSONArray();
        if(var0 != null) {
            Iterator var2 = var0.iterator();

            while(var2.hasNext()) {
                User var3 = (User)var2.next();
                JSONObject var4 = var3.toJSONObject();
                var1.put(var4);
            }
        }

        return var1;
    }

    public String toString() {
        return "User{email=\'" + this.email + '\'' + ", name=\'" + this.name + '\'' + ", avatar=\'" + this.avatar + '\'' + '}';
    }

    public boolean equals(Object var1) {
        if(this == var1) {
            return true;
        } else if(var1 != null && this.getClass() == var1.getClass()) {
            User var2;
            label45: {
                var2 = (User)var1;
                if(this.avatar != null) {
                    if(this.avatar.equals(var2.avatar)) {
                        break label45;
                    }
                } else if(var2.avatar == null) {
                    break label45;
                }

                return false;
            }

            label38: {
                if(this.email != null) {
                    if(this.email.equals(var2.email)) {
                        break label38;
                    }
                } else if(var2.email == null) {
                    break label38;
                }

                return false;
            }

            if(this.name != null) {
                if(!this.name.equals(var2.name)) {
                    return false;
                }
            } else if(var2.name != null) {
                return false;
            }

            return true;
        } else {
            return false;
        }
    }

    public int hashCode() {
        int var1 = this.email != null?this.email.hashCode():0;
        var1 = 31 * var1 + (this.name != null?this.name.hashCode():0);
        var1 = 31 * var1 + (this.avatar != null?this.avatar.hashCode():0);
        return var1;
    }
}


text:
require "tasks_visitors/inject_strings"

class WorkflowSerializer
  include Serialization::PanoptesRestpack
  include FilterHasMany
  include MediaLinksSerializer
  include CachedSerializer

  attributes :id, :display_name, :tasks, :steps, :classifications_count, :subjects_count,
             :created_at, :updated_at, :finished_at, :first_task, :primary_language,
             :version, :content_language, :prioritized, :grouped, :pairwise,
             :retirement, :retired_set_member_subjects_count, :href, :active, :mobile_friendly,
             :aggregation, :configuration, :public_gold_standard, :completeness

  can_include :project, :subject_sets, :tutorial_subject, :published_version

  media_include :attached_images, classifications_export: { include: false }

  can_filter_by :active, :mobile_friendly

  preload :subject_sets, :attached_images, :classifications_export, :published_version

  def self.paging_scope(params, scope, context)
    if params[:complete]
      # In Rails 5 convert to use ActiveModel::Type::Boolean.new.cast(value)
      complete_filter = ActiveRecord::Type::Boolean.new.type_cast_from_user(params[:complete])
      scope = if complete_filter
        scope.where(completeness: 1.0)
      else
        scope.where('completeness < 1.0')
      end
    end

    super(params, scope, context)
  end

  def version
    "#{@model.major_version}.#{content_version}"
  end

  def content_language
    @model.primary_language
  end

  def content_version
    @model.minor_version
  end

  def tasks
    TasksVisitors::InjectStrings.new(requested_version.strings).visit(requested_version.tasks)
    requested_version.tasks
  end

  def first_task
    requested_version.first_task
  end

  def requested_version
    if @context[:published]
      # The model itself is a valid duck type for a workflow version, since a
      # version is basically just a subset of a Workflow's columns.
      @model.published_version || @model
    else
      @model
    end
  end

  def retirement
    @model.retirement_with_defaults
  end
end


text:
class ResultLines < Array

	def intitialize(lines)
		lines.each do |line|
			self << line
		end
	end

	def cleanup
		self.compact.map(&:chomp!)
		self
	end

	def mark_result(options)
		result_index = options[:pre].to_i
		result_line = self[result_index]
		result_line.prepend '-> '
		self
	end

	def to_s
		self.join("\n ")
	end

end


text:
package com.ayranisthenewraki.heredot.herdot;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.ayranisthenewraki.heredot.herdot.model.Center;
import com.ayranisthenewraki.heredot.herdot.model.ShapeDetail;
import com.ayranisthenewraki.heredot.herdot.model.ShapeIdentifier;
import com.ayranisthenewraki.heredot.herdot.model.TimeLocationCouple;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.location.places.ui.SupportPlaceAutocompleteFragment;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    boolean putMarkerEnabled = false;
    boolean cirlceSelected = false;
    boolean cirlceAdded = false;
    LatLng selectedPoint;
    Double radius = 50.0;

    String timeLocationName = "";
    String timeText = "";
    String timeResolution = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);

        final Button markerToggle = (Button) findViewById(R.id.pinDropper);

        markerToggle.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(putMarkerEnabled){
                    putMarkerEnabled = false;
                    int image_resid = getApplicationContext().getResources().getIdentifier("pin", "drawable", getApplicationContext().getPackageName());
                    markerToggle.setBackgroundResource(image_resid);
                }
                else{
                    putMarkerEnabled = true;
                    int image_resid = getApplicationContext().getResources().getIdentifier("pin_selected", "drawable", getApplicationContext().getPackageName());
                    markerToggle.setBackgroundResource(image_resid);
                }

            }
        });

        final EditText nameInput = (EditText) findViewById(R.id.dateTimeName);
        final EditText timeInput = (EditText) findViewById(R.id.timeString);
        final Spinner timeResDropdown = (Spinner)findViewById(R.id.timeResSpinner);

        String[] timeItems = new String[]{"Century", "Decade", "Year", "Date"};
        ArrayAdapter<String> timeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, timeItems);
        timeResDropdown.setAdapter(timeAdapter);

        timeResDropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                if(timeResDropdown.getSelectedItemPosition()==0)
                    timeInput.setHint("19th");
                else if(timeResDropdown.getSelectedItemPosition()==1)
                    timeInput.setHint("1970s");
                else if(timeResDropdown.getSelectedItemPosition()==2)
                    timeInput.setHint("2015");
                else if(timeResDropdown.getSelectedItemPosition()==3)
                    timeInput.setHint("27/03/2016");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });

        final Button addTimeLocationButton = (Button) findViewById(R.id.addTimeLocationCouple);

        addTimeLocationButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){

                timeLocationName = nameInput.getText().toString();
                timeText = timeInput.getText().toString();
                timeResolution = timeResDropdown.getSelectedItem().toString();
                if(timeLocationName.length()==0 || timeText.length()==0){
                    android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(MapsActivity.this).create();
                    alertDialog.setTitle("Alert");
                    alertDialog.setMessage("Please fill all fields to continue");
                    alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    alertDialog.show();
                }
                else{
                    TimeLocationCouple tlc = new TimeLocationCouple();
                    tlc.setName(timeLocationName);
                    tlc.setTime(timeText);
                    tlc.setTimeType(timeResolution);
                    ShapeIdentifier shapeId = new ShapeIdentifier();
                    shapeId.setLng(selectedPoint.longitude);
                    shapeId.setLat(selectedPoint.latitude);
                    if(cirlceAdded){
                        shapeId.setType(0);
                        ShapeDetail shape = new ShapeDetail();
                        shape.setRadius(radius);
                        Center center = new Center();
                        center.setLat(selectedPoint.latitude);
                        center.setLng(selectedPoint.longitude);
                        shape.setCenter(center);
                        shapeId.setShape(shape);
                    }else{
                        shapeId.setType(1);
                    }
                    tlc.setShape(shapeId);

                    goBackToAddItemView(view, tlc);
                }

            }
        });

    }

    public void goBackToAddItemView(View view, TimeLocationCouple tlc) {
        Intent intent = new Intent();
        intent.putExtra("userToken", intent.getStringExtra("userToken"));
        Bundle bundle = new Bundle();
        bundle.putSerializable("timeLocation", tlc);
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void drawCircle(){

        // Instantiating CircleOptions to draw a circle around the marker
        CircleOptions circleOptions = new CircleOptions();

        // Specifying the center of the circle
        circleOptions.center(selectedPoint);

        // Radius of the circle
        circleOptions.radius(radius);

        // Border color of the circle
        circleOptions.strokeColor(Color.BLACK);

        // Fill color of the circle
        circleOptions.fillColor(0x30ff0000);

        // Border width of the circle
        circleOptions.strokeWidth(2);

        // Adding the circle to the GoogleMap
        mMap.addCircle(circleOptions);

    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

        // Add a marker in Sydney and move the camera
        selectedPoint = new LatLng(41.085, 29.046666666666667);
        mMap.addMarker(new MarkerOptions().position(selectedPoint).title("Selection"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(selectedPoint, 15));

        final Button circleTool = (Button) findViewById(R.id.circleTool);
        final Button increaseRadius = (Button) findViewById(R.id.increaseRadius);
        final Button decreaseRadius = (Button) findViewById(R.id.decreaseRadius);

        circleTool.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                if(cirlceSelected){
                    cirlceSelected = false;
                    int image_resid = getApplicationContext().getResources().getIdentifier("circle", "drawable", getApplicationContext().getPackageName());
                    circleTool.setBackgroundResource(image_resid);
                    increaseRadius.setVisibility(View.INVISIBLE);
                    decreaseRadius.setVisibility(View.INVISIBLE);
                }
                else{
                    cirlceSelected = true;
                    int image_resid = getApplicationContext().getResources().getIdentifier("circle_selected", "drawable", getApplicationContext().getPackageName());
                    circleTool.setBackgroundResource(image_resid);
                    if(!cirlceAdded){
                        radius = 50.0;
                        drawCircle();
                        cirlceAdded = true;
                    }
                    increaseRadius.setVisibility(View.VISIBLE);
                    decreaseRadius.setVisibility(View.VISIBLE);
                }
            }
        });

        increaseRadius.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(selectedPoint));
                radius += 10;
                drawCircle();
            }
        });

        decreaseRadius.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                mMap.clear();
                mMap.addMarker(new MarkerOptions().position(selectedPoint));
                if(radius>10){
                    radius -= 10;
                }
                else if(radius == 10){
                    radius = 0.0;
                    cirlceAdded = false;
                }
                drawCircle();
            }
        });

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {
                if(putMarkerEnabled){
                    mMap.clear();
                    selectedPoint = point;
                    cirlceAdded = false;
                    mMap.addMarker(new MarkerOptions().position(point));
                }
            }
        });

        SupportPlaceAutocompleteFragment autocompleteFragment = (SupportPlaceAutocompleteFragment)
                getSupportFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(Place place) {
                mMap.clear();
                selectedPoint = place.getLatLng();
                mMap.moveCamera(CameraUpdateFactory.newLatLng(selectedPoint));
                mMap.addMarker(new MarkerOptions().position(selectedPoint));
                EditText name = (EditText) findViewById(R.id.dateTimeName);
                name.setText(place.getName());
            }

            @Override
            public void onError(Status status) {
                // TODO: Handle the error.
                System.out.println("An error occurred: " + status);
            }
        });
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapsActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();

            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }
}


text:
/**
 *
 */
package cn.hcc.rc.boot.jar.base.endpoint;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by rocket.lo on 2017-05-04
 */
@RestController
//@RequestMapping("/base")
public class HeyJude {
    @RequestMapping("/hey")
    public String home() {
        return "Hey Jude! Lalalala...";
    }
}


text:
import Encoder from '../Encoder'

const meta = {
  name: 'rail-fence-cipher',
  title: 'Rail fence cipher',
  category: 'Ciphers',
  type: 'encoder'
}

/**
 * Encoder brick for Rail fence cipher encoding and decoding
 */
export default class RailFenceCipherEncoder extends Encoder {
  /**
   * Returns brick meta.
   * @return {object}
   */
  static getMeta () {
    return meta
  }

  /**
   * Constructor
   */
  constructor () {
    super()
    this.addSettings([
      {
        name: 'key',
        type: 'number',
        value: 2,
        integer: true,
        min: 2,
        max: 99,
        // Pick a random key between 2 and 8
        randomizeValue: random => random.nextInteger(2, 8)
      },
      {
        name: 'offset',
        type: 'number',
        value: 0,
        integer: true,
        min: 0,
        randomizable: false
      }
    ])
  }

  /**
   * Performs encode on given content.
   * @protected
   * @param {Chain} content
   * @return {number[]|string|Uint8Array|Chain} Encoded content
   */
  performEncode (content) {
    const { key: rows, offset } = this.getSettingValues()
    const length = content.getLength()

    // Cycle after which fence matrix repeats
    const cycle = rows * 2 - 2

    // Prepare an empty string for each row
    const fenceRows = new Array(rows).fill('')

    // X -->
    //   W     I     R     E     E
    // Y  E   D S   E E   E A   C
    // |   A E   C V   D L   T N
    // V    R     O     F     O
    let x, y

    // Go through plaintext characters
    for (x = 0; x < length; x++) {
      // Calculate at what y position the fence is for the current x position
      y = rows - 1 - Math.abs(cycle / 2 - (x + offset) % cycle)
      // Append the the current plaintext character to the respective fence row
      fenceRows[y] += content.getCharAt(x)
    }

    // Glue fence rows together
    return fenceRows.join('')
  }

  /**
   * Performs decode on given content.
   * @protected
   * @param {Chain} content
   * @return {number[]|string|Uint8Array|Chain} Decoded content
   */
  performDecode (content) {
    const { key: rows, offset } = this.getSettingValues()
    const length = content.getLength()

    // Cycle after which fence matrix repeats
    const cycle = rows * 2 - 2

    // Create result array of code points
    const result = new Array(length)

    let j = -1
    let x, y

    // Go through virtual matrix rows (y) and cols (x)
    for (y = 0; y < rows; y++) {
      for (x = 0; x < length; x++) {
        // Check if the current x-y-position is situated on the zigzag fence
        if ((y + x + offset) % cycle === 0 || (y - x - offset) % cycle === 0) {
          // Set result for the current x-position
          result[x] = content.getCodePointAt(++j)
        }
      }
    }

    return result
  }
}


text:
package p;

public class BaseImpl implements Base {
  static class Inner implements Inner { }
}


text:
class Transform;

class RigidAnimationKeyFrame : public AnimationKeyFrame {
public:
	RigidAnimationKeyFrame();
	virtual ~RigidAnimationKeyFrame();

	void ResetKeyframeValues();

	inline glm::vec3 GetTranslation() const { return this->translation; }
	inline glm::quat GetRotation()    const { return this->orientationQuat; }
	inline glm::vec3 GetScaling()     const { return this->scaling; }

	void SetTranslation(glm::vec3 v);
	void SetRotation(glm::quat q);
	void SetScaling(glm::vec3 v);

	// @Override
	virtual void ApplyKeyFrameToTransform(Transform* transform) const;

private:
	void init();
	void destroy();

	glm::vec3 translation;
	glm::quat orientationQuat;
	glm::vec3 scaling;
};

#endif // RIGID_ANIMATION_KEY_FRAME_H


text:
package edu.cmu.lti.nlp.amr.ConceptInvoke
import edu.cmu.lti.nlp.amr._
import edu.cmu.lti.nlp.amr.Train._
import edu.cmu.lti.nlp.amr.BasicFeatureVector._

import java.lang.Math.abs
import java.lang.Math.log
import java.lang.Math.exp
import java.lang.Math.random
import java.lang.Math.floor
import java.lang.Math.min
import java.lang.Math.max
import scala.io.Source
import scala.util.matching.Regex
import scala.collection.mutable.Map
import scala.collection.mutable.Set
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import Double.{NegativeInfinity => minusInfty}

/*** Defined in package.scala ***
type PhraseConceptPair = (List[String], String, PhraseConceptFeatures)
********************************/

class Decoder1(featureNames: List[String],
               phraseConceptPairs: Array[PhraseConceptPair],
               useNER: Boolean = true)
    extends Decoder(featureNames) {
    // Base class has defined:
    // val features: Features

    val conceptInvoker = new Concepts(phraseConceptPairs)

    def decode(input: Input) : DecoderResult = {
        logger(1, "\n--- Decoder1 ---\n")
        logger(1, "Sentence: "+input.sentence.mkString(" "))
        //logger(1, "Weights:\n"+features.weights.toString)
        val sentence = input.sentence
        val bestState : Array[Option[(Double, PhraseConceptPair, Int)]] = sentence.map(x => None)    // (score, concept, backpointer)
        for (i <- Range(0, sentence.size)) {
            logger(2, "word = "+sentence(i))
            var conceptList = conceptInvoker.invoke(input,i)
            logger(2, "Possible invoked concepts: "+conceptList)
            // WARNING: the code below assumes that anything in the conceptList will not extend beyond the end of the sentence (and it shouldn't based on the code in Concepts)
            for (concept <- conceptList) {
                val score = features.localScore(input, concept, i, i + concept.words.size)
                logger(1, "concept = "+concept.toString)
                val endpoint = i + concept.words.size - 1
                logger(2, "score = "+score.toInt)
                if ((bestState(endpoint) == None && score >= 0) || (bestState(endpoint) != None && bestState(endpoint).get._1 <= score)) { // we use <= so that earlier concepts (i.e. ones our conceptTable) have higher priority
                    logger(2, "adding concept:"+concept)
                    bestState(endpoint) = Some((score, concept, i))
                }
            }
        }

        logger(2, "Chart = " + bestState.toList)

        // Follow backpointers
        var graph = Graph.Null
        var score = 0.0
        val feats = new FeatureVector()
        var i = bestState.size - 1
        graph.getNodeById.clear
        graph.getNodeByName.clear
        while (i >= 0) {
            if (bestState(i) != None) {
                val (localScore, concept, backpointer) = bestState(i).get
                logger(2, "Adding concept: "+concept.graphFrag)
                graph.addSpan(sentence, backpointer, i+1, concept.graphFrag)
                for (c <- conceptInvoker.invoke(input,i).filter(x => x.words == concept.words && x.graphFrag == concept.graphFrag)) { // add features for all matching phraseConceptPairs (this is what the Oracle decoder does, so we do the same here)
                    val f = features.localFeatures(input, c, i, i + concept.words.size)
                    feats += f
                    score += features.weights.dot(f)
                    logger(1, "\nphraseConceptPair: "+concept.toString)
                    logger(1, "feats:\n"+f.toString)
                    logger(1, "score:\n"+score.toString)
                }
                //feats += features.localFeatures(input, concept)
                //score += localScore
                i = backpointer
            }
            i -= 1
        }
        if (graph.getNodeById.size == 0) {  // no invoked concepts
            graph = Graph.AMREmpty
        }
        logger(1, "Decoder1 Spans:")
        for ((span, i) <- graph.spans.sortBy(x => x.words.toLowerCase).zipWithIndex) {
            logger(1, "Span "+(i+1).toString+":  "+span.words+" => "+span.amr)
        }
        logger(1, "Decoder1 feats:\n"+feats.toString)
        return DecoderResult(graph, feats, score)
    }

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using Stations.Models;
using Stations.Models.Enums;

namespace Stations.DataProcessor.Dto.Import
{
    public class TripDto
    {
        [Required]
        public string Train { get; set; }

        [Required]
        public string OriginStation { get; set; }

        [Required]
        public string DestinationStation { get; set; }

        [Required]
        public string DepartureTime { get; set; }

        [Required]
        public string ArrivalTime { get; set; }

        public string Status { get; set; } = "OnTime";

        public string TimeDifference { get; set; }

    }
}


text:
package org.projectomakase.omakase.jcr.query;

/**
 * Default {@link SQL2QueryBuilder} implementation. All of the search conditions are be applied to the specified node type.
 *
 * @author Richard Lucas
 */
public class DefaultSQL2QueryBuilder extends AbstractSQL2QueryBuilder {

    private static final String SELECT_CLAUSE = "SELECT node.* FROM [%s] AS node WHERE ISDESCENDANTNODE('%s')";

    private final String nodeType;
    private final String parentNodePath;

    public DefaultSQL2QueryBuilder(String nodeType, String parentNodePath) {
        this.nodeType = nodeType;
        this.parentNodePath = parentNodePath;
    }

    @Override
    public String build() {
        return build(String.format(SELECT_CLAUSE, nodeType, parentNodePath));
    }

}


text:
package net.openhft.chronicle.wire;

import net.openhft.chronicle.bytes.Bytes;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class Base40LongConverterTest extends WireTestCommon {
    @Test
    public void parse() {
        Base40LongConverter bic = Base40LongConverter.UPPER;
        for (String s : ",A,0,ZZ,99,ABCDEF,012345,ZZZZZZZZZZZZ,999999999999".split(",")) {
            assertEquals(s, bic.asString(bic.parse(s)));
        }
    }

    @Test
    public void parseLower() {
        Base40LongConverter bic = Base40LongConverter.LOWER;
        for (String s : ",a,0,zz,99,abcdef,012345,zzzzzzzzzzzz,999999999999".split(",")) {
            assertEquals(s, bic.asString(bic.parse(s)));
        }
    }

    @Test
    public void longConversion() {
        Sample sample = new Sample();
        sample.strategyId = Base40LongConverter.INSTANCE.parse("TEST");

        final String expectedToString = "!net.openhft.chronicle.wire.Base40LongConverterTest$Sample {\n" +
                "  strategyId: TEST\n" +
                "}\n";

        assertEquals(expectedToString, sample.toString());
    }

    private static class Sample extends SelfDescribingMarshallable {
        @LongConversion(Base40LongConverter.class)
        public long strategyId;
    }

    @Test
    public void allSafeCharsTextWire() {
        Wire wire = new TextWire(Bytes.allocateElasticOnHeap()).useTextDocuments();
        allSafeChars(wire);
    }

    @Test
    public void allSafeCharsYamlWire() {
        Wire wire = new YamlWire(Bytes.allocateElasticOnHeap()).useTextDocuments();
        allSafeChars(wire);
    }

    private void allSafeChars(Wire wire) {
        final LongConverter converter = Base40LongConverter.INSTANCE;
        for (long i = 0; i <= 40 * 40; i++) {
            wire.clear();
            wire.write("a").writeLong(converter, i);
            wire.write("b").sequence(i, (i2, v) -> {
                v.writeLong(converter, i2);
                v.writeLong(converter, i2);
            });
            assertEquals(wire.toString(),
                    i, wire.read("a").readLong(converter));
            wire.read("b").sequence(i, (i2, v) -> {
                assertEquals((long) i2, v.readLong(converter));
                assertEquals((long) i2, v.readLong(converter));
            });
        }
    }

}


text:
Install_pecl_phalcon() {
  if [ -e "${php_install_dir}/bin/phpize" ]; then
    pushd ${oneinstack_dir}/src > /dev/null
    PHP_detail_ver=$(${php_install_dir}/bin/php-config --version)
    PHP_main_ver=${PHP_detail_ver%.*}
    if [[ "${PHP_main_ver}" =~ ^5.[5-6]$|^7.[0-3]$ ]]; then
      phpExtensionDir=$(${php_install_dir}/bin/php-config --extension-dir)
      src_url=http://mirrors.linuxeye.com/oneinstack/src/cphalcon-${phalcon_ver}.tar.gz && Download_src
      tar xzf cphalcon-${phalcon_ver}.tar.gz
      pushd cphalcon-${phalcon_ver}/build > /dev/null
      echo "${CMSG}It may take a few minutes... ${CEND}"
      ./install --phpize ${php_install_dir}/bin/phpize --php-config ${php_install_dir}/bin/php-config --arch ${OS_BIT}bits
      popd > /dev/null
      if [ -f "${phpExtensionDir}/phalcon.so" ]; then
        echo 'extension=phalcon.so' > ${php_install_dir}/etc/php.d/04-phalcon.ini
        echo "${CSUCCESS}PHP phalcon module installed successfully! ${CEND}"
        rm -rf cphalcon-${phalcon_ver}
      else
        echo "${CFAILURE}PHP phalcon module install failed, Please contact the author! ${CEND}"
      fi
    else
      echo "${CWARNING}Your php ${PHP_detail_ver} does not support phalcon! ${CEND}";
    fi
    popd > /dev/null
  fi
}

Uninstall_pecl_phalcon() {
  if [ -e "${php_install_dir}/etc/php.d/04-phalcon.ini" ]; then
    rm -f ${php_install_dir}/etc/php.d/04-phalcon.ini
    echo; echo "${CMSG}PHP phalcon module uninstall completed${CEND}"
  else
    echo; echo "${CWARNING}PHP phalcon module does not exist! ${CEND}"
  fi
}


text:
var fs     = require('fs'),
    path   = require('path'),
    orm    = require('orm'),
    config = {
            host: 'localhost',
            database: 'myDatabase',
            user: null,
            password: null,
            protocol: 'mysql',
            socketPath: null,
            port: 3306,
            debug: false,
            pool: false,
            strdates: false,
            timezone: 'local'
        };

exports.register = function (plugin, options, next) {

    Object.keys(options).forEach(function(k) {
        if (config[k] !== undefined) {
            config[k] = options[k];
        }
    });

    var models = {};
        sequelize = new Sequelize(config.database, config.username, config.password, {
            dialect: config.dialect,
            port: config.port,
            host: config.host,
            logging: config.logging,
            native: config.native
        });

    orm.connect({
        host:       config.host,
        database:   config.database,
        user:       config.user,
        password:   config.password,
        protocol:   config.protocol,
        socketPath: config.socketPath,
        port:       config.port,
        query: {
            debug:    config.debug,
            pool:     config.pool,
            strdates: config.strdates,
            timezone: config.timezone
        }
    }, function(err, db) {
        if (!!err) {
            plugin.log(['hapi-orm', 'error'], 'Error connecting to database. ' + err);
            return next(err);
        }
        if (config.models) {
            config.models = path.resolve(config.models);
            fs.readdirSync(config.models).forEach(function(file) {
                if (file.toLowerCase() !== config.associationFile) {
                    var model = require(path.join(config.models, file));

                    models[model.name] =
                        db.define(model.name, model.model, model.options);
                }
            });
            /*if (fs.existsSync(path.join(config.models, config.associationFile))) {
                var associations = require(path.join(config.models, config.associationFile)),
                    assoc = null;

                for (var i = 0, length = associations.length; i < length; i ++) {
                    assoc = associations[i];
                    if (models[assoc.source] && models[assoc.target]) {
                        assoc.options = assoc.options || {};
                        if (assoc.options.through && assoc.options.through.model) {
                            assoc.options.through.model = models[assoc.options.through.model];
                        }

                        switch (assoc.type) {
                            case 'oneone':
                                models[assoc.source].hasOne(models[assoc.target], assoc.options);
                                models[assoc.target].belongsTo(models[assoc.source], assoc.options);
                                break;
                            case 'onemany':
                                models[assoc.source].hasMany(models[assoc.target], assoc.options);
                                models[assoc.target].belongsTo(models[assoc.source], assoc.options);
                                break;
                            case 'manymany':
                                models[assoc.source].hasMany(models[assoc.target], assoc.options);
                                models[assoc.target].hasMany(models[assoc.source], assoc.options);
                                break;
                        }
                    }
                }
            }*/
        }
        plugin.expose('db', db);
        plugin.expose('models', models);

        next();
    });
};

exports.register.attributes = {
    pkg: require('./package.json')
};


text:
namespace Microsoft.Azure.Management.EventGrid.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.EventGrid;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Represents an operation returned by the GetOperations request
    /// </summary>
    public partial class Operation
    {
        /// <summary>
        /// Initializes a new instance of the Operation class.
        /// </summary>
        public Operation()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the Operation class.
        /// </summary>
        /// <param name="name">Name of the operation</param>
        /// <param name="display">Display name of the operation</param>
        /// <param name="origin">Origin of the operation. Possible values
        /// include: 'User', 'System', 'UserAndSystem'</param>
        /// <param name="properties">Properties of the operation</param>
        public Operation(string name = default(string), OperationInfo display = default(OperationInfo), string origin = default(string), object properties = default(object))
        {
            Name = name;
            Display = display;
            Origin = origin;
            Properties = properties;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets name of the operation
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets display name of the operation
        /// </summary>
        [JsonProperty(PropertyName = "display")]
        public OperationInfo Display { get; set; }

        /// <summary>
        /// Gets or sets origin of the operation. Possible values include:
        /// 'User', 'System', 'UserAndSystem'
        /// </summary>
        [JsonProperty(PropertyName = "origin")]
        public string Origin { get; set; }

        /// <summary>
        /// Gets or sets properties of the operation
        /// </summary>
        [JsonProperty(PropertyName = "properties")]
        public object Properties { get; set; }

    }
}


text:
<?php

namespace Adldap\Models\Events;

class Deleting extends Event
{
    //
}


text:
***DEPRECATED*** please use [crystal-mysql](https://github.com/waterlink/crystal-mysql).

## Contributors

- [sdogruyol](https://github.com/sdogruyol) Sdogruyol - creator, maintainer


text:
<!--
Copyright (c) 2019 The Khronos Group Inc.
Use of this source code is governed by an MIT-style license that can be
found in the LICENSE.txt file.
-->

<!DOCTYPE html>
<html style="margin: 0; padding: 0;">
<head>
<meta charset="utf-8">
<title>Simple WebGL context</title>
<script src="../../../js/webgl-test-utils.js"> </script>
</head>
<body style="margin: 0; padding: 0; overflow: hidden;">
<canvas id="c" width="1680" height="1050" style="width: 256px; height: 256px;"> <!-- scaled to fit page better -->
<script id="vshader" type="x-shader/x-vertex">
attribute vec4 vPosition;
void main()
{
    gl_Position = vPosition;
}
</script>

<script id="fshader" type="x-shader/x-fragment">
void main()
{
    gl_FragColor = vec4(1.0,0.0,0.0,1.0);
}
</script>

<script>
"use strict";
var wtu = WebGLTestUtils;

var gl = wtu.create3DContext("c", { antialias: false });
var program = wtu.setupProgram(gl, ["vshader", "fshader"], ["vPosition"]);

var vertexObject = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0,0.75,0, -0.75,-0.75,0, 0.75,-0.75,0 ]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);

gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, 3);

if (parent) {
    window.glContext = gl;
    parent.postMessage("Ready", "*");
}
</script>
</body>
</html>


text:
package play.modules.search.store.extractors;

import play.db.jpa.Blob;

public interface TextExtractor {
    public boolean handles (String mime);
    public String extract (Blob blob);
}


text:
require 'rubygems'
require 'bundler/setup'
require 'interwetten'
require 'webmock/rspec'
require "nokogiri"
require 'active_support/core_ext/object/to_query'

Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.run_all_when_everything_filtered = true
  config.filter_run :focus

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = 'random'
end


text:
Blockly.Python['action_test'] = function(block) {

	var speed_left = Blockly.Python.valueToCode(block, 'speed_left', Blockly.Python.ORDER_ATOMIC) || '255';

	var speed_right = Blockly.Python.valueToCode(block, 'speed_right', Blockly.Python.ORDER_ATOMIC) || '255';

	var rot_left = Blockly.Python.valueToCode(block, 'rot_left', Blockly.Python.ORDER_ATOMIC) || '255';

	var rot_right = Blockly.Python.valueToCode(block, 'rot_right', Blockly.Python.ORDER_ATOMIC) || '255';

  var code = 'testMotor('+speed_left+','+speed_right+','+rot_left+','+rot_right+')\n';
  return code;
};

Blockly.Python['action_go'] = function(block) {
  var go_dropdown = block.getFieldValue('go_dropdown');
  var go_steps = Blockly.Python.valueToCode(block, 'go_steps', Blockly.Python.ORDER_ATOMIC) || '5';

  var code = 'go(\"'+go_dropdown+'\", '+go_steps+')\n';
  return code;
};

Blockly.Python['action_stop'] = function(block) {

  var code = 'stop()\n';
  return code;
};

Blockly.Python['action_turn'] = function(block) {
  var turn_dropdown = block.getFieldValue('turn_dropdown');

  var code = 'turn(\"'+turn_dropdown+'\")\n';
  return code;
};

Blockly.Python['action_go_simple'] = function(block) {
  var go_dropdown = block.getFieldValue('go_simple_dropdown');
  var go_steps= '5';

  var code = 'go(\"'+go_dropdown+'\", '+go_steps+')\n';
  return code;
};

Blockly.Python['action_say'] = function(block) {
  var say_text = Blockly.Python.valueToCode(block, 'say_text', Blockly.Python.ORDER_ATOMIC) || 'Hello World';

  var code = 'say(\"'+say_text+'\")\n';
  return code;
};


text:
class PhysicsDoer;

class ScriptRunner : public QObject
{
    Q_OBJECT
public:
    ScriptRunner(QUrl url, QString script_file, QStringList args, bool debug, QStringList lib_path);

public slots:
    // start the engine
    void bootstrap();

private:
    QThread * m_thread;
    QUrl m_url;
    QString m_main_script_filename;
    QStringList m_args;
    bool m_debug;

    QScriptEngine * m_engine;
    QScriptValue m_handler_map;
    QScriptValue m_point_class;
    QScriptValue m_entity_class;
    QScriptValue m_item_class;
    QScriptValue m_block_class;

    mineflayer_GamePtr m_game;
    bool m_started_game;

    bool m_exiting;

    StdinReader m_stdin_reader;
    QTextStream m_stderr;
    QTextStream m_stdout;

    struct TimedFunction {
        int id;
        bool repeat;
        QScriptValue this_ref;
        QScriptValue function;
        TimedFunction() {}
        TimedFunction(int id, bool repeat, QScriptValue this_ref, QScriptValue function) :
            id(id),
            repeat(repeat),
            this_ref(this_ref),
            function(function) {}
    };

    QHash<int, QTimer *> m_timer_ptrs;
    QHash<QTimer *, TimedFunction> m_script_timers;
    int m_timer_count;

#ifdef MINEFLAYER_GUI_ON
    QScriptEngineDebugger * m_debugger;
#endif

    QStringList m_lib_path;

    QSet<QString> m_included_filenames;
private:
    void raiseEvent(QString event_name, const QScriptValueList & args = QScriptValueList());
    static bool argCount(QScriptContext *context, QScriptValue & error, int arg_count_min, int arg_count_max = -1);
    static bool maybeThrowArgumentError(QScriptContext *context, QScriptValue & error, bool arg_is_valid);
    int nextTimerId();

    int setTimeout(QScriptValue func, int ms, QScriptValue this_obj, bool repeat);

    QString internalReadFile(const QString &path);
    QScriptValue evalJsonContents(const QString &file_contents, const QString &file_name = QString());
    void checkEngine(const QString & while_doing_what = QString());
    QScriptValue jsPoint(const mineflayer_Int3D &pt);
    QScriptValue jsPoint(const mineflayer_Double3D &pt);
    static bool fromJsPoint(QScriptContext *context, QScriptValue &error, QScriptValue point_value, mineflayer_Double3D &point);
    static bool fromJsPoint(QScriptContext *context, QScriptValue &error, QScriptValue point_value, mineflayer_Int3D &floored_point);
    QScriptValue jsItem(mineflayer_Item item);
    QScriptValue jsBlock(mineflayer_Block block);
    QScriptValue jsEntity(mineflayer_Entity * entity);

    // JavaScript utils
    static QScriptValue include(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue exit(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue print(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue debug(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue setTimeout(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue clearTimeout(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue setInterval(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue clearInterval(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue readFile(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue writeFile(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue args(QScriptContext * context, QScriptEngine * engine);

    // mf functions
    static QScriptValue chat(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue timeOfDay(QScriptContext *context, QScriptEngine *engine);
    static QScriptValue itemStackHeight(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue isPhysical(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue isSafe(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue isDiggable(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue health(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue blockAt(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue isBlockLoaded(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue signTextAt(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue self(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue setControlState(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue clearControlStates(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue lookAt(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue respawn(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue entity(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue startDigging(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue stopDigging(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue canPlaceBlock(QScriptContext * context, QScriptEngine * engine);

    static QScriptValue selectEquipSlot(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue selectedEquipSlot(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue openInventoryWindow(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue clickInventorySlot(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue clickUniqueSlot(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue clickOutsideWindow(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue closeWindow(QScriptContext * context, QScriptEngine * engine);

    static QScriptValue inventoryItem(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue uniqueWindowItem(QScriptContext * context, QScriptEngine * engine);

    static QScriptValue dimension(QScriptContext * context, QScriptEngine * engine);

    // hax functions
    static QScriptValue setPosition(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue setGravityEnabled(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue attackEntity(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue setJesusModeEnabled(QScriptContext * context, QScriptEngine * engine);

    static QScriptValue placeBlock(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue activateItem(QScriptContext * context, QScriptEngine * engine);
    static QScriptValue activateBlock(QScriptContext * context, QScriptEngine * engine);

private slots:
    void dispatchTimeout();
    void cleanup();
    void handleReadLine(QString line);

private slots: // non-static callbacks
    void handlePlayerPositionUpdated();
    void handleEntitySpawned(mineflayer_Entity * entity);
    void handleEntityDespawned(mineflayer_Entity * entity);
    void handleEntityMoved(mineflayer_Entity * entity);
    void handleAnimation(mineflayer_Entity * entity, mineflayer_AnimationType animation_type);
    void handleChunkUpdated(const mineflayer_Int3D &start, const mineflayer_Int3D &size);
    void handleSignUpdated(const mineflayer_Int3D &location, QString text);
    void handlePlayerHealthUpdated();
    void handleInventoryUpdated();
    void handlePlayerDied();
    void handlePlayerSpawned(int world);
    void handleChatReceived(QString username, QString message);
    void handleNonSpokenChatReceived(QString message);
    void handleTimeUpdated(double seconds);
    void handleLoginStatusUpdated(mineflayer_LoginStatus status);
    void handleStoppedDigging(mineflayer_StoppedDiggingReason reason);
    void handleWindowOpened(mineflayer_WindowType window_type);
    void handleEquippedItemChanged();

private: // static callbacks
    static void chatReceived (void * context, mineflayer_Utf8 username, mineflayer_Utf8 message);
    static void timeUpdated (void * context, double seconds);
    static void nonSpokenChatReceived (void * context, mineflayer_Utf8 message);

    static void entitySpawned(void * context, mineflayer_Entity * entity);
    static void entityDespawned(void * context, mineflayer_Entity * entity);
    static void entityMoved(void * context, mineflayer_Entity * entity);
    static void animation(void * context, mineflayer_Entity * entity, mineflayer_AnimationType animation_type);

    static void chunkUpdated(void * context, mineflayer_Int3D start, mineflayer_Int3D size);
    static void signUpdated(void * context, mineflayer_Int3D location, mineflayer_Utf8 text);
    static void playerPositionUpdated(void * context);
    static void playerHealthUpdated(void * context);
    static void playerDied(void * context);
    static void playerSpawned(void * context, int world);
    static void stoppedDigging(void * context, mineflayer_StoppedDiggingReason reason);
    static void loginStatusUpdated(void * context, mineflayer_LoginStatus status);

    static void windowOpened(void * context, mineflayer_WindowType window_type);

    static void inventoryUpdated(void * context);
    static void equippedItemChanged(void * context);
};

#endif // SCRIPTRUNNER_H