text:
import { ReflectiveInjector } from '@angular/core';
import { Http, ConnectionBackend, RequestOptions, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';

import { ResourceService } from './resource.service';
import { Category, SubCategory, Resource } from './resource.model';

describe('ResourceService', () => {

  let injector: ReflectiveInjector;
  let backend: MockBackend;
  let resourceService: ResourceService;

  function createResponse(body: any) {
    return new Response(new ResponseOptions({ body: JSON.stringify(body) }));
  }

  beforeEach(() => {
    injector = ReflectiveInjector.resolveAndCreate([
      ResourceService,
      { provide: ConnectionBackend, useClass: MockBackend },
      { provide: RequestOptions, useClass: BaseRequestOptions },
      Http
    ]);

    backend = injector.get(ConnectionBackend);
    resourceService = injector.get(ResourceService);
  });

  it('should be creatable', () => {
    expect(resourceService).toBeTruthy();
  });

  it('should make a single connection to the server', () => {
    expect(backend.connectionsArray.length).toEqual(1);
    expect(backend.connectionsArray[0].request.url).toEqual('generated/resources.json');
  });

  describe('#categories', () => {

    let categories: Category[];
    let testData: any;

    beforeEach(() => {
      testData = getTestResources();
      backend.connectionsArray[0].mockRespond(createResponse(testData));
      resourceService.categories.subscribe(results => categories = results);
    });

    it('categories observable should complete', () => {
      let completed = false;
      resourceService.categories.subscribe(null, null, () => completed = true);
      expect(true).toBe(true, 'observable completed');
    });

    it('should reshape contributors.json to sorted category array', () => {
      const actualIds = categories.map(c => c.id).join(',');
      expect(actualIds).toBe('cat-1,cat-3');
    });

    it('should convert ids to canonical form', () => {
      // canonical form is lowercase with dashes for spaces
      const cat = categories[1];
      const sub = cat.subCategories[0];
      const res = sub.resources[0];

      expect(cat.id).toBe('cat-3', 'category id');
      expect(sub.id).toBe('cat3-subcat2', 'subcat id');
      expect(res.id).toBe('cat3-subcat2-res1', 'resources id');
    });

    it('resource knows its category and sub-category titles', () => {
      const cat = categories[1];
      const sub = cat.subCategories[0];
      const res = sub.resources[0];
      expect(res.category).toBe(cat.title, 'category title');
      expect(res.subCategory).toBe(sub.title, 'subcategory title');
    });

    it('should have expected SubCategories of "Cat 3"', () => {
      const actualIds = categories[1].subCategories.map(s => s.id).join(',');
      expect(actualIds).toBe('cat3-subcat2,cat3-subcat1');
    });

    it('should have expected sorted resources of "Cat 1:SubCat1"', () => {
      const actualIds = categories[0].subCategories[0].resources.map(r => r.id).join(',');
      expect(actualIds).toBe('a-a-a,s-s-s,z-z-z');
    });
  });

  it('should do WHAT(?) if the request fails');
});

function getTestResources() {
  // tslint:disable:quotemark
  return {
    "Cat 3": {
      "order": 3,
      "subCategories": {
        "Cat3 SubCat1": {
          "order": 2,
          "resources": {
            "Cat3 SubCat1 Res1": {
              "desc": "Meetup in Barcelona, Spain. ",
              "rev": true,
              "title": "Angular Beers",
              "url": "http://www.meetup.com/AngularJS-Beers/"
            },
            "Cat3 SubCat1 Res2": {
              "desc": "Angular Camps in Barcelona, Spain.",
              "rev": true,
              "title": "Angular Camp",
              "url": "http://angularcamp.org/"
            }
          }
        },
        "Cat3 SubCat2": {
          "order": 1,
          "resources": {
            "Cat3 SubCat2 Res1": {
              "desc": "A community index of components and libraries",
              "rev": true,
              "title": "Catalog of Angular Components & Libraries",
              "url": "https://a/b/c"
            }
          }
        },
      }
    },
    "Cat 1": {
      "order": 1,
      "subCategories": {
        "Cat1 SubCat1": {
          "order": 1,
          "resources": {
            "S S S": {
              "desc": "SSS",
              "rev": true,
              "title": "Sssss",
              "url": "http://s/s/s"
            },
            "A A A": {
             "desc": "AAA",
              "rev": true,
              "title": "Aaaa",
              "url": "http://a/a/a"
            },
            "Z Z Z": {
             "desc": "ZZZ",
              "rev": true,
              "title": "Zzzzz",
              "url": "http://z/z/z"
            }
          }
        },
      },
    }
  };
}


text:
[kakao](../../index.md) / [com.agoda.kakao.screen](../index.md) / [Screen](index.md) / [<init>](./-init-.md)

# <init>

`Screen()`

Container class for UI elements.

This class groups UI elements and grants access to basic actions,
such as tapBack() and closeSoftKeyboard()

### Parameters

`T` - type of your screen, done to enable invoke() for its children

**See Also**

[ScreenActions](../-screen-actions/index.md)

redpajama_set_name: RedPajamaGithub


text:
import Ember from 'ember';

export default Ember.Controller.extend({
  users: null,

  actions: {

    selectUser: function(user) {
      this.set('selectedUser', user);
    },

    selectEmployee: function(employee) {
      this.set('selectedEmployee', employee);
    },

    createTask: function() {
      var that = this;

      var user = this.get('selectedUser');
      var name = this.get('name');
      var description = this.get('description');
      var dueDate = this.get('dueDate');
      var employee = this.get('selectedEmployee');
      var vendor = this.controllerFor('s.vendors.vendor').get('vendor');

      var newTask = this.store.createRecord('task', {
        name: name,
        description: description,
        dueDate: dueDate,
        employee: employee,
        assignedTo: user,
        vendor: vendor
      })
      newTask.save().then(function(newTask){
        that.controllerFor('s.vendors.vendor.tasks.task').toggleProperty('isShowingTaskSuccess');
        that.transitionToRoute('s.vendors.vendor.tasks.task', newTask);
      });
    }
  }
});


text:
<?php

declare(strict_types=1);

namespace StructType;

use InvalidArgumentException;
use WsdlToPhp\PackageBase\AbstractStructBase;

/**
 * This class stands for SuggestionsViewOptionsType StructType
 * @package Ews
 * @subpackage Structs
 * @author WsdlToPhp <contact@wsdltophp.com>
 */
class EwsSuggestionsViewOptionsType extends AbstractStructBase
{
    /**
     * The DetailedSuggestionsWindow
     * Meta information extracted from the WSDL
     * - maxOccurs: 1
     * - minOccurs: 1
     * @var \StructType\EwsDuration
     */
    protected \StructType\EwsDuration $DetailedSuggestionsWindow;
    /**
     * The GoodThreshold
     * Meta information extracted from the WSDL
     * - maxOccurs: 1
     * - minOccurs: 0
     * @var int|null
     */
    protected ?int $GoodThreshold = null;
    /**
     * The MaximumResultsByDay
     * Meta information extracted from the WSDL
     * - maxOccurs: 1
     * - minOccurs: 0
     * @var int|null
     */
    protected ?int $MaximumResultsByDay = null;
    /**
     * The MaximumNonWorkHourResultsByDay
     * Meta information extracted from the WSDL
     * - maxOccurs: 1
     * - minOccurs: 0
     * @var int|null
     */
    protected ?int $MaximumNonWorkHourResultsByDay = null;
    /**
     * The MeetingDurationInMinutes
     * Meta information extracted from the WSDL
     * - maxOccurs: 1
     * - minOccurs: 0
     * @var int|null
     */
    protected ?int $MeetingDurationInMinutes = null;
    /**
     * The MinimumSuggestionQuality
     * Meta information extracted from the WSDL
     * - maxOccurs: 1
     * - minOccurs: 0
     * @var string|null
     */
    protected ?string $MinimumSuggestionQuality = null;
    /**
     * The CurrentMeetingTime
     * Meta information extracted from the WSDL
     * - maxOccurs: 1
     * - minOccurs: 0
     * @var string|null
     */
    protected ?string $CurrentMeetingTime = null;
    /**
     * The GlobalObjectId
     * Meta information extracted from the WSDL
     * - maxOccurs: 1
     * - minOccurs: 0
     * @var string|null
     */
    protected ?string $GlobalObjectId = null;
    /**
     * Constructor method for SuggestionsViewOptionsType
     * @uses EwsSuggestionsViewOptionsType::setDetailedSuggestionsWindow()
     * @uses EwsSuggestionsViewOptionsType::setGoodThreshold()
     * @uses EwsSuggestionsViewOptionsType::setMaximumResultsByDay()
     * @uses EwsSuggestionsViewOptionsType::setMaximumNonWorkHourResultsByDay()
     * @uses EwsSuggestionsViewOptionsType::setMeetingDurationInMinutes()
     * @uses EwsSuggestionsViewOptionsType::setMinimumSuggestionQuality()
     * @uses EwsSuggestionsViewOptionsType::setCurrentMeetingTime()
     * @uses EwsSuggestionsViewOptionsType::setGlobalObjectId()
     * @param \StructType\EwsDuration $detailedSuggestionsWindow
     * @param int $goodThreshold
     * @param int $maximumResultsByDay
     * @param int $maximumNonWorkHourResultsByDay
     * @param int $meetingDurationInMinutes
     * @param string $minimumSuggestionQuality
     * @param string $currentMeetingTime
     * @param string $globalObjectId
     */
    public function __construct(\StructType\EwsDuration $detailedSuggestionsWindow, ?int $goodThreshold = null, ?int $maximumResultsByDay = null, ?int $maximumNonWorkHourResultsByDay = null, ?int $meetingDurationInMinutes = null, ?string $minimumSuggestionQuality = null, ?string $currentMeetingTime = null, ?string $globalObjectId = null)
    {
        $this
            ->setDetailedSuggestionsWindow($detailedSuggestionsWindow)
            ->setGoodThreshold($goodThreshold)
            ->setMaximumResultsByDay($maximumResultsByDay)
            ->setMaximumNonWorkHourResultsByDay($maximumNonWorkHourResultsByDay)
            ->setMeetingDurationInMinutes($meetingDurationInMinutes)
            ->setMinimumSuggestionQuality($minimumSuggestionQuality)
            ->setCurrentMeetingTime($currentMeetingTime)
            ->setGlobalObjectId($globalObjectId);
    }
    /**
     * Get DetailedSuggestionsWindow value
     * @return \StructType\EwsDuration
     */
    public function getDetailedSuggestionsWindow(): \StructType\EwsDuration
    {
        return $this->DetailedSuggestionsWindow;
    }
    /**
     * Set DetailedSuggestionsWindow value
     * @param \StructType\EwsDuration $detailedSuggestionsWindow
     * @return \StructType\EwsSuggestionsViewOptionsType
     */
    public function setDetailedSuggestionsWindow(\StructType\EwsDuration $detailedSuggestionsWindow): self
    {
        $this->DetailedSuggestionsWindow = $detailedSuggestionsWindow;

        return $this;
    }
    /**
     * Get GoodThreshold value
     * @return int|null
     */
    public function getGoodThreshold(): ?int
    {
        return $this->GoodThreshold;
    }
    /**
     * Set GoodThreshold value
     * @param int $goodThreshold
     * @return \StructType\EwsSuggestionsViewOptionsType
     */
    public function setGoodThreshold(?int $goodThreshold = null): self
    {
        // validation for constraint: int
        if (!is_null($goodThreshold) && !(is_int($goodThreshold) || ctype_digit($goodThreshold))) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide an integer value, %s given', var_export($goodThreshold, true), gettype($goodThreshold)), __LINE__);
        }
        $this->GoodThreshold = $goodThreshold;

        return $this;
    }
    /**
     * Get MaximumResultsByDay value
     * @return int|null
     */
    public function getMaximumResultsByDay(): ?int
    {
        return $this->MaximumResultsByDay;
    }
    /**
     * Set MaximumResultsByDay value
     * @param int $maximumResultsByDay
     * @return \StructType\EwsSuggestionsViewOptionsType
     */
    public function setMaximumResultsByDay(?int $maximumResultsByDay = null): self
    {
        // validation for constraint: int
        if (!is_null($maximumResultsByDay) && !(is_int($maximumResultsByDay) || ctype_digit($maximumResultsByDay))) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide an integer value, %s given', var_export($maximumResultsByDay, true), gettype($maximumResultsByDay)), __LINE__);
        }
        $this->MaximumResultsByDay = $maximumResultsByDay;

        return $this;
    }
    /**
     * Get MaximumNonWorkHourResultsByDay value
     * @return int|null
     */
    public function getMaximumNonWorkHourResultsByDay(): ?int
    {
        return $this->MaximumNonWorkHourResultsByDay;
    }
    /**
     * Set MaximumNonWorkHourResultsByDay value
     * @param int $maximumNonWorkHourResultsByDay
     * @return \StructType\EwsSuggestionsViewOptionsType
     */
    public function setMaximumNonWorkHourResultsByDay(?int $maximumNonWorkHourResultsByDay = null): self
    {
        // validation for constraint: int
        if (!is_null($maximumNonWorkHourResultsByDay) && !(is_int($maximumNonWorkHourResultsByDay) || ctype_digit($maximumNonWorkHourResultsByDay))) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide an integer value, %s given', var_export($maximumNonWorkHourResultsByDay, true), gettype($maximumNonWorkHourResultsByDay)), __LINE__);
        }
        $this->MaximumNonWorkHourResultsByDay = $maximumNonWorkHourResultsByDay;

        return $this;
    }
    /**
     * Get MeetingDurationInMinutes value
     * @return int|null
     */
    public function getMeetingDurationInMinutes(): ?int
    {
        return $this->MeetingDurationInMinutes;
    }
    /**
     * Set MeetingDurationInMinutes value
     * @param int $meetingDurationInMinutes
     * @return \StructType\EwsSuggestionsViewOptionsType
     */
    public function setMeetingDurationInMinutes(?int $meetingDurationInMinutes = null): self
    {
        // validation for constraint: int
        if (!is_null($meetingDurationInMinutes) && !(is_int($meetingDurationInMinutes) || ctype_digit($meetingDurationInMinutes))) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide an integer value, %s given', var_export($meetingDurationInMinutes, true), gettype($meetingDurationInMinutes)), __LINE__);
        }
        $this->MeetingDurationInMinutes = $meetingDurationInMinutes;

        return $this;
    }
    /**
     * Get MinimumSuggestionQuality value
     * @return string|null
     */
    public function getMinimumSuggestionQuality(): ?string
    {
        return $this->MinimumSuggestionQuality;
    }
    /**
     * Set MinimumSuggestionQuality value
     * @uses \EnumType\EwsSuggestionQuality::valueIsValid()
     * @uses \EnumType\EwsSuggestionQuality::getValidValues()
     * @throws InvalidArgumentException
     * @param string $minimumSuggestionQuality
     * @return \StructType\EwsSuggestionsViewOptionsType
     */
    public function setMinimumSuggestionQuality(?string $minimumSuggestionQuality = null): self
    {
        // validation for constraint: enumeration
        if (!\EnumType\EwsSuggestionQuality::valueIsValid($minimumSuggestionQuality)) {
            throw new InvalidArgumentException(sprintf('Invalid value(s) %s, please use one of: %s from enumeration class \EnumType\EwsSuggestionQuality', is_array($minimumSuggestionQuality) ? implode(', ', $minimumSuggestionQuality) : var_export($minimumSuggestionQuality, true), implode(', ', \EnumType\EwsSuggestionQuality::getValidValues())), __LINE__);
        }
        $this->MinimumSuggestionQuality = $minimumSuggestionQuality;

        return $this;
    }
    /**
     * Get CurrentMeetingTime value
     * @return string|null
     */
    public function getCurrentMeetingTime(): ?string
    {
        return $this->CurrentMeetingTime;
    }
    /**
     * Set CurrentMeetingTime value
     * @param string $currentMeetingTime
     * @return \StructType\EwsSuggestionsViewOptionsType
     */
    public function setCurrentMeetingTime(?string $currentMeetingTime = null): self
    {
        // validation for constraint: string
        if (!is_null($currentMeetingTime) && !is_string($currentMeetingTime)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($currentMeetingTime, true), gettype($currentMeetingTime)), __LINE__);
        }
        $this->CurrentMeetingTime = $currentMeetingTime;

        return $this;
    }
    /**
     * Get GlobalObjectId value
     * @return string|null
     */
    public function getGlobalObjectId(): ?string
    {
        return $this->GlobalObjectId;
    }
    /**
     * Set GlobalObjectId value
     * @param string $globalObjectId
     * @return \StructType\EwsSuggestionsViewOptionsType
     */
    public function setGlobalObjectId(?string $globalObjectId = null): self
    {
        // validation for constraint: string
        if (!is_null($globalObjectId) && !is_string($globalObjectId)) {
            throw new InvalidArgumentException(sprintf('Invalid value %s, please provide a string, %s given', var_export($globalObjectId, true), gettype($globalObjectId)), __LINE__);
        }
        $this->GlobalObjectId = $globalObjectId;

        return $this;
    }
}


text:
'use strict';

const error = require('stax2/backend/errorHandling');
const notification = require('stax2/backend/boundaries/push');
const uuid = require('uuid');
const config = require('config/environment');
const request = require('request');
// const rp = require('request-promise');
const Promise = require('bluebird');
// const async = require('async');
const coW = require('../../../util').coW;
const co = require('co');
const responseBody = require('util').responseBody;
const executeQuery = require('util').executeQuery;

const _this = this;

//------------------------------- getCurrWeek -----------------------------------//

/*
 * Description: Get current week value from credit config table
 */

let getCurrWeek = coW(function* getCurrWeek(req) {
    const configObj = yield getCreditConfigOptions(req);
    return configObj.current_week;
});

//------------------------------- getCreditConfigOptions -----------------------------------//

/*
 * Description: Returns configuration value object for credits associated to different types.
 */

let getCreditConfigOptions = coW(function* getCreditConfigOptions(req) {
    const query = 'SELECT * from credits_configure';
    const credit_options = yield executeQuery(query);
    const credObj = credit_options.rows.reduce((prev, curr) => {
        prev[curr.type] = curr.value;
        return prev;
    }, {});
    return credObj;
});

//------------------------------- getFreemiumOptions -----------------------------------//

/*
 * Description: get freemium option for user.
 */

let getFreemiumOptions = coW(function* getFreemiumOptions(req) {
    const credOpt = yield getCreditConfigOptions(req);
    return {
        credit: Math.abs(+credOpt.freemium_credit),
        dollar: Math.abs(+credOpt.freemium_dollar)
    }
});

//------------------------------- setConfigValue -----------------------------------//

/*
 * Description: To update configuration value for different options by admin.
 */

let setConfigValue = coW(function* setConfigValue(req) {
    // req.body =  {val: '2', id: 'a3ded9f3-4cfc-4594-9a52-81fc4c9eaf95', type: 'weekly'};
    yield updateConfig(req);
    return yield addToWeekly(req);
});

//------------------------------- updateConfig -----------------------------------//

/*
 * Description: Update credits_configure table values.
 */

let updateConfig = coW(function* updateConfig(req) {
    const query = 'UPDATE credits_configure SET value = ? WHERE type = ?';
    const params = [req.body.val, req.body.type];

    return yield execQuery(query, params);
});

//------------------------------- addToWeekly -----------------------------------//

/*
 * Description: Add entry to credits_weekly table if any admin updates a value.
 */

let addToWeekly = coW(function* addToWeekly(req) {
    let created = new Date();
    let admin_id = req.body.id;

    const query = 'INSERT INTO credits_weekly (created, admin_id, credit, type) VALUES (?, ?, ?, ?)';
    return yield execQuery(query, [created, admin_id, req.body.val, req.body.type], { prepare: true });
});

//------------------------------- getWeeklyHashtag -----------------------------------//

/*
 * Description: calculate weekly hashtag credits for user
 */

let getWeeklyHashtag = coW(function* getWeeklyHashtag(req) {
    const configObj = yield getCreditConfigOptions(req);
    const currWeek = configObj.current_week;
    const max_hastag = configObj.hashtag_max;
    req.body.type = 'hashtag';
    const query = 'SELECT credit from credits_transaction WHERE user_id = ? AND week = ? AND credit_type = ? allow filtering';
    const params = [req.body.user_id, currWeek, req.body.type];

    let hashtag_list = (yield execQuery(query, params, { prepare: true })).rows;
    let sum = hashtag_list.reduce((prev, curr) => {
        return prev + (+curr.credit)
    }, 0)
    console.log(sum, max_hastag, hashtag_list)
    if (sum < +max_hastag) {
        return yield applyCredit(req);
    } else {
        return 'Already reached maximum hashtag credit';
        // throw new Error('Already reached maximum hashtag credit');
    }
});

//------------------------------- applyCredit -----------------------------------//

/*
 * Description: Add an entry to transaction table and update user's credit value.
 */

let applyCredit = coW(function* applyCredit(req) {
    const configObj = yield getCreditConfigOptions(req);
    if (!!req.body.type && configObj[req.body.type]) {
        req.body = Object.assign(req.body, {
            "used_credit": configObj[req.body.type],
            "type": req.body.type,
            "tid": uuid.v4(),
            "created": (new Date()).toISOString()
        })

        req.body.credits = yield getUserCredit(req);
        return [yield addToTranscation(req), yield updateUser(req)].join(' and ');
    } else {
        throw new Error('Invalid type of transaction');
    }
});

//------------------------------- getUserCredit -----------------------------------//

/*
 * Description: Get user credit from user table.
 */

let getUserCredit = coW(function* getUserCredit(req) {
    const query = 'SELECT id, credits FROM user WHERE id = ?';
    const params = [req.body.user_id];
    console.log(params);

    let userInfo = yield execQuery(query, params, { prepare: true });
    return +userInfo.rows[0].credits;
});

//------------------------------- updateUser -----------------------------------//

/*
 * Description:  Add a description
 */

let updateUser = coW(function* updateUser(req) {
    console.log('Credits: ', req.body.type);
    let query = '';
    let params = [];
    let updated_credits = +req.body.credits + +req.body.used_credit;
    updated_credits = (updated_credits < 0) ? 0 : updated_credits;

    if (req.body.type == 'signup_credit') {
        query = 'UPDATE user SET credits = ?, signup_credit = ? WHERE id = ?';
        params = [`${updated_credits}`, true, req.body.user_id];
    } else {
        query = 'UPDATE user SET credits = ? WHERE id = ?';
        params = [`${updated_credits}`, req.body.user_id];
    }

    yield execQuery(query, params, { prepare: true });
    return 'updated user credits';
});

//------------------------------- addToTranscation -----------------------------------//

/*
 * Description:  Add a description
 */

let addToTranscation = coW(function* addToTranscation(req) {
    const configObj = yield getCreditConfigOptions();
    const credit_action = +req.body.used_credit > -1 ? 'add' : 'used';

    const query = 'INSERT INTO credits_transaction (transaction_id, created, credit, credit_action, credit_type, user_id, week) VALUES ( ?, ?, ?, ?, ?, ?, ?)';
    const params = [req.body.tid, req.body.created, req.body.used_credit, credit_action, req.body.type, req.body.user_id, configObj.current_week];

    yield execQuery(query, params, { prepare: true });
    return 'added a credit transaction';
});

//------------------------------- addWeeklyCreditAll -----------------------------------//

/*
 * Description: CRON job method that will run on weekly basis.
 */

let addWeeklyCreditAll = coW(function* addWeeklyCreditAll(req) {
    console.log('running addWeeklyCreditAll');
    req.body = {};
    const configObj = yield getCreditConfigOptions(req);
    let weeklyCount = configObj.weekly;

    // get all users with negative transactions
    let negative_transactions = (yield execQuery('SELECT * FROM credits_transaction WHERE week = ? AND credit < ? ALLOW FILTERING', [configObj.current_week, '0'], { prepare: true })).rows;
    if (!negative_transactions.length) {
        yield increaseWeek();
        const response = 'no matching transactions this week';
        console.log(response);
        return response;
    }

    // calculate the credits to be added to each of these users
    let users_credits_to_add = negative_transactions.reduce((prev, curr) => {
        (typeof prev[curr.user_id] == 'undefined') ? prev[curr.user_id] = 0: '';
        let newCreditAmount = prev[curr.user_id] + Math.abs(curr.credit);
        prev[curr.user_id] = (newCreditAmount > weeklyCount) ? +weeklyCount : newCreditAmount;
        return prev;
    }, {});

    // add weekly credits to above users
    if (users_credits_to_add.length != 0) {
        const userIds = Object.keys(users_credits_to_add);
        for (let i = 0; i < userIds.length; i++) {
            let obj = {};
            obj['body'] = {
                "user_id": userIds[i],
                "used_credit": `${users_credits_to_add[userIds[i]]}`,
                "type": 'weekly',
                "tid": uuid.v4(),
                "created": (new Date()).toISOString()
            };
            obj.body.credits = yield getUserCredit(obj);
            [yield addToTranscation(obj), yield updateUser(obj)].join(' and ');
        }

        yield increaseWeek();

        const response = `weekly adds of max ${weeklyCount} credits completed for ${userIds.length} users!`;
        console.log(response);
        return response;
    } else {
        yield increaseWeek();

        const response = 'No weekly adds required this week for any user';
        console.log(response);
        return response;
    }
});

//------------------------------- increaseWeek -----------------------------------//

/*
 * Description: adds week to next value
 */

let increaseWeek = coW(function* increaseWeek(req) {
    const configObj = yield getCreditConfigOptions(req);
    // updating current week  + 1
    return yield updateConfig({
        body: {
            type: 'current_week',
            val: `${+configObj.current_week + 1}`
                // val: `1` // for debugging
        }
    })
});

module.exports = {
    getCurrWeek,
    getCreditConfigOptions,
    getFreemiumOptions,
    getWeeklyHashtag,
    getUserCredit,
    setConfigValue,
    applyCredit,
    addWeeklyCreditAll
}


text:
permalink: false
title: Hello world
date: 2016-01-07
slug: hello-world
category: blog
---

Hi y'all. If you read this, that means I've started my little developer's blog that doubles as a project because none of [those static site builders](https://www.staticgen.com/) are any good. Wait, stop, scratch that. I just need to learn JS and Node, more like it. _And_ [reading code is harder than writing](http://www.joelonsoftware.com/articles/fog0000000069.html).

Here's [the repo](https://github.com/hoichi/hoichi.io), if you're curious. It's pretty messy and pretty much everything screams for rewriting, but it's a start.


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=4 sw=4 et tw=99 ft=cpp:
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla SpiderMonkey JavaScript 1.9 code, released
 * June 12, 2009.
 *
 * The Initial Developer of the Original Code is
 *   the Mozilla Corporation.
 *
 * Contributor(s):
 *   David Anderson <danderson@mozilla.com>
 *   Andreas Gal <gal@mozilla.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "jsapi.h"

class RecursiveSlotMap : public SlotMap
{
  protected:
    unsigned downPostSlots;
    LIns *rval_ins;

  public:
    RecursiveSlotMap(TraceRecorder& rec, unsigned downPostSlots, LIns* rval_ins)
      : SlotMap(rec), downPostSlots(downPostSlots), rval_ins(rval_ins)
    {
    }

    JS_REQUIRES_STACK void
    adjustTypes()
    {
        /* Check if the return value should be promoted. */
        if (slots[downPostSlots].lastCheck == TypeCheck_Demote)
            rval_ins = mRecorder.lir->ins1(LIR_i2d, rval_ins);
        /* Adjust any global variables. */
        for (unsigned i = downPostSlots + 1; i < slots.length(); i++)
            adjustType(slots[i]);
    }

    JS_REQUIRES_STACK void
    adjustTail(TypeConsensus consensus)
    {
        /*
         * exit->sp_adj = ((downPostSlots + 1) * sizeof(double)) - nativeStackBase
         *
         * Store at exit->sp_adj - sizeof(double)
         */
        ptrdiff_t retOffset = downPostSlots * sizeof(double) -
                              mRecorder.tree->nativeStackBase;
        mRecorder.lir->insStore(mRecorder.addName(rval_ins, "rval_ins"),
                                 mRecorder.lirbuf->sp, retOffset, ACCSET_STACK);
    }
};

class UpRecursiveSlotMap : public RecursiveSlotMap
{
  public:
    UpRecursiveSlotMap(TraceRecorder& rec, unsigned downPostSlots, LIns* rval_ins)
      : RecursiveSlotMap(rec, downPostSlots, rval_ins)
    {
    }

    JS_REQUIRES_STACK void
    adjustTail(TypeConsensus consensus)
    {
        LirBuffer* lirbuf = mRecorder.lirbuf;
        LirWriter* lir = mRecorder.lir;

        /*
         * The native stack offset of the return value once this frame has
         * returned, is:
         *      -tree->nativeStackBase + downPostSlots * sizeof(double)
         *
         * Note, not +1, since the offset is 0-based.
         *
         * This needs to be adjusted down one frame. The amount to adjust must
         * be the amount down recursion added, which was just guarded as
         * |downPostSlots|. So the offset is:
         *
         *      -tree->nativeStackBase + downPostSlots * sizeof(double) -
         *                                   downPostSlots * sizeof(double)
         * Or:
         *      -tree->nativeStackBase
         *
         * This makes sense because this slot is just above the highest sp for
         * the down frame.
         */
        lir->insStore(rval_ins, lirbuf->sp, -mRecorder.tree->nativeStackBase, ACCSET_STACK);

        lirbuf->sp = lir->ins2(LIR_addp, lirbuf->sp,
                               lir->insImmWord(-int(downPostSlots) * sizeof(double)));
        lir->insStore(lirbuf->sp, lirbuf->state, offsetof(TracerState, sp), ACCSET_OTHER);
        lirbuf->rp = lir->ins2(LIR_addp, lirbuf->rp,
                               lir->insImmWord(-int(sizeof(FrameInfo*))));
        lir->insStore(lirbuf->rp, lirbuf->state, offsetof(TracerState, rp), ACCSET_OTHER);
    }
};

#if defined DEBUG
JS_REQUIRES_STACK void
TraceRecorder::assertDownFrameIsConsistent(VMSideExit* anchor, FrameInfo* fi)
{
    JS_ASSERT(anchor->recursive_down);
    JS_ASSERT(anchor->recursive_down->callerHeight == fi->callerHeight);

    unsigned downPostSlots = fi->callerHeight;
    JSValueType* typeMap = fi->get_typemap();

    captureStackTypes(1, typeMap);
    const JSValueType* m1 = anchor->recursive_down->get_typemap();
    for (unsigned i = 0; i < downPostSlots; i++) {
        if (m1[i] == typeMap[i])
            continue;
        if ((typeMap[i] == JSVAL_TYPE_INT32 && m1[i] == JSVAL_TYPE_DOUBLE) ||
            (typeMap[i] == JSVAL_TYPE_DOUBLE && m1[i] == JSVAL_TYPE_INT32)) {
            continue;
        }
        JS_NOT_REACHED("invalid RECURSIVE_MISMATCH exit");
    }
    JS_ASSERT(memcmp(anchor->recursive_down, fi, sizeof(FrameInfo)) == 0);
}
#endif

JS_REQUIRES_STACK VMSideExit*
TraceRecorder::downSnapshot(FrameInfo* downFrame)
{
    JS_ASSERT(!pendingSpecializedNative);

    /* Build the typemap the exit will have. Note extra stack slot for return value. */
    unsigned downPostSlots = downFrame->callerHeight;
    unsigned ngslots = tree->globalSlots->length();
    unsigned exitTypeMapLen = downPostSlots + 1 + ngslots;
    JSValueType* exitTypeMap = (JSValueType*)alloca(sizeof(JSValueType) * exitTypeMapLen);
    JSValueType* typeMap = downFrame->get_typemap();

    /* Add stack slots. */
    for (unsigned i = 0; i < downPostSlots; i++)
        exitTypeMap[i] = typeMap[i];

    /* Add the return type. */
    JS_ASSERT_IF(*cx->regs->pc != JSOP_RETURN, *cx->regs->pc == JSOP_STOP);
    if (*cx->regs->pc == JSOP_RETURN)
        exitTypeMap[downPostSlots] = determineSlotType(&stackval(-1));
    else
        exitTypeMap[downPostSlots] = JSVAL_TYPE_UNDEFINED;

    /* Add global types. */
    determineGlobalTypes(&exitTypeMap[downPostSlots + 1]);

    VMSideExit* exit = (VMSideExit*)
        traceMonitor->traceAlloc->alloc(sizeof(VMSideExit) + sizeof(JSValueType) * exitTypeMapLen);

    PodZero(exit);
    exit->from = fragment;
    exit->calldepth = 0;
    JS_ASSERT(unsigned(exit->calldepth) == callDepth);
    exit->numGlobalSlots = ngslots;
    exit->numStackSlots = downPostSlots + 1;
    exit->numStackSlotsBelowCurrentFrame = cx->fp()->down->argv ?
        nativeStackOffset(&cx->fp()->argv[-2]) / sizeof(double) : 0;
    exit->exitType = UNSTABLE_LOOP_EXIT;
    exit->block = cx->fp()->down->maybeBlockChain();
    exit->pc = downFrame->pc + JSOP_CALL_LENGTH;
    exit->imacpc = NULL;
    exit->sp_adj = ((downPostSlots + 1) * sizeof(double)) - tree->nativeStackBase;
    exit->rp_adj = exit->calldepth * sizeof(FrameInfo*);
    exit->nativeCalleeWord = 0;
    exit->lookupFlags = js_InferFlags(cx, 0);
    memcpy(exit->fullTypeMap(), exitTypeMap, sizeof(JSValueType) * exitTypeMapLen);
#if defined JS_JIT_SPEW
    TreevisLogExit(cx, exit);
#endif
    return exit;
}

static JS_REQUIRES_STACK Value *
DownFrameSP(JSContext *cx)
{
    FrameRegsIter i(cx);
    ++i;
    JS_ASSERT(i.fp() == cx->fp()->down);
    return i.sp();
}

JS_REQUIRES_STACK AbortableRecordingStatus
TraceRecorder::upRecursion()
{
    JS_ASSERT((JSOp)*cx->fp()->down->savedPC == JSOP_CALL);
    JS_ASSERT(js_CodeSpec[js_GetOpcode(cx, cx->fp()->down->getScript(),
              cx->fp()->down->savedPC)].length == JSOP_CALL_LENGTH);

    JS_ASSERT(callDepth == 0);

    /*
     * If some operation involving interpreter frame slurping failed, go to
     * that code right away, and don't bother with emitting the up-recursive
     * guards again.
     */
    if (anchor && (anchor->exitType == RECURSIVE_EMPTY_RP_EXIT ||
        anchor->exitType == RECURSIVE_SLURP_MISMATCH_EXIT ||
        anchor->exitType == RECURSIVE_SLURP_FAIL_EXIT)) {
        return slurpDownFrames(cx->fp()->down->savedPC);
    }

    jsbytecode* return_pc = cx->fp()->down->savedPC;
    jsbytecode* recursive_pc = return_pc + JSOP_CALL_LENGTH;

    /*
     * It is possible that the down frame isn't the same at runtime. It's not
     * enough to guard on the PC, since the typemap could be different as well.
     * To deal with this, guard that the FrameInfo on the callstack is 100%
     * identical.
     *
     * Note that though the counted slots is called "downPostSlots", this is
     * the number of slots after the CALL instruction has theoretically popped
     * callee/this/argv, but before the return value is pushed. This is
     * intended since the FrameInfo pushed by down recursion would not have
     * the return value yet. Instead, when closing the loop, the return value
     * becomes the sole stack type that deduces type stability.
     */
    unsigned totalSlots = NativeStackSlots(cx, 1);
    unsigned downPostSlots = totalSlots - NativeStackSlots(cx, 0);
    FrameInfo* fi = (FrameInfo*)alloca(sizeof(FrameInfo) + totalSlots * sizeof(JSValueType));
    fi->block = NULL;
    fi->pc = (jsbytecode*)return_pc;
    fi->imacpc = NULL;

    /*
     * Need to compute this from the down frame, since the stack could have
     * moved on this one.
     */
    fi->spdist = DownFrameSP(cx) - cx->fp()->down->slots();
    JS_ASSERT(cx->fp()->numActualArgs() == cx->fp()->down->numActualArgs());
    fi->set_argc(uint16(cx->fp()->numActualArgs()), false);
    fi->callerHeight = downPostSlots;
    fi->callerArgc = cx->fp()->down->numActualArgs();

    if (anchor && anchor->exitType == RECURSIVE_MISMATCH_EXIT) {
        /*
         * Case 0: Anchoring off a RECURSIVE_MISMATCH guard. Guard on this FrameInfo.
         * This is always safe because this point is only reached on simple "call myself"
         * recursive functions.
         */
#if defined DEBUG
        assertDownFrameIsConsistent(anchor, fi);
#endif
        fi = anchor->recursive_down;
    } else if (recursive_pc != fragment->root->ip) {
        /*
         * Case 1: Guess that down-recursion has to started back out, infer types
         * from the down frame.
         */
        captureStackTypes(1, fi->get_typemap());
    } else {
        /* Case 2: Guess that up-recursion is backing out, infer types from our Tree. */
        JS_ASSERT(tree->nStackTypes == downPostSlots + 1);
        JSValueType* typeMap = fi->get_typemap();
        for (unsigned i = 0; i < downPostSlots; i++)
            typeMap[i] = tree->typeMap[i];
    }

    fi = traceMonitor->frameCache->memoize(fi);

    /*
     * Guard that there are more recursive frames. If coming from an anchor
     * where this was already computed, don't bother doing it again.
     */
    if (!anchor || anchor->exitType != RECURSIVE_MISMATCH_EXIT) {
        VMSideExit* exit = snapshot(RECURSIVE_EMPTY_RP_EXIT);

        /* Guard that rp >= sr + 1 */
        guard(true,
              lir->ins2(LIR_gep, lirbuf->rp,
                        lir->ins2(LIR_addp,
                                  lir->insLoad(LIR_ldp, lirbuf->state,
                                               offsetof(TracerState, sor), ACCSET_OTHER),
                                  INS_CONSTWORD(sizeof(FrameInfo*)))),
              exit);
    }

    debug_only_printf(LC_TMRecorder, "guardUpRecursive fragment->root=%p fi=%p\n", (void*)fragment->root, (void*)fi);

    /* Guard that the FrameInfo above is the same FrameInfo pointer. */
    VMSideExit* exit = snapshot(RECURSIVE_MISMATCH_EXIT);
    LIns* prev_rp = lir->insLoad(LIR_ldp, lirbuf->rp, -int32_t(sizeof(FrameInfo*)), ACCSET_RSTACK);
    guard(true, lir->ins2(LIR_eqp, prev_rp, INS_CONSTPTR(fi)), exit);

    /*
     * Now it's time to try and close the loop. Get a special exit that points
     * at the down frame, after the return has been propagated up.
     */
    exit = downSnapshot(fi);

    LIns* rval_ins;
    if (*cx->regs->pc == JSOP_RETURN) {
        JS_ASSERT(!anchor || anchor->exitType != RECURSIVE_SLURP_FAIL_EXIT);
        rval_ins = get(&stackval(-1));
        JS_ASSERT(rval_ins);
    } else {
        rval_ins = INS_UNDEFINED();
    }

    JSValueType returnType = exit->stackTypeMap()[downPostSlots];
    if (returnType == JSVAL_TYPE_INT32) {
        JS_ASSERT(*cx->regs->pc == JSOP_RETURN);
        JS_ASSERT(determineSlotType(&stackval(-1)) == JSVAL_TYPE_INT32);
        JS_ASSERT(isPromoteInt(rval_ins));
        rval_ins = demote(lir, rval_ins);
    }

    UpRecursiveSlotMap slotMap(*this, downPostSlots, rval_ins);
    for (unsigned i = 0; i < downPostSlots; i++)
        slotMap.addSlot(exit->stackType(i));
    if (*cx->regs->pc == JSOP_RETURN)
        slotMap.addSlot(&stackval(-1));
    else
        slotMap.addSlot(JSVAL_TYPE_UNDEFINED);
    VisitGlobalSlots(slotMap, cx, *tree->globalSlots);
    if (recursive_pc == (jsbytecode*)fragment->root->ip) {
        debug_only_print0(LC_TMTracer, "Compiling up-recursive loop...\n");
    } else {
        debug_only_print0(LC_TMTracer, "Compiling up-recursive branch...\n");
        exit->exitType = RECURSIVE_UNLINKED_EXIT;
        exit->recursive_pc = recursive_pc;
    }
    JS_ASSERT(tree->recursion != Recursion_Disallowed);
    if (tree->recursion != Recursion_Detected)
        tree->recursion = Recursion_Unwinds;
    return closeLoop(slotMap, exit);
}

class SlurpInfo
{
public:
    unsigned curSlot;
    JSValueType* typeMap;
    VMSideExit* exit;
    unsigned slurpFailSlot;
};

/*
 * The three types of anchors that can cause this type of trace to be built are:
 *   RECURSIVE_SLURP_MISMATCH_EXIT
 *   RECURSIVE_SLURP_FAIL_EXIT
 *   RECURSIVE_EMPTY_RP_EXIT
 *
 * EMPTY_RP means that recursion is unwinding, but there are no more frames.
 * This triggers a "slurp trace" to be built. A slurp trace does three things:
 *   1) Checks to see if cx->fp returns to the same point the recursive trace
 *      is trying to unwind to.
 *   2) Pops the inline frame cx->fp, such that cx->fp is now cx->fp->down.
 *   3) Converts the new top-frame slots/sp into the tracer frame.
 *
 * SLURP_MISMATCH means that while trying to convert an interpreter frame,
 * it is owned by the same script, but does not return to the same pc. At this
 * point the frame has not been popped yet.
 *
 * SLURP_FAIL means that the interpreter frame has been popped, the return
 * value has been written to the native stack, but there was a type mismatch
 * while unboxing the interpreter slots.
 */
JS_REQUIRES_STACK AbortableRecordingStatus
TraceRecorder::slurpDownFrames(jsbytecode* return_pc)
{
    /* Missing - no go */
    if (cx->fp()->numActualArgs() != cx->fp()->numFormalArgs())
        RETURN_STOP_A("argc != nargs");

    LIns* argv_ins;
    unsigned frameDepth;
    unsigned downPostSlots;

    FrameRegsIter i(cx);
    LIns* fp_ins = addName(entryFrameIns(), "fp");

    /*
     * When first emitting slurp code, do so against the down frame. After
     * popping the interpreter frame, it is illegal to resume here, as the
     * down frame has been moved up. So all this code should be skipped if
     * anchoring off such an exit.
     */
    if (!anchor || anchor->exitType != RECURSIVE_SLURP_FAIL_EXIT) {
        fp_ins = addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, down), ACCSET_OTHER),
                         "downFp");
        ++i;

        argv_ins = addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, argv), ACCSET_OTHER),
                           "argv");

        /* If recovering from a SLURP_MISMATCH, all of this is unnecessary. */
        if (!anchor || anchor->exitType != RECURSIVE_SLURP_MISMATCH_EXIT) {
            /* fp->down should not be NULL. */
            guard(false, lir->insEqP_0(fp_ins), RECURSIVE_LOOP_EXIT);

            /* fp->down->argv should not be NULL. */
            guard(false, lir->insEqP_0(argv_ins), RECURSIVE_LOOP_EXIT);

            /*
             * Guard on the script being the same. This might seem unnecessary,
             * but it lets the recursive loop end cleanly if it doesn't match.
             * With only the pc check, it is harder to differentiate between
             * end-of-recursion and recursion-returns-to-different-pc.
             */
            guard(true,
                  lir->ins2(LIR_eqp,
                            addName(lir->insLoad(LIR_ldp, fp_ins,
                                                 JSStackFrame::offsetScript(), ACCSET_OTHER),
                                    "script"),
                            INS_CONSTPTR(cx->fp()->down->getScript())),
                  RECURSIVE_LOOP_EXIT);
        }

        /* fp->down->savedPC should be == pc. */
        guard(true,
              lir->ins2(LIR_eqp,
                        addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, savedPC),
                                             ACCSET_OTHER),
                                "savedPC"),
                        INS_CONSTPTR(return_pc)),
              RECURSIVE_SLURP_MISMATCH_EXIT);

        /* fp->down->argc should be == argc. */
        guard(true,
              lir->ins2(LIR_eqi,
                        addName(lir->insLoad(LIR_ldi, fp_ins, JSStackFrame::offsetNumActualArgs(),
                                             ACCSET_OTHER),
                                "argc"),
                        INS_CONST(cx->fp()->numActualArgs())),
              MISMATCH_EXIT);

        /* Pop the interpreter frame. */
        LIns* args[] = { lirbuf->state, cx_ins };
        guard(false, lir->insEqI_0(lir->insCall(&js_PopInterpFrame_ci, args)), MISMATCH_EXIT);

        /* Compute slots for the down frame. */
        downPostSlots = NativeStackSlots(cx, 1) - NativeStackSlots(cx, 0);
        frameDepth = 1;
    } else {
        /* Note: loading argv from fp, not fp->down. */
        argv_ins = addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, argv), ACCSET_OTHER),
                           "argv");

        /* Slots for this frame, minus the return value. */
        downPostSlots = NativeStackSlots(cx, 0) - 1;
        frameDepth = 0;
    }

    /*
     * This is a special exit used as a template for the stack-slurping code.
     * LeaveTree will ignore all but the final slot, which contains the return
     * value. The slurpSlot variable keeps track of the last slot that has been
     * unboxed, as to avoid re-unboxing when taking a SLURP_FAIL exit.
     */
    unsigned numGlobalSlots = tree->globalSlots->length();
    unsigned safeSlots = NativeStackSlots(cx, frameDepth) + 1 + numGlobalSlots;
    jsbytecode* recursive_pc = return_pc + JSOP_CALL_LENGTH;
    VMSideExit* exit = (VMSideExit*)
        traceMonitor->traceAlloc->alloc(sizeof(VMSideExit) + sizeof(JSValueType) * safeSlots);
    PodZero(exit);
    exit->pc = (jsbytecode*)recursive_pc;
    exit->from = fragment;
    exit->exitType = RECURSIVE_SLURP_FAIL_EXIT;
    exit->numStackSlots = downPostSlots + 1;
    exit->numGlobalSlots = numGlobalSlots;
    exit->sp_adj = ((downPostSlots + 1) * sizeof(double)) - tree->nativeStackBase;
    exit->recursive_pc = recursive_pc;

    /*
     * Build the exit typemap. This may capture extra types, but they are
     * thrown away.
     */
    JSValueType* typeMap = exit->stackTypeMap();
    jsbytecode* oldpc = cx->regs->pc;
    cx->regs->pc = exit->pc;
    captureStackTypes(frameDepth, typeMap);
    cx->regs->pc = oldpc;
    if (!anchor || anchor->exitType != RECURSIVE_SLURP_FAIL_EXIT) {
        JS_ASSERT_IF(*cx->regs->pc != JSOP_RETURN, *cx->regs->pc == JSOP_STOP);
        if (*cx->regs->pc == JSOP_RETURN)
            typeMap[downPostSlots] = determineSlotType(&stackval(-1));
        else
            typeMap[downPostSlots] = JSVAL_TYPE_UNDEFINED;
    } else {
        typeMap[downPostSlots] = anchor->stackTypeMap()[anchor->numStackSlots - 1];
    }
    determineGlobalTypes(&typeMap[exit->numStackSlots]);
#if defined JS_JIT_SPEW
    TreevisLogExit(cx, exit);
#endif

    /*
     * Return values are tricky because there are two cases. Anchoring off a
     * slurp failure (the second case) means the return value has already been
     * moved. However it can still be promoted to link trees together, so we
     * load it from the new location.
     *
     * In all other cases, the return value lives in the tracker and it can be
     * grabbed safely.
     */
    LIns* rval_ins;
    intptr_t offset = exit->sp_adj - sizeof(double);
    JSValueType returnType = exit->stackTypeMap()[downPostSlots];

    if (!anchor || anchor->exitType != RECURSIVE_SLURP_FAIL_EXIT) {
        /*
         * It is safe to read cx->regs->pc here because the frame hasn't
         * been popped yet. We're guaranteed to have a return or stop.
         */
        JSOp op = JSOp(*cx->regs->pc);
        JS_ASSERT(op == JSOP_RETURN || op == JSOP_STOP);

        if (op == JSOP_RETURN) {
            rval_ins = get(&stackval(-1));
            if (returnType == JSVAL_TYPE_INT32) {
                JS_ASSERT(determineSlotType(&stackval(-1)) == JSVAL_TYPE_INT32);
                JS_ASSERT(isPromoteInt(rval_ins));
                rval_ins = demote(lir, rval_ins);
            }
        } else {
            rval_ins = INS_UNDEFINED();
        }

        /*
         * The return value must be written out early, before slurping can fail,
         * otherwise it will not be available when there's a type mismatch.
         */
        lir->insStore(rval_ins, lirbuf->sp, offset, ACCSET_STACK);
    } else {
        switch (returnType)
        {
          case JSVAL_TYPE_BOOLEAN:
          case JSVAL_TYPE_UNDEFINED:
          case JSVAL_TYPE_INT32:
            rval_ins = lir->insLoad(LIR_ldi, lirbuf->sp, offset, ACCSET_STACK);
            break;
          case JSVAL_TYPE_DOUBLE:
            rval_ins = lir->insLoad(LIR_ldd, lirbuf->sp, offset, ACCSET_STACK);
            break;
          case JSVAL_TYPE_FUNOBJ:
          case JSVAL_TYPE_NONFUNOBJ:
          case JSVAL_TYPE_STRING:
          case JSVAL_TYPE_NULL:
            rval_ins = lir->insLoad(LIR_ldp, lirbuf->sp, offset, ACCSET_STACK);
            break;
          default:
            JS_NOT_REACHED("unknown type");
            RETURN_STOP_A("unknown type");
        }
    }

    /* Slurp */
    SlurpInfo info;
    info.curSlot = 0;
    info.exit = exit;
    info.typeMap = typeMap;
    info.slurpFailSlot = (anchor && anchor->exitType == RECURSIVE_SLURP_FAIL_EXIT) ?
                         anchor->slurpFailSlot : 0;

    JSStackFrame *const fp = i.fp();

    /* callee */
    slurpSlot(argv_ins, -2 * ptrdiff_t(sizeof(Value)), &fp->argv[-2], &info);
    /* this */
    slurpSlot(argv_ins, -1 * ptrdiff_t(sizeof(Value)), &fp->argv[-1], &info);
    /* args[0..n] */
    for (unsigned i = 0; i < JS_MAX(fp->numActualArgs(), fp->numFormalArgs()); i++)
        slurpSlot(argv_ins, i * sizeof(Value), &fp->argv[i], &info);
    /* argsobj */
    slurpFrameObjPtrSlot(fp_ins, JSStackFrame::offsetArgsObj(), fp->addressArgsObj(), &info);
    /* scopeChain */
    slurpFrameObjPtrSlot(fp_ins, JSStackFrame::offsetScopeChain(), fp->addressScopeChain(), &info);
    /* vars */
    LIns* slots_ins = addName(lir->ins2(LIR_addp, fp_ins, INS_CONSTWORD(sizeof(JSStackFrame))),
                              "slots");
    for (unsigned i = 0; i < fp->getFixedCount(); i++)
        slurpSlot(slots_ins, i * sizeof(Value), &fp->slots()[i], &info);
    /* stack vals */
    unsigned nfixed = fp->getFixedCount();
    Value* stack = fp->base();
    LIns* stack_ins = addName(lir->ins2(LIR_addp,
                                        slots_ins,
                                        INS_CONSTWORD(nfixed * sizeof(Value))),
                              "stackBase");

    size_t limit = size_t(i.sp() - fp->base());
    if (anchor && anchor->exitType == RECURSIVE_SLURP_FAIL_EXIT)
        limit--;
    else
        limit -= fp->numFormalArgs() + 2;
    for (size_t i = 0; i < limit; i++)
        slurpSlot(stack_ins, i * sizeof(Value), &stack[i], &info);

    JS_ASSERT(info.curSlot == downPostSlots);

    /* Jump back to the start */
    exit = copy(exit);
    exit->exitType = UNSTABLE_LOOP_EXIT;
#if defined JS_JIT_SPEW
    TreevisLogExit(cx, exit);
#endif

    RecursiveSlotMap slotMap(*this, downPostSlots, rval_ins);
    for (unsigned i = 0; i < downPostSlots; i++)
        slotMap.addSlot(typeMap[i]);
    if (*cx->regs->pc == JSOP_RETURN)
        slotMap.addSlot(&stackval(-1), typeMap[downPostSlots]);
    else
        slotMap.addSlot(JSVAL_TYPE_UNDEFINED);
    VisitGlobalSlots(slotMap, cx, *tree->globalSlots);
    debug_only_print0(LC_TMTracer, "Compiling up-recursive slurp...\n");
    exit = copy(exit);
    if (exit->recursive_pc == fragment->root->ip)
        exit->exitType = UNSTABLE_LOOP_EXIT;
    else
        exit->exitType = RECURSIVE_UNLINKED_EXIT;
    debug_only_printf(LC_TMTreeVis, "TREEVIS CHANGEEXIT EXIT=%p TYPE=%s\n", (void*)exit,
                      getExitName(exit->exitType));
    JS_ASSERT(tree->recursion >= Recursion_Unwinds);
    return closeLoop(slotMap, exit);
}

class ImportFrameSlotsVisitor : public SlotVisitorBase
{
    TraceRecorder &mRecorder;
public:
    ImportFrameSlotsVisitor(TraceRecorder &recorder) : mRecorder(recorder)
    {}

    JS_REQUIRES_STACK JS_ALWAYS_INLINE bool
    visitStackSlots(Value *vp, size_t count, JSStackFrame* fp) {
        /* N.B. vp may point to a JSObject*. */
        for (size_t i = 0; i < count; ++i)
            mRecorder.get(vp++);
        return true;
    }

    JS_REQUIRES_STACK JS_ALWAYS_INLINE bool
    visitFrameObjPtr(JSObject **p, JSStackFrame* fp) {
        /* visitStackSlots only uses the address of its argument. */
        return visitStackSlots((Value *)p, 1, fp);
    }
};

JS_REQUIRES_STACK AbortableRecordingStatus
TraceRecorder::downRecursion()
{
    JSStackFrame* fp = cx->fp();
    JSScript *script = fp->getScript();
    if ((jsbytecode*)fragment->ip < script->code ||
        (jsbytecode*)fragment->ip >= script->code + script->length) {
        RETURN_STOP_A("inner recursive call must compile first");
    }

    /* Adjust the stack by the budget the down-frame needs. */
    int slots = NativeStackSlots(cx, 1) - NativeStackSlots(cx, 0);
    JS_ASSERT(unsigned(slots) ==
              NativeStackSlots(cx, 1) - fp->numActualArgs() - 2 - fp->getFixedCount() - 2);

    /* Guard that there is enough stack space. */
    JS_ASSERT(tree->maxNativeStackSlots >= tree->nativeStackBase / sizeof(double));
    int guardSlots = slots + tree->maxNativeStackSlots -
                     tree->nativeStackBase / sizeof(double);
    LIns* sp_top = lir->ins2(LIR_addp, lirbuf->sp, lir->insImmWord(guardSlots * sizeof(double)));
    guard(true, lir->ins2(LIR_ltp, sp_top, eos_ins), OOM_EXIT);

    /* Guard that there is enough call stack space. */
    LIns* rp_top = lir->ins2(LIR_addp, lirbuf->rp,
                             lir->insImmWord((tree->maxCallDepth + 1) * sizeof(FrameInfo*)));
    guard(true, lir->ins2(LIR_ltp, rp_top, eor_ins), OOM_EXIT);

    /*
     * For every slot in the new frame that is not in the tracker, create a load
     * in the tracker. This is necessary because otherwise snapshot() will see
     * missing imports and use the down frame, rather than the new frame.
     * This won't affect performance because the loads will be killed if not
     * used.
     */
    ImportFrameSlotsVisitor visitor(*this);
    VisitStackSlots(visitor, cx, callDepth);

    /* Add space for a new JIT frame. */
    lirbuf->sp = lir->ins2(LIR_addp, lirbuf->sp, lir->insImmWord(slots * sizeof(double)));
    lir->insStore(lirbuf->sp, lirbuf->state, offsetof(TracerState, sp), ACCSET_OTHER);
    lirbuf->rp = lir->ins2(LIR_addp, lirbuf->rp, lir->insImmWord(sizeof(FrameInfo*)));
    lir->insStore(lirbuf->rp, lirbuf->state, offsetof(TracerState, rp), ACCSET_OTHER);
    --callDepth;
    clearCurrentFrameSlotsFromTracker(nativeFrameTracker);

    /*
     * If the callee and caller have identical call sites, this is a down-
     * recursive loop. Otherwise something special happened. For example, a
     * recursive call that is unwinding could nest back down recursively again.
     * In this case, we build a fragment that ideally we'll never invoke
     * directly, but link from a down-recursive branch. The UNLINKED_EXIT tells
     * closeLoop() that the peer trees should match the recursive pc, not the
     * tree pc.
     */
    VMSideExit* exit;
    if ((jsbytecode*)fragment->root->ip == script->code)
        exit = snapshot(UNSTABLE_LOOP_EXIT);
    else
        exit = snapshot(RECURSIVE_UNLINKED_EXIT);
    exit->recursive_pc = script->code;
    debug_only_print0(LC_TMTracer, "Compiling down-recursive function call.\n");
    JS_ASSERT(tree->recursion != Recursion_Disallowed);
    tree->recursion = Recursion_Detected;
    return closeLoop(exit);
}

#if JS_BITS_PER_WORD == 32
JS_REQUIRES_STACK inline LIns*
TraceRecorder::slurpDoubleSlot(LIns* addr_ins, ptrdiff_t offset, VMSideExit* exit)
{
    LIns* tag_ins = lir->insLoad(LIR_ldi, addr_ins, offset + sTagOffset, ACCSET_OTHER);
    return unbox_number_as_double(addr_ins, offset, tag_ins, exit, ACCSET_OTHER);
}

JS_REQUIRES_STACK LIns*
TraceRecorder::slurpObjectSlot(LIns* addr_ins, ptrdiff_t offset, JSValueType type, VMSideExit* exit)
{
    LIns* tag_ins = lir->insLoad(LIR_ldi, addr_ins, offset + sTagOffset, ACCSET_OTHER);
    return unbox_object(addr_ins, offset, tag_ins, type, exit, ACCSET_OTHER);
}

JS_REQUIRES_STACK inline LIns*
TraceRecorder::slurpNonDoubleObjectSlot(LIns* addr_ins, ptrdiff_t offset, JSValueType type, VMSideExit* exit)
{
    LIns* tag_ins = lir->insLoad(LIR_ldi, addr_ins, offset + sTagOffset, ACCSET_OTHER);
    return unbox_non_double_object(addr_ins, offset, tag_ins, type, exit, ACCSET_OTHER);
}
#elif JS_BITS_PER_WORD == 64
JS_REQUIRES_STACK inline LIns*
TraceRecorder::slurpDoubleSlot(LIns* addr_ins, ptrdiff_t offset, VMSideExit* exit)
{
    LIns* v_ins = lir->insLoad(LIR_ldq, addr_ins, offset, ACCSET_OTHER);
    return unbox_number_as_double(v_ins, exit);
}

JS_REQUIRES_STACK LIns*
TraceRecorder::slurpObjectSlot(LIns* addr_ins, ptrdiff_t offset, JSValueType type, VMSideExit* exit)
{
    LIns* v_ins = lir->insLoad(LIR_ldq, addr_ins, offset, ACCSET_OTHER);
    return unbox_object(v_ins, type, exit);
}

JS_REQUIRES_STACK inline LIns*
TraceRecorder::slurpNonDoubleObjectSlot(LIns* addr_ins, ptrdiff_t offset, JSValueType type, VMSideExit* exit)
{
    LIns* v_ins = lir->insLoad(LIR_ldq, addr_ins, offset, ACCSET_OTHER);
    return unbox_non_double_object(v_ins, type, exit);
}
#endif

JS_REQUIRES_STACK inline LIns*
TraceRecorder::slurpSlot(LIns* addr_ins, ptrdiff_t offset, Value* vp, VMSideExit* exit)
{
    if (exit->slurpType == JSVAL_TYPE_DOUBLE)
        return slurpDoubleSlot(addr_ins, offset, exit);
    if (exit->slurpType == JSVAL_TYPE_FUNOBJ || exit->slurpType == JSVAL_TYPE_NONFUNOBJ)
        return slurpObjectSlot(addr_ins, offset, exit->slurpType, exit);
    JSValueType type = exit->slurpType;
    return slurpNonDoubleObjectSlot(addr_ins, offset, type, exit);
}

JS_REQUIRES_STACK void
TraceRecorder::slurpSlot(LIns* addr_ins, ptrdiff_t offset, Value* vp, SlurpInfo* info)
{
    /* Don't re-read slots that aren't needed. */
    if (info->curSlot < info->slurpFailSlot) {
        info->curSlot++;
        return;
    }
    VMSideExit* exit = copy(info->exit);
    exit->slurpFailSlot = info->curSlot;
    exit->slurpType = info->typeMap[info->curSlot];

    /* Make sure that we don't try and record infinity branches */
    JS_ASSERT_IF(anchor && anchor->exitType == RECURSIVE_SLURP_FAIL_EXIT &&
                 info->curSlot == info->slurpFailSlot,
                 anchor->slurpType != exit->slurpType);

    LIns* val = slurpSlot(addr_ins, offset, vp, exit);
    lir->insStore(val,
                  lirbuf->sp,
                  -tree->nativeStackBase + ptrdiff_t(info->curSlot) * sizeof(double),
                  ACCSET_STACK);
    info->curSlot++;
}

JS_REQUIRES_STACK void
TraceRecorder::slurpFrameObjPtrSlot(LIns* addr_ins, ptrdiff_t offset, JSObject** p, SlurpInfo* info)
{
    /* Don't re-read slots that aren't needed. */
    if (info->curSlot < info->slurpFailSlot) {
        info->curSlot++;
        return;
    }
    VMSideExit* exit = copy(info->exit);
    exit->slurpFailSlot = info->curSlot;
    exit->slurpType = info->typeMap[info->curSlot];

    /* Make sure that we don't try and record infinity branches */
    JS_ASSERT_IF(anchor && anchor->exitType == RECURSIVE_SLURP_FAIL_EXIT &&
                 info->curSlot == info->slurpFailSlot,
                 anchor->slurpType != exit->slurpType);

    LIns *val;
    LIns *ptr_val = lir->insLoad(LIR_ldp, addr_ins, offset, ACCSET_OTHER);
    LIns *ptr_is_null_ins = lir->insEqP_0(ptr_val);
    if (exit->slurpType == JSVAL_TYPE_NULL) {
        guard(true, ptr_is_null_ins, exit);
        val = INS_NULL();
    } else {
        JS_ASSERT(exit->slurpType == JSVAL_TYPE_NONFUNOBJ);
        guard(false, ptr_is_null_ins, exit);
        val = ptr_val;
    }

    lir->insStore(val,
                  lirbuf->sp,
                  -tree->nativeStackBase + ptrdiff_t(info->curSlot) * sizeof(double),
                  ACCSET_STACK);
    info->curSlot++;
}


text:
package org.wisdom.monitor.service;

/**
 * HealthCheck interface.
 * <p/>
 * It allows applications to register their own Heath Check.
 */
public interface HealthCheck {

    /**
     * @return The name of the check.
     */
    public String name();

    /**
     * @return the current state. {@literal false} denotes a broken state.
     * @throws Exception when a health check throw an exception, it denotes a broken state.
     */
    public boolean check() throws Exception;

}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CopyOnFirstWriteList (ebean 11.35.3 API)</title>
<meta name="date" content="2019-03-05">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

io.ebean.common

Class CopyOnFirstWriteList<E>

java.lang.Object

java.util.AbstractCollection<E>

java.util.AbstractList<E>

io.ebean.common.CopyOnFirstWriteList<E>

All Implemented Interfaces:

Serializable, Iterable<E>, Collection<E>, List<E>

public final class CopyOnFirstWriteList<E>
extends AbstractList<E>
implements List<E>, Serializable

List that copies itself on first write access. Needed to keep memory footprint low and the ability
to modify lists from cache.

Author:

Roland Praml, FOCONIS AG

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

CopyOnFirstWriteList(List<E> list)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
add(E e)

void
add(int index,
   E element)

boolean
addAll(Collection<? extends E> c)

boolean
addAll(int index,
      Collection<? extends E> c)

void
clear()

boolean
contains(Object o)

boolean
containsAll(Collection<?> c)

boolean
equals(Object o)

E
get(int index)

int
hashCode()

int
indexOf(Object o)

boolean
isEmpty()

int
lastIndexOf(Object o)

E
remove(int index)

boolean
remove(Object o)

boolean
removeAll(Collection<?> c)

boolean
removeIf(java.util.function.Predicate<? super E> filter)

void
replaceAll(java.util.function.UnaryOperator<E> operator)

boolean
retainAll(Collection<?> c)

E
set(int index,
   E element)

int
size()

void
sort(Comparator<? super E> c)

Object[]
toArray()

<T> T[]
toArray(T[] a)

Methods inherited from class java.util.AbstractList

iterator, listIterator, listIterator, subList

Methods inherited from class java.util.AbstractCollection

toString

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Methods inherited from interface java.util.List

iterator, listIterator, listIterator, spliterator, subList

Methods inherited from interface java.util.Collection

parallelStream, stream

Methods inherited from interface java.lang.Iterable

forEach

Constructor Detail

CopyOnFirstWriteList

public CopyOnFirstWriteList(List<E> list)

Method Detail

size

public int size()

Specified by:

size in interface Collection<E>

Specified by:

size in interface List<E>

Specified by:

size in class AbstractCollection<E>

isEmpty

public boolean isEmpty()

Specified by:

isEmpty in interface Collection<E>

Specified by:

isEmpty in interface List<E>

Overrides:

isEmpty in class AbstractCollection<E>

contains

public boolean contains(Object o)

Specified by:

contains in interface Collection<E>

Specified by:

contains in interface List<E>

Overrides:

contains in class AbstractCollection<E>

toArray

public Object[] toArray()

Specified by:

toArray in interface Collection<E>

Specified by:

toArray in interface List<E>

Overrides:

toArray in class AbstractCollection<E>

toArray

public <T> T[] toArray(T[] a)

Specified by:

toArray in interface Collection<E>

Specified by:

toArray in interface List<E>

Overrides:

toArray in class AbstractCollection<E>

add

public boolean add(E e)

Specified by:

add in interface Collection<E>

Specified by:

add in interface List<E>

Overrides:

add in class AbstractList<E>

remove

public boolean remove(Object o)

Specified by:

remove in interface Collection<E>

Specified by:

remove in interface List<E>

Overrides:

remove in class AbstractCollection<E>

containsAll

public boolean containsAll(Collection<?> c)

Specified by:

containsAll in interface Collection<E>

Specified by:

containsAll in interface List<E>

Overrides:

containsAll in class AbstractCollection<E>

addAll

public boolean addAll(Collection<? extends E> c)

Specified by:

addAll in interface Collection<E>

Specified by:

addAll in interface List<E>

Overrides:

addAll in class AbstractCollection<E>

addAll

public boolean addAll(int index,
                      Collection<? extends E> c)

Specified by:

addAll in interface List<E>

Overrides:

addAll in class AbstractList<E>

removeAll

public boolean removeAll(Collection<?> c)

Specified by:

removeAll in interface Collection<E>

Specified by:

removeAll in interface List<E>

Overrides:

removeAll in class AbstractCollection<E>

retainAll

public boolean retainAll(Collection<?> c)

Specified by:

retainAll in interface Collection<E>

Specified by:

retainAll in interface List<E>

Overrides:

retainAll in class AbstractCollection<E>

replaceAll

public void replaceAll(java.util.function.UnaryOperator<E> operator)

Specified by:

replaceAll in interface List<E>

removeIf

public boolean removeIf(java.util.function.Predicate<? super E> filter)

Specified by:

removeIf in interface Collection<E>

sort

public void sort(Comparator<? super E> c)

Specified by:

sort in interface List<E>

clear

public void clear()

Specified by:

clear in interface Collection<E>

Specified by:

clear in interface List<E>

Overrides:

clear in class AbstractList<E>

equals

public boolean equals(Object o)

Specified by:

equals in interface Collection<E>

Specified by:

equals in interface List<E>

Overrides:

equals in class AbstractList<E>

hashCode

public int hashCode()

Specified by:

hashCode in interface Collection<E>

Specified by:

hashCode in interface List<E>

Overrides:

hashCode in class AbstractList<E>

get

public E get(int index)

Specified by:

get in interface List<E>

Specified by:

get in class AbstractList<E>

set

public E set(int index,
             E element)

Specified by:

set in interface List<E>

Overrides:

set in class AbstractList<E>

add

public void add(int index,
                E element)

Specified by:

add in interface List<E>

Overrides:

add in class AbstractList<E>

remove

public E remove(int index)

Specified by:

remove in interface List<E>

Overrides:

remove in class AbstractList<E>

indexOf

public int indexOf(Object o)

Specified by:

indexOf in interface List<E>

Overrides:

indexOf in class AbstractList<E>

lastIndexOf

public int lastIndexOf(Object o)

Specified by:

lastIndexOf in interface List<E>

Overrides:

lastIndexOf in class AbstractList<E>

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2019. All rights reserved.


text:
@interface FFWeekHeaderCell : UICollectionViewCell

@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) NSDate *date;

- (void)cleanCell;

@end


text:
package com.webcohesion.ofx4j.domain.data.signup;

import com.webcohesion.ofx4j.domain.data.TransactionWrappedRequestMessage;
import com.webcohesion.ofx4j.meta.ChildAggregate;
import com.webcohesion.ofx4j.meta.Aggregate;

/**
 * @author Ryan Heaton
 */
@Aggregate ( "ACCTINFOTRNRQ" )
public class AccountInfoRequestTransaction extends TransactionWrappedRequestMessage<AccountInfoRequest> {

  private AccountInfoRequest message;

  /**
   * The wrapped message.
   *
   * @return The wrapped message.
   */
  @ChildAggregate ( required = true, order = 30 )
  public AccountInfoRequest getMessage() {
    return message;
  }

  /**
   * The wrapped message.
   *
   * @param message The wrapped message.
   */
  public void setMessage(AccountInfoRequest message) {
    this.message = message;
  }

  // Inherited.
  public void setWrappedMessage(AccountInfoRequest message) {
    setMessage(message);
  }
}


text:
from network import PolicyNetwork
import numpy as np
import os
from players import PolicyPlayer, RandomPlayer
from position import Position
import tensorflow as tf
import util

flags = tf.app.flags
flags.DEFINE_string('run_dir', 'latest', 'Run directory')
flags.DEFINE_string('exploratory_network', 'policy',
                    'Name of exploratory player')
flags.DEFINE_string('playout_network', 'policy', 'Name of playout player')
flags.DEFINE_float('exploratory_temperature', 20.0,
                   'Softmax temperature in exploratory network')
flags.DEFINE_float('playout_temperature', 1.0,
                   'Softmax temperature in playout network')
flags.DEFINE_integer('max_sample_move', 30, '')
flags.DEFINE_integer('num_games', 100000, 'Number of games per sample move')
flags.DEFINE_integer('max_random_moves', 10,
                     'Max random moves before exploratory player')
config = flags.FLAGS

class PositionGenerator(object):
  def __init__(self, config):
    self.config = config

    session = tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(
        allow_growth=True)))
    self.random_player = RandomPlayer()
    self.exploratory_network = PolicyNetwork(config.exploratory_network)
    self.exploratory_player = PolicyPlayer(self.exploratory_network, session)

    self.playout_network = PolicyNetwork(
        config.playout_network,
        reuse=config.exploratory_network == config.playout_network)
    self.playout_player = PolicyPlayer(self.playout_network, session)

    self.run_dir = util.run_directory(config)
    util.restore_network_or_fail(session, self.run_dir,
                                 self.exploratory_network)
    util.restore_network_or_fail(session, self.run_dir, self.playout_network)

  def generate_positions(self):
    with open(os.path.join(self.run_dir, 'rollout_positions.txt'), 'w') as f:
      for sample_move in range(3, self.config.max_sample_move):
        print('Generating rollouts after %d exploratory moves' % sample_move)
        examples = self.play_games(config.num_games, sample_move)
        for position, sample_move, num_moves, result in examples:
          f.write('%r %d %d %d\n' % (position, sample_move, num_moves, result))

  def play_games(self, num_games, sample_move):
    # Create games
    games = [Game() for _ in range(num_games)]

    # Initialize with random setup
    random_moves = min(self.config.max_random_moves, sample_move - 1)
    for _ in range(random_moves):
      self.play_move(games, self.random_player)

    # Play exploratory moves
    random_setup_games = games
    for _ in range(random_moves, sample_move - 1):
      self.play_move(games, self.exploratory_player)

    # Remove finished games
    games = [game for game in games if not game.position.gameover()]

    # Play random move
    self.play_move(games, self.random_player)
    # Save positions
    sample_positions = [game.position for game in games]

    # Playout game
    incomplete_games = games
    while incomplete_games:
      self.play_move(incomplete_games, self.playout_player)
      incomplete_games = [
          game for game in incomplete_games if not game.position.gameover()
      ]

    results = [game.result for game in games]
    sample_moves = [
        np.count_nonzero(position.disks) for position in sample_positions
    ]
    num_moves = [game.num_moves for game in games]
    position_results = list(
        zip(sample_positions, sample_moves, num_moves, results))

    if len(position_results) < num_games:
      return position_results + self.play_games(
          num_games - len(position_results), sample_move)
    else:
      return position_results

  def play_move(self, games, player):
    positions = [game.position for game in games]
    moves = player.play(positions)

    for game, move in zip(games, moves):
      game.move(move)

class Game(object):
  def __init__(self):
    self.position = Position()
    self.num_moves = 0
    self.result = None

  def move(self, move):
    if not self.position.gameover():
      self.position = self.position.move(move)
      self.num_moves += 1

      if self.position.gameover():
        self.result = self.position.result

def main(_):
  position_generator = PositionGenerator(config)
  position_generator.generate_positions()

if __name__ == '__main__':
  tf.app.run()


text:
package com.intel.icecp.core.messages;

import com.intel.icecp.core.Message;
import java.util.HashMap;

/**
 *
 */
public class ConfigurationMessage extends HashMap<String, Object> implements Message {

}


text:
'use strict';

const ReactRelayContext = require('./ReactRelayContext');
const ReactRelayFragmentContainer = require('./ReactRelayFragmentContainer');
const ReactRelayLocalQueryRenderer = require('./ReactRelayLocalQueryRenderer');
const ReactRelayPaginationContainer = require('./ReactRelayPaginationContainer');
const ReactRelayQueryRenderer = require('./ReactRelayQueryRenderer');
const ReactRelayRefetchContainer = require('./ReactRelayRefetchContainer');
const EntryPointContainer = require('./relay-hooks/EntryPointContainer.react');
const loadEntryPoint = require('./relay-hooks/loadEntryPoint');
const {loadQuery} = require('./relay-hooks/loadQuery');
const RelayEnvironmentProvider = require('./relay-hooks/RelayEnvironmentProvider');
const useClientQuery = require('./relay-hooks/useClientQuery');
const useEntryPointLoader = require('./relay-hooks/useEntryPointLoader');
const useFragment = require('./relay-hooks/useFragment');
const useLazyLoadQuery = require('./relay-hooks/useLazyLoadQuery');
const useMutation = require('./relay-hooks/useMutation');
const usePaginationFragment = require('./relay-hooks/usePaginationFragment');
const usePreloadedQuery = require('./relay-hooks/usePreloadedQuery');
const useQueryLoader = require('./relay-hooks/useQueryLoader');
const useRefetchableFragment = require('./relay-hooks/useRefetchableFragment');
const useRelayEnvironment = require('./relay-hooks/useRelayEnvironment');
const useSubscribeToInvalidationState = require('./relay-hooks/useSubscribeToInvalidationState');
const useSubscription = require('./relay-hooks/useSubscription');
const RelayRuntime = require('relay-runtime');
const ProfilerContext = require('./relay-hooks/ProfilerContext');

export type {
  $FragmentRef,
  $RelayProps,
  RelayFragmentContainer,
  RelayPaginationContainer,
  RelayPaginationProp,
  RelayProp,
  RelayRefetchContainer,
  RelayRefetchProp,
} from './ReactRelayTypes';
export type * from './relay-hooks/EntryPointTypes.flow';
export type {
  MatchContainerProps,
  MatchPointer,
} from './relay-hooks/MatchContainer';
export type {ProfilerContextType} from './relay-hooks/ProfilerContext';
export type {LoadMoreFn} from './relay-hooks/useLoadMoreFunction';
export type {UseMutationConfig} from './relay-hooks/useMutation';
export type {UseQueryLoaderLoadQueryOptions} from './relay-hooks/useQueryLoader';
export type {
  RefetchFn,
  RefetchFnDynamic,
  Options as RefetchOptions,
} from './relay-hooks/useRefetchableFragmentNode';
export type {
  DataID,
  DeclarativeMutationConfig,
  Direction,
  Disposable,
  // RelayRuntime has two environment exports: one interface, one concrete.
  IEnvironment as Environment,
  GraphQLTaggedNode,
  MutationType,
  NormalizationSelector,
  OperationDescriptor,
  RangeOperation,
  ReaderSelector,
  RelayContext,
  Snapshot,
  Variables,
  FetchPolicy,
} from 'relay-runtime';

/**
 * The public interface to react-relay.
 * Currently contains both Relay Hooks and legacy Container APIs.
 * Will eventually only export the interface from ./hooks.js.
 */
module.exports = {
  ConnectionHandler: RelayRuntime.ConnectionHandler,
  QueryRenderer: ReactRelayQueryRenderer,
  LocalQueryRenderer: ReactRelayLocalQueryRenderer,

  MutationTypes: RelayRuntime.MutationTypes,
  RangeOperations: RelayRuntime.RangeOperations,

  ReactRelayContext,

  applyOptimisticMutation: RelayRuntime.applyOptimisticMutation,
  commitLocalUpdate: RelayRuntime.commitLocalUpdate,
  commitMutation: RelayRuntime.commitMutation,
  createFragmentContainer: ReactRelayFragmentContainer.createContainer,
  createPaginationContainer: ReactRelayPaginationContainer.createContainer,
  createRefetchContainer: ReactRelayRefetchContainer.createContainer,
  fetchQuery_DEPRECATED: RelayRuntime.fetchQuery_DEPRECATED,
  graphql: RelayRuntime.graphql,
  readInlineData: RelayRuntime.readInlineData,
  requestSubscription: RelayRuntime.requestSubscription,

  // Relay Hooks
  EntryPointContainer: EntryPointContainer,
  RelayEnvironmentProvider: RelayEnvironmentProvider,

  ProfilerContext: ProfilerContext,

  fetchQuery: RelayRuntime.fetchQuery,

  loadQuery: loadQuery,
  loadEntryPoint: loadEntryPoint,

  useClientQuery: useClientQuery,
  useFragment: useFragment,
  useLazyLoadQuery: useLazyLoadQuery,
  useEntryPointLoader: useEntryPointLoader,
  useQueryLoader: useQueryLoader,
  useMutation: useMutation,
  usePaginationFragment: usePaginationFragment,
  usePreloadedQuery: usePreloadedQuery,
  useRefetchableFragment: useRefetchableFragment,
  useRelayEnvironment: useRelayEnvironment,
  useSubscribeToInvalidationState: useSubscribeToInvalidationState,
  useSubscription: useSubscription,
};


text:
<?php

namespace Zend\Rest\Client;

/**
 * Zend_Rest_Server_Exception
 *
 * @uses       \Zend\Rest\Exception
 * @package    Zend_Rest
 * @subpackage Client
 * @copyright  Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
interface Exception extends \Zend\Rest\Exception
{}


text:
package org.optaplanner.core.impl.localsearch.decider.acceptor.tabu;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.optaplanner.core.api.score.buildin.simple.SimpleScore;
import org.optaplanner.core.impl.heuristic.move.Move;
import org.optaplanner.core.impl.localsearch.decider.acceptor.tabu.size.FixedTabuSizeStrategy;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchMoveScope;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchPhaseScope;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchStepScope;
import org.optaplanner.core.impl.solver.scope.DefaultSolverScope;
import org.optaplanner.core.impl.testdata.domain.TestdataEntity;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class EntityTabuAcceptorTest {

    @Test
    public void tabuSize() {
        EntityTabuAcceptor acceptor = new EntityTabuAcceptor();
        acceptor.setTabuSizeStrategy(new FixedTabuSizeStrategy(2));
        acceptor.setAspirationEnabled(true);

        TestdataEntity e0 = new TestdataEntity("e0");
        TestdataEntity e1 = new TestdataEntity("e1");
        TestdataEntity e2 = new TestdataEntity("e2");
        TestdataEntity e3 = new TestdataEntity("e3");
        TestdataEntity e4 = new TestdataEntity("e4");

        DefaultSolverScope solverScope = new DefaultSolverScope();
        solverScope.setBestScore(SimpleScore.valueOf(0));
        LocalSearchPhaseScope phaseScope = new LocalSearchPhaseScope(solverScope);
        acceptor.phaseStarted(phaseScope);

        LocalSearchStepScope stepScope0 = new LocalSearchStepScope(phaseScope);
        LocalSearchMoveScope moveScope1 = buildMoveScope(stepScope0, e1);
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e0)));
        assertEquals(true, acceptor.isAccepted(moveScope1));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e2)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e3)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e4)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e2))); // repeated call
        stepScope0.setStep(moveScope1.getMove());
        acceptor.stepEnded(stepScope0);
        phaseScope.setLastCompletedStepScope(stepScope0);

        LocalSearchStepScope stepScope1 = new LocalSearchStepScope(phaseScope);
        LocalSearchMoveScope moveScope2 = buildMoveScope(stepScope1, e2);
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e0)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e1)));
        assertEquals(true, acceptor.isAccepted(moveScope2));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e3)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e4)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e2))); // repeated call
        stepScope1.setStep(moveScope2.getMove());
        acceptor.stepEnded(stepScope1);
        phaseScope.setLastCompletedStepScope(stepScope1);

        LocalSearchStepScope stepScope2 = new LocalSearchStepScope(phaseScope);
        LocalSearchMoveScope moveScope4 = buildMoveScope(stepScope2, e4);
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, e0)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e1)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e2)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, e3)));
        assertEquals(true, acceptor.isAccepted(moveScope4));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e2))); // repeated call
        stepScope2.setStep(moveScope4.getMove());
        acceptor.stepEnded(stepScope2);
        phaseScope.setLastCompletedStepScope(stepScope2);

        LocalSearchStepScope stepScope3 = new LocalSearchStepScope(phaseScope);
        LocalSearchMoveScope moveScope3 = buildMoveScope(stepScope3, e3);
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, e0)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, e1)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e2)));
        assertEquals(true, acceptor.isAccepted(moveScope3));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e2))); // repeated call
        stepScope3.setStep(moveScope3.getMove());
        acceptor.stepEnded(stepScope3);
        phaseScope.setLastCompletedStepScope(stepScope3);

        LocalSearchStepScope stepScope4 = new LocalSearchStepScope(phaseScope);
        LocalSearchMoveScope moveScope1Again = buildMoveScope(stepScope4, e1);
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope4, e0)));
        assertEquals(true, acceptor.isAccepted(moveScope1Again));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope4, e2)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope4, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope4, e4)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope4, e2))); // repeated call
        stepScope4.setStep(moveScope1Again.getMove());
        acceptor.stepEnded(stepScope4);
        phaseScope.setLastCompletedStepScope(stepScope4);

        acceptor.phaseEnded(phaseScope);
    }

    @Test
    public void tabuSizeMultipleEntitiesPerStep() {
        EntityTabuAcceptor acceptor = new EntityTabuAcceptor();
        acceptor.setTabuSizeStrategy(new FixedTabuSizeStrategy(2));
        acceptor.setAspirationEnabled(true);

        TestdataEntity e0 = new TestdataEntity("e0");
        TestdataEntity e1 = new TestdataEntity("e1");
        TestdataEntity e2 = new TestdataEntity("e2");
        TestdataEntity e3 = new TestdataEntity("e3");
        TestdataEntity e4 = new TestdataEntity("e4");

        DefaultSolverScope solverScope = new DefaultSolverScope();
        solverScope.setBestScore(SimpleScore.valueOf(0));
        LocalSearchPhaseScope phaseScope = new LocalSearchPhaseScope(solverScope);
        acceptor.phaseStarted(phaseScope);

        LocalSearchStepScope stepScope0 = new LocalSearchStepScope(phaseScope);
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e0)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e1)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e2)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e3)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e4)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e0, e1)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e0, e2)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e0, e3)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e0, e4)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e1, e2)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e1, e3)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e1, e4)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e2, e3)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e2, e4)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope0, e3, e4)));
        stepScope0.setStep(buildMoveScope(stepScope0, e0, e2).getMove());
        acceptor.stepEnded(stepScope0);
        phaseScope.setLastCompletedStepScope(stepScope0);

        LocalSearchStepScope stepScope1 = new LocalSearchStepScope(phaseScope);
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e0)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e1)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e2)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e3)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e0, e1)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e0, e2)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e0, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e0, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e1, e2)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e1, e3)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e1, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e2, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, e2, e4)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, e3, e4)));
        stepScope1.setStep(buildMoveScope(stepScope1, e1).getMove());
        acceptor.stepEnded(stepScope1);
        phaseScope.setLastCompletedStepScope(stepScope1);

        LocalSearchStepScope stepScope2 = new LocalSearchStepScope(phaseScope);
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e0)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e1)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e2)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, e3)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e0, e1)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e0, e2)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e0, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e0, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e1, e2)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e1, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e1, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e2, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope2, e2, e4)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope2, e3, e4)));
        stepScope2.setStep(buildMoveScope(stepScope2, e3, e4).getMove());
        acceptor.stepEnded(stepScope2);
        phaseScope.setLastCompletedStepScope(stepScope2);

        LocalSearchStepScope stepScope3 = new LocalSearchStepScope(phaseScope);
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, e0)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e1)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, e2)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e0, e1)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope3, e0, e2)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e0, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e0, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e1, e2)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e1, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e1, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e2, e3)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e2, e4)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope3, e3, e4)));
        stepScope3.setStep(buildMoveScope(stepScope3, e0).getMove());
        acceptor.stepEnded(stepScope3);
        phaseScope.setLastCompletedStepScope(stepScope3);

        acceptor.phaseEnded(phaseScope);
    }

    @Test
    public void aspiration() {
        EntityTabuAcceptor acceptor = new EntityTabuAcceptor();
        acceptor.setTabuSizeStrategy(new FixedTabuSizeStrategy(2));
        acceptor.setAspirationEnabled(true);

        TestdataEntity e0 = new TestdataEntity("e0");
        TestdataEntity e1 = new TestdataEntity("e1");

        DefaultSolverScope solverScope = new DefaultSolverScope();
        solverScope.setBestScore(SimpleScore.valueOf(-100));
        LocalSearchPhaseScope phaseScope = new LocalSearchPhaseScope(solverScope);
        acceptor.phaseStarted(phaseScope);

        LocalSearchStepScope stepScope0 = new LocalSearchStepScope(phaseScope);
        stepScope0.setStep(buildMoveScope(stepScope0, e1).getMove());
        acceptor.stepEnded(stepScope0);
        phaseScope.setLastCompletedStepScope(stepScope0);

        LocalSearchStepScope stepScope1 = new LocalSearchStepScope(phaseScope);
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, -120, e0)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, -20, e0)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, -120, e1)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, -20, e1)));
        assertEquals(false, acceptor.isAccepted(buildMoveScope(stepScope1, -120, e0, e1)));
        assertEquals(true, acceptor.isAccepted(buildMoveScope(stepScope1, -20, e0, e1)));
        stepScope1.setStep(buildMoveScope(stepScope1, -20, e1).getMove());
        acceptor.stepEnded(stepScope1);
        phaseScope.setLastCompletedStepScope(stepScope1);

        acceptor.phaseEnded(phaseScope);
    }

    private LocalSearchMoveScope buildMoveScope(LocalSearchStepScope stepScope, TestdataEntity... entities) {
        return buildMoveScope(stepScope, 0, entities);
    }

    private LocalSearchMoveScope buildMoveScope(LocalSearchStepScope stepScope, int score, TestdataEntity... entities) {
        LocalSearchMoveScope moveScope = new LocalSearchMoveScope(stepScope);
        Move move = mock(Move.class);
        when(move.getPlanningEntities()).thenReturn((Collection) Arrays.asList(entities));
        moveScope.setMove(move);
        moveScope.setScore(SimpleScore.valueOf(score));
        return moveScope;
    }

}


text:
@interface WXDetailCell ()

@property (weak, nonatomic) IBOutlet UIImageView *detailImage;

@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

@property (weak, nonatomic) IBOutlet UILabel *ratinLabel;

@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@end

@implementation WXDetailCell

- (void)awakeFromNib {
    // Initialization code
}

- (void)setDetails:(WXDetail *)details {
    _details = details;

    [self.detailImage sd_setImageWithURL:[NSURL URLWithString:details.userImage] placeholderImage:[UIImage imageNamed:@"msg_new"]];
    self.detailImage.layer.cornerRadius = self.detailImage.width * 0.5;
    self.detailImage.layer.masksToBounds = YES;
    self.nameLabel.text = details.nickname;
    self.ratinLabel.text = [NSString stringWithFormat:@"%.1f", details.rating];
    self.contentLabel.text = details.content;

}

@end


text:
package greendroid.widget.item;
import com.cyrilmottier.android.greendroid.R;
import greendroid.widget.itemview.ItemView;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.ListView;

/**
 * Acts as a separator between important {@link ListView} sections. A separator
 * display a text on a single line.
 *
 * @author Cyril Mottier
 */
public class SeparatorItem extends TextItem {

    /**
     * @hide
     */
    public SeparatorItem() {
        this(null);
    }

    /**
     * Constructs a SeparatorItem made of the given text
     *
     * @param text The text for this SeparatorItem
     */
    public SeparatorItem(String text) {
        super(text);
        enabled = false;
    }

    @Override
    public ItemView newView(Context context, ViewGroup parent) {
        return createCellFromXml(context, R.layout.gd_separator_item_view, parent);
    }

}


text:
import pygame, math

ais={}

def register_ai(name):
	def _internal(cls):
		ais[name]=cls
		cls.name=name
		return cls
	return _internal

@register_ai("empty")
class AI(object):
	def update(self, dt):
		pass

def get_angle(x1, x2, y1, y2):
	delta_angle=math.degrees(math.atan2(y2-y1, -(x2-x1)))+90
	return delta_angle

def get_rel_angle(delta_angle, self_angle):
	return math.degrees(math.atan2(
			math.sin(math.radians(delta_angle)-math.radians(self_angle)),
			math.cos(math.radians(delta_angle)-math.radians(self_angle))
		))

@register_ai("projectile_ai")
class ProjectileAI(AI):
	def __init__(self):
		self.create_time=pygame.time.get_ticks()
	def update(self, dt):
		self.ship.accel_direction=1
		self.ship.turn_direction=0
		if pygame.time.get_ticks()-self.create_time>self.ship.type.raw.get("lifetime", 5000):
			self.ship.marked_for_death=True

		for ship in game.client.owned_entities.values():
			if ship.faction!=self.ship.faction and ship is not self.ship:
				# print(ship.rect, self.ship.rect)
				if ship.rect.colliderect(self.ship.rect) and not ship.type.raw.get("is_projectile"):
					self.ship.marked_for_death=True
					ship.take_damage(self.ship.type.raw.get("damage", 10))

		if self.ship.target:
			if self.ship.type.max_rot_speed>0 and not self.ship.target.marked_for_death:
				angle=get_rel_angle(get_angle(self.ship.rect.centerx, self.ship.target.rect.centerx,
					self.ship.rect.centery, self.ship.target.rect.centery), self.ship.angle)
				if abs(angle)>10:
					if angle>0:
						self.ship.turn_direction=1
					else:
						self.ship.turn_direction=-1

@register_ai("hostile_ai")
class HostileAI(AI):
	def update(self, dt):
		if self.ship.target:
			if self.ship.type.max_rot_speed>0 and not self.ship.target.marked_for_death:
				angle=get_rel_angle(get_angle(self.ship.rect.centerx, self.ship.target.rect.centerx,
					self.ship.rect.centery, self.ship.target.rect.centery), self.ship.angle)
				if abs(angle)>5:
					self.ship.accel_direction=0
					if angle>0:
						self.ship.turn_direction=1
					else:
						self.ship.turn_direction=-1
				else:
					self.ship.turn_direction=0
					self.ship.accel_direction=1
					self.ship.fire_selected()

		min_dist=-1
		min_ship=self.ship.target
		for e in game.client.owned_entities.values():
			if e.faction!=self.ship.faction:
				dist=math.sqrt((self.ship.rect.centerx-e.rect.centerx)**2+(self.ship.rect.centery-e.rect.centery)**2)
				if dist<min_dist or min_dist==-1:
					min_dist=dist
					min_ship=e
		for e in game.client.remote_entities.values():
			if e.faction!=self.ship.faction:
				dist=math.sqrt((self.ship.rect.centerx-e.rect.centerx)**2+(self.ship.rect.centery-e.rect.centery)**2)
				if dist<min_dist or min_dist==-1:
					min_dist=dist
					min_ship=e
		self.ship.target=min_ship
		print(self.ship.target)

import game


text:
package fsnotify

import "golang.org/x/sys/unix"

const openMode = unix.O_NONBLOCK | unix.O_RDONLY


text:
\begin{figure}[H]
\centering
\includegraphics[width=6in]{figs/run_61/run_61_T_vs_r_mesh_ctkescatter}
\caption{Scatter plot of azimuthal velocity vs radius, turbulent kinetic energy, at $z/c$=10.00, $V_{free}$=15.31, station 7.}
\label{fig:run_61_T_vs_r_mesh_ctkescatter}
\end{figure}