text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>net.vayzd</groupId>
        <artifactId>orbit</artifactId>
        <version>1.12-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>orbit-spigot</artifactId>
    <packaging>jar</packaging>
    <version>1.12-SNAPSHOT</version>

    <repositories>
        <!-- SpigotMC Repository -->
        <repository>
            <id>spigot-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <scope>provided</scope>
            <version>1.11.2-R0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>net.vayzd</groupId>
            <artifactId>orbit-datastore</artifactId>
            <scope>compile</scope>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <sourceDirectory>${basedir}/src/main/java/</sourceDirectory>
        <resources>
            <resource>
                <targetPath>.</targetPath>
                <filtering>true</filtering>
                <directory>${basedir}/src/main/resources/</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <finalName>Orbit-${project.parent.version}</finalName>
    </build>
</project>


text:
<?php

namespace Datatheke\Bundle\ApiBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

use FOS\OAuthServerBundle\Document\AuthCode as BaseAuthCode;

/**
 * @MongoDB\Document
 */
class AuthCode extends BaseAuthCode
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\ReferenceOne(targetDocument="Client")
     */
    protected $client;

    /**
     * @MongoDB\ReferenceOne(targetDocument="Datatheke\Bundle\CoreBundle\Document\User")
     */
    protected $user;
}

redpajama_set_name: RedPajamaGithub


text:
* * *

title: Digital Citizenship view: page_curriculum theme: none

* * *

<%= partial('curriculum_header', :unplugged=>true, :title=> 'Digital Citizenship',:disclaimer=>'Basic lesson time includes activity only. Introductory and Wrap-Up suggestions can be used to delve deeper when time allows.', :time=>30) %>

[content]

[together]

## Преглед на урока

In collaboration with [Common Sense Media](https://www.commonsensemedia.org/educators/scope-and-sequence), this lesson helps students learn to think critically about the user information that some websites request or require. Students learn the difference between private information and personal information, distinguishing what is safe and unsafe to share online.

Students will also explore what it means to be responsible and respectful to their offline and online communities as a step toward learning how to be good digital citizens.

[summary]

## Резюме на обучението

### **Getting Started** - 15 minutes

1) [Review](#Review)
2) [Vocabulary](#Vocab)
3) [Personal vs. Private Online](#GetStarted)

### **Activity: Digital Citizens** - 30 minutes

4) [Digital Citizens](#Activity1)

### **Wrap-up** - 10 minutes

5) [Flash Chat](#WrapUp) - What did we learn?
6) [Vocab Shmocab](#Shmocab)

### **Assessment** - 5 minutes

7) [Digital Citizens Assessment](#Assessment)

[/summary]

## Цели на урока

### Учениците ще:

  * Compare and contrast their responsibilities to their online and offline communities
  * Understand what type of information can put them at risk for identity theft and other scams
  * Reflect on the characteristics that make someone an upstanding citizen
  * Devise resolutions to digital dilemmas

[/together]

[together]

# Ръководство за обучение

## Материали, ресурси и подготовка

### За учениците

  * [Papercraft Super Heroes](https://www.google.com/search?q=cubeecraft+superheroes&es_sm=119&tbm=isch&tbo=u&source=univ&sa=X&ei=v9SxU4TnJdHroATI5YDYCA&ved=0CCEQsAQ&biw=1273&bih=635)
  * Pens, Pencils, & Scissors
  * [Super Digital Citizen Assessment](Assessment20-DigitalCitizenship.pdf) for each student

### За учителя

  * [Lesson Video](http://youtu.be/fIlqt3P8Nsg?list=PL2DhNKNdmOtpGJ79ZYYttiEmc-1Aq8hxm)
  * This Teacher Lesson Guide
  * A good selection of male and female [Papercraft Super Heroes](https://www.google.com/search?q=cubeecraft+superheroes&es_sm=119&tbm=isch&tbo=u&source=univ&sa=X&ei=v9SxU4TnJdHroATI5YDYCA&ved=0CCEQsAQ&biw=1273&bih=635) sheets for the whole class
  * Print one [Super Digital Citizen Assessment](Assessment20-DigitalCitizenship.pdf) for each student

[/together]

[together]

## Getting Started (15 min)

###  1) Review

This is a great time to review the last lesson that you went through with your class. We suggest you alternate between asking questions of the whole class and having students talk about their answers in small groups.

Here are some questions that you can ask in review:

  * What did we do last time?

  * What do you wish we had had a chance to do?

  * Did you think of any questions after the lesson that you want to ask?

  * What was your favorite part of the last lesson?

[tip]

# Съвет за урока

Finishing the review by asking about the students' favorite things helps to leave a positive impression of the previous exercise, increasing excitement for the activity that you are about to introduce.

[/tip]

###  2) Vocabulary

Този урок има една нова и важна дума:

[centerIt]

![](vocab.png)

[/centerIt]

**Digital Citizen** - Say it with me: Dih-jih-tal Sit-i-zen
Someone who acts safely, responsibly, and respectfully online

###  3) Personal vs. Private Online

  * Ask "What types of information do you think are okay to share publicly online or on a profile that others will see?"
  * What are some examples of websites where you must register in order to participate?
      * Write the names of the websites on the board.
      * What information is required and why do you think it is required?
          * Information may be required to help distinguish one person from another.
          * The website may keep a record of who uses it.
      * Explain that it's important to know that sharing some kinds of user information can put you and your family's privacy at risk.
      * Point out that you do not have to fill out fields on websites if they are not required.
          * Required fields are usually marked by an asterisk (*) or are highlighted in red.
  * Elementary school students should never register for sites that require private information without the approval and guidance of a parent or guardian.
  * Here is an example of public versus private information:

![](info.png)

[tip]

# Съвет за урока

If you have access to a computer, feel free to navigate to a site that might require this type of information, such as Gmail or Facebook.

[/tip]

  * Explain that some people will actively try to get you to share this kind of information so that they can use it to take over your identity. Once a thief has taken someone's identity, he or she can use that person's name to get a driver's license or buy things, even if the person whose identity they stole isn't old enough to do these things!
      * It's often not until much later that people realize that their identity has been stolen. Identity thieves may also apply for credit cards in other people's names and run up big bills that they don't pay off. Let students know that identity thieves often target children and teens because they have a clean credit history and their parents are unlikely to be aware that someone is taking on their child's identity.

Now, let's see what we can do to keep ourselves safe.

[/together]

[together]

## Дейности: (20 минути)

###  4) [Papercraft Super Heroes](https://www.google.com/search?q=cubeecraft+superheroes&es_sm=119&tbm=isch&tbo=u&source=univ&sa=X&ei=v9SxU4TnJdHroATI5YDYCA&ved=0CCEQsAQ&biw=1273&bih=635)

  * Spiderman says "With great power comes great responsibility." This is also true when working or playing on the Internet.
  * The things we read, see, and hear online can lead people to have all sorts of feelings (e.g., happy, hurt, excited, angry, curious).
      * What we do and say online can be powerful.
  * The Internet allows us to learn about anything, talk to people at any time (no matter where they are in the world), and share our knowledge and creative projects with other people.
      * This also means that negative comments can spread very quickly to friends of all ages.
  * CREATE a three-column chart with the terms "Safe," "Responsible," and "Respectful" written at the top of each column. Invite students to shout out words or phrases that describe how people can act safely, responsibly, and respectfully online, and then write them in the appropriate column.

![](chart.png)

Now, let's really make sure we understand how to be a Super Digital Citizen!

**Directions:**

> 1) Have each student grab a small selection of papercraft sheets and encourage them to blend the pieces to make their very own super hero.
>
> 2) Allow plenty of time for students to cut, glue, and color.
>
> 3) Give students a 5 minute warning to wrap up.
>
> 4) Separate students into groups of 2-4 and tell them to use their super heroes and leftover supplies to stage a scene in which one superhero sees an act of poor digital citizenship. Then have the superhero fix the problem … and save the day!
>
> 5) Go around the room, having each student explain their scene to the class.

[tip]

# Съвет за урока

For more in-depth modules, you can find additions to this curriculum at the [Common Sense Media](https://www.commonsensemedia.org/educators/scope-and-sequence) page on Scope and Sequence.

[/tip]

[/together]

[together]

## Заключение (5 мин)

###  5) Flash Chat: What did we learn?

  * What is a good way to act responsibly online?
  * What kinds of personal information could you share about yourself without showing your identity?
  * What kinds of superpowers or qualities did your digital superheroes have in common?
  * What does Spider-Man's motto "With great power comes great responsibility" mean to you, as someone who uses the Internet?

[tip]

# Съвет за урока

Флаш чат въпросите са предназначени да предизвикат мислене и дискусия за това как урокът се отнася към заобикалящия ни свят и възможното бъдеще. Преценете дали искате да обсъдите тези въпроси общо с класа, в групи, или по двойки.

[/tip]

###  6) Vocab Shmocab

  * Кое от тези определения и дума научихме днес?

> "One who is afraid of spiders"
> "A baby horse"
> "Someone who acts safely, responsibly, and respectfully online"
>
>
> > .. .и каква е думата, която сме научили?

[/together]

[together]

## Assessment (5 min)

### 7) [Digital Citizen Assessment](Assessment20-DigitalCitizenship.pdf)

  * Hand out the assessment worksheet and allow students to complete the activity independently after the instructions have been well explained.
  * This should feel familiar, thanks to the previous activities.

[/together]

[together]

## Разширено обучение

Използвайте тези дейности за подобряване на Ученическия климат в класа. Те могат да бъдат използвани и като извънкласни дейности или в друга форма.

### Common Sense Media

  * Visit [Common Sense Media](https://www.commonsensemedia.org/educators/scope-and-sequence) to learn more about how you can keep your students safe in this digital age.

[/together]

[standards]

## Връзки и информация

### ISTE стандарти

  * 1.c - употреба модели и симулации за опознаването на сложни системи и проблеми.
  * 2.d - Работа в екип по проект за решаване на проблеми.
  * 5.a - Advocate and practice safe, legal, and responsible use of information and technology.
  * 5.b - Exhibit a positive attitude toward using technology that supports collaboration, learning, and productivity.
  * 5.d. - Exhibit leadership for digital citizenship.
  * 6.a - разбиране и използване на технологични системи.

### CSTA К-12 Стандарти по компютърни науки

  * CI.L1:3-01. Practice responsible digital citizenship (legal and ethical behaviors) in the use of technology systems and software.
  * CI.L1:6-01. Discuss basic issues related to responsible use of technology and information, and the consequences of inappropriate use.
  * CI.L1:6-02. Identify the impact of technology (e.g. social networking, cyber bullying, mobile computing and communication, web technologies, cyber security, and virtualization) on personal life and society.
  * CI.L1:6-04. Understand ethical issues that relate to computers and networks (e.g., equity of access, security, privacy, copyright, and intellectual property).
  * CI.L2-01. Exhibit legal and ethical behaviors when using information and technology and discuss the consequences of misuse.
  * CI.L2-05. Describe ethical issues that relate to computers and networks (e.g., security, privacy, ownership, and information sharing).
  * CPP.L2-06. Demonstrate good practices in personal information security: using passwords, encryption, secure transactions.

### Common Core Language Arts

  * SL.3.1 - Engage effectively in a range of collaborative discussions (one-on-one, in groups, and teacher-led) with diverse partners on grade 3 topics and texts, building on others' ideas and expressing their own clearly.
  * SL.3.3 - Ask and answer questions about information from a speaker, offering appropriate elaboration and detail.
  * L.3.6 - Acquire and use accurately grade-appropriate conversational, general academic, and domain-specific words and phrases, including those that signal spatial and temporal relationships.
  * SL.4.1 - Engage effectively in a range of collaborative discussions (one-on-one, in groups, and teacher-led) with diverse partners on grade 4 topics and texts, building on others' ideas and expressing their own clearly.
  * L.4.6 - Acquire and use accurately grade-appropriate general academic and domain-specific words and phrases, including those that signal precise actions, emotions, or states of being and that are basic to a particular topic.
  * SL.5.1 - Engage effectively in a range of collaborative discussions (one-on-one, in groups, and teacher-led) with diverse partners on grade 5 topics and texts, building on others' ideas and expressing their own clearly.
  * L.5.6 - Acquire and use accurately grade-appropriate general academic and domain-specific words and phrases, including those that signal contrast, addition, and other logical relationships.

[/standards]

[/content]

<link rel="stylesheet" type="text/css" href="../docs/morestyle.css" />


text:
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{% trans "Solum" %}{% endblock %}

{% block page_header %}
  {% include "horizon/common/_page_header.html" with title=_("Solum - Assemblies") %}
{% endblock page_header %}

{% block main %}
  {{ table.render }}
{% endblock %}


text:
package training.tests;

import org.openqa.selenium.By;

import org.testng.Assert;
import org.testng.annotations.Test;

import java.nio.file.Path;
import java.nio.file.Paths;

// Задание 12. Сценарий добавления товара
public class TrainingTest008 extends TestBase{

    @Test(description = "Задание 12. Сценарий добавления товара")
    public void addNewProduct() {
        // Логин в панель администрирования учебного приложения
        loginInStore(loginPass, loginPass);
        // Открываем меню Catalog - Кликаем на пункт меню
        clickOnElement(By.xpath("//span[.='Catalog']"));
        // Кликаем на пункт подменю
        clickOnElement(By.xpath("//ul[@class='docs']//span[.='Catalog']"));

        // Нажимаем на кнопку Add New Product
        clickOnElement(By.xpath("//a[contains(text(),'Add New Product')]"));
        // Данные нового товара
        NewProduct product = new NewProduct();
        // Переходим на закладку General
        clickOnElement(By.xpath("//div[@class='tabs']//a[.='General']"));
        // Заполняем Status - Enabled
        clickOnElement(By.xpath("//label[contains(text(),'Enabled')]/input"));
        // Заполняем поле Name
        enterText(By.cssSelector("[name^=name]"), product.getName());
        // Заполняем поле Code
        enterText(By.name("code"), product.getCode());
        // Заполняем Categories - выставляем все галочки
        checkElementsCheckbox(By.name("categories[]"));
        // Заполняем поле Default Category - выбираем случайный
        selectElement(By.cssSelector("select[name=default_category_id]"), null);
        // Заполняем Gender - выставляем все галочки
        checkElementsCheckbox(By.name("product_groups[]"));
        // Заполняем поле Quantity
        enterText(By.name("quantity"), product.getQuantity());
        // Заполняем поле Quantity Unit - выбираем случайный
        selectElement(By.cssSelector("select[name=quantity_unit_id]"), null);
        // Заполняем поле Delivery Status - выбираем случайный
        selectElement(By.cssSelector("select[name=delivery_status_id]"), null);
        // Заполняем поле Sold Out Status - выбираем случайный
        selectElement(By.cssSelector("select[name=sold_out_status_id]"), null);
        // Заполняем поле Upload Images путем к файлу с картинкой
        Path filePath = Paths.get("new_duck_1.png");
        attachFile(By.name("new_images[]"), filePath.toAbsolutePath().toString());
        // Заполняем поле Date Valid From
        enterText(By.name("date_valid_from"), product.getDateValidFrom());
        // Заполняем поле Date Valid To
        enterText(By.name("date_valid_to"), product.getDateValidTo());

        // Переходим на закладку Information
        clickOnElement(By.xpath("//div[@class='tabs']//a[.='Information']"));
        // Заполняем поле Manufacturer - выбираем случайный
        selectElement(By.cssSelector("select[name=manufacturer_id]"), null);
        // Заполняем поле Supplier - выбираем случайный
        selectElement(By.cssSelector("select[name=supplier_id]"), null);
        // Заполняем поле Keywords
        enterText(By.name("keywords"), product.getKeywords());
        // Заполняем поле Short Description
        enterText(By.cssSelector("[name^=short_description"), product.getShortDescription());
        // Заполняем поле Description
        getDriver().findElement(By.cssSelector("div.trumbowyg-editor")).sendKeys(product.getDescription());
        // Заполняем поле Head Title
        enterText(By.cssSelector("[name^=head_title"), product.getHeadTitle());
        // Заполняем поле Meta Description
        enterText(By.cssSelector("[name^=meta_description"), product.getMetaDescription());

        // Переходим на закладку Prices
        clickOnElement(By.xpath("//div[@class='tabs']//a[.='Prices']"));
        // Заполняем поле Purchase Price
        enterText(By.name("purchase_price"), product.getPurchasePrice());
        selectElement(By.cssSelector("select[name=purchase_price_currency_code"), null);
        // Заполняем поле Tax Class
        selectElement(By.cssSelector("select[name=tax_class_id"), null);
        // Заполняем поле Price
        enterText(By.name("prices[USD]"), product.getPricesUsd());
        // Price Incl. Tax (?) - автоматически заполняется
        // Заполняем поле Price
        enterText(By.name("prices[EUR]"), product.getPricesEur());
        // Price Incl. Tax (?) - автоматически заполняется
        // Нажимаем на кнопку Save
        clickOnElement(By.name("save"));

        // кликаем на пункт меню Catalog
        clickOnElement(By.xpath("//span[.='Catalog']"));
        // Кликаем на пункт подменю
        clickOnElement(By.xpath("//ul[@class='docs']//span[.='Catalog']"));
        // Проверяем, что продукт появился в каталоге
        Assert.assertTrue(isElementPresent(By.xpath("//tr[@class='row']//a[.='" + product.getName() + "']")));

    }

}


text:
<!DOCTYPE HTML>

<title>org.apache.sysds.runtime.controlprogram (Apache SystemDS 2.3.0-SNAPSHOT API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Package org.apache.sysds.runtime.controlprogram

Class Summary

Class
Description

BasicProgramBlock

ForProgramBlock

FunctionProgramBlock

IfProgramBlock

LocalVariableMap

Replaces HashMap⟨String, Data⟩ as the table of
 variable names and references.

ParForProgramBlock

The ParForProgramBlock has the same execution semantics as a ForProgamBlock but executes
 the independent iterations in parallel.

ParForProgramBlock.PartitionFormat

Convenience class to package PDataPartitionFormat and its parameters.

Program

ProgramBlock

WhileProgramBlock

Enum Summary

Enum
Description

ParForProgramBlock.PDataPartitioner

ParForProgramBlock.PDataPartitionFormat

ParForProgramBlock.PExecMode

ParForProgramBlock.POptMode

ParForProgramBlock.PResultMerge

ParForProgramBlock.PTaskPartitioner

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.

Copyright © 2021 The Apache Software Foundation. All rights reserved.


text:
package com.example.rest;

import com.example.domain.Note;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import java.util.List;

@Stateless
public class NoteResourceImpl implements NoteResource {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<Note> getNotes()
    {
        return entityManager.createQuery("from Note order by id", Note.class).getResultList();
    }

    @Override
    public void removeNote(Long noteId)
    {
        final Note note = entityManager.find(Note.class, noteId);
        if (null == note) {
            throw new NoResultException("No note with id " + noteId + " found");
        }
        entityManager.remove(note);
    }

    @Override
    public Note saveNote(Note note)
    {
        entityManager.persist(note);
        return note;
    }
}


text:
class Player
{
    public:
        //Init the player
        Player();

        //RectangleShape for our bounding box
        sf::RectangleShape boundingBox;

        //Our respawn time
        sf::Time spawnTime;

        //Player sprites and textures
        sf::Sprite body;
        sf::Sprite legs;
        sf::Texture bodyTexture;
        sf::Texture legsTexture;

        //Players position and velocity
        sf::Vector2f position;
        sf::Vector2f velocity;
        int maxVelocity;

        //Player dimensions
        sf::Vector2f size;

        //Players health
        float health;

        //The starting health
        float startingHealth;

        //Do we render the player?
        bool isActive;

        //Do we animate the player?
        bool isWalking;

        //Do we play the reload animation?
        bool isReloading;

		//Are we playing the respawn sound
        bool isPlayingRespawnSound;

        //Animate the player
        void animateLegs();
        void animateReload();

        //Load our textures
        bool loadTexture(std::string bodyPath);

        //Handle player input
        void handlePlayerEvents(sf::Event event);

        //Move the player
        void movePlayer();

        //Check for collisions against the player and X object.
        bool checkCollision(Collision &collision, Camera &camera);

        //Damage the player if they are touching these collision boxes
        bool checkDamageCollision(Collision &collision, float damageAmount);

        //Play some sounds if the player collides with these tiles
        bool checkAudioCollsion(Collision &collision);

        //End the players life prematurely.
        void killPlayer(SoundManager &soundmngr);

        //Allow the player to respawn at a random spawn point
        void respawn(Camera &camera, SoundManager &soundmngr, int randomNumber = 0);

        //Update player attributes
        void update();

    private:
        //Locations where the player can respawn
        std::vector<sf::Vector2f> spawnPoints;

        //How many spawn points there are
        int MAX_SPAWN_POINTS = 10;

        //How many keys are presed
        int keyCounter = 0;

        //Our fixed respawn time that doesnt change
        const sf::Time respawnTime = sf::milliseconds(1200);
};

#endif // PLAYER_H


text:
package org.apache.ignite.cache.hibernate;

import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCheckedException;
import org.hibernate.cache.CacheException;
import org.hibernate.cache.spi.GeneralDataRegion;
import org.hibernate.cache.spi.QueryResultsRegion;
import org.hibernate.cache.spi.TimestampsRegion;
import org.jetbrains.annotations.Nullable;

/**
 * Implementation of {@link GeneralDataRegion}. This interface defines common contract for {@link QueryResultsRegion}
 * and {@link TimestampsRegion}.
 */
public class HibernateGeneralDataRegion extends HibernateRegion implements GeneralDataRegion {
    /**
     * @param factory Region factory.
     * @param name Region name.
     * @param ignite Grid.
     * @param cache Region cache.
     */
    public HibernateGeneralDataRegion(HibernateRegionFactory factory, String name,
        Ignite ignite, HibernateCacheProxy cache) {
        super(factory, name, ignite, cache);
    }

    /** {@inheritDoc} */
    @Nullable @Override public Object get(Object key) throws CacheException {
        try {
            return cache.get(key);
        } catch (IgniteCheckedException e) {
            throw new CacheException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public void put(Object key, Object val) throws CacheException {
        try {
            cache.put(key, val);
        } catch (IgniteCheckedException e) {
            throw new CacheException(e);
        }
    }

    /** {@inheritDoc} */
    @Override public void evict(Object key) throws CacheException {
        HibernateAccessStrategyAdapter.evict(ignite, cache, key);
    }

    /** {@inheritDoc} */
    @Override public void evictAll() throws CacheException {
        HibernateAccessStrategyAdapter.evictAll(cache);
    }
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Track {

    var $CI;

    public function __construct() {
        //parent::__construct();
        //    Chargement des ressources pour tout le contrôleur
        $this->CI = &get_instance();
        //$this->CI->load->model('procesos/Audit_model', 'AuditManager');
        $this->CI->load->model('audit/Audit_model', 'AuditManager');
    }

    public function track_user() {
        // Start off with the session stuff we know
        $options_echappees_audit = array();
        $options_non_echappees_audit = array();

        // getting the agent

        $options_echappees_audit['agentId'] = $this->CI->session->userdata('person_id');
//        $options_echappees_audit['agentId'] = $this->CI->agent->browser();
        //var_dump($this->CI->session->userdata());
        $user_info = $this->CI->session->userdata('user_info');

        if ($user_info) {
            $options_echappees_audit['nombre'] = $user_info->nombre;
            //$options_echappees_audit['apellido'] = $user_info->BPERS_APELLIDO_PATER;
        }else{
            $options_echappees_audit['agentId'] = $this->CI->session->userdata('identity');
            $options_echappees_audit['nombre'] = $this->CI->session->userdata('username');
        }

        // getting the client IP address (we first asks whether it is behind a proxy)
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $options_echappees_audit['adresseIp'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $options_echappees_audit['adresseIp'] = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            $options_echappees_audit['adresseIp'] = $_SERVER['REMOTE_ADDR'];
        }
        //getting client's domain
        $options_echappees_audit['domaine'] = gethostbyaddr($options_echappees_audit['adresseIp']);

        $options_echappees_audit['navigator'] = $_SERVER['HTTP_USER_AGENT'];

        // REFERER
        if (isset($_SERVER['HTTP_REFERER'])) {
            //if (eregi($_SERVER['HTTP_HOST'], $_SERVER['HTTP_REFERER'])) {
            if (preg_match("/" . $_SERVER['HTTP_HOST'] . "/i", $_SERVER['HTTP_REFERER'])) {
                $options_echappees_audit['referer'] = '';
            } else {
                $options_echappees_audit['referer'] = $_SERVER['HTTP_REFERER'];
            }
        } else {
            $options_echappees_audit['referer'] = '';
        }

        // active page
        if ($_SERVER['QUERY_STRING'] == "") {
            $options_echappees_audit['pageCourant'] = $_SERVER['PHP_SELF'];
        } else {
            $options_echappees_audit['pageCourant'] = $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
        }

        // Next up, we want to know what page we're on, use the router class
        $options_echappees_audit['controller'] = $this->CI->router->class;
        $options_echappees_audit['function'] = $this->CI->router->method;

        // We don't need it, but we'll log the URI just in case
        $options_echappees_audit['url'] = uri_string();

        // And write it to the database
        $this->CI->AuditManager->create($options_echappees_audit, $options_non_echappees_audit);
    }

}


text:
var settings;
var storage;

module.exports = {
    init: function(_settings) {
        settings = _settings;

        var storageType = settings.storageModule || "localfilesystem";

        storage = require("./"+storageType).init(settings);
        return storage;
    },
};

module.exports.__defineGetter__("storage", function() { return storage; });


text:
package jenkins.plugins.http_request.util;

import java.net.MalformedURLException;
import java.net.URL;

import hudson.util.FormValidation;

/**
 * @author Janario Oliveira
 */
public class HttpRequestValidation {

    public static FormValidation checkUrl(String value) {
        try {
            new URL(value);
            return FormValidation.ok();
        } catch (MalformedURLException ex) {
            return FormValidation.error("Invalid url");
        }
    }
}


text:
<?php

final class PhabricatorDefaultRequestExceptionHandler
  extends PhabricatorRequestExceptionHandler {

  public function getRequestExceptionHandlerPriority() {
    return 900000;
  }

  public function getRequestExceptionHandlerDescription() {
    return pht('Handles all other exceptions.');
  }

  public function canHandleRequestException(
    AphrontRequest $request,
    Exception $ex) {

    if (!$this->isPhabricatorSite($request)) {
      return false;
    }

    return true;
  }

  public function handleRequestException(
    AphrontRequest $request,
    Exception $ex) {

    $viewer = $this->getViewer($request);

    // Always log the unhandled exception.
    phlog($ex);

    $class = get_class($ex);
    $message = $ex->getMessage();

    if ($ex instanceof AphrontSchemaQueryException) {
      $message .= "\n\n".pht(
        "NOTE: This usually indicates that the MySQL schema has not been ".
        "properly upgraded. Run '%s' to ensure your schema is up to date.",
        'bin/storage upgrade');
    }

    if (PhabricatorEnv::getEnvConfig('phabricator.developer-mode')) {
      $trace = id(new AphrontStackTraceView())
        ->setUser($viewer)
        ->setTrace($ex->getTrace());
    } else {
      $trace = null;
    }

    $content = phutil_tag(
      'div',
      array('class' => 'aphront-unhandled-exception'),
      array(
        phutil_tag('div', array('class' => 'exception-message'), $message),
        $trace,
      ));

    $dialog = new AphrontDialogView();
    $dialog
      ->setTitle(pht('Unhandled Exception ("%s")', $class))
      ->setClass('aphront-exception-dialog')
      ->setUser($viewer)
      ->appendChild($content);

    if ($request->isAjax()) {
      $dialog->addCancelButton('/', pht('Close'));
    }

    return id(new AphrontDialogResponse())
      ->setDialog($dialog)
      ->setHTTPResponseCode(500);
  }

}


text:
declare namespace integrations.telegram {

    interface TelegramEvent {
    }

}

module integrations.telegram {

    let updatePosition: number = 0;
    let inhibitor: number = 0;
    let skipCount: number = 0;

    export class TelegramHook {

        constructor(private botToken: string) {
        }

        public sendToTelegram(chatId: number, text: string) {
            let client = heat.createHTTPClient();
            return client.get(
                `https://api.telegram.org/bot${this.botToken}/sendMessage?chat_id=${chatId}&parse_mode=Markdown&text=${text}`
            );
        }

        public getTelegramUpdates() {
            // retard the requests to telegram service while the chat silent
            if (skipCount > 0) {
                skipCount--;
                return null;
            } else {
                if (inhibitor > 100500)
                    inhibitor = 0;
                if (inhibitor > 100)
                    skipCount = 3;
                else if (inhibitor > 30)
                    skipCount = 2;
                else if (inhibitor > 10)
                    skipCount = 1;
            }

            let client = heat.createHTTPClient();
            let response = client.get(`https://api.telegram.org/bot${this.botToken}/getUpdates?offset=${updatePosition + 1}`);
            let payload = JSON.parse(response);
            for (let update of payload.result) {
                if (update.update_id > updatePosition)
                    updatePosition = update.update_id;
            }
            if (payload.result && payload.result.length > 0) {
                console.log("Telegram updates: " + JSON.stringify(payload));
                inhibitor = 0;
            } else {
                inhibitor++;
            }
            return payload;
        }

    }

}


text:
package org.apache.nifi.processors.evtx.parser;

import com.google.common.primitives.UnsignedInteger;
import org.apache.nifi.logging.ComponentLog;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Random;
import java.util.zip.CRC32;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;

public class FileHeaderTest {
    private final Random random = new Random();
    private FileHeader fileHeader;
    private int oldestChunk = 111;
    private int currentChunkNumber = 112;
    private int nextRecordNumber = 113;
    private int headerSize = 114;
    private int minorVersion = 1;
    private int majorVersion = 3;
    private int headerChunkSize = 4096;
    private int chunkCount = 0;
    private int flags = 340942;

    @BeforeEach
    public void setup() throws IOException {
        TestBinaryReaderBuilder testBinaryReaderBuilder = new TestBinaryReaderBuilder();
        testBinaryReaderBuilder.putString(FileHeader.ELF_FILE);
        testBinaryReaderBuilder.putQWord(oldestChunk);
        testBinaryReaderBuilder.putQWord(currentChunkNumber);
        testBinaryReaderBuilder.putQWord(nextRecordNumber);
        testBinaryReaderBuilder.putDWord(headerSize);
        testBinaryReaderBuilder.putWord(minorVersion);
        testBinaryReaderBuilder.putWord(majorVersion);
        testBinaryReaderBuilder.putWord(headerChunkSize);
        testBinaryReaderBuilder.putWord(chunkCount);
        byte[] unused = new byte[75];
        random.nextBytes(unused);
        testBinaryReaderBuilder.put(unused);
        testBinaryReaderBuilder.put((byte) 0);

        CRC32 crc32 = new CRC32();
        crc32.update(testBinaryReaderBuilder.toByteArray());

        testBinaryReaderBuilder.putDWord(flags);
        testBinaryReaderBuilder.putDWord(UnsignedInteger.valueOf(crc32.getValue()));

        fileHeader = new FileHeader(new ByteArrayInputStream(testBinaryReaderBuilder.toByteArray(4096)), mock(ComponentLog.class));
    }

    @Test
    public void testInit() {
        assertEquals(FileHeader.ELF_FILE, fileHeader.getMagicString());
        assertEquals(oldestChunk, fileHeader.getOldestChunk().intValue());
        assertEquals(currentChunkNumber, fileHeader.getCurrentChunkNumber().intValue());
        assertEquals(nextRecordNumber, fileHeader.getNextRecordNumber().intValue());
        assertEquals(headerSize, fileHeader.getHeaderSize().intValue());
        assertEquals(minorVersion, fileHeader.getMinorVersion());
        assertEquals(majorVersion, fileHeader.getMajorVersion());
        assertEquals(headerChunkSize, fileHeader.getHeaderChunkSize());
        assertEquals(chunkCount, fileHeader.getChunkCount());
        assertEquals(flags, fileHeader.getFlags().intValue());
    }
}


text:
<?php
namespace Album\Action;

use Album\Form\AlbumDataForm;
use Album\Model\Repository\AlbumRepositoryInterface;
use Interop\Container\ContainerInterface;
use Zend\Expressive\Router\RouterInterface;
use Zend\Expressive\Template\TemplateRendererInterface;

/**
 * Class AlbumUpdateHandleFactory
 *
 * @package Album\Action
 */
class AlbumUpdateHandleFactory
{
    /**
     * @param ContainerInterface $container
     *
     * @return AlbumUpdateHandleAction
     */
    public function __invoke(ContainerInterface $container)
    {
        $router          = $container->get(RouterInterface::class);
        $albumRepository = $container->get(AlbumRepositoryInterface::class);
        $albumForm       = $container->get(AlbumDataForm::class);

        return new AlbumUpdateHandleAction(
            $router, $albumRepository, $albumForm
        );
    }
}


text:
/*****************************************************************************
 * name:		be_ai_weight.c
 *
 * desc:		fuzzy logic
 *
 * $Archive: /MissionPack/code/botlib/be_ai_weight.c $
 *
 *****************************************************************************/

#include "../qcommon/q_shared.h"
#include "l_memory.h"
#include "l_log.h"
#include "l_utils.h"
#include "l_script.h"
#include "l_precomp.h"
#include "l_struct.h"
#include "l_libvar.h"
#include "aasfile.h"
#include "botlib.h"
#include "be_aas.h"
#include "be_aas_funcs.h"
#include "be_interface.h"
#include "be_ai_weight.h"

#define MAX_INVENTORYVALUE			999999
#define EVALUATERECURSIVELY

#define MAX_WEIGHT_FILES			128
weightconfig_t	*weightFileList[MAX_WEIGHT_FILES];

//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
int ReadValue(source_t *source, float *value)
{
	token_t token;

	if (!PC_ExpectAnyToken(source, &token)) return qfalse;
	if (!strcmp(token.string, "-"))
	{
		SourceWarning(source, "negative value set to zero\n");
		if (!PC_ExpectTokenType(source, TT_NUMBER, 0, &token)) return qfalse;
	} //end if
	if (token.type != TT_NUMBER)
	{
		SourceError(source, "invalid return value %s\n", token.string);
		return qfalse;
	} //end if
	*value = token.floatvalue;
	return qtrue;
} //end of the function ReadValue
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
int ReadFuzzyWeight(source_t *source, fuzzyseperator_t *fs)
{
	if (PC_CheckTokenString(source, "balance"))
	{
		fs->type = WT_BALANCE;
		if (!PC_ExpectTokenString(source, "(")) return qfalse;
		if (!ReadValue(source, &fs->weight)) return qfalse;
		if (!PC_ExpectTokenString(source, ",")) return qfalse;
		if (!ReadValue(source, &fs->minweight)) return qfalse;
		if (!PC_ExpectTokenString(source, ",")) return qfalse;
		if (!ReadValue(source, &fs->maxweight)) return qfalse;
		if (!PC_ExpectTokenString(source, ")")) return qfalse;
	} //end if
	else
	{
		fs->type = 0;
		if (!ReadValue(source, &fs->weight)) return qfalse;
		fs->minweight = fs->weight;
		fs->maxweight = fs->weight;
	} //end if
	if (!PC_ExpectTokenString(source, ";")) return qfalse;
	return qtrue;
} //end of the function ReadFuzzyWeight
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
void FreeFuzzySeperators_r(fuzzyseperator_t *fs)
{
	if (!fs) return;
	if (fs->child) FreeFuzzySeperators_r(fs->child);
	if (fs->next) FreeFuzzySeperators_r(fs->next);
	FreeMemory(fs);
} //end of the function FreeFuzzySeperators
//===========================================================================
//
// Parameter:			-
// Returns:				-
// Changes Globals:		-
//===========================================================================
void FreeWeightConfig2(weightconfig_t *config)
{
	int i;

	for (i = 0; i < config->numweights; i++)
	{
		FreeFuzzySeperators_r(config->weights[i].firstseperator);
		if (config->weights[i].name) FreeMemory(config->weights[i].name);
	} //end for
	FreeMemory(config);
} //end of the function FreeWeightConfig2
//===========================================================================
//
// Parameter:			-
// Returns:				-
// Changes Globals:		-
//===========================================================================
void FreeWeightConfig(weightconfig_t *config)
{
	if (!LibVarGetValue("bot_reloadcharacters")) return;
	FreeWeightConfig2(config);
} //end of the function FreeWeightConfig
//===========================================================================
//
// Parameter:			-
// Returns:				-
// Changes Globals:		-
//===========================================================================
fuzzyseperator_t *ReadFuzzySeperators_r(source_t *source)
{
	int newindent, index, def, founddefault;
	token_t token;
	fuzzyseperator_t *fs, *lastfs, *firstfs;

	founddefault = qfalse;
	firstfs = NULL;
	lastfs = NULL;
	if (!PC_ExpectTokenString(source, "(")) return NULL;
	if (!PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token)) return NULL;
	index = token.intvalue;
	if (!PC_ExpectTokenString(source, ")")) return NULL;
	if (!PC_ExpectTokenString(source, "{")) return NULL;
	if (!PC_ExpectAnyToken(source, &token)) return NULL;
	do
	{
		def = !strcmp(token.string, "default");
		if (def || !strcmp(token.string, "case"))
		{
			fs = (fuzzyseperator_t *) GetClearedMemory(sizeof(fuzzyseperator_t));
			fs->index = index;
			if (lastfs) lastfs->next = fs;
			else firstfs = fs;
			lastfs = fs;
			if (def)
			{
				if (founddefault)
				{
					SourceError(source, "switch already has a default\n");
					FreeFuzzySeperators_r(firstfs);
					return NULL;
				} //end if
				fs->value = MAX_INVENTORYVALUE;
				founddefault = qtrue;
			} //end if
			else
			{
				if (!PC_ExpectTokenType(source, TT_NUMBER, TT_INTEGER, &token))
				{
					FreeFuzzySeperators_r(firstfs);
					return NULL;
				} //end if
				fs->value = token.intvalue;
			} //end else
			if (!PC_ExpectTokenString(source, ":") || !PC_ExpectAnyToken(source, &token))
			{
				FreeFuzzySeperators_r(firstfs);
				return NULL;
			} //end if
			newindent = qfalse;
			if (!strcmp(token.string, "{"))
			{
				newindent = qtrue;
				if (!PC_ExpectAnyToken(source, &token))
				{
					FreeFuzzySeperators_r(firstfs);
					return NULL;
				} //end if
			} //end if
			if (!strcmp(token.string, "return"))
			{
				if (!ReadFuzzyWeight(source, fs))
				{
					FreeFuzzySeperators_r(firstfs);
					return NULL;
				} //end if
			} //end if
			else if (!strcmp(token.string, "switch"))
			{
				fs->child = ReadFuzzySeperators_r(source);
				if (!fs->child)
				{
					FreeFuzzySeperators_r(firstfs);
					return NULL;
				} //end if
			} //end else if
			else
			{
				SourceError(source, "invalid name %s\n", token.string);
				return NULL;
			} //end else
			if (newindent)
			{
				if (!PC_ExpectTokenString(source, "}"))
				{
					FreeFuzzySeperators_r(firstfs);
					return NULL;
				} //end if
			} //end if
		} //end if
		else
		{
			FreeFuzzySeperators_r(firstfs);
			SourceError(source, "invalid name %s\n", token.string);
			return NULL;
		} //end else
		if (!PC_ExpectAnyToken(source, &token))
		{
			FreeFuzzySeperators_r(firstfs);
			return NULL;
		} //end if
	} while(strcmp(token.string, "}"));
	//
	if (!founddefault)
	{
		SourceWarning(source, "switch without default\n");
		fs = (fuzzyseperator_t *) GetClearedMemory(sizeof(fuzzyseperator_t));
		fs->index = index;
		fs->value = MAX_INVENTORYVALUE;
		fs->weight = 0;
		fs->next = NULL;
		fs->child = NULL;
		if (lastfs) lastfs->next = fs;
		else firstfs = fs;
		lastfs = fs;
	} //end if
	//
	return firstfs;
} //end of the function ReadFuzzySeperators_r
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
weightconfig_t *ReadWeightConfig(char *filename)
{
	int newindent, avail = 0, n;
	token_t token;
	source_t *source;
	fuzzyseperator_t *fs;
	weightconfig_t *config = NULL;
#ifdef DEBUG
	int starttime;

	starttime = Sys_MilliSeconds();
#endif //DEBUG

	if (!LibVarGetValue("bot_reloadcharacters"))
	{
		avail = -1;
		for( n = 0; n < MAX_WEIGHT_FILES; n++ )
		{
			config = weightFileList[n];
			if( !config )
			{
				if( avail == -1 )
				{
					avail = n;
				} //end if
				continue;
			} //end if
			if( strcmp( filename, config->filename ) == 0 )
			{
				//botimport.Print( PRT_MESSAGE, "retained %s\n", filename );
				return config;
			} //end if
		} //end for

		if( avail == -1 )
		{
			botimport.Print( PRT_ERROR, "weightFileList was full trying to load %s\n", filename );
			return NULL;
		} //end if
	} //end if

	PC_SetBaseFolder(BOTFILESBASEFOLDER);
	source = LoadSourceFile(filename);
	if (!source)
	{
		botimport.Print(PRT_ERROR, "counldn't load %s\n", filename);
		return NULL;
	} //end if
	//
	config = (weightconfig_t *) GetClearedMemory(sizeof(weightconfig_t));
	config->numweights = 0;
	Q_strncpyz( config->filename, filename, sizeof(config->filename) );
	//parse the item config file
	while(PC_ReadToken(source, &token))
	{
		if (!strcmp(token.string, "weight"))
		{
			if (config->numweights >= MAX_WEIGHTS)
			{
				SourceWarning(source, "too many fuzzy weights\n");
				break;
			} //end if
			if (!PC_ExpectTokenType(source, TT_STRING, 0, &token))
			{
				FreeWeightConfig(config);
				FreeSource(source);
				return NULL;
			} //end if
			StripDoubleQuotes(token.string);
			config->weights[config->numweights].name = (char *) GetClearedMemory(strlen(token.string) + 1);
			strcpy(config->weights[config->numweights].name, token.string);
			if (!PC_ExpectAnyToken(source, &token))
			{
				FreeWeightConfig(config);
				FreeSource(source);
				return NULL;
			} //end if
			newindent = qfalse;
			if (!strcmp(token.string, "{"))
			{
				newindent = qtrue;
				if (!PC_ExpectAnyToken(source, &token))
				{
					FreeWeightConfig(config);
					FreeSource(source);
					return NULL;
				} //end if
			} //end if
			if (!strcmp(token.string, "switch"))
			{
				fs = ReadFuzzySeperators_r(source);
				if (!fs)
				{
					FreeWeightConfig(config);
					FreeSource(source);
					return NULL;
				} //end if
				config->weights[config->numweights].firstseperator = fs;
			} //end if
			else if (!strcmp(token.string, "return"))
			{
				fs = (fuzzyseperator_t *) GetClearedMemory(sizeof(fuzzyseperator_t));
				fs->index = 0;
				fs->value = MAX_INVENTORYVALUE;
				fs->next = NULL;
				fs->child = NULL;
				if (!ReadFuzzyWeight(source, fs))
				{
					FreeMemory(fs);
					FreeWeightConfig(config);
					FreeSource(source);
					return NULL;
				} //end if
				config->weights[config->numweights].firstseperator = fs;
			} //end else if
			else
			{
				SourceError(source, "invalid name %s\n", token.string);
				FreeWeightConfig(config);
				FreeSource(source);
				return NULL;
			} //end else
			if (newindent)
			{
				if (!PC_ExpectTokenString(source, "}"))
				{
					FreeWeightConfig(config);
					FreeSource(source);
					return NULL;
				} //end if
			} //end if
			config->numweights++;
		} //end if
		else
		{
			SourceError(source, "invalid name %s\n", token.string);
			FreeWeightConfig(config);
			FreeSource(source);
			return NULL;
		} //end else
	} //end while
	//free the source at the end of a pass
	FreeSource(source);
	//if the file was located in a pak file
	botimport.Print(PRT_MESSAGE, "loaded %s\n", filename);
#ifdef DEBUG
	if (bot_developer)
	{
		botimport.Print(PRT_MESSAGE, "weights loaded in %d msec\n", Sys_MilliSeconds() - starttime);
	} //end if
#endif //DEBUG
	//
	if (!LibVarGetValue("bot_reloadcharacters"))
	{
		weightFileList[avail] = config;
	} //end if
	//
	return config;
} //end of the function ReadWeightConfig
#if 0
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
qboolean WriteFuzzyWeight(FILE *fp, fuzzyseperator_t *fs)
{
	if (fs->type == WT_BALANCE)
	{
		if (fprintf(fp, " return balance(") < 0) return qfalse;
		if (!WriteFloat(fp, fs->weight)) return qfalse;
		if (fprintf(fp, ",") < 0) return qfalse;
		if (!WriteFloat(fp, fs->minweight)) return qfalse;
		if (fprintf(fp, ",") < 0) return qfalse;
		if (!WriteFloat(fp, fs->maxweight)) return qfalse;
		if (fprintf(fp, ");\n") < 0) return qfalse;
	} //end if
	else
	{
		if (fprintf(fp, " return ") < 0) return qfalse;
		if (!WriteFloat(fp, fs->weight)) return qfalse;
		if (fprintf(fp, ";\n") < 0) return qfalse;
	} //end else
	return qtrue;
} //end of the function WriteFuzzyWeight
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
qboolean WriteFuzzySeperators_r(FILE *fp, fuzzyseperator_t *fs, int indent)
{
	if (!WriteIndent(fp, indent)) return qfalse;
	if (fprintf(fp, "switch(%d)\n", fs->index) < 0) return qfalse;
	if (!WriteIndent(fp, indent)) return qfalse;
	if (fprintf(fp, "{\n") < 0) return qfalse;
	indent++;
	do
	{
		if (!WriteIndent(fp, indent)) return qfalse;
		if (fs->next)
		{
			if (fprintf(fp, "case %d:", fs->value) < 0) return qfalse;
		} //end if
		else
		{
			if (fprintf(fp, "default:") < 0) return qfalse;
		} //end else
		if (fs->child)
		{
			if (fprintf(fp, "\n") < 0) return qfalse;
			if (!WriteIndent(fp, indent)) return qfalse;
			if (fprintf(fp, "{\n") < 0) return qfalse;
			if (!WriteFuzzySeperators_r(fp, fs->child, indent + 1)) return qfalse;
			if (!WriteIndent(fp, indent)) return qfalse;
			if (fs->next)
			{
				if (fprintf(fp, "} //end case\n") < 0) return qfalse;
			} //end if
			else
			{
				if (fprintf(fp, "} //end default\n") < 0) return qfalse;
			} //end else
		} //end if
		else
		{
			if (!WriteFuzzyWeight(fp, fs)) return qfalse;
		} //end else
		fs = fs->next;
	} while(fs);
	indent--;
	if (!WriteIndent(fp, indent)) return qfalse;
	if (fprintf(fp, "} //end switch\n") < 0) return qfalse;
	return qtrue;
} //end of the function WriteItemFuzzyWeights_r
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
qboolean WriteWeightConfig(char *filename, weightconfig_t *config)
{
	int i;
	FILE *fp;
	weight_t *ifw;

	fp = fopen(filename, "wb");
	if (!fp) return qfalse;

	for (i = 0; i < config->numweights; i++)
	{
		ifw = &config->weights[i];
		if (fprintf(fp, "\nweight \"%s\"\n", ifw->name) < 0) return qfalse;
		if (fprintf(fp, "{\n") < 0) return qfalse;
		if (ifw->firstseperator->index > 0)
		{
			if (!WriteFuzzySeperators_r(fp, ifw->firstseperator, 1)) return qfalse;
		} //end if
		else
		{
			if (!WriteIndent(fp, 1)) return qfalse;
			if (!WriteFuzzyWeight(fp, ifw->firstseperator)) return qfalse;
		} //end else
		if (fprintf(fp, "} //end weight\n") < 0) return qfalse;
	} //end for
	fclose(fp);
	return qtrue;
} //end of the function WriteWeightConfig
#endif
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
int FindFuzzyWeight(weightconfig_t *wc, char *name)
{
	int i;

	for (i = 0; i < wc->numweights; i++)
	{
		if (!strcmp(wc->weights[i].name, name))
		{
			return i;
		} //end if
	} //end if
	return -1;
} //end of the function FindFuzzyWeight
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
float FuzzyWeight_r(int *inventory, fuzzyseperator_t *fs)
{
	float scale, w1, w2;

	if (inventory[fs->index] < fs->value)
	{
		if (fs->child) return FuzzyWeight_r(inventory, fs->child);
		else return fs->weight;
	} //end if
	else if (fs->next)
	{
		if (inventory[fs->index] < fs->next->value)
		{
			//first weight
			if (fs->child) w1 = FuzzyWeight_r(inventory, fs->child);
			else w1 = fs->weight;
			//second weight
			if (fs->next->child) w2 = FuzzyWeight_r(inventory, fs->next->child);
			else w2 = fs->next->weight;
			//the scale factor
			if(fs->next->value == MAX_INVENTORYVALUE) // is fs->next the default case?
        		return w2;      // can't interpolate, return default weight
			else
				scale = (float) (inventory[fs->index] - fs->value) / (fs->next->value - fs->value);
			//scale between the two weights
			return (1 - scale) * w1 + scale * w2;
		} //end if
		return FuzzyWeight_r(inventory, fs->next);
	} //end else if
	return fs->weight;
} //end of the function FuzzyWeight_r
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
float FuzzyWeightUndecided_r(int *inventory, fuzzyseperator_t *fs)
{
	float scale, w1, w2;

	if (inventory[fs->index] < fs->value)
	{
		if (fs->child) return FuzzyWeightUndecided_r(inventory, fs->child);
		else return fs->minweight + random() * (fs->maxweight - fs->minweight);
	} //end if
	else if (fs->next)
	{
		if (inventory[fs->index] < fs->next->value)
		{
			//first weight
			if (fs->child) w1 = FuzzyWeightUndecided_r(inventory, fs->child);
			else w1 = fs->minweight + random() * (fs->maxweight - fs->minweight);
			//second weight
			if (fs->next->child) w2 = FuzzyWeight_r(inventory, fs->next->child);
			else w2 = fs->next->minweight + random() * (fs->next->maxweight - fs->next->minweight);
			//the scale factor
			if(fs->next->value == MAX_INVENTORYVALUE) // is fs->next the default case?
        		return w2;      // can't interpolate, return default weight
			else
				scale = (float) (inventory[fs->index] - fs->value) / (fs->next->value - fs->value);
			//scale between the two weights
			return (1 - scale) * w1 + scale * w2;
		} //end if
		return FuzzyWeightUndecided_r(inventory, fs->next);
	} //end else if
	return fs->weight;
} //end of the function FuzzyWeightUndecided_r
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
float FuzzyWeight(int *inventory, weightconfig_t *wc, int weightnum)
{
#ifdef EVALUATERECURSIVELY
	return FuzzyWeight_r(inventory, wc->weights[weightnum].firstseperator);
#else
	fuzzyseperator_t *s;

	s = wc->weights[weightnum].firstseperator;
	if (!s) return 0;
	while(1)
	{
		if (inventory[s->index] < s->value)
		{
			if (s->child) s = s->child;
			else return s->weight;
		} //end if
		else
		{
			if (s->next) s = s->next;
			else return s->weight;
		} //end else
	} //end if
	return 0;
#endif
} //end of the function FuzzyWeight
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
float FuzzyWeightUndecided(int *inventory, weightconfig_t *wc, int weightnum)
{
#ifdef EVALUATERECURSIVELY
	return FuzzyWeightUndecided_r(inventory, wc->weights[weightnum].firstseperator);
#else
	fuzzyseperator_t *s;

	s = wc->weights[weightnum].firstseperator;
	if (!s) return 0;
	while(1)
	{
		if (inventory[s->index] < s->value)
		{
			if (s->child) s = s->child;
			else return s->minweight + random() * (s->maxweight - s->minweight);
		} //end if
		else
		{
			if (s->next) s = s->next;
			else return s->minweight + random() * (s->maxweight - s->minweight);
		} //end else
	} //end if
	return 0;
#endif
} //end of the function FuzzyWeightUndecided
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
void EvolveFuzzySeperator_r(fuzzyseperator_t *fs)
{
	if (fs->child)
	{
		EvolveFuzzySeperator_r(fs->child);
	} //end if
	else if (fs->type == WT_BALANCE)
	{
		//every once in a while an evolution leap occurs, mutation
		if (random() < 0.01) fs->weight += crandom() * (fs->maxweight - fs->minweight);
		else fs->weight += crandom() * (fs->maxweight - fs->minweight) * 0.5;
		//modify bounds if necesary because of mutation
		if (fs->weight < fs->minweight) fs->minweight = fs->weight;
		else if (fs->weight > fs->maxweight) fs->maxweight = fs->weight;
	} //end else if
	if (fs->next) EvolveFuzzySeperator_r(fs->next);
} //end of the function EvolveFuzzySeperator_r
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
void EvolveWeightConfig(weightconfig_t *config)
{
	int i;

	for (i = 0; i < config->numweights; i++)
	{
		EvolveFuzzySeperator_r(config->weights[i].firstseperator);
	} //end for
} //end of the function EvolveWeightConfig
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
void ScaleFuzzySeperator_r(fuzzyseperator_t *fs, float scale)
{
	if (fs->child)
	{
		ScaleFuzzySeperator_r(fs->child, scale);
	} //end if
	else if (fs->type == WT_BALANCE)
	{
		//
		fs->weight = (float) (fs->maxweight + fs->minweight) * scale;
		//get the weight between bounds
		if (fs->weight < fs->minweight) fs->weight = fs->minweight;
		else if (fs->weight > fs->maxweight) fs->weight = fs->maxweight;
	} //end else if
	if (fs->next) ScaleFuzzySeperator_r(fs->next, scale);
} //end of the function ScaleFuzzySeperator_r
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
void ScaleWeight(weightconfig_t *config, char *name, float scale)
{
	int i;

	if (scale < 0) scale = 0;
	else if (scale > 1) scale = 1;
	for (i = 0; i < config->numweights; i++)
	{
		if (!strcmp(name, config->weights[i].name))
		{
			ScaleFuzzySeperator_r(config->weights[i].firstseperator, scale);
			break;
		} //end if
	} //end for
} //end of the function ScaleWeight
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
void ScaleFuzzySeperatorBalanceRange_r(fuzzyseperator_t *fs, float scale)
{
	if (fs->child)
	{
		ScaleFuzzySeperatorBalanceRange_r(fs->child, scale);
	} //end if
	else if (fs->type == WT_BALANCE)
	{
		float mid = (fs->minweight + fs->maxweight) * 0.5;
		//get the weight between bounds
		fs->maxweight = mid + (fs->maxweight - mid) * scale;
		fs->minweight = mid + (fs->minweight - mid) * scale;
		if (fs->maxweight < fs->minweight)
		{
			fs->maxweight = fs->minweight;
		} //end if
	} //end else if
	if (fs->next) ScaleFuzzySeperatorBalanceRange_r(fs->next, scale);
} //end of the function ScaleFuzzySeperatorBalanceRange_r
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
void ScaleFuzzyBalanceRange(weightconfig_t *config, float scale)
{
	int i;

	if (scale < 0) scale = 0;
	else if (scale > 100) scale = 100;
	for (i = 0; i < config->numweights; i++)
	{
		ScaleFuzzySeperatorBalanceRange_r(config->weights[i].firstseperator, scale);
	} //end for
} //end of the function ScaleFuzzyBalanceRange
//===========================================================================
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
int InterbreedFuzzySeperator_r(fuzzyseperator_t *fs1, fuzzyseperator_t *fs2,
								fuzzyseperator_t *fsout)
{
	if (fs1->child)
	{
		if (!fs2->child || !fsout->child)
		{
			botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal child\n");
			return qfalse;
		} //end if
		if (!InterbreedFuzzySeperator_r(fs2->child, fs2->child, fsout->child))
		{
			return qfalse;
		} //end if
	} //end if
	else if (fs1->type == WT_BALANCE)
	{
		if (fs2->type != WT_BALANCE || fsout->type != WT_BALANCE)
		{
			botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal balance\n");
			return qfalse;
		} //end if
		fsout->weight = (fs1->weight + fs2->weight) / 2;
		if (fsout->weight > fsout->maxweight) fsout->maxweight = fsout->weight;
		if (fsout->weight > fsout->minweight) fsout->minweight = fsout->weight;
	} //end else if
	if (fs1->next)
	{
		if (!fs2->next || !fsout->next)
		{
			botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal next\n");
			return qfalse;
		} //end if
		if (!InterbreedFuzzySeperator_r(fs1->next, fs2->next, fsout->next))
		{
			return qfalse;
		} //end if
	} //end if
	return qtrue;
} //end of the function InterbreedFuzzySeperator_r
//===========================================================================
// config1 and config2 are interbreeded and stored in configout
//
// Parameter:				-
// Returns:					-
// Changes Globals:		-
//===========================================================================
void InterbreedWeightConfigs(weightconfig_t *config1, weightconfig_t *config2,
								weightconfig_t *configout)
{
	int i;

	if (config1->numweights != config2->numweights ||
		config1->numweights != configout->numweights)
	{
		botimport.Print(PRT_ERROR, "cannot interbreed weight configs, unequal numweights\n");
		return;
	} //end if
	for (i = 0; i < config1->numweights; i++)
	{
		InterbreedFuzzySeperator_r(config1->weights[i].firstseperator,
									config2->weights[i].firstseperator,
									configout->weights[i].firstseperator);
	} //end for
} //end of the function InterbreedWeightConfigs
//===========================================================================
//
// Parameter:			-
// Returns:				-
// Changes Globals:		-
//===========================================================================
void BotShutdownWeights(void)
{
	int i;

	for( i = 0; i < MAX_WEIGHT_FILES; i++ )
	{
		if (weightFileList[i])
		{
			FreeWeightConfig2(weightFileList[i]);
			weightFileList[i] = NULL;
		} //end if
	} //end for
} //end of the function BotShutdownWeights


text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Abot.Poco
{
    /// Result of crawling a page
    /// <remarks>
    /// We use this wrapper class to enable using responses obtained by methods different than executing an HttpWebRequest.
    /// E.g. one may use a browser control embedded in the application to get a page content and construct an instance of this class
    /// to pass it to Abot.
    /// </remarks>
    public class HttpWebResponseWrapper
    {
        private HttpWebResponse InternalResponse;
        private byte[] Content;
        private Lazy<Stream> ContentStream;

        #region Constructors

        /// Constructs a response based on the received system http response.
        public HttpWebResponseWrapper(HttpWebResponse response)
        {
            this.InternalResponse = response;

            if (response == null)
                return;

            this.StatusCode = response.StatusCode;
            this.ContentType = response.ContentType;
            this.ContentLength = response.ContentLength;
            this.Headers = response.Headers;
            this.CharacterSet = response.CharacterSet;
            this.ContentEncoding = response.ContentEncoding;
            this.Cookies = response.Cookies;
            this.IsFromCache = response.IsFromCache;
            this.IsMutuallyAuthenticated = response.IsMutuallyAuthenticated;
            this.LastModified = GetLastModified(response);
            this.Method = response.Method;
            this.ProtocolVersion = response.ProtocolVersion;
            this.ResponseUri = response.ResponseUri;
            this.Server = response.Server;
            this.StatusDescription = response.StatusDescription;
        }

        private static DateTime GetLastModified(HttpWebResponse response)
        {
            try
            {
                return response.LastModified;
            }
            catch (ProtocolViolationException)
            {
                return DateTime.MinValue;
            }
        }

        /// Constructs a response based on custom parameters.
        /// <remarks>Recieves parameters neccesarily set for Abot to work.</remarks>
        public HttpWebResponseWrapper(HttpStatusCode statusCode, string contentType, byte[] content, NameValueCollection headers)
        {
            this.StatusCode = statusCode;
            this.Headers = headers;
            this.ContentType = contentType;
            this.ContentLength = content != null ? content.Length : 0;
            this.Content = content;
            this.ContentStream = new Lazy<Stream>(() => this.Content != null ? new MemoryStream(this.Content) : null);
        }

        /// Constructs an empty response to be filled later.
        public HttpWebResponseWrapper() { }

        #endregion

        #region Properties

        /// Status code returned by the server
        public HttpStatusCode StatusCode { get; set; }
        /// Server designated type of content
        public string ContentType { get; set; }
        /// Server designated length of content in bytes
        public long ContentLength { get; set; }
        /// Collection of headers in the response
        public NameValueCollection Headers { get; set; }
        /// Gets the character set of the response.
        public string CharacterSet { get; set; }
        /// Gets the method that is used to encode the body of the response.
        public string ContentEncoding { get; set; }
        /// Gets or sets the cookies that are associated with this response.
        public CookieCollection Cookies { get; set; }
        /// Was the response generated from the local cache?
        public bool IsFromCache { get; set; }
        /// Gets a System.Boolean value that indicates whether both client and server were authenticated.
        public bool IsMutuallyAuthenticated { get; set; }
        /// Gets the last date and time that the contents of the response were modified.
        public DateTime LastModified { get; set; }
        /// Gets the method that is used to return the response.
        public string Method { get; set; }
        /// Gets the version of the HTTP protocol that is used in the response.
        public Version ProtocolVersion { get; set; }
        /// Gets the URI of the Internet resource that responded to the request.
        public Uri ResponseUri { get; set; }
        /// Gets the name of the server that sent the response.
        public string Server { get; set; }
        /// Gets the status description returned with the response.
        public string StatusDescription { get; set; }

        #endregion

        #region Stream Methods

        /// Gets the actual response data.
        public Stream GetResponseStream()
        {
            return this.InternalResponse != null ?
                this.InternalResponse.GetResponseStream() :
                this.ContentStream.Value;
        }

        /// Gets the header with the given name.
        public string GetResponseHeader(string header)
        {
            return this.Headers != null ? this.Headers[header] : null;
        }

        #endregion
    }
}


text:
In order to call a RESTful JSON API from a Scala application,
you need the following steps:

1. Create a Sbt project, which contains the MIDL definition of the RESTful JSON API
   that you will call in your Scala application.
   The project is also known as the API's SDK.
2. Publish the JAR package of SDK (optional).
3. Add the dependency to the SDK into your Scala application's `build.sbt`.
4. In your Scala application, initilize the service defined in SDK and invoke methods of the service.

In this article,
you will create an application
that queries the public organization memberships for a specified Github user.
The application is a Scala Play web project.
It will call [Github API](https://developer.github.com/v3/) via a Microbuilder SDK,
which is also created in this article.

## Requirement

Microbuilder requires [Haxe](http://haxe.org/) for code generation,
and [Sbt](http://www.scala-sbt.org/) to manage build pipeline.

You need download and install [Haxe 3.2.1](http://haxe.org/download/) and
[Sbt 0.13.9](http://www.scala-sbt.org/download.html),
then setup Haxelib with the folloiwing commands:

    haxelib setup ~/.haxelib.d
    haxelib install hxjava
    haxelib install dox

## Create the SDK

### Sbt configuration for SDK

Prepare an empty directory for the SDK project.
Then, create `project/plugins.sbt`
and add [sbt-microbuilder](https://github.com/ThoughtWorksInc/sbt-microbuilder) dependency into it.

    // project/plugins.sbt
    addSbtPlugin("com.thoughtworks.microbuilder" % "sbt-microbuilder" % "3.0.2")

There are multiple plugins in the sbt-microbuilder library.
`MicrobuilderJavaSdk` is one of these plugins.
The plugin will add necessary settings for a SDK project for JVM target.

So you edit build.sbt, and add `enablePlugins(MicrobuilderJavaSdk)`:

    // build.sbt
    enablePlugins(MicrobuilderJavaSdk)

    organization := "com.thoughtworks.microbuilder.tutorial"

    name := "github-sdk"

### MIDL API definition

By default, your MIDL is under `src/haxe` directory,
and the package name of your MIDL is caculated from `organization` and `name` settings in your `build.sbt`.

The interface of MIDL API should be put under `com.thoughtworks.microbuilder.tutorial.githubSdk.rpc` package,
or `src/haxe/com/thoughtworks/microbuilder/tutorial/githubSdk/rpc` directory.
You can run `sbt jsonStreamServiceModules::packageName` in shell to check that.

Now you define [List user organizations](https://developer.github.com/v3/orgs/#list-user-organizations)
endpoint in a MIDL interface.

    // src/haxe/com/thoughtworks/microbuilder/tutorial/githubSdk/rpc/IOrganizationService.hx
    package com.thoughtworks.microbuilder.tutorial.githubSdk.rpc;

    import jsonStream.rpc.Future;
    import haxe.ds.Vector;
    import com.thoughtworks.microbuilder.tutorial.githubSdk.model.OrganizationSummary;

    @:nativeGen
    interface IOrganizationService {

      @:route("GET", "users/{username}/orgs")
      function listUserOrganizations(username:String):Future<Vector<OrganizationSummary>>;

      // TODO: Other endpoints described at https://developer.github.com/v3/orgs/

    }

### MIDL JSON schema definition

The MIDL reference to a MIDL JSON schema `OrganizationSummary`,
which should be defined under `com.thoughtworks.microbuilder.tutorial.githubSdk.model` package,
or `src/haxe/com/thoughtworks/microbuilder/tutorial/githubSdk/model` directory.
You can run `sbt jsonStreamModelModules::packageName` in shell to check that.

    // src/haxe/com/thoughtworks/microbuilder/tutorial/githubSdk/model/OrganizationSummary.hx
    package com.thoughtworks.microbuilder.tutorial.githubSdk.model;

    @:final
    class OrganizationSummary {

      public function new() {}

      public var login:String;

      public var id:Int;

      public var url:String;

      public var avatar_url:String;

      public var description:String;

    }

Now you can execute the following command to compile and package the SDK to a JAR.

    sbt haxelibInstallDependencies package

## Publish the SDK

See [Publishing](http://www.scala-sbt.org/0.13/docs/Publishing.html) in Sbt documentation for how to setup Sbt to publish your SDK.

See this [repository](https://github.com/ThoughtWorksInc/github-sdk/tree/v1.0.2) for the complete code base.

## Setup a Play project

Now, create your client-side application.

First, create the project with the help of `sbt` or `activator`. You can see the documentation from [Play Framework web site](https://www.playframework.com/).

## Add SDK dependencies

Then, add the SDK dependencies to your `build.sbt`:

    // Dependency to the Github SDK we just created.
    libraryDependencies += "com.thoughtworks.microbuilder.tutorial" %% "github-sdk" % "1.0.2"

    // Runtime library to integrate SDK into a Play application.
    libraryDependencies += "com.thoughtworks.microbuilder" %% "microbuilder-play" % "3.1.0"

    // A library that deals with asynchronous operation.
    libraryDependencies += "com.thoughtworks.each" %% "each" % "0.5.1"

Alternatively, You can embed the code base of SDK as a child project of the Play project,
if you don't want to publish the SDK.
See [Multi-project builds](http://www.scala-sbt.org/0.13/docs/Multi-Project.html) for more information.

## Use the SDK

After the SDK dependencies are added, we can create a controller which use `IOrganizationService` sending RESTful requests.

    package com.thoughtworks.microbuilder.tutorial.organizationList.controllers

    import play.api.mvc.{Action, Controller}

    import scala.concurrent.{ExecutionContext, Future}

    import scalaz.std.scalaFuture._
    import com.thoughtworks.each.Monadic._

    import com.thoughtworks.microbuilder.play.Implicits._

    import com.thoughtworks.microbuilder.tutorial.githubSdk.model.OrganizationSummary
    import com.thoughtworks.microbuilder.tutorial.githubSdk.rpc.IOrganizationService
    import com.thoughtworks.microbuilder.tutorial.organizationList.views.html.renderOrganizationList

    class OrganizationListController(organizationService: IOrganizationService)(implicit ec: ExecutionContext) extends Controller {

      def showOrganizationList(username: String) = Action.async(throwableMonadic[Future] {
        val future: Future[Array[OrganizationSummary]] = organizationService.listUserOrganizations(username)
        Ok(renderOrganizationList(username, future.each))
      })

    }

In this example, you convert result of `listUserOrganizations` to a asynchronous `Future`,
then use [Scalaz](https://scalaz.github.io/scalaz) and [Each](https://github.com/ThoughtWorksInc/each) handling the future.
Then, you pass the result to a Twirl template `renderOrganizationList` to render the HTML,
which will be created later in this article.

## Other Play configurations

In order to use the `OrganizationListController`,
add corresponding Play's routes configuration for it.

    # conf/routes
    GET        /users/:username        com.thoughtworks.microbuilder.tutorial.organizationList.controllers.OrganizationListController.showOrganizationList(username:String)

Then, create the Twirl template `renderOrganizationList` used by `OrganizationListController`

    @import com.thoughtworks.microbuilder.tutorial.githubSdk.model.OrganizationSummary
    @(username: String, organizations: Array[OrganizationSummary])

@username's organizations

          @for(organization <- organizations) {

              @organization.login

          }

This template renders data got from Github API.

## Initialize the SDK

As we defined before,
the `organizationService:IOrganizationService` is a parameter of `OrganizationListController`,
which should be initialized in the Play framework's [application entry point](https://www.playframework.com/documentation/2.4.x/ScalaCompileTimeDependencyInjection#Application-entry-point).

    package com.thoughtworks.microbuilder.tutorial.organizationList

    import com.thoughtworks.microbuilder.play.PlayOutgoingJsonService
    import com.thoughtworks.microbuilder.tutorial.githubSdk.proxy.MicrobuilderOutgoingProxyFactory._
    import com.thoughtworks.microbuilder.tutorial.githubSdk.proxy.MicrobuilderRouteConfigurationFactory._
    import com.thoughtworks.microbuilder.tutorial.githubSdk.rpc.IOrganizationService
    import com.thoughtworks.microbuilder.tutorial.organizationList.controllers.OrganizationListController
    import play.api.libs.ws.ning.NingWSComponents
    import play.api.{BuiltInComponentsFromContext, Application, ApplicationLoader}
    import play.api.ApplicationLoader.Context
    import router.Routes

    class Loader extends ApplicationLoader {
      override def load(context: Context): Application = {

        val components = new BuiltInComponentsFromContext(context) with NingWSComponents {
          implicit def executionContext = actorSystem.dispatcher

          lazy val organizationService = PlayOutgoingJsonService.newProxy[IOrganizationService]("https://api.github.com/", wsApi)

          lazy val organizationListController = new OrganizationListController(organizationService)

          override lazy val router = new Routes(httpErrorHandler, organizationListController)
        }

        components.application
      }
    }

The `Loader` prepared an `IOrganizationService` instance from `newProxy` method,
and passed the  `IOrganizationService` to the constructor of `OrganizationListController`.
As a result,
the `OrganizationListController` is able to use methods on `IOrganizationService` as we shown before.

Note that `newProxy` method will look for implcit stubs that generated from MIDL. They are `com.thoughtworks.microbuilder.tutorial.githubSdk.proxy.MicrobuilderOutgoingProxyFactory` and
`com.thoughtworks.microbuilder.tutorial.githubSdk.proxy.MicrobuilderRouteConfigurationFactory`.
You must import `MicrobuilderOutgoingProxyFactory._` and `MicrobuilderRouteConfigurationFactory._` to enable those implicit values generated in the two classes.

Now you built the entire application.
You can run it from Sbt

    sbt run

Then visit http://localhost:9000/users/your-user-name to see your Github organization list.

You can find the entire example of client-side application at [organization-list](https://github.com/ThoughtWorksInc/organization-list).


text:
Fixer.io
========

Fixer.io provides currency exchange rate information in an API form by leveraging data that the European Central Bank puts out in CSV format. This allows me to provide you with currency conversion rates in AngelBot.

Commands
--------

currencies
    Show a list of currencies that the European Central Bank tracks and their identifier. When using functions in this module use the identifiers. IE: GBP or USD.

rates [Currency]
    Show a list of the latest exchange rates against a given base currency. By default, since the information is based on the European Central Bank, this returns exchange rates against the Euro. You can ask for any currency available in currencies however. For instance: USD or JPY.
    Ex: rates AUD - Exchange rates for the Australian Dollar

convert [amt] [currency] to [other currency]
    Convert an amount of one currency into another. This may not work in every combination. For some reason the European Central Bank doesn't store every combination. Make sure that amount is a number, it may start with a symbol. the word to must be present. It is part of the command.
    Ex: convert $125.37 USD to JPY - convert 125.37 US Dollars to Japanese Yen.


text:
#ifndef TENSORFLOW_UTIL_TENSOR_FORMAT_H_
#define TENSORFLOW_UTIL_TENSOR_FORMAT_H_

#include <vector>

#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

enum TensorFormat {
  FORMAT_NHWC = 0,
  FORMAT_NCHW = 1,
};

// Parse tensor format from the given string.
// Return true if the parsing succeeds, and false if it fails.
bool FormatFromString(const string& format_str, TensorFormat* format);

// Convert a tensor format into string.
string ToString(TensorFormat format);

// Return the position index from a format given a dimension specification with
// a char. The chars can be N (batch), C (channels), H (y), W (x), or
// 0 .. (NDIMS-1).
template <int NDIMS>
inline int32 GetTensorDimIndex(TensorFormat format, char dimension) {
  if (format == FORMAT_NHWC) {
    switch (dimension) {
      case 'N':
        return 0;
      case '0':
        return 1;
      case '1':
        return 2;
      case '2':
        return 3;
      case 'H':
        return NDIMS - 1;
      case 'W':
        return NDIMS;
      case 'C':
        return 1 + NDIMS;
      default:
        LOG(FATAL) << "Invalid dimension: " << dimension;
        return -1; // Avoid compiler warning about missing return value
    }
  } else if (format == FORMAT_NCHW) {
    switch (dimension) {
      case 'N':
        return 0;
      case 'C':
        return 1;
      case '0':
        return 2;
      case '1':
        return 3;
      case '2':
        return 4;
      case 'H':
        return NDIMS;
      case 'W':
        return NDIMS + 1;
      default:
        LOG(FATAL) << "Invalid dimension: " << dimension;
        return -1; // Avoid compiler warning about missing return value
    }
  } else {
    LOG(FATAL) << "Invalid format: " << static_cast<int>(format);
    return -1; // Avoid compiler warning about missing return value
  }
}

inline int32 GetTensorDimIndex(TensorFormat format, char dimension) {
  return GetTensorDimIndex<2>(format, dimension);
}

// Return the given tensor dimension from a tensor. The tensor is interpretted
// using the specified format, and a dimension specification using a char.
inline int64 GetTensorDim(const Tensor& tensor, TensorFormat format,
                          char dimension) {
  int index = GetTensorDimIndex<2>(format, dimension);
  CHECK(index >= 0 && index < tensor.dims())
      << "Invalid index from the dimension: " << index << ", " << format << ", "
      << dimension;
  return tensor.dim_size(index);
}

// Return the given tensor dimension from a vector that represents the
// dimensions of a tensor.
// The tensor is interpretted using the specified format, and a dimension
// specification using a char.
inline int64 GetTensorDim(const TensorShape& tensor_shape, TensorFormat format,
                          char dimension) {
  int index = GetTensorDimIndex<2>(format, dimension);
  CHECK(index >= 0 && index < tensor_shape.dims())
      << "Invalid index from the dimension: " << index << ", " << format << ", "
      << dimension;
  return tensor_shape.dim_size(index);
}

// Return the given tensor dimension from a tensor shape.
// The tensor is interpretted using the specified format, and a dimension
// specification using a char.
template <typename T>
T GetTensorDim(const std::vector<T>& attributes, TensorFormat format,
               char dimension) {
  int index = GetTensorDimIndex<2>(format, dimension);
  CHECK(index >= 0 && index < attributes.size())
      << "Invalid index from the dimension: " << index << ", " << format << ", "
      << dimension;
  return attributes[index];
}

// Return the string that specifies the data format for convnet operations.
string GetConvnetDataFormatAttrString();

// Return a tensor shape from the given format, and tensor dimensions.
inline TensorShape ShapeFromFormat(TensorFormat format, int64 N, int64 H,
                                   int64 W, int64 C) {
  std::vector<int64> dim_sizes(4);
  dim_sizes[GetTensorDimIndex<2>(format, 'N')] = N;
  dim_sizes[GetTensorDimIndex<2>(format, 'H')] = H;
  dim_sizes[GetTensorDimIndex<2>(format, 'W')] = W;
  dim_sizes[GetTensorDimIndex<2>(format, 'C')] = C;
  return TensorShape(dim_sizes);
}

// Return a tensor shape from the given format, and tensor dimensions.
inline TensorShape ShapeFromFormat(TensorFormat dst_format,
                                   const TensorShape& src_shape,
                                   TensorFormat src_format) {
  if (src_format == dst_format) {
    return src_shape;
  }
  std::vector<int64> dim_sizes(4);
  dim_sizes[GetTensorDimIndex<2>(dst_format, 'N')] =
      GetTensorDim(src_shape, src_format, 'N');
  dim_sizes[GetTensorDimIndex<2>(dst_format, 'H')] =
      GetTensorDim(src_shape, src_format, 'H');
  dim_sizes[GetTensorDimIndex<2>(dst_format, 'W')] =
      GetTensorDim(src_shape, src_format, 'W');
  dim_sizes[GetTensorDimIndex<2>(dst_format, 'C')] =
      GetTensorDim(src_shape, src_format, 'C');
  return TensorShape(dim_sizes);
}

}  // namespace tensorflow

#endif  // TENSORFLOW_UTIL_TENSOR_FORMAT_H_


text: require('../pipethrough')(encodeURIComponent);


text:
<component name="ProjectDictionaryState">
  <dictionary name="bomattsson" />
</component>


text:
print('importing packages')
import time
import sqlite3
import json
import requests
import datetime
import pytz
from datetime import date
from multiprocessing.pool import Pool

###### Create/connect to database (sqlite file)

print('connecting to db')
conn = sqlite3.connect('mastercard_db.sqlite')
cur = conn.cursor()

###### Defining Functions, Convert dates into different types, date/day/string, chunkIt splits currency codes into approximately equal chunks

print('defining functions')
def day_calculator(date):
    return (date - date_1).days + 1
def date_calculator(day):
    return date_1+datetime.timedelta(day-1)
def date_stringer(date):
    return date.strftime('%Y-%m-%d')
def chunkIt(seq, num):
  avg = len(seq) / float(num)
  out = []
  last = 0.0

  while last < len(seq):
    out.append(seq[int(last):int(last + avg)])
    last += avg

  return out

###### Defining constants, first_date is first_date in database, now is datetime in EST, today is last date rates available for, date_1 is first date rates available for

print('defining constants')
start_from_id = int(input('from_id initial value: '))
start_to_ids= [int(x) for x in input('List of to_ids, seperated by spaces').split()]
n = len(start_to_ids)

base_url = 'https://www.mastercard.us/settlement/currencyrate/fxDate={date_};transCurr={from_};crdhldBillCurr={to_};bankFee=0.00;transAmt=1/conversion-rate'

first_date=date(2016,2,29)
now = datetime.datetime.now(pytz.timezone('US/Eastern'))
if now.hour < 14:
    today=now.date() - datetime.timedelta(days=1)
else:
    today=now.date()
print('today: ', today)
date_1=today - datetime.timedelta(days=364)
if date_1.weekday()==6:
    date_1=date_1+datetime.timedelta(days=1)
if date_1.weekday()==5:
    date_1=date_1+datetime.timedelta(days=2)
print(date_1)

date_string = date_stringer(date_1)
print('first date in period', date_1, 'today:',today)
late_day=day_calculator(date(2016,10,14))

print('grabbing codes from db')
cur.execute('SELECT code FROM Currency_Codes')
code_tuples=cur.fetchall()
codes = [ x[0] for x in code_tuples ]
number_of_codes = len(codes)

######### Extracts all exchnage rates from 14th Oct onward

def extract_rates(from_id,to_id):
    if to_id>151:
        entry='done'
        entries.append(entry)
        return entries
    if from_id is 'done':
        entry='done'
        entries.append(entry)
        return entries

    ######### Creates URL

    else:
        from_c = codes[from_id-1]
        to_c = codes[to_id-1]
        print(from_c,to_c)
        day=late_day
        date=date_calculator(day)
        print('extracting rates...')
        while (today - date).days >=0:
            date_string=date_stringer(date)
            url=base_url.format(date_=date_string,from_=from_c,to_=to_c)

            #Retries if requests doesn't return a json file (server errors)
            while True:
                try:
                    r = requests.get(url)
                    JSON=r.json()
                except:
                    time.sleep(5)
                    continue
                break
            ######### Error Handling

            if 'errorCode' in JSON['data']:
                if JSON['data']['errorCode'] in ('104','114'):
                    print('data not available for this date')
                    day = day + 1
                    date = date_calculator(day)
                    continue
                elif JSON['data']['errorCode'] in ('500','401','400'):
                    print('error code: ',JSON['data']['errorCode'])
                    print('Server having technical problems')
                    time.sleep(500)
                    continue

                else:
                    print('error code: ',JSON['data']['errorCode'])
                    print('conversion rate too small')
                    break

            ######### Adds conversion rate with date_id and currency ids

            else:
                rate = JSON['data']['conversionRate']
                day = day_calculator(date)
                date_id=(date_1-first_date).days+day
                entry=(rate,from_id,to_id,date_id)
                entries.append(entry)
                day+=1
                date=date_calculator(day)

        return entries

print('initiating')
entries=list()
chunks=chunkIt(range(start_from_id,152),n)
for code in codes[(start_from_id-1):]:
    try:
        to_ids
    except:
        to_ids = start_to_ids
        from_ids = [chunks[x][0] for x in range(0,n)]
        last_from_ids = [chunks[x][-1] for x in range(0,n)]
    while any(from_ids[x] != 'done' for x in range(0,n)):
        while all(to_id <=151 for to_id in to_ids):
            entries.clear()
            for i in range (0,n):
                if from_ids[i] is to_ids[i]:
                        to_ids[i] +=1
                        continue
            for i in range (0,n):
                print(from_ids[i],to_ids[i])

            start_time = datetime.datetime.now()
            ### Multithread with n threads
            p = Pool(processes=n)
            ### Returns list of n lists of entries for the year for n currency codes
            entries_list =p.starmap(extract_rates, [(from_ids[x],to_ids[x]) for x in range(0,n) ])
            p.close()
            for entries in entries_list:
                for entry in entries:
                    if entry == 'done':
                        pass
                    else:
                        cur.execute('''INSERT OR REPLACE INTO Rates
                        (rate, from_id, to_id, date_id)
                        VALUES ( ?, ?, ?, ?)''',
                        (entry[0], entry[1], entry[2], entry[3]) )
                conn.commit()
                end_time = datetime.datetime.now()
                print('Duration: {}'.format(end_time - start_time))
            to_ids[:] = [x+1 for x in to_ids]

            ### Updates current date to ensure that if time has passed still collecting data for all available dates

            now = datetime.datetime.now(pytz.timezone('US/Eastern'))
            if now.hour < 14:
                today=now.date() - datetime.timedelta(days=1)
            else:
                today=now.date()
            date_1=today - datetime.timedelta(days=364)
            if date_1.weekday()==6:
                date_1=date_1+datetime.timedelta(days=1)
            if date_1.weekday()==5:
                date_1=date_1+datetime.timedelta(days=2)

        from_ids[:] = ['done' if from_ids[x] in ('done',last_from_ids[x]) else from_ids[x]+1  for x in range(0,n)]
        print (from_ids)
        to_ids[:] = [1] * n


text:
module.exports = function (req, res) {
	var keystone = req.keystone;
	if (!keystone.security.csrf.validate(req)) {
		return res.apiError(403, 'invalid csrf');
	}
	req.list.model.findById(req.params.id, function (err, item) {
		if (err) return res.status(500).json({ error: 'database error', detail: err });
		if (!item) return res.status(404).json({ error: 'not found', id: req.params.id });
		req.list.updateItem(item, req.body, { files: req.files }, function (err) {
			if (err) {
				var status = err.error === 'validation errors' ? 400 : 500;
				var error = err.error === 'database error' ? err.detail : err;
				return res.apiError(status, error);
			}
			res.json(req.list.getData(item));
		});
	});
};


text:
function karaf_check() {
   KARAF_HOME=$1
   INSTANCES_FILE=$KARAF_HOME/instances/instance.properties
   for i in {1..5};
     do
       if [ ! -f $INSTANCES_FILE ]; then
         sleep 1
       else
         break
       fi
     done
   if [ -f $INSTANCES_FILE ]; then
      for j in {1..5};
         do
           PID=`cat $INSTANCES_FILE | grep "item.0.pid" | awk -F "=" '{print $2}'`
           if [ "$PID" = "" ]; then
             sleep 1
           else
            break
           fi
     done
     if ps -p $PID > /dev/null; then
       echo "Fabric is started successfully"
     else
       echo "Command Failed: Karaf process ($PID) is not running"
     fi
   else
     echo "Command Failed:Could not find Karaf instance.properties"
   fi
}


text:
module TokyoMetro::Factory
end


text:
;*****************************************************************************
;* x86-optimized Float DSP functions
;*
;* Copyright 2006 Loren Merritt
;*
;* This file is part of FFmpeg.
;*
;* FFmpeg is free software; you can redistribute it and/or
;* modify it under the terms of the GNU Lesser General Public
;* License as published by the Free Software Foundation; either
;* version 2.1 of the License, or (at your option) any later version.
;*
;* FFmpeg is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;* Lesser General Public License for more details.
;*
;* You should have received a copy of the GNU Lesser General Public
;* License along with FFmpeg; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;******************************************************************************

%include "x86inc.asm"
%include "x86util.asm"

SECTION .text

;-----------------------------------------------------------------------------
; void vector_fmul(float *dst, const float *src0, const float *src1, int len)
;-----------------------------------------------------------------------------
%macro VECTOR_FMUL 0
cglobal vector_fmul, 4,4,2, dst, src0, src1, len
    lea       lenq, [lend*4 - 2*mmsize]
ALIGN 16
.loop:
    mova      m0,   [src0q + lenq]
    mova      m1,   [src0q + lenq + mmsize]
    mulps     m0, m0, [src1q + lenq]
    mulps     m1, m1, [src1q + lenq + mmsize]
    mova      [dstq + lenq], m0
    mova      [dstq + lenq + mmsize], m1

    sub       lenq, 2*mmsize
    jge       .loop
    REP_RET
%endmacro

INIT_XMM sse
VECTOR_FMUL
%if HAVE_AVX_EXTERNAL
INIT_YMM avx
VECTOR_FMUL
%endif

;------------------------------------------------------------------------------
; void ff_vector_fmac_scalar(float *dst, const float *src, float mul, int len)
;------------------------------------------------------------------------------

%macro VECTOR_FMAC_SCALAR 0
%if UNIX64
cglobal vector_fmac_scalar, 3,3,3, dst, src, len
%else
cglobal vector_fmac_scalar, 4,4,3, dst, src, mul, len
%endif
%if ARCH_X86_32
    VBROADCASTSS m0, mulm
%else
%if WIN64
    mova       xmm0, xmm2
%endif
    shufps     xmm0, xmm0, 0
%if cpuflag(avx)
    vinsertf128  m0, m0, xmm0, 1
%endif
%endif
    lea    lenq, [lend*4-2*mmsize]
.loop:
    mulps    m1, m0, [srcq+lenq       ]
    mulps    m2, m0, [srcq+lenq+mmsize]
    addps    m1, m1, [dstq+lenq       ]
    addps    m2, m2, [dstq+lenq+mmsize]
    mova  [dstq+lenq       ], m1
    mova  [dstq+lenq+mmsize], m2
    sub    lenq, 2*mmsize
    jge .loop
    REP_RET
%endmacro

INIT_XMM sse
VECTOR_FMAC_SCALAR
%if HAVE_AVX_EXTERNAL
INIT_YMM avx
VECTOR_FMAC_SCALAR
%endif


text:
import React from 'react';
import ReactDOM from 'react-dom';
import Todo from './components/Todo';

class App extends React.Component {
  helloWorld() {
    console.log("hello");
  }
  render(){
    console.log(this.helloWorld());
    return(
      <div><Todo /> </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));


text:
const DynamicPreviewPage = ({ pageContext }) => {
    if(typeof window !== `undefined`){
        //look for and grab the `ContentID` query string
        const contentID = getParameterByName({ name: `ContentID`, url: window.location.href });
        const itemPath = pageContext.redirects[contentID];

        //matched item
        if(itemPath) {
            //i.e. `/posts/some-post-title`
            window.location = itemPath;
        } else {
            //unknown item, so redirect to the parent-page (assuming it is a listing page)
            //i.e. `/posts/some-post-title`
            let path = pageContext.redirects[Object.keys(pageContext.redirects)[0]];
            //i.e. `/posts/
            const parentPath = path.substring(0, path.lastIndexOf('/'));
            //i.e. `/posts/some-post-title`
            window.location = parentPath;
        }
    }
    //no render
    return null;
}

const getParameterByName = ({ name, url}) => {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

export default DynamicPreviewPage;