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

    angular
        .module('customers')
        .controller('NewCustomerDialogController', NewCustomerDialogController);

    NewCustomerDialogController.$inject = ['$mdDialog'];

    function NewCustomerDialogController($mdDialog) {
        var vm = this;

        vm.save = $mdDialog.hide;
        vm.cancel = $mdDialog.cancel;
        vm.userInput = {};

        // *********************************
        // Internal methods
        // *********************************

        //TODO submit user input on enter key
        //TODO validation
    }

})();

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file
 *   This file implements the OpenThread platform abstraction for logging.
 *
 */

#include <openthread/config.h>
#include <openthread-core-config.h>

#include <openthread/cli.h>
#include <openthread/platform/logging.h>

#include "utils/code_utils.h"

#if (OPENTHREAD_CONFIG_LOG_OUTPUT ==  OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED)
void otPlatLog(otLogLevel aLogLevel, otLogRegion aLogRegion, const char *aFormat, ...)
{
#if OPENTHREAD_ENABLE_CLI_LOGGING
    va_list args;
    va_start(args, aFormat);
    otCliLog(aLogLevel, aLogRegion, aFormat, args);
    va_end(args);
#else
    (void)aLogLevel;
    (void)aLogRegion;
    (void)aFormat;
#endif // OPENTHREAD_ENABLE_CLI_LOGGING
}
#endif


text:
#ifndef skgpu_graphite_ComputePassTask_DEFINED
#define skgpu_graphite_ComputePassTask_DEFINED

#include "src/gpu/graphite/ComputePipeline.h"
#include "src/gpu/graphite/ComputePipelineDesc.h"
#include "src/gpu/graphite/ComputeTypes.h"
#include "src/gpu/graphite/Task.h"

#include <vector>

namespace skgpu::graphite {

class Buffer;
class ComputePipeline;
class CommandBuffer;
class ResourceProvider;

/**
 * ComputePassTask records a compute kernel and its associated resources into a single compute pass
 * within a command buffer. The creation of bound resources and their binding layout is left up to
 * the caller and must be compatible with the provided the compute pipeline layout.
 */
// TODO(b/240604614): This class could facilitate some of this and also enforce layout validation
// depending on how we decide to define and combine compute shader code.
// TODO(b/240625222): This class could consume multiple ComputePass objects and encode them
// together. The individual passes could execute in parallel depending on the desired data-flow.
class ComputePassTask final : public Task {
public:
    static sk_sp<ComputePassTask> Make(std::vector<ResourceBinding> bindings,
                                       const ComputePipelineDesc&,
                                       const ComputePassDesc&);

    ~ComputePassTask() override = default;

    bool prepareResources(ResourceProvider*, const SkRuntimeEffectDictionary*) override;
    bool addCommands(ResourceProvider*, CommandBuffer*) override;

private:
    ComputePassTask(std::vector<ResourceBinding> bindings,
                    const ComputePipelineDesc&,
                    const ComputePassDesc&);

    const ComputePipelineDesc fPipelineDesc;
    const ComputePassDesc fComputePassDesc;
    const std::vector<ResourceBinding> fBindings;

    sk_sp<ComputePipeline> fPipeline;
};

}  // namespace skgpu::graphite

#endif  // skgpu_graphite_ComputePassTask_DEFINED


text:
package org.yeastrc.ms.domain.run.ms2file.impl;

import org.yeastrc.ms.domain.run.ms2file.MS2NameValuePair;

public class NameValuePair implements MS2NameValuePair {

    private String name;
    private String value;

    public NameValuePair() {
        super();
    }

    public NameValuePair(String name, String value) {
        super();
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}


text:
class TplBirstDuplicateSpaceSerializer < ActiveModel::Serializer
  attributes :id, :from_space_id_str, :to_space_name, :with_membership, :with_data
end


text:
//=============================================================================
// Copyright (c) 2017 Ryooooooga
// https://github.com/Ryooooooga
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom
// the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//=============================================================================

#ifndef INCLUDE_NENE_SERIALIZATION_BINARYDESERIALIZER_HPP
#define INCLUDE_NENE_SERIALIZATION_BINARYDESERIALIZER_HPP

#include <memory>
#include "../Endian.hpp"
#include "../Uncopyable.hpp"
#include "../Reader/IReader.hpp"

namespace Nene::Serialization
{
	/**
	 * @brief      Binary deserializer.
	 */
	class BinaryDeserializer final
		: private Uncopyable
	{
		IReader& reader_;
		Endian::Order order_;

	public:
		/**
		 * @brief      Constructor.
		 *
		 * @param      reader  The input reader.
		 * @param[in]  endian  The serializer byte order.
		 */
		explicit BinaryDeserializer(IReader& reader, Endian::Order byteOrder = Endian::Order::native) noexcept;

		/**
		 * @brief      Destructor.
		 */
		~BinaryDeserializer() =default;

		/**
		 * @brief      Returns the serializer byte order.
		 *
		 * @return     The serializer byte order.
		 */
		[[nodiscard]]
		Endian::Order byteOrder() const noexcept;

		/**
		 * @brief      Deserializes the data.
		 *
		 * @param      data  The data to read.
		 *
		 * @tparam     T     The data type.
		 *
		 * @return     `*this`.
		 */
		template <typename T>
		BinaryDeserializer& serialize(T& data);

		/**
		 * @brief      Reads data.
		 *
		 * @param      data  The pointer to the data.
		 * @param[in]  size  The data size.
		 */
		void read(void* data, std::size_t size);
	};
}

#include "BinaryDeserializer.inl.hpp"

#endif  // #ifndef INCLUDE_NENE_SERIALIZATION_BINARYDESERIALIZER_HPP


text:
'use strict';

var program = require('commander');
var packageData = require('../package.json');

program
  .version(packageData.version)
  .description(packageData.description)
  .parse(process.argv);

// Defer requires for better performance on outputing helps

var Bluebird      = require('../lib/promise/bluebird-mod');
var path          = require('path');
var chalk         = require('chalk');
var _             = require('lodash');
var Log           = require('../lib/util/log');
var readFileAsync = require('../lib/fs-util/read-file-async');
var copy          = require('../lib/fs-util/copy');
var creatEmpty    = require('../lib/fs-util/create-empty');

var info = Log.info;

function logFileCreation(file) {
  var log = _.flow(chalk.green, function (str) { return 'Created ' + str; }, info);
  return _.ary(_.partial(log, file), 0);
}

Bluebird
  .resolve(['playground.yml', 'playground.json'])
  .tryInOrder(readFileAsync)
  .catch(function (err) {
    info('Did not find playground file, scaffold files for you.');

    var p1 = copy(path.join(__dirname, '..', 'template', 'playground.yml'), 'playground.yml')
      .tap(logFileCreation('playground.yml'));

    var p2 = copy(path.join(__dirname, '..', 'template', 'html.html'), 'html.html')
      .tap(logFileCreation('html.html'));

    var p3 = creatEmpty('css.css').tap(logFileCreation('css.css'));
    var p4 = creatEmpty('javascript.js').tap(logFileCreation('javascript.js'));

    Bluebird
      .join(p1, p2, p3, p4)
      .done(_.partial(info, 'Run ' + chalk.green('wpg') + ' to start live-reload server'));
  })
  .then(function () {
    require('../index').start();
  });


text:
<?php

namespace My\BetBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use My\BetBundle\Entity\User;
use My\BetBundle\Form\UserType;

class RecommendController extends Controller
{

   public function registrationAction()
   {
      $entity = new User();
      $form = $this->createForm(new UserType(), $entity);

      return $this->render('MyBetBundle:Recommend:registration.html.twig', array('entity' => $entity, 'form' => $form->createView()));
   }

   public function createAction(Request $request)
   {
      $entity = new User();
      $form = $this->createForm(new UserType(), $entity);
      $form->bind($request);

      if ($form->isValid()) {
         $em = $this->getDoctrine()->getManager();
         $em->persist($entity);
         $em->flush();

         return $this->redirect($this->generateUrl('player_registration'));
      }

      return array(
          'entity' => $entity,
          'form' => $form->createView(),
      );
   }

   public function offersAction()
   {
      $em = $this->getDoctrine()->getEntityManager();
      $categoryOffer = array();
      $categories = $em->getRepository('MyBetBundle:Category')->findAll();
      foreach ($categories as $category) {
         $offersObject = $em->getRepository('MyBetBundle:Offer')->findOffersByMatchdayAndCategory(1, $category->getName());
         foreach ($offersObject as $offer) {
            $categoryOffer[$category->getName()][] = $offer;
         }
      }

      return $this->render('MyBetBundle:Recommend:offers.html.twig', array('offers' => $categoryOffer));
   }

   // algorytm user-based
   // oparty na użytkowniku
   public function userBasedAction()
   {
      $thisUser = 1; // ID zalogowanego usera
      $matchday = 1; // obecny numer kolejki
      $diffPractise = 3; // różnica dla "Practice"
      $diffHighestWin = 3; // różnica dla "Highest win"
      $diffTeam = 2; // różnica dla "Team"

      $kNNResult = array();  // tablica wyników
      $offersThisUserIds = array();   // tablica na wszyskie wybierane przez usera oferty
      $newArray = array(); // tablica na oferty userów z grupy tych 5 najbardziej podobnych userów
      // połączenie z bazą danych
      $em = $this->getDoctrine()->getEntityManager();

      // pobieramy dane zalogowanego Usera
      $u = $em->getRepository('MyBetBundle:User')->getUserProfile($thisUser);

      // dla zalog. usera pobieramy niepowtarzające się oferty z obecnej kolejki
      $offersThisUser = $em->getRepository('MyBetBundle:Bet')->findAllUserBetsFromMatchday($matchday, $thisUser);

      // pobieramy tylko same ID bets usera zalogowanego
      foreach ($offersThisUser as $curr => $val) {
         $offersThisUserIds[] = $val['id'];
      }

      // rożnica wieku między najstarszym a najmłodszym użytkownikiem systemu
      $diffAges = $em->getRepository('MyBetBundle:Profile')->getDifferenceBetweenMaxAndMinAge();

      // pobieramy wszystkich userów
      $users = $em->getRepository('MyBetBundle:User')->getAllUserProfile();

      // dla każdego Usera wyliczamy współczynnik podobieństwa
      // (na podstawie algorytmu k najbliższych sąsiadów)
      foreach ($users as $user) {

         if ($user['id'] != $thisUser) {

            $qualityAge = round(abs(($u[0]['age']) - ($user['age'])) / $diffAges[1], 4);

            $qualityPractice = round(abs(($this->getPrcVal($u[0]['practice'])) - ($this->getPrcVal($user['practice']))) / $diffPractise, 4);

            $qualityHighestWin = round(abs(($this->getHiWinVal($u[0]['highest_win'])) - ($this->getHiWinVal($user['highest_win']))) / $diffHighestWin, 4);

            $qualityTeam = round(abs(($this->getTeamValue($u[0]['team1'], $user['team1'])) - ($this->getTeamValue($u[0]['team2'], $user['team2']))) / $diffTeam, 4);

            $sumValue = $qualityAge + $qualityPractice + $qualityHighestWin + $qualityTeam;

            // tutaj zapisujemy rezultaty
            $kNNResult[$user['id']] = array(
                'value' => $sumValue
            );
         }
      }

      // sortujemy tablicę
      arsort($kNNResult);

      // pobieramy z tablicy 5 najlepszych wyników
      // (dzięki temu mamy grupę 5 najbardziej podobnych użytkowników)
      $sliceArray = array_slice($kNNResult, 0, 5, true);

      // dodajemy nowy index do tablicy do przechowywania ofert podobnych userów
      foreach ($sliceArray as $key => $value) {
         $sliceArray[$key]['bets'] = $em->getRepository('MyBetBundle:Bet')->findAllUserBetsFromMatchday($matchday, $key);
      }

      // pobieramy same oferty tych 5ciu wybranych userów
      foreach ($sliceArray as $userKey => $userValue) {
         foreach ($userValue['bets'] as $betKey => $betValue) {
            // tablica wszystkich pobranych ofert tych 5ciu userów
            $newArray[] = $betValue['id'];
         }
      }

      // usuwamy zduplikowane oferty
      $unsetDuplicateValues = array_unique($newArray);

      // różnica między tablicą bets 5ciu userów, a tablicą zalog. usera
      $arrayAllRecommendOffers = array_diff($unsetDuplicateValues, $offersThisUserIds);

      // jeśli wyników jest mniej niż 50 to pokazujemy wszystkie oferty
      // w innym przypadku pokazujemy tylko losowych 40
      if ((count($arrayAllRecommendOffers)) >= 50) {
         $someRecommendOffers = array_rand($arrayAllRecommendOffers, 40);
         for ($i = 0; $i < count($someRecommendOffers); $i++) {
            $recommend[] = $arrayAllRecommendOffers[$someRecommendOffers[$i]];
         }
      } else {
         $recommend = $arrayAllRecommendOffers;
      }

      // pobieramy zarekomendowane oferty
      $recommendOffers = $em->getRepository('MyBetBundle:Offer')->findRecommendOffer($matchday, $recommend);

      // wyświetlamy
      return $this->render('MyBetBundle:Recommend:userbased.html.twig', array('offers' => $recommendOffers));
   }

   public function getPrcVal($practice)
   {
      switch ($practice) {
         case 'I am beginning':
            return 1;
            break;
         case 'About 1 year':
            return 2;
            break;
         case '1-2 years':
            return 3;
            break;
         case '2-5 years':
            return 4;
            break;
      }
   }

   public function getHiWinVal($highWin)
   {
      switch ($highWin) {
         case 'do 100 zł.':
            return 1;
            break;
         case '100-300 zł.':
            return 2;
            break;
         case '300-500 zł.':
            return 3;
            break;
         case '500-1000 zł.':
            return 4;
            break;
      }
   }

   public function getTeamValue($teamU1, $teamU2)
   {
      return ($teamU1 == $teamU2) ? 1 : 3;
   }

   // algorytm user-based collaborative filtering
   // kolaboratywne filtrowanie oparte na użytkowniku
   public function collaborativeFilteringAction()
   {
      $thisUser = 1; // ID zalogowanego usera
      $matchday = 1; // obecny numer kolejki
      // połączenie z bazą danych
      $em = $this->getDoctrine()->getEntityManager();

      // wszyscy użytkownicy, którzy wysłali kupony w tej kolejce oprócz zalog. usera
//      $users = $em->getRepository('MyBetBundle:User')->findUsersWhichSendKuponInThisMatchday($matchday, $thisUser);
      // wszystkie oferty z tej kolejki
      $offers = $em->getRepository('MyBetBundle:Offer')->findOffersByMatchday($matchday);

      // dla zalog. usera pobieramy niepowtarzające się oferty z tej kolejki
      $offersThisUser = $em->getRepository('MyBetBundle:Bet')->findAllUserBetsFromMatchday($matchday, $thisUser);

      // pobranie tylko samych ID bets usera zalogowanego
      foreach ($offersThisUser as $curr => $val) {
         $offersThisUserIds[] = $val['id'];
      }

      // dla zalog. usera tworzymy wektor
      $vectorThisUser = $this->createVector($offers, $offersThisUser);

      // pobieramy userow wraz z ich ofertami z kuponów
      $usersBets = $em->getRepository('MyBetBundle:Bet')->findAllUserBetsFromMatchday2($matchday);

      // przerabiamy pobrane dane, aby indeksy odpowiadały ID usera, a wartości były tablicami z ID ofert
      $users = array();
      foreach ($usersBets as $row) {
         $users[$row['uid']][] = $row['oid'];
      }

      $euklidesResult = array();
      foreach ($users as $user => $value) {
         // dla każdego usera tworzymy wektor
         $vectorAnotherUser = $this->createVector($offers, $value);
         // dla każdego usera sprawdzamy jakie jest podobieństwo z zalog. userem
         // tworzymy tablicę z dwoma elementami
         // 1) tablica bets użytkownika, 2) obliczona wartość podobieństwa
         $euklidesResult[$user] = array(
             'bets' => $value,
             'value' => $this->euklides($vectorThisUser, $vectorAnotherUser)
         );
      }

      // posortowanie wartości w kolejności od najwyższej do najniższej
      arsort($euklidesResult);

      // pobranie 5ciu userów o nawyższych wartościach
      // (dzięki temu mamy 5ciu najbardziej podobnych userów)
      $sliceArray = array_slice($euklidesResult, 0, 5, true);

      // pobranie samych bets tych 5ciu podobnych userów
      foreach ($sliceArray as $userKey => $userValue) {
         foreach ($userValue['bets'] as $betKey => $betValue) {
            // tablica wszystkich pobranych ofert tych 5ciu userów
            $newArray[] = $betValue;
         }
      }

      // usunięcie zduplikowanych ofert
      $unsetDuplicateValues = array_unique($newArray);

      // różnica między tablicą bets 5ciu userów, a tablicą zalog. usera
      $arrayAllRecommendOffers = array_diff($unsetDuplicateValues, $offersThisUserIds);

      // jeśli wyników jest mniej niż 50 to pokaż wszystkie oferty
      // w innym przypadku pokaż tylko losowych 40
      if ((count($arrayAllRecommendOffers)) >= 50) {
         $someRecommendOffers = array_rand($arrayAllRecommendOffers, 40);
         for ($i = 0; $i < count($someRecommendOffers); $i++) {
            $recommend[] = $arrayAllRecommendOffers[$someRecommendOffers[$i]];
         }
      } else {
         $recommend = $arrayAllRecommendOffers;
      }

      $recommendOffers = $em->getRepository('MyBetBundle:Offer')->findRecommendOffer($matchday, $recommend);

      return $this->render('MyBetBundle:Recommend:collaborative.html.twig', array('offers' => $recommendOffers));
   }

   public function createVector(array $offers, array $userBets)
   {
      foreach ($offers as $offer) {
         if (in_array($offer, $userBets)) {
            $vector[] = 1;
         } else {
            $vector[] = 0;
         }
      }

      return $vector;
   }

   public function euklides(array $vectorFirstUser, array $vectorSecondUser)
   {
      $distanceBetweenTwoPoints = 0;
      for ($i = 0; $i < count($vectorFirstUser); $i++) {
         $distanceBetweenTwoPoints += (($vectorFirstUser[$i]) - ($vectorSecondUser[$i])) ^ 2;
      }
      $distanceBetweenTwoPoints = sqrt($distanceBetweenTwoPoints);
      $similarity = 1 / (1 + $distanceBetweenTwoPoints);
      $result = round($similarity, 4);
      return $result;
   }

   public function userKuponsAction()
   {
      $user = 1;
      $em = $this->getDoctrine()->getEntityManager();
      $kupons = $em->getRepository('MyBetBundle:Kupon')->findByUser($user);
      return $this->render('MyBetBundle:Recommend:kupons.html.twig', array('kupons' => $kupons));
   }

   public function kuponsAction()
   {
      $test = 'User kupons';
      $kupon = 1;
      $em = $this->getDoctrine()->getEntityManager();
      $bets = $em->getRepository('MyBetBundle:Bet')->findByKupon($kupon);
      return $this->render('MyBetBundle:Recommend:kupons.html.twig', array('test' => $test));
   }

   public function accountAction()
   {
      $test = 'User Account';
      return $this->render('MyBetBundle:Recommend:account.html.twig', array('test' => $test));
   }
}


text:
<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>The HTML5 Template</title>
  <meta name="description" content="The HTML5 Template">
  <meta name="author" content="YOUR NAME HERE">

  <link rel="stylesheet" href="css/styles.css?v=1.0">

  <!--[if lt IE 9]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
</head>

<body>

  <script src="js/scripts.js"></script>
</body>
</html>
<!-- Source: http://www.sitepoint.com/a-basic-html5-template/ -->


text:
require "spec_helper"

RSpec.describe RSpec::JsonMatchers::Matchers::BeJsonMatcher, "#with_content" do
  let(:expectations) do
    Module.new do
      include RSpec::JsonMatchers::Expectations::Mixins::BuiltIn
    end
  end

  before(:each) do
    expectations.constants.each do |expectation_klass_name|
      stub_const(
        expectation_klass_name.to_s,
        expectations.const_get(expectation_klass_name),
      )
    end
  end

  context "when subject is NOT valid JSON" do
    subject { "" }

    it "does NOT match" do
      should_not be_json.with_content({})
    end
  end

  context "when subject is valid JSON object" do
    subject { {}.to_json }

    context "and expected type does NOT match" do
      it "does NOT match" do
        should_not be_json.with_content([])
      end
    end
    context "and expected type DOES match" do
      it "DOES match" do
        should be_json.with_content({})
      end
    end
  end
  context "when subject is valid JSON array" do
    subject { [].to_json }

    context "and expected type does NOT match" do
      it "does NOT match" do
        should_not be_json.with_content({})
      end
    end
    context "and expected type DOES match" do
      it "DOES match" do
        should be_json.with_content([])
      end
    end
  end

  describe "validation of JSON object" do
    context "with no nesting" do
      subject { actual.to_json }

      let(:actual) do
        {
          a: 1,
        }
      end
      let!(:expected) do
        HashWithContent[{
          a: 1,
        }]
      end

      context "and subject is exactly matched with expected" do
        it "DOES match" do
          should be_json.with_content(expected)
        end
      end

      context "and subject is exactly matched with expected with string keys" do
        let!(:expected) do
          HashWithContent[{
            "a" => 1,
          }]
        end

        it "DOES match" do
          should be_json.with_content(expected)
        end
      end

      context "and subject has different content then expected" do
        let!(:expected) do
          HashWithContent[{
            a: 2,
          }]
        end

        it "does NOT match" do
          should_not be_json.with_content(expected)
        end
      end

      context "and expected has less keys than actual" do
        let!(:expected) do
          HashWithContent[{
          }]
        end

        it "DOES match" do
          should be_json.with_content(expected)
        end
      end

      context "and subject and expected have some common properties" do
        context "and subject has more properties" do
          before { actual.merge!(b: 1) }

          it "DOES match" do
            should be_json.with_content(expected)
          end
        end

        context "and expected has more properties" do
          context "and subject has more properties" do
            let!(:expected) do
              HashWithContent[{
                a: 1,
                b: 1,
              }]
            end

            it "does NOT match" do
              should_not be_json.with_content(expected)
            end
          end
        end
      end
    end

    context "with max 2 levels deep" do
      subject { actual.to_json }

      let(:actual) do
        {
          a: {
            b: 1,
          },
        }
      end
      let!(:expected) do
        HashWithContent[{
          a: HashWithContent[{
            b: 1,
          }],
        }]
      end

      context "and subject is exactly matched with expected" do
        it "DOES match" do
          should be_json.with_content(expected)
        end
      end

      context "and subject has different content then expected" do
        context "the only difference is the content of the deepest key" do
          let!(:expected) do
            HashWithContent[{
              a: HashWithContent[{
                b: 2,
              }],
            }]
          end

          it "does NOT match" do
            should_not be_json.with_content(expected)
          end
        end
        context "the only difference is the nesting" do
          let!(:expected) do
            HashWithContent[{
              a: 1,
            }]
          end

          it "does NOT match" do
            should_not be_json.with_content(expected)
          end
        end
      end
    end

    context "with max 3 levels deep" do
      subject { actual.to_json }

      let(:actual) do
        {
          a: {
            b: {
              c: 1,
            },
          },
        }
      end
      let!(:expected) do
        HashWithContent[{
          a: HashWithContent[{
            b: HashWithContent[{
              c: 1,
            }],
          }],
        }]
      end

      context "and subject is exactly matched with expected" do
        it "DOES match" do
          should be_json.with_content(expected)
        end
      end

      context "and subject has different content then expected" do
        context "the only difference is the content of the deepest key" do
          let!(:expected) do
            HashWithContent[{
              a: HashWithContent[{
                b: HashWithContent[{
                  c: 2,
                }],
              }],
            }]
          end

          it "does NOT match" do
            should_not be_json.with_content(expected)
          end
        end
        context "the only difference is the nesting" do
          let!(:expected) do
            HashWithContent[{
              a: HashWithContent[{
                b: 2,
              }],
            }]
          end

          it "does NOT match" do
            should_not be_json.with_content(expected)
          end
        end
      end
    end
  end
end


text:
import { expose } from "../../dist-esm/worker"

expose(async function add(a, b) {
  return a + b
})


text:
#include "tensorflow/core/lib/histogram/histogram.h"
#include <float.h>
#include <math.h>
#include <vector>
#include "tensorflow/core/framework/summary.pb.h"

#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
namespace histogram {

static std::vector<double>* InitDefaultBucketsInner() {
  std::vector<double> buckets;
  std::vector<double> neg_buckets;
  // Make buckets whose range grows by 10% starting at 1.0e-12 up to 1.0e20
  double v = 1.0e-12;
  while (v < 1.0e20) {
    buckets.push_back(v);
    neg_buckets.push_back(-v);
    v *= 1.1;
  }
  buckets.push_back(DBL_MAX);
  neg_buckets.push_back(-DBL_MAX);
  std::reverse(neg_buckets.begin(), neg_buckets.end());
  std::vector<double>* result = new std::vector<double>;
  result->insert(result->end(), neg_buckets.begin(), neg_buckets.end());
  result->push_back(0.0);
  result->insert(result->end(), buckets.begin(), buckets.end());
  return result;
}

static gtl::ArraySlice<double> InitDefaultBuckets() {
  static std::vector<double>* default_bucket_limits = InitDefaultBucketsInner();
  return *default_bucket_limits;
}

Histogram::Histogram() : bucket_limits_(InitDefaultBuckets()) { Clear(); }

// Create a histogram with a custom set of bucket limits,
// specified in "custom_buckets[0..custom_buckets.size()-1]"
Histogram::Histogram(gtl::ArraySlice<double> custom_bucket_limits)
    : custom_bucket_limits_(custom_bucket_limits.begin(),
                            custom_bucket_limits.end()),
      bucket_limits_(custom_bucket_limits_) {
#ifndef NDEBUG
  DCHECK_GT(bucket_limits_.size(), 0);
  // Verify that the bucket boundaries are strictly increasing
  for (size_t i = 1; i < bucket_limits_.size(); i++) {
    DCHECK_GT(bucket_limits_[i], bucket_limits_[i - 1]);
  }
#endif
  Clear();
}

bool Histogram::DecodeFromProto(const HistogramProto& proto) {
  if ((proto.bucket_size() != proto.bucket_limit_size()) ||
      (proto.bucket_size() == 0)) {
    return false;
  }
  min_ = proto.min();
  max_ = proto.max();
  num_ = proto.num();
  sum_ = proto.sum();
  sum_squares_ = proto.sum_squares();
  custom_bucket_limits_.clear();
  custom_bucket_limits_.insert(custom_bucket_limits_.end(),
                               proto.bucket_limit().begin(),
                               proto.bucket_limit().end());
  bucket_limits_ = custom_bucket_limits_;
  buckets_.clear();
  buckets_.insert(buckets_.end(), proto.bucket().begin(), proto.bucket().end());
  return true;
}

void Histogram::Clear() {
  min_ = bucket_limits_[bucket_limits_.size() - 1];
  max_ = -DBL_MAX;
  num_ = 0;
  sum_ = 0;
  sum_squares_ = 0;
  buckets_.resize(bucket_limits_.size());
  for (size_t i = 0; i < bucket_limits_.size(); i++) {
    buckets_[i] = 0;
  }
}

void Histogram::Add(double value) {
  int b =
      std::upper_bound(bucket_limits_.begin(), bucket_limits_.end(), value) -
      bucket_limits_.begin();

  buckets_[b] += 1.0;
  if (min_ > value) min_ = value;
  if (max_ < value) max_ = value;
  num_++;
  sum_ += value;
  sum_squares_ += (value * value);
}

double Histogram::Median() const { return Percentile(50.0); }

// Linearly map the variable x from [x0, x1] unto [y0, y1]
double Histogram::Remap(double x, double x0, double x1, double y0,
                        double y1) const {
  return y0 + (x - x0) / (x1 - x0) * (y1 - y0);
}

// Pick tight left-hand-side and right-hand-side bounds and then
// interpolate a histogram value at percentile p
double Histogram::Percentile(double p) const {
  if (num_ == 0.0) return 0.0;

  double threshold = num_ * (p / 100.0);
  double cumsum_prev = 0;
  for (size_t i = 0; i < buckets_.size(); i++) {
    double cumsum = cumsum_prev + buckets_[i];

    // Find the first bucket whose cumsum >= threshold
    if (cumsum >= threshold) {
      // Prevent divide by 0 in remap which happens if cumsum == cumsum_prev
      // This should only get hit when p == 0, cumsum == 0, and cumsum_prev == 0
      if (cumsum == cumsum_prev) {
        continue;
      }

      // Calculate the lower bound of interpolation
      double lhs = (i == 0 || cumsum_prev == 0) ? min_ : bucket_limits_[i - 1];
      lhs = std::max(lhs, min_);

      // Calculate the upper bound of interpolation
      double rhs = bucket_limits_[i];
      rhs = std::min(rhs, max_);

      double weight = Remap(threshold, cumsum_prev, cumsum, lhs, rhs);
      return weight;
    }

    cumsum_prev = cumsum;
  }
  return max_;
}

double Histogram::Average() const {
  if (num_ == 0.0) return 0;
  return sum_ / num_;
}

double Histogram::StandardDeviation() const {
  if (num_ == 0.0) return 0;
  double variance = (sum_squares_ * num_ - sum_ * sum_) / (num_ * num_);
  return sqrt(variance);
}

std::string Histogram::ToString() const {
  std::string r;
  char buf[200];
  snprintf(buf, sizeof(buf), "Count: %.0f  Average: %.4f  StdDev: %.2f\n", num_,
           Average(), StandardDeviation());
  r.append(buf);
  snprintf(buf, sizeof(buf), "Min: %.4f  Median: %.4f  Max: %.4f\n",
           (num_ == 0.0 ? 0.0 : min_), Median(), max_);
  r.append(buf);
  r.append("------------------------------------------------------\n");
  const double mult = num_ > 0 ? 100.0 / num_ : 0.0;
  double sum = 0;
  for (size_t b = 0; b < buckets_.size(); b++) {
    if (buckets_[b] <= 0.0) continue;
    sum += buckets_[b];
    snprintf(buf, sizeof(buf), "[ %10.2g, %10.2g ) %7.0f %7.3f%% %7.3f%% ",
             ((b == 0) ? -DBL_MAX : bucket_limits_[b - 1]),  // left
             bucket_limits_[b],                              // right
             buckets_[b],                                    // count
             mult * buckets_[b],                             // percentage
             mult * sum);                                    // cum percentage
    r.append(buf);

    // Add hash marks based on percentage; 20 marks for 100%.
    int marks = static_cast<int>(20 * (buckets_[b] / num_) + 0.5);
    r.append(marks, '#');
    r.push_back('\n');
  }
  return r;
}

void Histogram::EncodeToProto(HistogramProto* proto,
                              bool preserve_zero_buckets) const {
  proto->Clear();
  proto->set_min(min_);
  proto->set_max(max_);
  proto->set_num(num_);
  proto->set_sum(sum_);
  proto->set_sum_squares(sum_squares_);
  for (size_t i = 0; i < buckets_.size();) {
    double end = bucket_limits_[i];
    double count = buckets_[i];
    i++;
    if (!preserve_zero_buckets && count <= 0.0) {
      // Find run of empty buckets and collapse them into one
      while (i < buckets_.size() && buckets_[i] <= 0.0) {
        end = bucket_limits_[i];
        count = buckets_[i];
        i++;
      }
    }
    proto->add_bucket_limit(end);
    proto->add_bucket(count);
  }
  if (proto->bucket_size() == 0.0) {
    // It's easier when we restore if we always have at least one bucket entry
    proto->add_bucket_limit(DBL_MAX);
    proto->add_bucket(0.0);
  }
}

// ThreadSafeHistogram implementation.
bool ThreadSafeHistogram::DecodeFromProto(const HistogramProto& proto) {
  mutex_lock l(mu_);
  return histogram_.DecodeFromProto(proto);
}

void ThreadSafeHistogram::Clear() {
  mutex_lock l(mu_);
  histogram_.Clear();
}

void ThreadSafeHistogram::Add(double value) {
  mutex_lock l(mu_);
  histogram_.Add(value);
}

void ThreadSafeHistogram::EncodeToProto(HistogramProto* proto,
                                        bool preserve_zero_buckets) const {
  mutex_lock l(mu_);
  histogram_.EncodeToProto(proto, preserve_zero_buckets);
}

double ThreadSafeHistogram::Median() const {
  mutex_lock l(mu_);
  return histogram_.Median();
}

double ThreadSafeHistogram::Percentile(double p) const {
  mutex_lock l(mu_);
  return histogram_.Percentile(p);
}

double ThreadSafeHistogram::Average() const {
  mutex_lock l(mu_);
  return histogram_.Average();
}

double ThreadSafeHistogram::StandardDeviation() const {
  mutex_lock l(mu_);
  return histogram_.StandardDeviation();
}

std::string ThreadSafeHistogram::ToString() const {
  mutex_lock l(mu_);
  return histogram_.ToString();
}

}  // namespace histogram
}  // namespace tensorflow


text:
<?php

namespace Bab\RabbitMq\Configuration;

use Symfony\Component\Yaml\Parser;

class Yaml extends FromArray
{
    public function __construct(string $filePath)
    {
        if (!file_exists($filePath)) {
            throw new \InvalidArgumentException(sprintf('File "%s" doesn\'t exist', $filePath));
        }

        $yaml = new Parser();

        $configuration = $yaml->parse(file_get_contents($filePath));

        parent::__construct($configuration);
    }
}


text:
classdef TestTopsSpace < TestCase

    properties
        nDims = 10;
    end

    methods
        function self = TestTopsSpace(name)
            self = self@TestCase(name);
        end

        function space = randomSpace(self)
            % make several dimensions
            dims = topsDimension.empty(0, self.nDims);
            for ii = 1:self.nDims
                name = sprintf('dim %d', ii);
                min = (rand(1,1) - 0.5) * 1e6;
                max = (rand(1,1) - 0.5) * 1e6;
                nPoints = ii;
                dims(ii) = topsDimension(name, min, max, nPoints);
            end

            % aggregate dimensions into a space
            space = topsSpace('abc', dims);
        end

        function testMinMaxSubs(self)
            space = self.randomSpace();

            % get the min value from each dimension
            mins = [space.dimensions.minimum];
            subs = space.subscriptsForValues(mins);
            subValues = space.valuesForSubscripts(subs);
            assertElementsAlmostEqual(mins, subValues, ...
                'inaccurate min subscripts')

            % get the max value from each dimension
            maxs = [space.dimensions.maximum];
            subs = space.subscriptsForValues(maxs);
            subValues = space.valuesForSubscripts(subs);
            assertElementsAlmostEqual(maxs, subValues, ...
                'inaccurate max subscripts')
        end

        function testSillySubs(self)
            space = self.randomSpace();

            % make some silly values
            mins = [space.dimensions.minimum];
            maxs = [space.dimensions.maximum];
            sillys = mins + ...
                rand(1,numel(space.dimensions)) .* (maxs - mins);

            % get subscripts nearest the silly values
            sillySubs = space.subscriptsForValues(sillys);
            values = space.valuesForSubscripts(sillySubs);
            valueSubs = space.subscriptsForValues(values);
            assertEqual(sillySubs, valueSubs, ...
                'inaccurate subscripts for values')
        end

        function testGrandIndexes(self)
            space = self.randomSpace();

            % convert grand indexes to subscripts and back
            indexes = round(linspace(1, space.nPoints, 1000));
            for ii = indexes
                subscripts = space.subscriptsForIndex(ii);
                grandIndex = space.indexForSubscripts(subscripts);
                assertEqual(ii, grandIndex, ...
                    'inaccurate grand indexing')
            end
        end
    end
end


text:
    <script>
        function getUrlParameter(sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                    sURLVariables = sPageURL.split('&'),
                    sParameterName,
                    i;

            for (i = 0; i < sURLVariables.length; i++) {
                sParameterName = sURLVariables[i].split('=');

                if (sParameterName[0] === sParam) {
                    return sParameterName[1] === undefined ? true : sParameterName[1];
                }
            }
        };
           var link = getUrlParameter('l');
        window.location = "../page.html?l=tutorial/" + link;

    </script>


text:
static NSString* const dnalbumTableViewCellReuseIdentifier = @"dnalbumTableViewCellReuseIdentifier";

@interface DNAlbumTableViewController ()
@property (nonatomic, strong) ALAssetsLibrary *assetsLibrary;
@property (nonatomic, strong) NSArray *groupTypes;

#pragma mark - dataSources
@property (nonatomic, strong) NSArray *assetsGroups;
@end

@implementation DNAlbumTableViewController

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];
    [self setupData];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - mark setup Data and View
- (void)loadData
{
    __typeof__(self) __weak weakSelf = self;
    //__weak typeof(self) weakSelf = self;
    [self loadAssetsGroupsWithTypes:self.groupTypes completion:^(NSArray *groupAssets)
     {
         weakSelf.assetsGroups = groupAssets;
         [weakSelf.tableView reloadData];
     }];
}

- (void)setupData
{
    self.groupTypes = @[@(ALAssetsGroupAll)];
    self.assetsGroups  = [NSMutableArray new];
}

- (void)setupView
{
    self.title = NSLocalizedStringFromTable(@"albumTitle", @"DNImagePicker", @"photos");
    [self createBarButtonItemAtPosition:DNImagePickerNavigationBarPositionRight
                                   text:NSLocalizedStringFromTable(@"cancel", @"DNImagePicker", @"取消")
                                 action:@selector(cancelAction:)];

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:dnalbumTableViewCellReuseIdentifier];
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.tableFooterView = view;
}

#pragma mark - ui actions
- (void)cancelAction:(id)sender
{
    DNImagePickerController *navController = [self dnImagePickerController];
    if (navController && [navController.imagePickerDelegate respondsToSelector:@selector(dnImagePickerControllerDidCancel:)]) {
        [navController.imagePickerDelegate dnImagePickerControllerDidCancel:navController];
    }
}

#pragma mark - getter/setter
- (ALAssetsLibrary *)assetsLibrary
{
    if (nil == _assetsLibrary) {
        _assetsLibrary = [[ALAssetsLibrary alloc] init];
    }
    return _assetsLibrary;
}

- (DNImagePickerController *)dnImagePickerController
{

    if (nil == self.navigationController
        ||
        ![self.navigationController isKindOfClass:[DNImagePickerController class]])
    {
        NSAssert(false, @"check the navigation controller");
    }
    return (DNImagePickerController *)self.navigationController;
}

- (NSAttributedString *)albumTitle:(ALAssetsGroup *)assetsGroup
{
    NSString *albumTitle = [assetsGroup valueForProperty:ALAssetsGroupPropertyName];
    NSString *numberString = [NSString stringWithFormat:@"  (%@)",@(assetsGroup.numberOfAssets)];
    NSString *cellTitleString = [NSString stringWithFormat:@"%@%@",albumTitle,numberString];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:cellTitleString];
    [attributedString setAttributes: @{
                                       NSFontAttributeName : [UIFont systemFontOfSize:16.0f],
                                       NSForegroundColorAttributeName : [UIColor blackColor],
                                       }
                              range:NSMakeRange(0, albumTitle.length)];
    [attributedString setAttributes:@{
                                      NSFontAttributeName : [UIFont systemFontOfSize:16.0f],
                                      NSForegroundColorAttributeName : [UIColor grayColor],
                                      } range:NSMakeRange(albumTitle.length, numberString.length)];
    return attributedString;

}

- (void)showUnAuthorizedTipsView
{
    DNUnAuthorizedTipsView *view  = [[DNUnAuthorizedTipsView alloc] initWithFrame:self.tableView.frame];
    self.tableView.backgroundView = view;
//    [self.tableView addSubview:view];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.assetsGroups.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:dnalbumTableViewCellReuseIdentifier forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    ALAssetsGroup *group = self.assetsGroups[indexPath.row];
    cell.textLabel.attributedText = [self albumTitle:group];

    //choose the latest pic as poster image
    __weak UITableViewCell *blockCell = cell;
    [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:group.numberOfAssets-1] options:NSEnumerationConcurrent usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if (result) {
            *stop = YES;
            blockCell.imageView.image = [UIImage imageWithCGImage:result.thumbnail];
        }
    }];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

#pragma mark - tableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ALAssetsGroup *group = self.assetsGroups[indexPath.row];
    NSURL *url = [group valueForProperty:ALAssetsGroupPropertyURL];
    DNImageFlowViewController *imageFlowViewController = [[DNImageFlowViewController alloc] initWithGroupURL:url];
    [self.navigationController pushViewController:imageFlowViewController animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - get assetGroups
- (void)loadAssetsGroupsWithTypes:(NSArray *)types completion:(void (^)(NSArray *assetsGroups))completion
{
    __block NSMutableArray *assetsGroups = [NSMutableArray array];
    __block NSUInteger numberOfFinishedTypes = 0;

    for (NSNumber *type in types) {
        __typeof__(self) __weak weakSelf = self;
        //__weak typeof(self) weakSelf = self;
        [self.assetsLibrary enumerateGroupsWithTypes:[type unsignedIntegerValue]
                                          usingBlock:^(ALAssetsGroup *assetsGroup, BOOL *stop)
         {
             if (assetsGroup) {
                 // Filter the assets group
                 [assetsGroup setAssetsFilter:ALAssetsFilterFromDNImagePickerControllerFilterType([[weakSelf dnImagePickerController] filterType])];
                 // Add assets group
                 if (assetsGroup.numberOfAssets > 0) {
                     // Add assets group
                     [assetsGroups addObject:assetsGroup];
                 }
             } else {
                 numberOfFinishedTypes++;
             }

             // Check if the loading finished
             if (numberOfFinishedTypes == types.count) {
                 //sort
                 NSArray *sortedAssetsGroups = [assetsGroups sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

                     ALAssetsGroup *a = obj1;
                     ALAssetsGroup *b = obj2;

                     NSNumber *apropertyType = [a valueForProperty:ALAssetsGroupPropertyType];
                     NSNumber *bpropertyType = [b valueForProperty:ALAssetsGroupPropertyType];
                     if ([apropertyType compare:bpropertyType] == NSOrderedAscending)
                     {
                         return NSOrderedDescending;
                     }
                     return NSOrderedSame;
                 }];

                 // Call completion block
                 if (completion) {
                     completion(sortedAssetsGroups);
                 }
             }
         } failureBlock:^(NSError *error) {
//             NSLog(@"%@",error.description);
             if ([ALAssetsLibrary authorizationStatus] != ALAuthorizationStatusAuthorized){
                 [self showUnAuthorizedTipsView];
             }
         }];
    }
}
@end


text:
<!doctype html>

    <title>Brython</title>
    <meta charset=UTF-8>
    <meta name=robots content="index, follow">
    <meta name=description content=Brython>
    <meta name=author content="Pierre Quentel">
    <meta name=keywords content="Python, Brython">
    <meta name=viewport content="width=device-width,initial-scale=1,maximum-scale=1">
    <link rel="shortcut icon" href=brython.png type=image/x-icon >
    Please enable Javascript to view this page correctly.
    <link rel=stylesheet href="doc/doc_brython.css">

Groups

Group (English)

Groupe (français)

Grupo (español)

Grupo (português)

Gruppo (italiano)


text:
List of books

This is a template for a simple marketing or informational website. It includes a large callout called the hero unit and three supporting pieces of content. Use it as a starting point to create something more unique.

Register new book »

{{book.title}}

{{book.author}}

{{book.year}}

{{book.registeredDate|date}}

{{book.description}}

Details


text:
package jetbrains.exodus.env;

import jetbrains.exodus.ByteIterable;
import jetbrains.exodus.ExodusException;
import jetbrains.exodus.tree.ITree;
import jetbrains.exodus.tree.ITreeCursor;
import org.jetbrains.annotations.NotNull;

import java.util.ConcurrentModificationException;

final class CursorImpl implements Cursor {

    private static final String CANT_DELETE_MODIFIED_MSG = "Can't delete (pair not found in mutable tree)";

    @NotNull
    private final StoreImpl store;
    @NotNull
    private final TransactionBase txn;
    private ITreeCursor treeCursor;
    private volatile boolean isClosed;

    CursorImpl(@NotNull final StoreImpl store, @NotNull final TransactionBase txn) {
        this.store = store;
        this.txn = txn;
        treeCursor = null;
        isClosed = false;
    }

    @Override
    public boolean getNext() {
        checkTreeCursor();
        return treeCursor.getNext();
    }

    @Override
    public boolean getNextDup() {
        checkTreeCursor();
        return treeCursor.getNextDup();
    }

    @Override
    public boolean getNextNoDup() {
        checkTreeCursor();
        return treeCursor.getNextNoDup();
    }

    @Override
    public boolean getPrev() {
        checkTreeCursor();
        return treeCursor.getPrev();
    }

    @Override
    public boolean getPrevDup() {
        checkTreeCursor();
        return treeCursor.getPrevDup();
    }

    @Override
    public boolean getPrevNoDup() {
        checkTreeCursor();
        return treeCursor.getPrevNoDup();
    }

    @Override
    public boolean getLast() {
        checkTreeCursor();
        return treeCursor.getLast();
    }

    @Override
    @NotNull
    public ByteIterable getKey() {
        checkTreeCursor();
        return treeCursor.getKey();
    }

    @Override
    @NotNull
    public ByteIterable getValue() {
        checkTreeCursor();
        return treeCursor.getValue();
    }

    @Override
    public ByteIterable getSearchKey(@NotNull final ByteIterable key) {
        checkTreeCursor();
        setTreeNodesCache();
        return treeCursor.getSearchKey(key);
    }

    @Override
    public ByteIterable getSearchKeyRange(@NotNull final ByteIterable key) {
        checkTreeCursor();
        setTreeNodesCache();
        return treeCursor.getSearchKeyRange(key);
    }

    @Override
    public boolean getSearchBoth(@NotNull final ByteIterable key, @NotNull final ByteIterable value) {
        checkTreeCursor();
        setTreeNodesCache();
        return treeCursor.getSearchBoth(key, value);
    }

    @Override
    public ByteIterable getSearchBothRange(@NotNull final ByteIterable key, @NotNull final ByteIterable value) {
        checkTreeCursor();
        setTreeNodesCache();
        return treeCursor.getSearchBothRange(key, value);
    }

    @Override
    public int count() {
        checkTreeCursor();
        return treeCursor.count();
    }

    @Override
    public void close() {
        if (isClosed) {
            throw new ExodusException("Cursor is already closed");
        }
        if (treeCursor != null) {
            treeCursor.close();
        }
        isClosed = true;
    }

    @Override
    public boolean deleteCurrent() {
        final TransactionImpl txn = EnvironmentImpl.throwIfReadonly(this.txn,
                "Can't delete a key/value pair of cursor in read-only transaction");
        if (treeCursor == null) {
            treeCursor = txn.getMutableTree(store).openCursor();
        } else {
            if (!treeCursor.isMutable()) {
                final ByteIterable key = treeCursor.getKey();
                final ByteIterable value = treeCursor.getValue();
                final ITreeCursor newCursor = txn.getMutableTree(store).openCursor();
                if (newCursor.getSearchBoth(key, value)) {
                    treeCursor = newCursor; // navigated to same pair, ready to delete
                } else {
                    throw new ConcurrentModificationException(CANT_DELETE_MODIFIED_MSG);
                }
            }
        }
        return treeCursor.deleteCurrent();
    }

    private void checkTreeCursor() {
        if (treeCursor == null) {
            treeCursor = txn.getTree(store).openCursor();
        }
    }

    private void setTreeNodesCache() {
        final ITree tree = treeCursor.getTree();
        if (tree != null) {
            tree.setTreeNodesCache(store.getEnvironment().getTreeNodesCache());
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Graphics.BufferFormat (libgdx API)</title>
<meta name="date" content="2016-02-02">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx

Class Graphics.BufferFormat

java.lang.Object

com.badlogic.gdx.Graphics.BufferFormat

Enclosing interface:

Graphics

public static class Graphics.BufferFormat
extends java.lang.Object

Class describing the bits per pixel, depth buffer precision, stencil precision and number of MSAA samples.

Field Summary

Fields

Modifier and Type
Field and Description

int
a

int
b

boolean
coverageSampling

whether coverage sampling anti-aliasing is used.

int
depth

int
g

int
r

int
samples

number of samples for multi-sample anti-aliasing (MSAA)

int
stencil

Constructor Summary

Constructors

Constructor and Description

BufferFormat(int r,
            int g,
            int b,
            int a,
            int depth,
            int stencil,
            int samples,
            boolean coverageSampling)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

r

public final int r

g

public final int g

b

public final int b

a

public final int a

depth

public final int depth

stencil

public final int stencil

samples

public final int samples

number of samples for multi-sample anti-aliasing (MSAA)

coverageSampling

public final boolean coverageSampling

whether coverage sampling anti-aliasing is used. in that case you have to clear the coverage buffer as well!

Constructor Detail

BufferFormat

public BufferFormat(int r,
                    int g,
                    int b,
                    int a,
                    int depth,
                    int stencil,
                    int samples,
                    boolean coverageSampling)

Method Detail

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
import pygame as pg
from os import path
from collections import deque

TILESIZE = 48
GRIDWIDTH = 30
GRIDHEIGHT = 15
WIDTH = TILESIZE * GRIDWIDTH
HEIGHT = TILESIZE * GRIDHEIGHT
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
YELLOW = (255, 255, 0)
DARKGRAY = (40, 40, 40)
LIGHTGRAY = (140, 140, 140)

font_name = pg.font.match_font('hack')
def draw_text(text, size, color, x, y, align="topleft"):
    font = pg.font.Font(font_name, size)
    text_surface = font.render(text, True, color)
    text_rect = text_surface.get_rect(**{align: (x, y)})
    screen.blit(text_surface, text_rect)

class Queue:
    # convenience wrapper around collections.deque
    def __init__(self):
        self.elements = deque()

    def empty(self):
        return len(self.elements) == 0

    def put(self, x):
        self.elements.append(x)

    def get(self):
        return self.elements.popleft()

class SimpleGraph:
    def __init__(self):
        self.edges = {}

    def neighbors(self, id):
        return self.edges[id]

class SquareGrid:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.walls = []

    def in_bounds(self, loc):
        x, y = loc
        return 0 <= x < self.width and 0 <= y < self.height

    def passable(self, loc):
        return loc not in self.walls

    def neighbors(self, loc):
        x, y = loc
        results = [(x + 1, y), (x, y - 1), (x - 1, y), (x, y + 1)]
        if test_h:
            # aesthetics
            if (x + y) % 2:
                results.reverse()
        results = filter(self.in_bounds, results)
        results = filter(self.passable, results)
        return results

def draw_grid(grid, paths, dist):
    for x in range(0, WIDTH, TILESIZE):
        pg.draw.line(screen, LIGHTGRAY, (x, 0), (x, HEIGHT))
    for y in range(0, HEIGHT, TILESIZE):
        pg.draw.line(screen, LIGHTGRAY, (0, y), (WIDTH, y))
    for wall in grid.walls:
        x, y = wall
        r = pg.Rect(x * TILESIZE, y * TILESIZE, TILESIZE, TILESIZE)
        pg.draw.rect(screen, LIGHTGRAY, r)

    if paths and not show_dist:
        for loc in paths:
            x, y = loc
            if not paths[loc]:
                screen.blit(home_img, (x * TILESIZE, y * TILESIZE))
            else:
                x1, y1 = paths[loc]
                if x == x1:
                    if y > y1:
                        dir = 'Up'
                    else:
                        dir = 'Down'
                elif y == y1:
                    if x > x1:
                        dir = 'Left'
                    else:
                        dir = 'Right'
                screen.blit(arrows[dir], (x * TILESIZE, y * TILESIZE))
    else:
        for loc in dist:
            x, y = loc
            sx = x * TILESIZE + TILESIZE / 2
            sy = y * TILESIZE + TILESIZE / 2
            if loc == start:
                screen.blit(home_img, (x * TILESIZE, y * TILESIZE))
            else:
                draw_text(str(dist[loc]), 18, WHITE, sx, sy, align="center")

def breadth_first_search1(graph, start):
    frontier = Queue()
    frontier.put(start)
    visited = {}
    visited[start] = True

    while not frontier.empty():
        current = frontier.get()
        print("Visiting %r" % current)
        for next in graph.neighbors(current):
            if next not in visited:
                frontier.put(next)
                visited[next] = True

def breadth_first_search2(graph, start):
    frontier = Queue()
    frontier.put(start)
    came_from = {}
    came_from[start] = None
    distance = {}
    distance[start] = 0

    while not frontier.empty():
        current = frontier.get()
        for next in graph.neighbors(current):
            if next not in came_from:
                frontier.put(next)
                came_from[next] = current
                distance[next] = distance[current] + 1
    return came_from, distance

pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
clock = pg.time.Clock()

# example_graph = SimpleGraph()
# example_graph.edges = {
#     'A': ['B'],
#     'B': ['A', 'C', 'D'],
#     'C': ['A'],
#     'D': ['E', 'A'],
#     'E': ['B']}
# breadth_first_search1(example_graph, 'A')

game_folder = path.dirname(__file__)
# icons
icon_folder = path.join(path.join(game_folder, '..'), 'icons')
home_img = pg.image.load(path.join(icon_folder, 'home.png')).convert_alpha()
home_img = pg.transform.scale(home_img, (int(TILESIZE / 1.2), int(TILESIZE / 1.2)))
home_img.fill((0, 255, 0, 255), special_flags=pg.BLEND_RGBA_MULT)
arrows = {}
for d in ['Up', 'Down', 'Right', 'Left']:
    fname = 'arrow%s.png' % d
    img = pg.image.load(path.join(icon_folder, fname)).convert_alpha()
    arrows[d] = pg.transform.scale(img, (int(TILESIZE / 1.2), int(TILESIZE / 1.2)))

g = SquareGrid(30, 15)
start = (8, 7)
test_h = True
show_dist = False
paths, dist = breadth_first_search2(g, start)

update = True
running = True
while running:
    clock.tick(FPS)
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                running = False
            if event.key == pg.K_h:
                test_h = not test_h
                paths, dist = breadth_first_search2(g, start)
            if event.key == pg.K_SPACE:
                show_dist = not show_dist
                update = True
        if event.type == pg.MOUSEBUTTONDOWN:
            mpos = pg.mouse.get_pos()
            x = mpos[0] // TILESIZE
            y = mpos[1] // TILESIZE
            if event.button == 1:
                # spawn/del walls
                if (x, y) in g.walls:
                    g.walls.remove((x, y))
                else:
                    g.walls.append((x, y))
            elif event.button == 3:
                # move destination
                if (x, y) not in g.walls:
                    start = (x, y)
            paths, dist = breadth_first_search2(g, start)
            update = True

    pg.display.set_caption("{:.2f}".format(clock.get_fps()))
    if update:
        screen.fill(DARKGRAY)
        draw_grid(g, paths, dist)
        pg.display.flip()
        update = False


text:
import 'source-map-support/register';
import * as cdk from '@aws-cdk/core';
import { YelbEcsStack } from '../lib/yelb-ecs-stack';

const app = new cdk.App();
new YelbEcsStack(app, 'YelbEcsStack');


text:
package edu.rice.cs.caper.bayou.core.parser.evidencel._1_0;

import edu.rice.cs.caper.bayou.core.lexer.evidencel._1_0.Token;
import edu.rice.cs.caper.bayou.core.lexer.evidencel._1_0.TokenTypeColon;
import edu.rice.cs.caper.bayou.core.lexer.evidencel._1_0.TokenTypeComma;
import edu.rice.cs.caper.bayou.core.lexer.evidencel._1_0.TokenTypeIdentifier;
import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public abstract class EvidenceLParserTests
{
    protected abstract EvidenceLParser makeParser();

    @Test
    public void parseEmpty() throws ParseException
    {
        EvidenceLParser parser = makeParser();

        SourceUnitNode unit = parser.parse(Collections.emptyList());

        Assert.assertEquals(0, unit.getElements().size());

    }

    @Test
    public void parseIdentifier() throws ParseException
    {
        EvidenceLParser parser = makeParser();

        SourceUnitNode unit = parser.parse(Collections.singletonList(Token.make("ident", new TokenTypeIdentifier())));
        List<EvidenceElement> evidence = unit.getElements();

        Assert.assertEquals(1, evidence.size());

    }

    @Test
    public void parseMultiCall() throws ParseException
    {
        EvidenceLParser parser = makeParser();

        // calls: setTitle, setMessage
        SourceUnitNode unit = parser.parse(Arrays.asList(
                Token.make("calls", new TokenTypeIdentifier()),
                Token.make(":", new TokenTypeColon()),
                Token.make("setTitle", new TokenTypeIdentifier()),
                Token.make(",", new TokenTypeComma()),
                Token.make("setMessage", new TokenTypeIdentifier())));

        List<EvidenceElement> evidences = unit.getElements();

        Assert.assertEquals(1, evidences.size());

        EvidenceElementWithTypeIdentifierNode evidence = (EvidenceElementWithTypeIdentifierNode)evidences.get(0);

        Assert.assertEquals("calls", evidence.getTypeIdentifier().getIdentifier());

        Assert.assertEquals(2, evidence.getIdentifierList().getIdentifiers().size());
        Assert.assertEquals("setTitle", evidence.getIdentifierList().getIdentifiers().get(0).getIdentifier());
        Assert.assertEquals("setMessage", evidence.getIdentifierList().getIdentifiers().get(1).getIdentifier());

    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OpenAPITest.Test
{
    public interface Testable
    {
        void Test();
    }
}


text:
@interface MQFunctions : NSObject {

}

+ (void)startDebugLog;
+ (void)debugLog:(NSString *)logText;

+ (NSString *)cropString:(NSString *)fullString between:(NSString *)beginString and:(NSString *)endString;
+ (NSString *) flattenHTML:(NSString *)theHTML;
+ (NSString *) humanReadableDate:(NSDate *)date;
+ (NSString *)cURLWithURLString:(NSString *)theURL;

@end


text:
<?php

// LANGUAGE variables
class LangVars
{
	//Class Common
	var $errNoSelect   = 'Erreur avec sql: erreur de sélection de %s';
	var $errNoConnect  = 'Erreur avec sqll: Erreur de connexion avec';
	var $errInScript   = 'Une erreur s\'est produite dans le script %s dans ligne %s: %s';

	//Class AjaxTableEditor
	//function setDefaults
	var $optLike       = 'Ressembler';
	var $optNotLike    = 'Non ressembler';
	var $optEq         = 'Égalité';
	var $optNotEq      = 'Non égalité';
	var $optGreat      = 'Plus de';
	var $optLess       = 'Moins de';
	var $optGreatEq    = 'Égalité ou Plus de';
	var $optLessEq     = 'Égalité ou Moins de';

	var $ttlAddRow     = 'Ajouter enregistrement';
	var $ttlEditRow    = 'Modifier enregistrement';
	var $ttlEditMult   = 'Modifier plusieurs lignes';
	var $ttlViewRow    = 'Afficher enregistrement';
	var $ttlShowHide   = 'Afficher/Cacher les colonnes';
	var $ttlOrderCols  = 'Ordre les colonnes';
	//function doDefault
	var $errNoAction   = 'Erreur dans le programme %s l\'action ne trouve pas.';
	//function doQuery
	var $errQuery      = 'Il y avait une erreur avec la requ�te suivante: ';
	var $errMysql      = 'mysql rapporte:';
	// function editMultRows
	var $edit1Row      = 'Vous pouvez modifier seulement 1 ligne à la fois.';
	// function valError
	var $errVal        = 'Les champs en rouge doivent être corrigés.';
	// function formatIcons
	var $ttlInfo       = 'Info';
	var $ttlEdit       = 'Modifier';
	var $ttlCopy       = 'Copier';
	var $ttlDelete     = 'Supprimer';
	// function getAdvancedSearchHtml
	var $lblSelect     = 'Selectionner';
	// All Buttons
	var $btnBack       = 'Retour';
	var $btnCancel     = 'Annuler';
	var $btnEdit       = 'Modifier';
	var $btnAdd        = 'Ajouter';
	var $btnUpdate     = 'Actualiser';
	var $btnView       = 'Afficher';
	var $btnCopy       = 'Copier';
	var $btnDelete     = 'Supprimer';
	var $btnExport     = 'Exporter';
	var $btnSearch     = 'Rechercher';
	var $btnCSearch    = 'supprimer la recherche';
	var $btnASearch    = 'Recherche avancée';
	var $btnQSearch    = 'Recherche rapide';
	var $btnReset      = 'Défaut';
	var $btnAddCrit    = 'Ajouter des critères';
	var $btnShowHide   = 'Afficher/Cacher les colonnes';
	var $btnOrderCols  = 'Ordre des colonnes';
	var $btnCFilters   = 'Supprimer Filtres';
	var $btnFilters    = 'Appliquer des filtres';
	// function displayTableHtml
	var $ttlDispRecs   = 'Afficher %s - %s de %s lignes';
	var $ttlDispNoRecs = 'Afficher 0 lignes';
	var $ttlRecords    = 'Lignes';
	var $ttlNoRecord   = 'Ne trouve pas des lignes';
	var $lblSearch     = 'Rechercher';
	var $lblPage       = 'Page numéro: ';
	var $lblDisplay    = 'Afficher ';
	var $lblMatch      = 'Correspondre: ';
	var $lblAllCrit    = 'Tous les critères';
	var $lblAnyCrit    = 'Un des critères';
	// function showHideColumns
	var $ttlColumn     = 'Colonne';
	var $ttlCheckBox   = 'Afficher';
	// function handleFileUpload
	var $errFileSize   = 'Le %s est trop grand';
	var $errFileReq   = '%s est champ obligatoire';
}
?>


text:
import {
  Component,
  Input,
  Output,
  EventEmitter,
  TemplateRef,
} from '@angular/core';
import { CalendarEvent } from 'calendar-utils';
import { Subject } from 'rxjs';
import { CalendarEventTimesChangedEvent } from '../common/calendar-event-times-changed-event.interface';
import { PlacementArray } from 'positioning';
import { CalendarWeekViewBeforeRenderEvent } from '../week/calendar-week.module';

export type CalendarDayViewBeforeRenderEvent =
  CalendarWeekViewBeforeRenderEvent;

/**
 * Shows all events on a given day. Example usage:
 *
 * ```typescript
 * <mwl-calendar-day-view
 *  [viewDate]="viewDate"
 *  [events]="events">
 * </mwl-calendar-day-view>
 * ```
 */
@Component({
  selector: 'mwl-calendar-day-view',
  template: `
    <mwl-calendar-week-view
      class="cal-day-view"
      [daysInWeek]="1"
      [viewDate]="viewDate"
      [events]="events"
      [hourSegments]="hourSegments"
      [hourDuration]="hourDuration"
      [hourSegmentHeight]="hourSegmentHeight"
      [minimumEventHeight]="minimumEventHeight"
      [dayStartHour]="dayStartHour"
      [dayStartMinute]="dayStartMinute"
      [dayEndHour]="dayEndHour"
      [dayEndMinute]="dayEndMinute"
      [refresh]="refresh"
      [locale]="locale"
      [eventSnapSize]="eventSnapSize"
      [tooltipPlacement]="tooltipPlacement"
      [tooltipTemplate]="tooltipTemplate"
      [tooltipAppendToBody]="tooltipAppendToBody"
      [tooltipDelay]="tooltipDelay"
      [hourSegmentTemplate]="hourSegmentTemplate"
      [eventTemplate]="eventTemplate"
      [eventTitleTemplate]="eventTitleTemplate"
      [eventActionsTemplate]="eventActionsTemplate"
      [snapDraggedEvents]="snapDraggedEvents"
      [allDayEventsLabelTemplate]="allDayEventsLabelTemplate"
      [currentTimeMarkerTemplate]="currentTimeMarkerTemplate"
      [validateEventTimesChanged]="validateEventTimesChanged"
      (eventClicked)="eventClicked.emit($event)"
      (hourSegmentClicked)="hourSegmentClicked.emit($event)"
      (eventTimesChanged)="eventTimesChanged.emit($event)"
      (beforeViewRender)="beforeViewRender.emit($event)"
    ></mwl-calendar-week-view>
  `,
})
export class CalendarDayViewComponent {
  /**
   * The current view date
   */
  @Input() viewDate: Date;

  /**
   * An array of events to display on view
   * The schema is available here: https://github.com/mattlewis92/calendar-utils/blob/c51689985f59a271940e30bc4e2c4e1fee3fcb5c/src/calendarUtils.ts#L49-L63
   */
  @Input() events: CalendarEvent[] = [];

  /**
   * The number of segments in an hour. Must divide equally into 60.
   */
  @Input() hourSegments: number = 2;

  /**
   * The height in pixels of each hour segment
   */
  @Input() hourSegmentHeight: number = 30;

  /**
   * The duration of each segment group in minutes
   */
  @Input() hourDuration: number;

  /**
   * The minimum height in pixels of each event
   */
  @Input() minimumEventHeight: number = 30;

  /**
   * The day start hours in 24 hour time. Must be 0-23
   */
  @Input() dayStartHour: number = 0;

  /**
   * The day start minutes. Must be 0-59
   */
  @Input() dayStartMinute: number = 0;

  /**
   * The day end hours in 24 hour time. Must be 0-23
   */
  @Input() dayEndHour: number = 23;

  /**
   * The day end minutes. Must be 0-59
   */
  @Input() dayEndMinute: number = 59;

  /**
   * An observable that when emitted on will re-render the current view
   */
  @Input() refresh: Subject<any>;

  /**
   * The locale used to format dates
   */
  @Input() locale: string;

  /**
   * The grid size to snap resizing and dragging of events to
   */
  @Input() eventSnapSize: number;

  /**
   * The placement of the event tooltip
   */
  @Input() tooltipPlacement: PlacementArray = 'auto';

  /**
   * A custom template to use for the event tooltips
   */
  @Input() tooltipTemplate: TemplateRef<any>;

  /**
   * Whether to append tooltips to the body or next to the trigger element
   */
  @Input() tooltipAppendToBody: boolean = true;

  /**
   * The delay in milliseconds before the tooltip should be displayed. If not provided the tooltip
   * will be displayed immediately.
   */
  @Input() tooltipDelay: number | null = null;

  /**
   * A custom template to use to replace the hour segment
   */
  @Input() hourSegmentTemplate: TemplateRef<any>;

  /**
   * A custom template to use for day view events
   */
  @Input() eventTemplate: TemplateRef<any>;

  /**
   * A custom template to use for event titles
   */
  @Input() eventTitleTemplate: TemplateRef<any>;

  /**
   * A custom template to use for event actions
   */
  @Input() eventActionsTemplate: TemplateRef<any>;

  /**
   * Whether to snap events to a grid when dragging
   */
  @Input() snapDraggedEvents: boolean = true;

  /**
   * A custom template to use for the all day events label text
   */
  @Input() allDayEventsLabelTemplate: TemplateRef<any>;

  /**
   * A custom template to use for the current time marker
   */
  @Input() currentTimeMarkerTemplate: TemplateRef<any>;

  /**
   * Allow you to customise where events can be dragged and resized to.
   * Return true to allow dragging and resizing to the new location, or false to prevent it
   */
  @Input() validateEventTimesChanged: (
    event: CalendarEventTimesChangedEvent
  ) => boolean;

  /**
   * Called when an event title is clicked
   */
  @Output() eventClicked = new EventEmitter<{
    event: CalendarEvent;
    sourceEvent: MouseEvent | KeyboardEvent;
  }>();

  /**
   * Called when an hour segment is clicked
   */
  @Output() hourSegmentClicked = new EventEmitter<{
    date: Date;
    sourceEvent: MouseEvent;
  }>();

  /**
   * Called when an event is resized or dragged and dropped
   */
  @Output() eventTimesChanged =
    new EventEmitter<CalendarEventTimesChangedEvent>();

  /**
   * An output that will be called before the view is rendered for the current day.
   * If you add the `cssClass` property to an hour grid segment it will add that class to the hour segment in the template
   */
  @Output() beforeViewRender =
    new EventEmitter<CalendarDayViewBeforeRenderEvent>();
}


text:
@-moz-document url(about:newtab) {
  body { background-color: black !important; }
  #newtab-customize-button { display: none; }
}


text:
package ilyag.ah52;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	EditText	et;

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.square) {
			String s = et.getText().toString();
			if ("".equals(s)) {
				return false;
			}
			Integer i = Integer.parseInt(s);
			Toast.makeText(getApplicationContext(), String.valueOf(Math.sqrt(i)), Toast.LENGTH_LONG).show();
		} else if (id == R.id.powerTwo) {
			String s = et.getText().toString();
			if ("".equals(s)) {
				return false;
			}
			Integer i = Integer.parseInt(s);
			Toast.makeText(getApplicationContext(), String.valueOf(Math.pow(i, 2)), Toast.LENGTH_LONG).show();
		} else {
			return false;
		}
		return true;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		et = (EditText) findViewById(R.id.editText);
		registerForContextMenu(et);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		if (v == et) {
			getMenuInflater().inflate(R.menu.menu, menu);
		}
	}
}


text:
package mutator

import (
	"reflect"
)

func Create(functionPointer interface{}) interface{} {
	//use reflection to find out what we need about the function providewd
	funcReflect := reflect.ValueOf(functionPointer)
	function := funcReflect.Elem()

	outType := function.Type().Out(0)

	//Start mutator function ----------------------------------------
	//this is the function that we will use as the template for the specific
	//mutator that we are going to create
	var mutate = func(in []reflect.Value) (out []reflect.Value) {
		inValue := in[0]
		outValue := reflect.New(outType).Elem()
		//scan for all tags in input that point to the ∆ output type
		for i := 0; i < inValue.NumField(); i++ {
			tag := inValue.Type().Field(i).Tag.Get("∆." + outType.String())
			//if we found one and it points to a setable field then try to set it
			if outValue.FieldByName(tag).CanSet() {
				outValue.FieldByName(tag).Set(inValue.Field(i))
			}
		}
		//the return type is an array of reflect values of length one of type
		return []reflect.Value{outValue}
	}
	//End mutator function ----------------------------------------

	//create the mutator function using reflection
	mutator := reflect.MakeFunc(function.Type(), mutate)

	//set the pointer in the original function pointer and also return it
	function.Set(mutator)
	return functionPointer
}


text:
package ru.harati.scavel.d3

import ru.harati.scavel.BasicTypes.{hasZero, isAdditive}
import ru.harati.scavel.{Operations, PrimitiveFactory, SelfPointed, Vec}
import ru.harati.scavel.d2.{Point2, Vec2}
import ru.harati.scavel.Operations.{AdditiveCollection, MappableCollection, hasLength, hasPlainDimension, isComparableCollection, isFoldableCollection}

/**
 * Created by loki on 06.04.2017.
 */
object Vec3 extends SelfPointed
  with MappableCollection[Vec3]
  with hasLength[Vec3]
  with AdditiveCollection[Vec3]
  with hasPlainDimension[Vec3]
  with isComparableCollection[Vec3]
  with isFoldableCollection[Vec3]
  with PrimitiveFactory[Vec3] {

  def apply[T](carrier: Point3[T]): Vec3[T] = new Vec3[T](carrier)
  def apply[T](a: T, b: T, c: T): Vec3[T] = Vec3(Point3(a, b, c))

  override def map[T, R](data: Vec3[T], function: (T) => R): Vec3[R] = Vec3(function(data.x), function(data.y), function(data.z))
  override def plus[T](a: Vec3[T], b: Vec3[T])(implicit additive: isAdditive[T]): Vec3[T] =
    Vec3(additive.plus(a.x, b.x), additive.plus(a.y, b.y), additive.plus(a.z, b.z))
  override def dimension[T](data: Vec3[T])(implicit field: hasZero[T]): Int = data.carrier.dimension
  override def length[T](data: Vec3[T])(implicit fractional: Fractional[T]): Double = {
    val x = fractional.toDouble(data.x)
    val y = fractional.toDouble(data.y)
    val z = fractional.toDouble(data.z)
    Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))
  }

  override def min[T](self: Vec3[T], that: Vec3[T])(implicit ord: Ordering[T]): Vec3[T] =
    Vec3(ord.min(self.x, that.x), ord.min(self.y, that.y), ord.min(self.z, that.z))
  override def max[T](self: Vec3[T], that: Vec3[T])(implicit ord: Ordering[T]): Vec3[T] =
    Vec3(ord.max(self.x, that.x), ord.max(self.y, that.y), ord.max(self.z, that.z))

  override def fold[T, R](data: Vec3[T], initial: R, trans: (R, T) => R): R = trans(trans(trans(initial, data.x), data.y), data.z)

  override def fill[T](data: T): Vec3[T] = Vec3(data, data, data)
}

class Vec3[@specialized(Int, Long, Float, Double) T](coordinates: Point3[T]) extends Vec[T] {
  @inline override def carrier: Point3[T] = coordinates
  @inline def x: T = carrier.x
  @inline def y: T = carrier.y
  @inline def z: T = carrier.z

  override def toString = s"Vec3($x, $y, $z)"
}


text:
hubot-rassle-names
==================

Generates and assigns wrestling names.


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>Qt 4.3: Qt Tutorial 7 - One Thing Leads to Another</title>
  <link rel="prev" href="tutorial-t6.html" />
  <link rel="contents" href="tutorial.html" />
  <link rel="next" href="tutorial-t8.html" />
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

[Previous: Chapter 6]
[Qt Tutorial]
[Next: Chapter 8]

Qt Tutorial 7 - One Thing Leads to Another

Files:

tutorial/t7/lcdrange.cpp

tutorial/t7/lcdrange.h

tutorial/t7/main.cpp

This example shows how to create custom widgets with signals and slots, and how to connect them together in more complex ways. For the first time, the source is split among several files which we've placed in the <tt>examples/tutorial/t7</tt> directory.

Line by Line Walkthrough

t7/lcdrange.h

This file is mainly lifted from <tt>main.cpp</tt> in Chapter 6; only the non-trivial changes are noted here.

 #ifndef LCDRANGE_H
 #define LCDRANGE_H

This, together with the <tt>#endif</tt> at the end of the file, is the standard C++ construction to avoid errors if a header file happens to be included more than once. If you don't use it already, it is a very good habit to develop.

 #include <QWidget>

<tt><QWidget></tt> is included since our <tt>LCDRange</tt> class inherits QWidget. The header file of a parent class must always be included - we cheated a bit in the previous chapters, and we let <tt><QWidget></tt> be included indirectly via other header files.

 class QSlider;

This is another classic trick, but one that's much less used often. Because we don't need QSlider in the interface of the class, only in the implementation, we use a forward declaration of the class in the header file and include the header file for QSlider in the <tt>.cpp</tt> file.

This makes the compilation of big projects much faster, because the compiler usually spends most of its time parsing header files, not the actual source code. This trick alone can often speed up compilations by a factor of two or more.

 class LCDRange : public QWidget
 {
     Q_OBJECT

 public:
     LCDRange(QWidget *parent = 0);

Note the <tt>Q_OBJECT</tt>. This macro must be included in all classes that contain signals and/or slots. If you are curious, it defines the functions that are implemented in the meta-object file.

     int value() const;

 public slots:
     void setValue(int value);

 signals:
     void valueChanged(int newValue);

These three members make up an interface between this widget and other components in a program. Until now, <tt>LCDRange</tt> didn't really have an API at all.

<tt>value()</tt> is a public function for accessing the value of the <tt>LCDRange</tt>, <tt>setValue()</tt> is our first custom slot, and <tt>valueChanged()</tt> is our first custom signal.

Slots must be implemented in the normal way (a slot is also a C++ member function). Signals are automatically implemented in the meta-object file. Signals follow the access rules of protected C++ functions (i.e., they can be emitted only by the class they are defined in or by classes inheriting from it).

The <tt>valueChanged()</tt> signal is used when the <tt>LCDRange</tt>'s value has changed.

t7/lcdrange.cpp

This file is mainly lifted from <tt>main.cpp</tt> in Chapter 6, and only the changes are noted here.

     connect(slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)));
     connect(slider, SIGNAL(valueChanged(int)),
             this, SIGNAL(valueChanged(int)));

This code is from the <tt>LCDRange</tt> constructor.

The first connect() call is the same that you have seen in the previous chapter. The second is new; it connects slider's valueChanged() signal to this object's <tt>valueChanged()</tt> signal. Yes, that's right. Signals can be connected to other signals. When the first is emitted, the second signal is also emitted.

Let's look at what happens when the user operates the slider. The slider sees that its value has changed and emits the valueChanged() signal. That signal is connected both to the display() slot of the QLCDNumber and to the <tt>valueChanged()</tt> signal of the <tt>LCDRange</tt>.

Thus, when the signal is emitted, <tt>LCDRange</tt> emits its own <tt>valueChanged()</tt> signal. In addition, QLCDNumber::display() is called and shows the new number.

Note that you're not guaranteed any particular order of execution; <tt>LCDRange::valueChanged()</tt> may be emitted before or after QLCDNumber::display() is called.

 int LCDRange::value() const
 {
     return slider->value();
 }

The implementation of <tt>value()</tt> is straightforward. It simply returns the slider's value.

 void LCDRange::setValue(int value)
 {
     slider->setValue(value);
 }

The implementation of <tt>setValue()</tt> is equally straightforward. Note that because the slider and LCD number are connected, setting the slider's value automatically updates the LCD number as well. In addition, the slider will automatically adjust the value if it is outside its legal range.

t7/main.cpp

     LCDRange *previousRange = 0;

     for (int row = 0; row < 3; ++row) {
         for (int column = 0; column < 3; ++column) {
             LCDRange *lcdRange = new LCDRange;
             grid->addWidget(lcdRange, row, column);
             if (previousRange)
                 connect(lcdRange, SIGNAL(valueChanged(int)),
                         previousRange, SLOT(setValue(int)));
             previousRange = lcdRange;
         }
     }

All of <tt>main.cpp</tt> is copied from the previous chapter except in the constructor for <tt>MyWidget</tt>. When we create the nine <tt>LCDRange</tt> objects, we connect them using the signals and slots mechanism. Each has its <tt>valueChanged()</tt> signal connected to the previous one's <tt>setValue()</tt> slot. Because <tt>LCDRange</tt> emits the <tt>valueChanged()</tt> signal when its value changes, we are here creating a chain of signals and slots.

Compiling the Application

Creating a makefile for a multi-file application is no different from creating one for a single-file application. If you've saved all the files in this example in their own directory, all you have to do is:

 qmake -project
 qmake

The first command tells qmake to create a <tt>.pro</tt> file. The second command tells it to create a (platform-specific) makefile based on the project file. You should now be able to type <tt>make</tt> (or <tt>nmake</tt> if you're using Visual Studio) to build your application.

Running the Application

On startup, the program's appearance is identical to the previous one. Try operating the slider to the bottom-right.

Exercises

Use the bottom-right slider to set all LCDs to 50. Then set the top six to 30 by clicking on the slider on the row above. Now, use the one to the left of the last one operated to set the first five LCDs back to 50.

Click to the left of the handle on the bottom-right slider. What happens? Why is this the correct behavior?

[Previous: Chapter 6]
[Qt Tutorial]
[Next: Chapter 8]

<address>

Copyright © 2008 Trolltech
Trademarks

Qt 4.3.5

</address>


text:
[![Build Status](https://github.com/mgomes/api_auth/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/mgomes/api_auth/actions)
[![Gem Version](https://badge.fury.io/rb/api-auth.svg)](https://badge.fury.io/rb/api-auth)

Logins and passwords are for humans. Communication between applications need to
be protected through different means.

ApiAuth is a Ruby gem designed to be used both in your client and server
HTTP-based applications. It implements the same authentication methods (HMAC-SHA2)
used by Amazon Web Services.

The gem will sign your requests on the client side and authenticate that
signature on the server side. If your server resources are implemented as a
Rails ActiveResource, it will integrate with that. It will even generate the
secret keys necessary for your clients to sign their requests.

Since it operates entirely using HTTP headers, the server component does not
have to be written in the same language as the clients.

## How it works

1. A canonical string is first created using your HTTP headers containing the
`content-type`, `X-Authorization-Content-SHA256`, request path and the date/time stamp.
If `content-type` or `X-Authorization-Content-SHA256` are not present, then a blank
string is used in their place. If the timestamp isn't present, a valid HTTP date is
automatically added to the request. The canonical string is computed as follows:

```ruby
canonical_string = "#{http method},#{content-type},#{X-Authorization-Content-SHA256},#{request URI},#{timestamp}"
```

e.g.,

```ruby
canonical_string = 'POST,application/json,,request_path,Tue, 30 May 2017 03:51:43 GMT'
```

2. This string is then used to create the signature which is a Base64 encoded
SHA1 HMAC, using the client's private secret key.

3. This signature is then added as the `Authorization` HTTP header in the form:

```ruby
Authorization = APIAuth "#{client access id}:#{signature from step 2}"
```

A cURL request would look like:

```sh
curl -X POST --header 'Content-Type: application/json' --header "Date: Tue, 30 May 2017 03:51:43 GMT" --header "Authorization: ${AUTHORIZATION}"  https://my-app.com/request_path`
```

5. On the server side, the SHA2 HMAC is computed in the same way using the
request headers and the client's secret key, which is known to only
the client and the server but can be looked up on the server using the client's
access id that was attached in the header. The access id can be any integer or
string that uniquely identifies the client. The signed request expires after 15
minutes in order to avoid replay attacks.

## References

* [Hash functions](https://en.wikipedia.org/wiki/Cryptographic_hash_function)
* [SHA-2 Hash function](https://en.wikipedia.org/wiki/SHA-2)
* [HMAC algorithm](https://en.wikipedia.org/wiki/HMAC)
* [RFC 2104 (HMAC)](https://tools.ietf.org/html/rfc2104)

## Requirement

This gem require Ruby >= 2.6 and Rails >= 6.0 if you use rails.

## Install

The gem doesn't have any dependencies outside of having a working OpenSSL
configuration for your Ruby VM. To install:

```sh
[sudo] gem install api-auth
```

Please note the dash in the name versus the underscore.

## Clients

ApiAuth supports many popular HTTP clients. Support for other clients can be
added as a request driver.

Here is the current list of supported request objects:

* Net::HTTP
* ActionDispatch::Request
* Curb (Curl::Easy)
* RestClient
* Faraday
* HTTPI
* HTTP

### HTTP Client Objects

Here's a sample implementation of signing a request created with RestClient.

Assuming you have a client access id and secret as follows:

```ruby
@access_id = "1044"
@secret_key = ApiAuth.generate_secret_key
```

A typical RestClient PUT request may look like:

```ruby
headers = { 'X-Authorization-Content-SHA256' => "dWiCWEMZWMxeKM8W8Yuh/TbI29Hw5xUSXZWXEJv63+Y=",
  'Content-Type' => "text/plain",
  'Date' => "Mon, 23 Jan 1984 03:29:56 GMT"
}

@request = RestClient::Request.new(
    url: "/resource.xml?foo=bar&bar=foo",
    headers: headers,
    method: :put
)
```

To sign that request, simply call the `sign!` method as follows:

```ruby
@signed_request = ApiAuth.sign!(@request, @access_id, @secret_key)
```

The proper `Authorization` request header has now been added to that request
object and it's ready to be transmitted. It's recommended that you sign the
request as one of the last steps in building the request to ensure the headers
don't change after the signing process which would cause the authentication
check to fail on the server side.

If you are signing a request for a driver that doesn't support automatic http
method detection (like Curb or httpi), you can pass the http method as an option
into the sign! method like so:

```ruby
@signed_request = ApiAuth.sign!(@request, @access_id, @secret_key, :override_http_method => "PUT")
```

If you want to use another digest existing in `OpenSSL::Digest`,
you can pass the http method as an option into the sign! method like so:

```ruby
@signed_request = ApiAuth.sign!(@request, @access_id, @secret_key, :digest => 'sha256')
```

With the `digest` option, the `Authorization` header will be change from:

```sh
Authorization = APIAuth 'client access id':'signature'
```

to:

```sh
Authorization = APIAuth-HMAC-DIGEST_NAME 'client access id':'signature'
```

### ActiveResource Clients

ApiAuth can transparently protect your ActiveResource communications with a
single configuration line:

```ruby
class MyResource < ActiveResource::Base
  with_api_auth(access_id, secret_key)
end
```

This will automatically sign all outgoing ActiveResource requests from your app.

### Flexirest

ApiAuth also works with [Flexirest](https://github.com/andyjeffries/flexirest) (used to be ActiveRestClient, but that is now unsupported) in a very similar way.
Simply add this configuration to your Flexirest initializer in your app and it will automatically sign all outgoing requests.

```ruby
Flexirest::Base.api_auth_credentials(@access_id, @secret_key)
```

### Faraday

ApiAuth provides a middleware for adding authentication to a Faraday connection:

```ruby
require 'faraday/api_auth'
Faraday.new do |f|
  f.request :api_auth, @access_id, @secret_key
end
```

The order of middlewares is important. You should make sure api_auth is last.

## Server

ApiAuth provides some built in methods to help you generate API keys for your
clients as well as verifying incoming API requests.

To generate a Base64 encoded API key for a client:

```ruby
ApiAuth.generate_secret_key
```

To validate whether or not a request is authentic:

```ruby
ApiAuth.authentic?(signed_request, secret_key)
```

The `authentic?` method uses the digest specified in the `Authorization` header.
For example SHA256 for:

```sh
Authorization = APIAuth-HMAC-SHA256 'client access id':'signature'
```

And by default SHA1 if the HMAC-DIGEST is not specified.

If you want to force the usage of another digest method, you should pass it as an option parameter:

```ruby
ApiAuth.authentic?(signed_request, secret_key, :digest => 'sha256')
```

For security, requests dated older or newer than a certain timespan are considered inauthentic.

This prevents old requests from being reused in replay attacks, and also ensures requests
can't be dated into the far future.

The default span is 15 minutes, but you can override this:

```ruby
ApiAuth.authentic?(signed_request, secret_key, :clock_skew => 60) # or 1.minute in ActiveSupport
```

If you want to sign custom headers, you can pass them as an array of strings in the options like so:

``` ruby
ApiAuth.authentic?(signed_request, secret_key, headers_to_sign: %w[HTTP_HEADER_NAME])
```

With the specified headers values being at the end of the canonical string in the same order.

If your server is a Rails app, the signed request will be the `request` object.

In order to obtain the secret key for the client, you first need to look up the
client's access_id. ApiAuth can pull that from the request headers for you:

``` ruby
ApiAuth.access_id(signed_request)
```

Once you've looked up the client's record via the access id, you can then verify
whether or not the request is authentic. Typically, the access id for the client
will be their record's primary key in the DB that stores the record or some other
public unique identifier for the client.

Here's a sample method that can be used in a `before_action` if your server is a
Rails app:

``` ruby
before_action :api_authenticate

def api_authenticate
  @current_account = Account.find_by_access_id(ApiAuth.access_id(request))
  head(:unauthorized) unless @current_account && ApiAuth.authentic?(request, @current_account.secret_key)
end
```

## Development

ApiAuth uses bundler for gem dependencies and RSpec for testing. Developing the
gem requires that you have all supported HTTP clients installed. Bundler will
take care of all that for you.

To run the tests:

Install the dependencies for a particular Rails version by specifying a gemfile in `gemfiles` directory:

```sh
BUNDLE_GEMFILE=gemfiles/rails_5.gemfile bundle install
```

Run the tests with those dependencies:

```sh
BUNDLE_GEMFILE=gemfiles/rails_5.gemfile bundle exec rake
```

If you'd like to add support for additional HTTP clients, check out the already
implemented drivers in `lib/api_auth/request_drivers` for reference. All of
the public methods for each driver are required to be implemented by your driver.

## Authors

* [Mauricio Gomes](https://github.com/mgomes)
* [Kevin Glowacz](https://github.com/kjg)
* [Florian Wininger](https://github.com/fwininger)

## Copyright

Copyright (c) 2014 Mauricio Gomes. See LICENSE.txt for further details.


text:
import { Component, Inject } from '@angular/core';
import { DialogComponent } from '@shared/components/dialog.component';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { Router } from '@angular/router';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FormattedData } from '@shared/models/widget.models';

export interface SelectEntityDialogData {
  entities: FormattedData[];
}

@Component({
  selector: 'tb-select-entity-dialog',
  templateUrl: './select-entity-dialog.component.html',
  styleUrls: ['./select-entity-dialog.component.scss']
})
export class SelectEntityDialogComponent extends DialogComponent<SelectEntityDialogComponent, FormattedData> {

  selectEntityFormGroup: FormGroup;

  constructor(protected store: Store<AppState>,
              protected router: Router,
              @Inject(MAT_DIALOG_DATA) public data: SelectEntityDialogData,
              public dialogRef: MatDialogRef<SelectEntityDialogComponent, FormattedData>,
              public fb: FormBuilder) {
    super(store, router, dialogRef);

    this.selectEntityFormGroup = this.fb.group(
      {
        entity: ['', Validators.required]
      }
    );
  }

  save(): void {
    this.dialogRef.close(this.selectEntityFormGroup.value.entity);
  }
}


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

public class MicrogameVolumeControl : MonoBehaviour
{
    [SerializeField]
    private AudioMixer microgameMixer;

    [SerializeField]
    private Mode mode;
    [SerializeField]
    private float volume;

    private enum Mode
    {
        decibals,
        volumeLevel
    }

    void LateUpdate()
    {
        float oldVolume;
        microgameMixer.GetFloat("MasterVolume", out oldVolume);
        if (mode == Mode.volumeLevel)
            oldVolume = AudioHelper.DecibalsToVolumeLevel(oldVolume);
        if (!MathHelper.Approximately(volume, oldVolume, .001f))
        {
            var newVolume = volume;
            if (mode == Mode.volumeLevel)
                newVolume = AudioHelper.VolumeLevelToDecibals(newVolume);
            microgameMixer.SetFloat("MasterVolume", newVolume);
        }
    }

}


text:
#ifndef _STVKELEMENTABCD_H_
#define _STVKELEMENTABCD_H_

#include "minivector.h"

/*
  This abstract class serves as storage space for the St.Venant-Kirchhoff A,B,C,D coefficients for a mesh element.
  See also StVKInternalForces.h .
*/

class StVKElementABCD
{
public:

  // the iterator can be different types in the derived implementation classes
  virtual Mat3d A(void * elementIterator, int i, int j) = 0;
  virtual double B(void * elementIterator, int i, int j) = 0;
  virtual Vec3d C(void * elementIterator, int i, int j, int k) = 0;
  virtual double D(void * elementIterator, int i, int j, int k, int l) = 0;

  virtual ~StVKElementABCD() {};

  virtual void AllocateElementIterator(void ** elementIterator);
  virtual void ReleaseElementIterator(void * elementIterator);
  virtual void PrepareElement(int el, void * elementIterator); // must call each time before accessing an element

protected:
};

#endif


text:
<?xml version="1.0"?>
<x xmlns:xinclude="http://www.w3.org/2001/XInclude">

   <doc xml:base="../ents/something.xml">

something

really

simple

</doc>
</x>