text:
<?php
namespace Timeline;

class Site_Util
{
	public static function get_accept_timeline_foreign_tables()
	{
		return array(
			'member',
			'note',
			'album_image',
			'album',
			'file',
			'thread',
		);
	}

	public static function get_type4key($type_key = null)
	{
		if (!$type_key) $type_key = 'normal';
		if (!$type = \Config::get('timeline.types.'.$type_key))
		{
			throw new \InvalidArgumentException('first parameter is invalid.');
		}

		return $type;
	}

	public static function get_key4type($target_type = null)
	{
		$types = conf('types', 'timeline');
		foreach ($types as $key => $type)
		{
			if ($type == $target_type) return $key;
		}

		throw new \InvalidArgumentException('first parameter is invalid.');
	}

	public static function check_type($target_type, $type_key)
	{
		return $target_type == self::get_type4key($type_key);
	}

	public static function check_type_enabled($type_key)
	{
		if (!$disabled_types = conf('disabledTypes', 'timeline')) return true;

		if (is_numeric($type_key)) $type_key = static::get_key4type($type_key);

		return ! in_array($type_key, $disabled_types);
	}

	public static function get_timeline_save_values($type_key = null)
	{
		$type = self::get_type4key($type_key);
		$foreign_table = null;
		$child_foreign_table = null;
		switch ($type_key)
		{
			case 'member_register':
				$foreign_table = 'member';
				break;
			case 'member_name':
				$foreign_table = 'member';
				break;
			case 'profile_image':
				$foreign_table = 'file';
				break;
			case 'note':
				$foreign_table = 'note';
				break;
			case 'thread':
				$foreign_table = 'thread';
				break;
			case 'album':
				$foreign_table = 'album';
				$child_foreign_table = 'album_image';
				break;
			case 'album_image':
				$foreign_table = 'album';
				$child_foreign_table = 'album_image';
				break;
			case 'album_image_profile':
				$foreign_table = 'album_image';
				break;
			case 'album_image_timeline':
				$foreign_table = 'album';
				$child_foreign_table = 'album_image';
				break;
		}

		return array($type, $foreign_table, $child_foreign_table);
	}

	public static function get_namespace4foreign_table($foreign_table)
	{
		switch ($foreign_table)
		{
			case 'note':
				return 'Note';
			case 'album':
			case 'album_image':
				return 'Album';
			case 'member':
			case 'file':
				return '';
		}

		throw new \InvalidArgumentException('first parameter is invalid.');;
	}

	public static function get_timeline_content($timeline_id, $type, $body = null, $foreign_table_obj = null, array $optional_info = null, $is_detail = false, $is_strip_tags = false)
	{
		switch ($type)
		{
			case \Config::get('timeline.types.normal'):// 通常 timeline 投稿(つぶやき)
			case \Config::get('timeline.types.album_image_timeline'):
			case \Config::get('timeline.types.member_name'):
				$return_body = self::get_normal_timeline_body($body, $type, $timeline_id,
					isset($optional_info['count']) ? $optional_info['count'] : 0, $is_detail);
				return $is_strip_tags ? \Security::strip_tags($return_body) : $return_body;

			case \Config::get('timeline.types.member_register'):// SNS への参加
				return __('message_join_complete_for', array('label' => FBD_SITE_NAME));

			case \Config::get('timeline.types.profile_image'):// profile 写真投稿
			case \Config::get('timeline.types.album_image_profile'):// profile 写真投稿(album_image)
				return __('message_set_complete_for', array('label' => term('profile', 'site.picture')));

			case \Config::get('timeline.types.note'):// note 投稿
				return __('message_post_for', array('label' => t('note.view')));

			case \Config::get('timeline.types.thread'):// thread 投稿
				return __('message_post_for', array('label' => t('thread.view')));

			case \Config::get('timeline.types.album'):// album 作成
				return __('message_post_for', array('label' => t('album.view')));

			case \Config::get('timeline.types.album_image'):// album_image 投稿
				$return_body = $foreign_table_obj ? render('timeline::_parts/body_for_add_album_image', array(
					'album_id' => $foreign_table_obj->id,
					'name' => $foreign_table_obj->name,
					'count' => isset($optional_info['count']) ? $optional_info['count'] : 0,
				)) : null;
				return $is_strip_tags ? \Security::strip_tags($return_body) : $return_body;

			//case \Config::get('timeline.types.member_name'):// ニックネーム変更
			//	break;
		}

		return null;
	}

	public static function get_timeline_ogp_contents($type, $body = '', $is_return_title_only = false)
	{
		switch ($type)
		{
			case \Config::get('timeline.types.member_register'):// SNS への参加
				$title = __('message_join_complete_for', array('label' => FBD_SITE_NAME));

			case \Config::get('timeline.types.profile_image'):// profile 写真投稿
			case \Config::get('timeline.types.album_image_profile'):// profile 写真投稿(album_image)
				$title = __('message_set_complete_for', array('label' => term('profile', 'site.picture')));

			case \Config::get('timeline.types.note'):// note 投稿
				$title = __('message_post_for', array('label' => t('note.view')));

			case \Config::get('timeline.types.thread'):// thread 投稿
				$title = __('message_post_for', array('label' => t('thread.view')));

			case \Config::get('timeline.types.album'):// album 作成
				$title = __('message_post_for', array('label' => t('album.view')));

			case \Config::get('timeline.types.album_image'):// album_image 投稿
				$title = __('message_post_for', array('label' => t('album.view')));

			case \Config::get('timeline.types.normal'):// 通常 timeline 投稿(つぶやき)
			case \Config::get('timeline.types.album_image_timeline'):
			case \Config::get('timeline.types.member_name'):
			default :
				$title = __('message_post_to', array('object' => t('timeline.view')));
		}
		if ($is_return_title_only) return $title;

		return array($title, FBD_SITE_DESCRIPTION);
	}

	public static function get_timeline_ogp_image_uri($type, $foreign_id, $timeline_id = null, $is_raw_size = false)
	{
		$images = static::get_timeline_images(
			$type,
			$foreign_id,
			$timeline_id
		);
		if (empty($images['list'])) return '';

		$file_cate = !empty($images['file_cate']) ? $images['file_cate'] : 'ai';
		$file_size = ($is_raw_size || empty($images['size'])) ? 'raw' : $images['size'];

		return \Site_Util::get_image_uri4image_list($images['list'], $file_cate, $file_size);
	}

	public static function get_normal_timeline_body($body, $type, $timeline_id, $image_count = 0, $is_detail = false)
	{
		if (!strlen($body) && $type == \Config::get('timeline.types.album_image_timeline'))
		{
			if (!$image_count)
			{
				return __('message_post_images_to_with_count', array('label' => t('timeline.view'), 'num' => $image_count));
			}

			return __('message_post_for_to', array('label' => t('site.picture'), 'object' => t('timeline.view')));
		}

		return convert_body($body, array(
			'is_truncate'    => !$is_detail,
			'truncate_width' => conf('articles.trim_width.body', 'timeline'),
			'truncate_line'  => conf('articles.truncate_lines.body', 'timeline'),
			'read_more_uri'  => 'timeline/'.$timeline_id,
			'mention2link'   => true,
		));
	}

	public static function get_quote_article($type, $foreign_table_obj, $is_detail = false)
	{
		$accept_types = array(
			\Config::get('timeline.types.note'),
			\Config::get('timeline.types.thread'),
			\Config::get('timeline.types.album'),
			\Config::get('timeline.types.album_image'),
		);
		if (!in_array($type, $accept_types)) return null;

		$title = array(
			'value' => '',
			'truncate_count' => conf('view_params_default.list.trim_width.title')
		);
		$body = array('value' => $foreign_table_obj->body);
		if (!$is_detail)
		{
			$body['truncate_count'] = \Config::get('timeline.articles.truncate_lines.body');
			$body['truncate_type']  = 'line';
		}
		$read_more_uri  = '';

		switch ($type)
		{
			case \Config::get('timeline.types.note'):
				$title['value'] = $foreign_table_obj->title;
				$read_more_uri = 'note/'.$foreign_table_obj->id;
				break;
			case \Config::get('timeline.types.thread'):
				$title['value'] = $foreign_table_obj->title;
				$read_more_uri = 'thread/'.$foreign_table_obj->id;
				break;
			case \Config::get('timeline.types.album'):
				$title['value'] = $foreign_table_obj->name;
				$read_more_uri = 'album/'.$foreign_table_obj->id;
				break;
			case \Config::get('timeline.types.album_image'):
				$read_more_uri = 'timeline/'.$foreign_table_obj->id;
				break;
		}

		return render('_parts/quote_article', array('title' => $title, 'body' => $body, 'read_more_uri' => $read_more_uri));
	}

	public static function get_detail_uri($timeline_id, $type, $foreign_table_obj = null)
	{
		$default = 'timeline/'.$timeline_id;
		if (!$foreign_table_obj) return $default;

		switch ($type)
		{
			case \Config::get('timeline.types.note'):
				return 'note/'.$foreign_table_obj->id;
				break;
			case \Config::get('timeline.types.thread'):
				return 'thread/'.$foreign_table_obj->id;
				break;
			case \Config::get('timeline.types.album'):
				return 'album/'.$foreign_table_obj->id;
				break;
		}

		return $default;
	}

	public static function get_type_for_save_comment_to_foreign_table()
	{
		return array(
			\Config::get('timeline.types.note'),
			\Config::get('timeline.types.album_image_profile'),
		);
	}

	public static function check_type_for_post_foreign_table_comment($type)
	{
		$types_for_save_comment_to_foreign_table = self::get_type_for_save_comment_to_foreign_table();
		if (in_array($type, $types_for_save_comment_to_foreign_table)) return true;

		return false;
	}

	public static function get_comment_parent_id($type, $timeline_id = 0, $foreign_id = 0)
	{
		return self::check_type_for_post_foreign_table_comment($type) ? $foreign_id : $timeline_id;
	}

	public static function get_comment_api_uri($action, $type, $timeline_id = 0, $foreign_id = 0)
	{
		$pre_path = 'timeline/';
		$id = $timeline_id;
		switch ($type)
		{
			case \Config::get('timeline.types.note'):// note 投稿
				$pre_path = 'note/';
				$id = $foreign_id;
				if ($action == 'get') $common_path = 'comment/api/list/'.$foreign_id.'.html';
				break;
			case \Config::get('timeline.types.thread'):// thread 投稿
				$pre_path = 'thread/';
				$id = $foreign_id;
				if ($action == 'get') $common_path = 'comment/api/list/'.$foreign_id.'.html';
				break;
			case \Config::get('timeline.types.album_image_profile'):// profile 写真投稿(album_image)
				$pre_path = 'album/image/';
				$id = $foreign_id;
				if ($action == 'get') $common_path = 'comment/api/list/'.$foreign_id.'.html';
				break;
		}

		switch ($action)
		{
			case 'create':
				$common_path = $id ? 'comment/api/create/'.$id.'.json' : 'comment/api/create.json';
				break;
			case 'delete':
				$common_path = $id ? 'comment/api/delete/'.$id.'.json' : 'comment/api/delete.json';
				break;
			case 'get':
			default :
				$common_path = $id ? 'comment/api/list/'.$id.'.json' : 'comment/api/list.json';
				break;
		}

		return $pre_path.$common_path;
	}

	public static function get_like_api_uri($type, $timeline_id = 0, $foreign_id = 0)
	{
		switch ($type)
		{
			case \Config::get('timeline.types.note'):// note 投稿
				return \Site_Util::get_api_uri_update_like('note', $foreign_id);
			case \Config::get('timeline.types.thread'):// thread 投稿
				return \Site_Util::get_api_uri_update_like('thread', $foreign_id);
			case \Config::get('timeline.types.album_image_profile'):// profile 写真投稿(album_image)
				return \Site_Util::get_api_uri_update_like('album/image', $foreign_id);
		}

		return sprintf('timeline/like/api/update/%d.json', $timeline_id);
	}

	public static function get_liked_member_api_uri4foreign_table($type, $timeline_id = 0, $foreign_id = 0)
	{
		switch ($type)
		{
			case \Config::get('timeline.types.note'):// note 投稿
				return \Site_Util::get_api_uri_get_liked_members('note', $foreign_id);
			case \Config::get('timeline.types.thread'):// thread 投稿
				return \Site_Util::get_api_uri_get_liked_members('thread', $foreign_id);
			case \Config::get('timeline.types.album_image_profile'):// profile 写真投稿(album_image)
				return \Site_Util::get_api_uri_get_liked_members('album/image', $foreign_id);
		}

		return \Site_Util::get_api_uri_get_liked_members('timeline', $timeline_id);
	}

	public static function check_type_to_get_access_from($type)
	{
		$types_to_get_access_from = array(
			\Config::get('timeline.types.album'),
			\Config::get('timeline.types.album_image'),
			\Config::get('timeline.types.album_image_timeline'),
		);

		return in_array($type, $types_to_get_access_from);
	}

	public static function get_timeline_images($type, $foreign_id, $timeline_id = null, $access_from = null, $is_detail = false)
	{
		// defaults
		$images = array();
		$images['file_cate']    = 'ai';
		$images['size']         = 'N_M';
		$images['column_count'] = 3;

		switch ($type)
		{
			case \Config::get('timeline.types.album_image_profile'):
				$images['list']   = array();
				if ($list = \Album\Model_AlbumImage::check_authority($foreign_id))
				{
					$images['list'][]       = $list;
					$images['column_count'] = 2;
				}
				break;

			case \Config::get('timeline.types.profile_image'):
				$images['list']   = array();
				if ($list = \Model_File::find($foreign_id))
				{
					$images['list'][]       = $list;
					$images['file_cate']    = 'm';
					$images['size']         = 'LL';
					$images['column_count'] = 2;
				}
				break;

			case \Config::get('timeline.types.note'):
				list($images['list'], $images['count_all']) = \Note\Model_NoteAlbumImage::get_album_image4note_id(
					$foreign_id,
					$is_detail ? 0 : \Config::get('timeline.articles.thumbnail.limit.default'),
					array('id' => 'asc'),
					true
				);
				$images['parent_page_uri'] = 'note/'.$foreign_id;
				break;

			case \Config::get('timeline.types.thread'):
				list($images['list'], $images['count_all']) = \Thread\Model_ThreadImage::get4thread_id($foreign_id, 3, true);
				$images['file_cate']    = 't';
				$images['size']         = 'M';
				$images['column_count'] = 3;
				$images['parent_page_uri'] = 'thread/'.$foreign_id;
				break;

			case \Config::get('timeline.types.album'):
			case \Config::get('timeline.types.album_image'):
				$images['list'] = array();
				$images['count'] = 0;
				if ($album_image_ids = Model_TimelineChildData::get_foreign_ids4timeline_id($timeline_id))
				{
					list($images['list'], $images['count']) = \Album\Model_AlbumImage::get_list_and_count(array(
						'where' => \Site_Model::get_where_public_flag4access_from(
							$access_from,
							array(array('id', 'in', $album_image_ids))
						),
						$is_detail ? 0 : 'limit' => \Config::get('timeline.articles.thumbnail.limit.default'),
						'order_by' => array('created_at' => 'asc'),
					));
				}
				$images['count_all'] = \Album\Model_AlbumImage::get_list_count(array(
					'where' => \Site_Model::get_where_public_flag4access_from(
						$access_from,
						array(array('album_id', $foreign_id))
					),
				));
				$images['parent_page_uri']  = 'album/'.$foreign_id;
				break;

			case \Config::get('timeline.types.album_image_timeline'):
				list($images['list'], $images['count']) = \Album\Model_AlbumImage::get_list_and_count(array(
					'where' => \Site_Model::get_where_public_flag4access_from(
						$access_from,
						array(array('id', 'in', Model_TimelineChildData::get_foreign_ids4timeline_id($timeline_id)))
					),
					$is_detail ? 0 : 'limit' => \Config::get('timeline.articles.thumbnail.limit.album_image_timeline'),
					'order_by' => array('created_at' => 'asc'),
				));
				$images['count_all'] = $images['count'];
				$images['parent_page_uri']  = 'timeline/'.$timeline_id;
				break;

			default :
				break;
		}

		return $images;
	}

	public static function get_timeline_object($type_key, $foreign_id)
	{
		if (in_array($type_key, array('album', 'album_image', 'member_name')))
		{
			$table = $type_key;
			if ($type_key == 'album_image') $table = 'album';
			if ($type_key == 'member_name') $table = 'member';
			$since_datetime = date('Y-m-d H:i:s', strtotime('- '.\Config::get('timeline.periode_to_update.'.$type_key)));
			if ($timeline = Model_Timeline::get4latest_foreign_data($table, $foreign_id, $since_datetime))
			{
				return $timeline;
			}
		}

		return Model_Timeline::forge();
	}

	public static function check_is_editable($type)
	{
		$editable_types = array(
			\Config::get('timeline.types.normal'),
			\Config::get('timeline.types.note'),
			\Config::get('timeline.types.album'),
			\Config::get('timeline.types.album_image_timeline'),
		);

		return in_array($type, $editable_types);
	}

	public static function get_edit_action_uri(Model_Timeline $timeline)
	{
		$table = '';
		$id = 0;
		switch (static::get_key4type($timeline->type))
		{
			case 'note':
			case 'album':
			case 'thread':
				$table = $timeline->foreign_table;
				$id = $timeline->foreign_id;
				break;
			case 'member_name':
				return 'member/profile/edit';
			case 'profile_image':
			case 'album_image_profile':
				return 'member/profile/image';
			case 'normal':
			case 'album_image_timeline':
			case 'member_register':
			case 'album_image':
			default :
				return '';
		}
		if (!$table || !$id) return '';

		return \Site_Util::get_action_uri($table, $id, 'edit');
	}

	public static function get_delete_api_uri(Model_Timeline $timeline)
	{
		$table = '';
		$id = 0;
		switch (static::get_key4type($timeline->type))
		{
			case 'note':
			case 'album':
			case 'thread':
			case 'album_image_profile':
				$table = $timeline->foreign_table;
				$id = $timeline->foreign_id;
				break;

			default :
				$table = 'timeline';
				$id = $timeline->id;
				break;
		}
		if (!$table || !$id) return '';

		return \Site_Util::get_action_uri($table, $id, 'delete', 'json');
	}

	public static function get_member_watch_content_api_uri(Model_Timeline $timeline)
	{
		list($foreign_table, $foreign_id_column) = self::get_member_watch_content_info4timeline_type($timeline->type);
		if (!$foreign_table || !$foreign_id_column) return sprintf('member/notice/api/update_watch_status/timeline/%s.json', $timeline->id);

		return sprintf('member/notice/api/update_watch_status/%s/%s.json', $foreign_table, $timeline->{$foreign_id_column});
	}

	public static function get_member_watch_content_info4timeline_type($timeline_type)
	{
		$types = \Config::get('timeline.types');
		$foreign_table = '';
		$foreign_id_column = '';
		switch ($timeline_type)
		{
			case $types['normal']:
			case $types['member_register']:
			case $types['member_name']:
			case $types['profile_image']:
			case $types['album']:
			case $types['album_image_timeline']:
				$foreign_table = 'timeline';
				$foreign_id_column = 'id';
				break;
			case $types['note']:
				$foreign_table = 'note';
				$foreign_id_column = 'foreign_id';
				break;
			case $types['album_image']:
			case $types['album_image_profile']:
				$foreign_table = 'album_image';
				$foreign_id_column = 'foreign_id';
				break;
		}

		return array($foreign_table, $foreign_id_column);
	}

	public static function get_public_flag_info(Model_Timeline $timeline)
	{
		$info = array(
			'model' => 'timeline',
			'public_flag_target_id' => $timeline->id,
			'have_children_public_flag' => false,
			'child_model' => null,
			'disabled_to_update' => false,
		);
		switch ($timeline->type)
		{
			case \Config::get('timeline.types.normal'):
			case \Config::get('timeline.types.album_image_timeline'):
				break;
			case \Config::get('timeline.types.note'):
				$info['model'] = 'note';
				$info['public_flag_target_id'] = $timeline->foreign_id;
				break;
			case \Config::get('timeline.types.thread'):
				$info['model'] = 'thread';
				$info['option_type'] = 'public';
				$info['public_flag_target_id'] = $timeline->foreign_id;
				break;
			case \Config::get('timeline.types.album'):
				$info['model'] = 'album';
				$info['public_flag_target_id'] = $timeline->foreign_id;
				$info['have_children_public_flag'] = true;
				$info['child_model'] = 'album_image';
				break;
			case \Config::get('timeline.types.member_register'):
			case \Config::get('timeline.types.member_name'):
			case \Config::get('timeline.types.profile_image'):
			case \Config::get('timeline.types.album_image_profile'):
			case \Config::get('timeline.types.album_image'):
				$info['disabled_to_update'] = array('message' => __('message_disabled_to_change'));
				break;
			default :
				break;
		}

		return $info;
	}

	public static function get_article_main_view($timeline_id, $access_from_member_relation = null, $is_detail = false)
	{
		if ($is_detail || !\Config::get('timeline.articles.cache.is_use'))
		{
			return self::get_article_main_content($timeline_id, $access_from_member_relation, $is_detail);
		}

		return self::get_view_cache($timeline_id, $access_from_member_relation, true);
	}

	public static function get_article_main_content($timeline_id, $access_from_member_relation = null, $is_detail = false)
	{
		$timeline = Model_Timeline::find($timeline_id, array('related' => array('member')));

		return render('timeline::_parts/article_main', array(
			'timeline' => $timeline,
			'access_from_member_relation' => $access_from_member_relation,
			'is_detail' => $is_detail,
		));
	}

	public static function get_cache_key($timeline_id, $access_from_member_relation = null)
	{
		$cache_key = \Config::get('timeline.articles.cache.prefix').$timeline_id;
		if ($access_from_member_relation) $cache_key .= '_'.$access_from_member_relation;

		return $cache_key;
	}

	public static function get_view_cache($timeline_id, $access_from_member_relation = null, $is_make_cache = false)
	{
		$cache_key = self::get_cache_key($timeline_id, $access_from_member_relation);
		$cache_expir = \Config::get('timeline.articles.cache.expir');
		try
		{
			$content =  \Cache::get($cache_key, $cache_expir);
		}
		catch (\CacheNotFoundException $e)
		{
			$content = null;
			if ($is_make_cache)
			{
				$content = self::get_article_main_content($timeline_id, $access_from_member_relation);
				\Cache::set($cache_key, $content, $cache_expir);
			}
		}

		return $content;
	}

	public static function delete_cache($timeline_id, $type = null)
	{
		$cache_keys = array(self::get_cache_key($timeline_id));
		if (!$type || self::check_type_to_get_access_from($type))
		{
			$relations = array('self', 'member', 'others', 'friend');
			foreach ($relations as $relation)
			{
				$cache_keys[] = self::get_cache_key($timeline_id, $relation);
			}
		}
		foreach ($cache_keys as $cache_key)
		{
			\Cache::delete($cache_key);
		}
	}

	public static function get_member_relation_member_ids($member_id_from, $timeline_viewType = null)
	{
		$follow_member_ids = null;
		$friend_member_ids = null;
		$timeline_viewType = Site_Model::validate_timeline_viewType($timeline_viewType);
		switch ($timeline_viewType)
		{
			case 1:
				$follow_member_ids = \Model_MemberRelation::get_member_ids($member_id_from, 'is_follow');
				break;
			case 2:
				$friend_member_ids = \Model_MemberRelation::get_member_ids($member_id_from, 'is_friend');
				break;
			case 3:
				$follow_member_ids = \Model_MemberRelation::get_member_ids($member_id_from, 'is_follow');
				$friend_member_ids = \Model_MemberRelation::get_member_ids($member_id_from, 'is_friend');
				break;
			case 0:
			default :
				break;
		}

		return array($follow_member_ids, $friend_member_ids);
	}

	public static function make_view_cache4foreign_table_and_foreign_id($foreign_table, $foreign_id, $type = null)
	{
		$timelines = \Timeline\Model_Timeline::get4foreign_table_and_foreign_ids($foreign_table, $foreign_id, $type);
		$timeline = array_shift($timelines);
		Site_Util::get_article_main_view($timeline->id);

		return \Cache::get(\Timeline\Site_Util::get_cache_key($timeline->id), \Config::get('timeline.articles.cache.expir'));
	}

	public static function get_importance_level($comment_count, $like_count)
	{
		if (!\Config::get('timeline.importanceLevel.isEnabled', false)) return;
		if (!$levels = (array)\Config::get('timeline.importanceLevel.levels')) return;

		$comment_count_rate = \Config::get('timeline.importanceLevel.commentCountRate', 2);
		$point = $comment_count * $comment_count_rate + $like_count;

		krsort($levels);
		foreach ($levels as $level => $limit)
		{
			if ($point > $limit) return (int)$level;
		}

		return 0;
	}

	public static function get_list4view($self_member_id = 0, $target_member_id = 0, $is_mytimeline = false, $viewType = null, $params = array())
	{
		list($list, $next_id) = Site_Model::get_list(
			$self_member_id,
			$target_member_id,
			$is_mytimeline,
			$viewType,
			$params['max_id'],
			$params['limit'],
			$params['is_latest'],
			$params['is_desc'],
			$params['since_id']
		);
		$liked_timeline_ids = (conf('like.isEnabled') && $self_member_id) ? \Site_Model::get_liked_ids('timeline', $self_member_id, $list) : array();
		$data = array(
			'list' => $list,
			'next_id' => $next_id,
			'since_id' => $params['since_id'] ?: 0,
			'is_display_load_before_link' => $params['max_id'] ? true : false,
			'liked_timeline_ids' => $liked_timeline_ids,
		);

		return $data;
	}

	public static function check_image_to_display_slide_modal($timeline_type)
	{
		if (!conf('site.common.thumbnailModalLink.isEnabled', 'page')) return false;

		return static::check_timeline_with_album_image4type($timeline_type);
	}

	public static function check_timeline_with_album_image4type($target_type)
	{
		$timeline_types_with_album_images = array(
			'normal',
			'note',
			'album',
			'album_image',
			'album_image_profile',
			'album_image_timeline',
		);

		return in_array(static::get_key4type($target_type), $timeline_types_with_album_images);
	}
}


text:
<?php

class Q_Logger_Writer_Null extends Q_Logger_Writer_Abstract
{
    protected function _write($message, $priority)
    {
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bugscript.pharmaroot.WholeSalers"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:orientation="vertical">

    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:src="@drawable/money"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"/>

    <EditText
        android:id="@+id/wholesalerEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:hint="Email"
        android:inputType="textEmailAddress"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="0dp" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:layout_editor_absoluteY="0dp"
        tools:layout_editor_absoluteX="8dp"
        android:layout_marginTop="10dp"
        android:hint="password"
        android:id="@+id/wholesallersPassword"
        android:inputType="numberPassword" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Login"
        android:id="@+id/wholesalersLogin"
        android:textColor="@color/white"
        android:background="@color/colorAccent"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Created by Pharma root team dedicated to the Ministry of Ayush"
        android:gravity="center"
        android:layout_marginTop="60dp"
        android:layout_marginBottom="8dp"/>

</LinearLayout>


text:
import { Base } from './base.js';
import { Vector, PolarVector, WrapVector, WrapPolarVector } from './vectorgeo.js';
import { BoundingShape } from './boundingshape.js';
import { BoundingCircle } from './boundingcircle.js';
import { BoundingBox } from './boundingbox.js';
import { Button } from './button.js';
import { TextButton } from './textbutton.js';
import { CollisionEvent } from './collisionevent.js';
import { CollisionGroup } from './collisiongroup.js';
import { Entity } from './entity.js';
import { Handler } from './handler.js';
import { Screen } from './screen.js';
import { LoadScreen } from './loadscreen.js';
import { MenuScreen } from './menuscreen.js';
import { SplashScreen } from './splashscreen.js';
import { TimedSplashScreen } from './timedsplashscreen.js';
import { Slider } from './slider.js';
import { ScreenGraph } from './screengraph.js';

export {
  Base,
  Vector, PolarVector, WrapVector, WrapPolarVector,
  BoundingShape, BoundingCircle, BoundingBox,
  Button, TextButton,
  CollisionEvent, CollisionGroup,
  Entity, Handler, Screen, LoadScreen, MenuScreen, SplashScreen, TimedSplashScreen,
  Slider, ScreenGraph};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Torch</string>

    <string name="turn_on">Turn On</string>
    <string name="turn_off">Turn Off</string>

    <string name="torch_unavailable">Cannot connect to torch :(</string>
</resources>


text:
import fetchService from '../../services/fetchService';

export const REQUEST_FOOD = 'REQUEST_FOOD';
export const RECEIVE_FOOD = 'RECEIVE_FOOD';
export const SELECT_CATEGORY = 'SELECT_CATEGORY';
export const INVALIDATE_CATEGORY = 'INVALIDATE_CATEGORY';

export function selectCategory(categoryId) {
  return {
    type: SELECT_CATEGORY,
    categoryId,
  };
}

export function invalidateCategory(categoryId) {
  return {
    type: INVALIDATE_CATEGORY,
    categoryId,
  };
}

function requestFood(categoryId) {
  return {
    type: REQUEST_FOOD,
    categoryId,
  };
}

function receiveFood(category, json) {
  return {
    type: RECEIVE_FOOD,
    category,
    food: json.data.children.map(child => child.data),
    receivedAt: Date.now(),
  };
}

function fetchFood(categoryId) {
  return (dispatch) => {
    dispatch(requestFood(categoryId));
    fetchService(`categories/${categoryId}/food`, 'GET')
      .then(food => dispatch(receiveFood(categoryId, food)));
  };
}

function shouldFetchFood(state, categoryId) {
  const food = state.foodByCategory[categoryId];
  if (!food) {
    return true;
  } if (food.isFetching) {
    return false;
  }
  return food.didInvalidate;
}

export function fetchFoodIfNeeded(categoryId) {
  return (dispatch, getState) => {
    if (shouldFetchFood(getState(), categoryId)) {
      return dispatch(fetchFood(categoryId));
    }
    return getState().foodByCategory[categoryId];
  };
}


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

namespace SharpNav.Collections.Generic
{
	/// <summary>
	/// Use a priority queue (heap) to determine which node is more important.
	/// </summary>
	/// <typeparam name="T">
	/// A type that has a cost for each instance via the <see cref="IValueWithCost"/> interface.
	/// </typeparam>
	public class PriorityQueue<T> : ICollection<T>
		where T : class, IValueWithCost
	{
		private T[] heap;
		private int capacity;
		private int size;

		/// <summary>
		/// Initializes a new instance of the <see cref="PriorityQueue{T}"/> class with a given capacity of size n.
		/// </summary>
		/// <param name="n">The maximum number of nodes that can be stored.</param>
		public PriorityQueue(int n)
		{
			capacity = n;
			size = 0;
			heap = new T[capacity + 1];
		}

		/// <summary>
		/// Gets the number of elements in the priority queue.
		/// </summary>
		public int Count
		{
			get
			{
				return size;
			}
		}

		/// <summary>
		/// Gets a value indicating whether the collection is read-only. For <see cref="PriorityQueue{T}"/>, this is
		/// always <c>true</c>.
		/// </summary>
		bool ICollection<T>.IsReadOnly
		{
			get
			{
				return false;
			}
		}

		/// <summary>
		/// Remove all the elements from the priority queue.
		/// </summary>
		public void Clear()
		{
			size = 0;
		}

		/// <summary>
		/// Determines whether the priority queue is empty
		/// </summary>
		/// <returns>True if empty, false if not</returns>
		public bool Empty()
		{
			return size == 0;
		}

		/// <summary>
		/// Return the node at the top of the heap.
		/// </summary>
		/// <returns>Top node in heap</returns>
		public T Top()
		{
			return (size > 0) ? heap[0] : null;
		}

		/// <summary>
		/// Remove the node at the top of the heap. Then, move the bottommost node to the top and trickle down
		/// until the nodes are in order.
		/// </summary>
		/// <returns>Node with lowest value in heap</returns>
		public T Pop()
		{
			if (size == 0)
				return null;

			T result = heap[0];
			size--;
			TrickleDown(0, heap[size]);
			return result;
		}

		/// <summary>
		/// Add the node at the bottom of the heap and move it up until the nodes ae in order.
		/// </summary>
		/// <param name="node">The node to add</param>
		public void Push(T node)
		{
			size++;
			BubbleUp(size - 1, node);
		}

		/// <summary>
		/// Returns whether the given item exists in the heap.
		/// </summary>
		/// <param name="item">Item to look for</param>
		/// <returns>True or False</returns>
		public bool Contains(T item)
		{
			for (int c = 0; c < size; c++)
				if (heap[c] == item)
					return true;

			return false;
		}

		/// <summary>
		/// Change the value of the node, which may involve some swapping of elements to maintain heap order.
		/// </summary>
		/// <param name="node">The node to modify</param>
		public void Modify(T node)
		{
			for (int i = 0; i < size; i++)
			{
				if (heap[i] == node)
				{
					BubbleUp(i, node);
					return;
				}
			}
		}

		/// <summary>
		/// Copies the contents of the <see cref="PriorityQueue{T}"/> to an array.
		/// </summary>
		/// <param name="array">The array to copy to.</param>
		/// <param name="arrayIndex">The index within the array to start copying to.</param>
		public void CopyTo(T[] array, int arrayIndex)
		{
			if (arrayIndex + heap.Length > array.Length)
				throw new ArgumentException("Array not large enough to hold priority queue", "array");

			Array.Copy(heap, 0, array, arrayIndex, heap.Length);
		}

		/// <summary>
		/// Gets the <see cref="PriorityQueue"/>'s enumerator.
		/// </summary>
		/// <returns>The enumerator.</returns>
		public IEnumerator<T> GetEnumerator()
		{
			return ((IEnumerable<T>)heap).GetEnumerator();
		}

		/// <summary>
		/// Calls <see cref="Push"/>.
		/// </summary>
		/// <param name="item">The item to add.</param>
		void ICollection<T>.Add(T item)
		{
			Push(item);
		}

		/// <summary>
		/// Unsupported, but necessary to implement <see cref="ICollection{T}"/>.
		/// </summary>
		/// <param name="item">An item.</param>
		/// <returns>Nothing. This method will always throw <see cref="InvalidOperationException"/>.</returns>
		/// <exception cref="InvalidOperationException">Will always be thrown. This is not a valid operation.</exception>
		bool ICollection<T>.Remove(T item)
		{
			throw new InvalidOperationException("This priority queue implementation only allows elements to be popped off the top, not removed.");
		}

		/// <summary>
		/// The non-generic version of <see cref="GetEnumerator"/>.
		/// </summary>
		/// <returns>A non-generic enumerator.</returns>
		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		/// <summary>
		/// While going up a priority queue, keep swapping elements until the element reaches the top.
		/// </summary>
		/// <param name="i">Index of current node</param>
		/// <param name="node">The node itself</param>
		private void BubbleUp(int i, T node)
		{
			int parent = (i - 1) / 2;

			while ((i > 0) && (heap[parent].Cost > node.Cost))
			{
				heap[i] = heap[parent];
				i = parent;
				parent = (i - 1) / 2;
			}

			heap[i] = node;
		}

		/// <summary>
		/// While moving down the priority queue, keep swapping elements.
		/// </summary>
		/// <param name="i">Index of current node</param>
		/// <param name="node">The node itself</param>
		private void TrickleDown(int i, T node)
		{
			int child = (i * 2) + 1;

			while (child < size)
			{
				//determine which child element has a smaller cost
				if (((child + 1) < size) && (heap[child].Cost > heap[child + 1].Cost))
					child++;

				heap[i] = heap[child];
				i = child;
				child = (i * 2) + 1;
			}

			BubbleUp(i, node);
		}
	}
}


text:
<?php

namespace Ictdata\IctdataBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class D_part_marcheType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('partDate')
            ->add('partParcMobilePostIam')
            ->add('partParcMobilePreIam')
            ->add('partParcMobilePostMed')
            ->add('partParcMobilePreMed')
            ->add('partParcMobilePostWana')
            ->add('partParcMobilePreWana')
            ->add('partParcFixeResidIam')
            ->add('partParcFixeProfIam')
            ->add('partParcFixeResidMed')
            ->add('partParcFixeProfMed')
            ->add('partParcFixeResidWana')
            ->add('partParcFixeProfWana')
            ->add('partParcLignesPubliIam')
            ->add('partParcLignesPubliMed')
            ->add('partParcInternetAdslIam')
            ->add('partParcInternetMobileIam')
            ->add('partParcInternetAdslMed')
            ->add('partParcInternetMobileMed')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Ictdata\IctdataBundle\Entity\D_part_marche'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'ictdata_ictdatabundle_d_part_marche';
    }
}


text:
module Tablator
  extend self

  autoload :Configuration, 'tablator/configuration'

  def configure(&block)
    Configuration.configure &block
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2017. Ronald D. Kurr kurr@jvmguy.com
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<configuration debug="false">

    <!-- grab Spring's configuration in case we want to take advantage of some of its features -->
    <include resource="org/springframework/boot/logging/logback/base.xml"/>

    <!-- required to ensure that bridging from java.util.logging does not cause a 20% performance hit -->
    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"/>

    <!-- 12 Factor says only log to STDOUT and STDERR and let the process manager worrying about sending it to the aggregator. -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
            <includeContext>false</includeContext>
            <timeZone>UTC</timeZone>
            <fieldNames>
                <timestamp>timestamp</timestamp>
                <message>message</message>
                <logger>component</logger>
                <version>[ignore]</version>
                <thread>[ignore]</thread>
                <levelValue>[ignore]</levelValue>
            </fieldNames>
        </encoder>
    </appender>

    <!-- An example of how to work in Spring properties into the logging configuration -->
<!--
    <springProperty name="serviceInstance" source="example.logging.serviceInstance"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>Instance = ${serviceInstance} %n</pattern>
        </encoder>
    </appender>
-->

    <logger name="org.kurron" level="ALL"/>
    <logger name="org.springframework" level="WARN"/>

    <!-- handles sending messages using background threads -->
    <appender name="ASYNC-CONSOLE" class="ch.qos.logback.classic.AsyncAppender">
        <!-- The maximum capacity of the blocking queue. By default, queueSize is set to 256. -->
        <queueSize>1024</queueSize>
        <appender-ref ref="CONSOLE"/>
    </appender>

    <root level="WARN">
        <appender-ref ref="ASYNC-CONSOLE"/>
    </root>
</configuration>


text:
package org.apache.bookkeeper.mledger.offload.jcloud;

import org.apache.bookkeeper.common.annotation.InterfaceAudience.LimitedPrivate;
import org.apache.bookkeeper.common.annotation.InterfaceStability.Unstable;

/**
 * The Index Entry in OffloadIndexBlock.
 * It consists of the message entry id, the tiered storage block part id for this message entry,
 * and the offset in tiered storage block for this message id.
 */
@Unstable
@LimitedPrivate
public interface OffloadIndexEntry {

    /**
     * Get the entryId that this entry contains.
     */
    long getEntryId();

    /**
     * Get the block part id of tiered storage.
     */
    int getPartId();

    /**
     * Get the offset of this block within the object.
     */
    long getOffset();

    /**
     * Get the offset of the block's data within the object.
     */
    long getDataOffset();
}


text:
<?php

namespace Oxygen\Core\Console;

use Illuminate\Console\Command as BaseCommand;

abstract class Command extends BaseCommand {

    /**
     * Prints a heading.
     *
     * @param string $text
     */
    public function heading($text) {
        $this->info('');
        $this->info('===================');
        $this->info($text);
        $this->info('===================');
        $this->info('');
    }

}


text:
Apply rubocop only diff from master.
We should KEEP our project 0 result rubocop points out.
Actually,however,you face projects which rubocop become angry more than 10000 times.
Then,you should KAIZEN your project step by step.
May this help you.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'diffcop', require: false
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install diffcop

## Usage

`bundle exec diffcop`

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/yohira0616/diffcop.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
FROM strongloop/node
ADD . /home/strongloop/app
WORKDIR /home/strongloop/app
RUN npm install
ENV NODE_ENV production
ENV APP_NAME inventario
CMD [ "slc", "run", "." ]


text:
<!DOCTYPE html>

        状态:

              {{todoUtilService.getStatus(todo).name}}

                {{status.name}}

        任务类型:

            {{todoUtilService.getType(todo).name}}

                {{type.name}}

        优先级:

              {{todoUtilService.getPriority(todo).desc}}

                {{priority.desc}}

        所属列表:

            {{todoUtilService.getTodolist(todo).name}}

              {{todolist.name}}

        截止日期:

          <input type="hidden" class="form-control" datepicker-popup="yyyy-MM-dd"
                 ng-change="todo.updateByAttrs(['assigneeId', 'dueDate'], false)"
                 ng-model="todo.dueDate" is-open="dtpOpened" close-text="关闭" clear-text="不指定" current-text="今天"
                 min-date="todoDueDateMin"/>

            {{ todo.dueDate | date: 'yyyy-MM-dd'}}
            未设置

            {{ todo.dueDate | date: 'yyyy-MM-dd'}}
            未设置

        执行人:

            {{todo.user.name}}

            推荐:{{recommend.name}}

                 {{user.name}}


text:
//
//  PlayerViewController.h
//  DesignShots
//
//  Created by lizhenjie on 4/29/16.
//  Copyright © 2016 swplzj. All rights reserved.
//

#import <UIKit/UIKit.h>

/**
 *  Player Detail
 */
@interface PlayerViewController : UIViewController

@end


text:
from edge.blast import blast_genome, EDGE_BLAST_DEFAULT_WORD_SIZE
from Bio.Seq import Seq

MIN_BINDING_LENGTH = 15
BINDING_LENGTH_HI = 20

def compute_pcr_product(
    primer_a_sequence,
    primer_a_binding_check_len,
    primer_a_blastres,
    primer_b_sequence,
    primer_b_binding_check_len,
    primer_b_blastres,
):
    """
    Computes a PCR product based on two blast results.
    """

    MIN_IDENTITIES = 0.95
    # probably an over-estimation, for misdirected primers on circular genome
    MAX_PCR_SIZE = 50000

    # primers must be on the same fragment
    if primer_a_blastres.fragment_id != primer_b_blastres.fragment_id:
        return None

    # primers must align to different senses
    primer_a_strand = primer_a_blastres.strand()
    primer_b_strand = primer_b_blastres.strand()
    if primer_a_strand == primer_b_strand:
        return None

    # forward primer aligns to the sense strand, binds to the antisense strand,
    # and elongates along the sense strand and copies sense strand bases; it
    # must align at the 3' end of the primer against the sense strand.
    #
    # reverse primer aligns to the antisense strand, binds to the sense strand,
    # and elongates along the antisense strand and copies antisense strand
    # bases; it must align at the 3' end of the primer against the antisense
    # strand.

    if primer_a_strand == 1:
        fwd_primer = primer_a_sequence
        fwd_primer_binding_check_len = primer_a_binding_check_len
        fwd_primer_res = primer_a_blastres
        rev_primer = primer_b_sequence
        rev_primer_res = primer_b_blastres
        rev_primer_binding_check_len = primer_b_binding_check_len
    else:
        fwd_primer = primer_b_sequence
        fwd_primer_res = primer_b_blastres
        fwd_primer_binding_check_len = primer_b_binding_check_len
        rev_primer = primer_a_sequence
        rev_primer_res = primer_a_blastres
        rev_primer_binding_check_len = primer_a_binding_check_len

    if (
        fwd_primer_res.query_end != fwd_primer_binding_check_len
        or rev_primer_res.query_end != rev_primer_binding_check_len
    ):
        return None

    # primers must align well
    if (
        primer_a_blastres.identity_ratio() < MIN_IDENTITIES
        or primer_b_blastres.identity_ratio() < MIN_IDENTITIES
        or primer_a_blastres.alignment_length() < MIN_BINDING_LENGTH
        or primer_b_blastres.alignment_length() < MIN_BINDING_LENGTH
    ):
        return None

    fragment = primer_a_blastres.fragment.indexed_fragment()

    # cannot produce product if elongated regions do not overlap. if we are on
    # a circular fragment, there will always be overlaps.
    if (
        fwd_primer_res.subject_end >= rev_primer_res.subject_end
        and fragment.circular is False
    ):
        return None

    # get sequence between primers
    bp_lo = fwd_primer_res.subject_end + 1
    bp_hi = rev_primer_res.subject_end - 1

    product_mid = fragment.get_sequence(bp_lo=bp_lo, bp_hi=bp_hi)
    if len(product_mid) > MAX_PCR_SIZE:
        return None

    product = "%s%s%s" % (
        fwd_primer,
        product_mid,
        str(Seq(rev_primer).reverse_complement()),
    )

    bs_start = (fwd_primer_res.subject_end + 1) - (
        fwd_primer_res.query_end - fwd_primer_res.query_start + 1
    )
    bs_end = (rev_primer_res.subject_end - 1) + (
        rev_primer_res.query_end - rev_primer_res.query_start + 1
    )

    bs_start = fragment.circ_bp(bs_start)
    bs_end = fragment.circ_bp(bs_end)

    return (product, dict(fragment=fragment, region=(bs_start, bs_end)))

def pcr_from_genome(
    genome, primer_a_sequence, primer_b_sequence,
    blast_word_size=EDGE_BLAST_DEFAULT_WORD_SIZE
):
    """
    PCR on genome, using two primer sequences. Returns tuple of PCR product
    sequence, primer a blast results, and primer b blast results. Produuct
    sequence may be None if primers do not bind unique or in a way that can
    result in a PCR product.

    A PCR can create a product if each primer uniquely binds to the genome,
    primers bind to the same fragment, on sense and antisense strands
    respectively, and non-overlapping in their sense strand binding positions
    """

    primer_a_results = []
    primer_a_binding_check_len = []
    primer_b_results = []
    primer_b_binding_check_len = []

    res = blast_genome(genome, "blastn", primer_a_sequence, word_size=blast_word_size)
    for r in res:
        primer_a_results.append(r)
        primer_a_binding_check_len.append(len(primer_a_sequence))

    res = blast_genome(genome, "blastn", primer_b_sequence, word_size=blast_word_size)
    for r in res:
        primer_b_results.append(r)
        primer_b_binding_check_len.append(len(primer_b_sequence))

    # checking various binding length
    for i in range(MIN_BINDING_LENGTH, BINDING_LENGTH_HI):
        p = primer_a_sequence[-i:]
        res = blast_genome(genome, "blastn", p, word_size=blast_word_size)
        for r in res:
            primer_a_results.append(r)
            primer_a_binding_check_len.append(len(p))

    # checking various binding length
    for i in range(MIN_BINDING_LENGTH, BINDING_LENGTH_HI):
        p = primer_b_sequence[-i:]
        res = blast_genome(genome, "blastn", p, word_size=blast_word_size)
        for r in res:
            primer_b_results.append(r)
            primer_b_binding_check_len.append(len(p))

    pcr_products = []
    uniq_products = {}
    for a_len, a_res in zip(primer_a_binding_check_len, primer_a_results):
        for b_len, b_res in zip(primer_b_binding_check_len, primer_b_results):
            product = compute_pcr_product(
                primer_a_sequence, a_len, a_res, primer_b_sequence, b_len, b_res
            )
            if product is not None:
                k = (product[0], a_res.fragment_id)
                if k not in uniq_products:
                    pcr_products.append(product)
                    uniq_products[k] = product

    if len(pcr_products) == 1:
        product, template_info = pcr_products[0]
        region = template_info["region"]
        fragment = template_info["fragment"]  # already an indexed fragment
        bp_lo, bp_hi = region
        return (
            product,
            primer_a_results,
            primer_b_results,
            dict(
                region=region,
                fragment_name=fragment.name,
                fragment_id=fragment.id,
                sequence=fragment.get_sequence(bp_lo=bp_lo, bp_hi=bp_hi),
                annotations=fragment.annotations(bp_lo=bp_lo, bp_hi=bp_hi),
            ),
        )
    else:
        return (None, primer_a_results, primer_b_results, None)


text:
package StaticString;

use strict;
use Hasher;

sub GenerateStrings($)
{
    my $stringsRef = shift;
    my %strings = %$stringsRef;

    my @result = ();

    while ( my ($name, $value) = each %strings ) {
        my $characterList = join("', '", split("", $value));
        push(@result, "static const UChar ${name}String16[] = { '$characterList', 0 };\n");
    }

    push(@result, "\n");

    while ( my ($name, $value) = each %strings ) {
        push(@result, "static const LChar ${name}String8[] = \"${value}\";\n");
    }

    push(@result, "\n");

    while ( my ($name, $value) = each %strings ) {
        my $length = length($value);
        my $hash = Hasher::GenerateHashValue($value);
        push(@result, <<END);
static StringImpl::StaticASCIILiteral ${name}Data = {
    ${name}String8,
    ${name}String16,
    StringImpl::StaticASCIILiteral::s_initialRefCount,
    $length,
    StringImpl::StaticASCIILiteral::s_initialFlags | (${hash} << StringImpl::StaticASCIILiteral::s_hashShift)
};
END
    }

    push(@result, "\n");

    while ( my ($name, $value) = each %strings ) {
        push(@result, "static StringImpl* ${name}Impl = reinterpret_cast<StringImpl*>(&${name}Data);\n");
    }

    push(@result, "\n");

    return join "", @result;
}

sub GenerateStringAsserts($)
{
    my $stringsRef = shift;
    my %strings = %$stringsRef;

    my @result = ();

    push(@result, "#ifndef NDEBUG\n");

    while ( my ($name, $value) = each %strings ) {
        push(@result, "    ${name}Impl->assertHashIsCorrect();\n");
    }

    push(@result, "#endif // NDEBUG\n");

    push(@result, "\n");

    return join "", @result;
}

1;


text:
package goexperiment

const RegabiReflect = false
const RegabiReflectInt = 0


text:
// ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;

namespace Microsoft.PSharp.TestingServices
{
    /// <summary>
    /// Interface to register interesting runtime operations.
    /// For race detection, the interesting operations are:
    /// 1. Reads and writes to the (shared) heap
    /// 2. Enqueues (posts) and dequeues (action begins)
    /// 3. Creation of a new machine
    /// In addition, this interface also allows clients to query
    /// the runtime for the currently running machine, and whether
    /// the runtime is in an action.
    /// </summary>
    public interface IRegisterRuntimeOperation
    {
        /// <summary>
        /// InAction[machineId.Value] = true iff the runtime executing an action
        /// in machine with Id machineId
        /// Reads and writes are instrumented only provided we're in an action.
        /// </summary>
        Dictionary<ulong, bool> InAction { get; set; }

        /// <summary>
        /// InMonitor = -1 iff the runtime is not inside a monitor
        /// and the monitor id otherwise
        /// </summary>
        long InMonitor { get; set; }

        /// <summary>
        /// Process a read to a heap location.
        /// </summary>
        /// <param name="source">The machine performing the read</param>
        /// <param name="sourceInformation"> Line number of this read</param>
        /// <param name="location">The base address for the heap location read</param>
        /// <param name="objHandle">The object handle</param>
        /// <param name="offset">The offset</param>
        /// <param name="isVolatile">Was the location declared volatile?</param>
        void RegisterRead(ulong source, string sourceInformation, UIntPtr location, UIntPtr objHandle, UIntPtr offset, bool isVolatile);

        /// <summary>
        /// Process a write to a heap location.
        /// </summary>
        /// <param name="source">The machine performing the write</param>
        /// <param name="sourceInformation"> Line number of this write</param>
        /// <param name="location">The base address for the heap location written</param>
        /// <param name="objHandle">The object handle</param>
        /// <param name="offset">The offset</param>
        /// <param name="isVolatile">Was the location declared volatile?</param>
        void RegisterWrite(ulong source, string sourceInformation, UIntPtr location, UIntPtr objHandle, UIntPtr offset, bool isVolatile);

        /// <summary>
        /// Process the enqueue of an event by a machine.
        /// </summary>
        /// <param name="source">The id of the machine that is the origin of the enqueue/post</param>
        /// <param name="target">The id of the machine receiving the event</param>
        /// <param name="e">The event sent</param>
        /// <param name="sequenceNumber">Is n if this is the n'th enqueue</param>
        void RegisterEnqueue(MachineId source, MachineId target, Event e, ulong sequenceNumber);

        /// <summary>
        /// Process the deq and begin of an action by a machine.
        /// </summary>
        /// <param name="source">The id of the machine that originally posted the event</param>
        /// <param name="target">The id of the machine processing the event</param>
        /// <param name="e">The event being processed</param>
        /// <param name="sequenceNumber">Is n if this is the n'th enqueue</param>
        void RegisterDequeue(MachineId source, MachineId target, Event e, ulong sequenceNumber);

        /// <summary>
        /// Update the internal data structures and vector clocks when a machine creates another machine.
        /// </summary>
        /// <param name="source">The id of the machine that is the creator.</param>
        /// <param name="target">The id of the machine that is freshly created.</param>
        void RegisterCreateMachine(MachineId source, MachineId target);

        /// <summary>
        /// Set the runtime an implementer should forward TryGetCurrentMachineId calls to.
        /// </summary>
        void RegisterRuntime(IMachineRuntime runtime);

        /// <summary>
        /// Return true if the runtime is currently executing a machine's action.
        /// If it is, write its id to the out parameter as a ulong.
        /// </summary>
        bool TryGetCurrentMachineId(out ulong machineId);

        /// <summary>
        /// Clear the internal state the reporter maintains.
        /// </summary>
        void ClearAll();
    }
}


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>T-Index</title>
<meta name="date" content="2015-02-13">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N O P Q R S T U V

T

terminaInventario() - Method in class gameshop.advance.controller.InventoryControllerSingleton

terminaInventario() - Method in interface gameshop.advance.interfaces.remote.factory.IInventarioControllerRemote

terminaPrenotazione() - Method in class gameshop.advance.controller.BookControllerSingleton

terminaPrenotazione() - Method in interface gameshop.advance.interfaces.remote.factory.IPrenotaProdottoRemote

toString() - Method in class gameshop.advance.config.Configuration

Ritorna tutti i dati di configurazione come stringa.

toString() - Method in class gameshop.advance.controller.valueData.AggiuntaProdotti

toString() - Method in class gameshop.advance.utility.IDProdotto

toString() - Method in class gameshop.advance.utility.Money

TotalObserver - Class in gameshop.advance.observer

Osservatore del totale da pagare di una transazione.

TotalObserver(IRemoteClient) - Constructor for class gameshop.advance.observer.TotalObserver

TransactionObserver - Class in gameshop.advance.observer

Observer della transazione.

TransactionObserver(IRemoteReservationClient) - Constructor for class gameshop.advance.observer.TransactionObserver

A B C D E F G H I L M N O P Q R S T U V

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="false" scanPeriod="60 seconds" debug="false">

	<property name="log_history_day" value="${springlearning.logback.log_history_day}" />
	<property name="log_history_hour" value="${springlearning.logback.log_history_hour}" />
	<property name="log_dir" value="${springlearning.logback.log_dir}" />
	<property name="log_pattern" value="%d{MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n%ex" />

	<!-- 全部日志 -->
	<appender name="all" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
			<level>INFO</level>
		</filter>
		<file>${log_dir}all.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log_dir}all.log.%d{yyyy-MM-dd}</fileNamePattern>
			<maxHistory>${log_history_day}</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>${log_pattern}</pattern>
		</encoder>
	</appender>

	<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
    	<!-- encoder 默认配置为PatternLayoutEncoder -->
    	<encoder>
      		<pattern>${log_pattern}</pattern>
    	</encoder>
  	</appender>

    <appender name="debug" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>DEBUG</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
		<file>${log_dir}debug.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log_dir}debug.log.%d{yyyy-MM-dd-HH}</fileNamePattern>
			<maxHistory>${log_history_hour}</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>${log_pattern}</pattern>
		</encoder>
	</appender>

  	<appender name="info" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>INFO</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
		<file>${log_dir}info.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log_dir}info.log.%d{yyyy-MM-dd}</fileNamePattern>
			<maxHistory>${log_history_day}</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>${log_pattern}</pattern>
		</encoder>
	</appender>

	<!-- 警告日志 -->
	<appender name="warn" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>WARN</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
		<file>${log_dir}warn.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log_dir}warn.log.%d{yyyy-MM-dd}</fileNamePattern>
			<maxHistory>${log_history_day}</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>${log_pattern}</pattern>
<!-- 			<immediateFlush>false</immediateFlush> -->
		</encoder>
	</appender>

	<!-- 错误日志 -->
	<appender name="error" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>ERROR</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
		<file>${log_dir}error.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log_dir}error.log.%d{yyyy-MM-dd}</fileNamePattern>
			<maxHistory>${log_history_day}</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>${log_pattern}</pattern>
		</encoder>
	</appender>

	<!-- 定时任务INFO日志 -->
	<appender name="timeTaskInfo" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>INFO</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
		<file>${log_dir}time-task-info.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log_dir}time-task-info.log.%d{yyyy-MM-dd}</fileNamePattern>
			<maxHistory>${log_history_day}</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>${log_pattern}</pattern>
		</encoder>
	</appender>

	<!-- 定时任务ERROR日志 -->
	<appender name="timeTaskError" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
			<level>ERROR</level>
			<onMatch>ACCEPT</onMatch>
			<onMismatch>DENY</onMismatch>
		</filter>
		<file>${log_dir}time-task-error.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<fileNamePattern>${log_dir}time-task-error.log.%d{yyyy-MM-dd}</fileNamePattern>
			<maxHistory>${log_history_day}</maxHistory>
		</rollingPolicy>
		<encoder>
			<pattern>${log_pattern}</pattern>
		</encoder>
	</appender>

    <logger name="org.springlearning" level="${springlearning.logback.minlevel}" additivity="false">
        <appender-ref ref="debug" />
        <appender-ref ref="info" />
        <appender-ref ref="warn" />
        <appender-ref ref="error" />
    </logger>

    <logger name="timeTask" level="INFO" additivity="false">
    	<appender-ref ref="timeTaskInfo" />
    	<appender-ref ref="timeTaskError" />
    </logger>

	<root level="INFO">
		<appender-ref ref="all" />
	</root>

</configuration>


text:
'''
  This file is part of the PyPhantomJS project.

  Copyright (C) 2011 James Roe <roejames12@hotmail.com>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import os
import codecs

from plugincontroller import add_action

from PyQt4.QtCore import qWarning, pyqtSlot

@pyqtSlot(str, str, result=bool)
@pyqtSlot(str, str, str, result=bool)
def saveToFile(self, text, fileName, mode='a'):
    if not os.path.isabs(fileName):
        scriptDir = os.path.dirname(os.path.abspath(self.m_scriptFile))
        fileName = os.path.join(scriptDir, fileName)

    try:
        with codecs.open(fileName, mode, 'utf-8') as f:
            f.write(text)
    except IOError:
        qWarning('phantom.saveToFile - Could not open file \'%s\' for writing' % fileName)
        return False

    return True

@add_action('Phantom')
def run_saveToFile(_locals):
    _locals.saveToFile = saveToFile


text:
package zmaster587.advancedRocketry.tile.multiblock.energy;

import io.netty.buffer.ByteBuf;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import zmaster587.advancedRocketry.api.AdvancedRocketryBlocks;
import zmaster587.advancedRocketry.api.Configuration;
import zmaster587.advancedRocketry.api.satellite.SatelliteBase;
import zmaster587.advancedRocketry.dimension.DimensionManager;
import zmaster587.advancedRocketry.dimension.DimensionProperties;
import zmaster587.advancedRocketry.item.ItemSatelliteIdentificationChip;
import zmaster587.libVulpes.LibVulpes;
import zmaster587.libVulpes.api.IUniversalEnergyTransmitter;
import zmaster587.libVulpes.block.BlockMeta;
import zmaster587.libVulpes.inventory.modules.ModuleBase;
import zmaster587.libVulpes.inventory.modules.ModuleText;
import zmaster587.libVulpes.network.PacketHandler;
import zmaster587.libVulpes.network.PacketMachine;
import zmaster587.libVulpes.tile.multiblock.TileMultiBlock;
import zmaster587.libVulpes.tile.multiblock.TileMultiPowerProducer;
import zmaster587.libVulpes.util.Vector3F;

import java.util.LinkedList;
import java.util.List;

public class TileMicrowaveReciever extends TileMultiPowerProducer implements ITickable {

	static final BlockMeta iron_block = new BlockMeta(AdvancedRocketryBlocks.blockSolarPanel);
	static final Object[][][] structure = new Object[][][] {
		{
			{iron_block, '*', '*', '*', iron_block},
			{'*', iron_block, iron_block, iron_block, '*'},
			{'*', iron_block, 'c', iron_block,'*'},
			{'*', iron_block, iron_block, iron_block, '*'},
			{iron_block, '*', '*', '*', iron_block},
		}};

	List<Long> connectedSatellites;
	boolean initialCheck;
	int powerMadeLastTick, prevPowerMadeLastTick;
	ModuleText textModule;
	public TileMicrowaveReciever() {
		connectedSatellites = new LinkedList<Long>();
		initialCheck = false;
		textModule = new ModuleText(40, 20, LibVulpes.proxy.getLocalizedString("msg.microwaverec.notgenerating"), 0x2b2b2b);
	}

	@Override
	public List<ModuleBase> getModules(int ID, EntityPlayer player) {
		List<ModuleBase> modules = super.getModules(ID, player);

		modules.add(textModule);

		return modules;
	}

	@Override
	public AxisAlignedBB getRenderBoundingBox() {
		return super.getRenderBoundingBox().grow(0, 2000, 0).offset(0, 1000, 0);
	}

	@Override
	public boolean shouldHideBlock(World world, BlockPos pos, IBlockState tile) {
		return false;
	}

	@Override
	public Object[][][] getStructure() {
		return structure;
	}

	@Override
	public List<BlockMeta> getAllowableWildCardBlocks() {
		List<BlockMeta> blocks = super.getAllowableWildCardBlocks();

		blocks.addAll(TileMultiBlock.getMapping('I'));
		blocks.add(iron_block);
		blocks.addAll(TileMultiBlock.getMapping('p'));

		return blocks;
	}

	@Override
	public String getMachineName() {
		return "tile.microwaveReciever.name";
	}

	public int getPowerMadeLastTick() {
		return powerMadeLastTick;
	}

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

		List list = new LinkedList<Long>();

		for(IInventory inv : itemInPorts) {
			for(int i = 0; i < inv.getSizeInventory(); i++) {
				ItemStack stack = inv.getStackInSlot(i);
				if(stack != null && stack.getItem() instanceof ItemSatelliteIdentificationChip) {
					ItemSatelliteIdentificationChip item = (ItemSatelliteIdentificationChip)stack.getItem();
					list.add(item.getSatelliteId(stack));
				}
			}
		}

		connectedSatellites = list;

	}

	@Override
	public void update() {

		if(!initialCheck && !world.isRemote) {
			completeStructure = attemptCompleteStructure(world.getBlockState(pos));
			onInventoryUpdated();
			initialCheck = true;
		}

		if(!isComplete())
			return;

		//Periodically check for obstructing blocks above the panel
		if(!world.isRemote && getPowerMadeLastTick() > 0 && world.getTotalWorldTime() % 100 == 0) {
			Vector3F<Integer> offset = getControllerOffset(getStructure());

			List<Entity> entityList = world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(this.getPos().getX() - offset.x, this.getPos().getY(), this.getPos().getZ() - offset.z, this.getPos().getX() - offset.x + getStructure()[0][0].length, 256, this.getPos().getZ() - offset.z + getStructure()[0].length));

			for(Entity e : entityList) {
				e.setFire(5);
			}

			for(int x=0 ; x < getStructure()[0][0].length; x++) {
				for(int z=0 ; z < getStructure()[0].length; z++) {

					BlockPos pos2;
					IBlockState state = world.getBlockState(pos2 = (world.getHeight(pos.add(x - offset.x, 128, z - offset.z)).add(0, -1, 0)));

					if(pos2.getY() > this.getPos().getY()) {
						if(!world.isAirBlock(pos2.add(0,1,0))) {
							world.setBlockToAir(pos2);
							world.playSound((double)pos2.getX(), (double)pos2.getY(), (double)pos2.getZ(), new SoundEvent(new ResourceLocation("fire.fire")), SoundCategory.BLOCKS, 1f, 3f, false);
						}
					}
				}
			}
		}

		DimensionProperties properties;
		if(!world.isRemote && (DimensionManager.getInstance().isDimensionCreated(world.provider.getDimension()) || world.provider.getDimension() == 0)) {
			properties = DimensionManager.getInstance().getDimensionProperties(world.provider.getDimension());

			int energyRecieved = 0;

			if(enabled) {
				for(long lng : connectedSatellites) {
					SatelliteBase satellite =  properties.getSatellite(lng);

					if(satellite instanceof IUniversalEnergyTransmitter) {
						energyRecieved += ((IUniversalEnergyTransmitter)satellite).transmitEnergy(EnumFacing.UP, false);
					}
				}
			}
			powerMadeLastTick = (int) (energyRecieved*Configuration.microwaveRecieverMulitplier);

			if(powerMadeLastTick != prevPowerMadeLastTick) {
				prevPowerMadeLastTick = powerMadeLastTick;
				PacketHandler.sendToNearby(new PacketMachine(this, (byte)1), world.provider.getDimension(),pos, 128);

			}
			producePower(powerMadeLastTick);
		}
		if(world.isRemote)
			textModule.setText(LibVulpes.proxy.getLocalizedString("msg.microwaverec.generating") + powerMadeLastTick + " " + LibVulpes.proxy.getLocalizedString("msg.powerunit.rfpertick"));
	}

	@Override
	public SPacketUpdateTileEntity getUpdatePacket() {
		NBTTagCompound nbt = new NBTTagCompound();
		nbt.setBoolean("canRender", canRender);
		nbt.setInteger("amtPwr", powerMadeLastTick);
		writeNetworkData(nbt);
		return new SPacketUpdateTileEntity(pos, 0, nbt);
	}

	@Override
	public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) {
		NBTTagCompound nbt = pkt.getNbtCompound();

		canRender = nbt.getBoolean("canRender");
		powerMadeLastTick = nbt.getInteger("amtPwr");
		readNetworkData(nbt);
	}

	@Override
	public NBTTagCompound getUpdateTag() {
		NBTTagCompound nbt = new NBTTagCompound();
		nbt.setBoolean("canRender", canRender);
		nbt.setInteger("amtPwr", powerMadeLastTick);
		writeToNBT(nbt);
		return nbt;
	}

	@Override
	public void handleUpdateTag(NBTTagCompound nbt) {
		powerMadeLastTick = nbt.getInteger("amtPwr");
		canRender = nbt.getBoolean("canRender");
		readNetworkData(nbt);
	}

	@Override
	public void writeDataToNetwork(ByteBuf out, byte id) {
		super.writeDataToNetwork(out, id);

		if(id == 1) {
			out.writeInt(powerMadeLastTick);
		}
	}

	@Override
	public void readDataFromNetwork(ByteBuf in, byte packetId,
			NBTTagCompound nbt) {
		super.readDataFromNetwork(in, packetId, nbt);

		if(packetId == 1) {
			nbt.setInteger("amtPwr", in.readInt());
		}
	}

	@Override
	public void useNetworkData(EntityPlayer player, Side side, byte id,
			NBTTagCompound nbt) {
		super.useNetworkData(player, side, id, nbt);

		if(id == 1) {
			powerMadeLastTick = nbt.getInteger("amtPwr");
		}
	}

	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound nbt) {
		super.writeToNBT(nbt);

		int[] intArray = new int[connectedSatellites.size()*2];

		for( int i =0; i < connectedSatellites.size()*2; i += 2 ) {
			connectedSatellites.get(i/2);
			intArray[i] = (int) (connectedSatellites.get(i/2) & 0xFFFFFFFF);
			intArray[i+1] = (int) ((connectedSatellites.get(i/2) >>> 32) & 0xFFFFFFFF);
		}

		nbt.setIntArray("satilliteList", intArray);

		return nbt;
	}

	@Override
	public void readFromNBT(NBTTagCompound nbt) {
		super.readFromNBT(nbt);

		int intArray[] = nbt.getIntArray("satilliteList");
		connectedSatellites.clear();
		for( int i =0; i < intArray.length/2; i+=2 ) {
			connectedSatellites.add(intArray[i] | (((long)intArray[i+1]) << 32));
		}

	}

}


text:
@protocol UIViewFocusDelegate<NSObject>

@optional

-(BOOL)canBecomeFocusedForView:(UIView*)view withSuperValue:(BOOL)superValue;

-(void)setNeedsFocusUpdateForView:(UIView*)view;

-(void)updateFocusIfNeededForView:(UIView*)view;

-(BOOL)shouldUpdateFocusInContext:(UIFocusUpdateContext *)context forView:(UIView*)view withSuperValue:(BOOL)superValue;

-(void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator forView:(UIView*)view;

-(UIView *)preferredFocusedViewForView:(UIView*)view withSuperValue:(UIView*)superValue;

@end

@interface UIViewWithFocusDelegate : UIView

@property (nonatomic, weak) NSObject<UIViewFocusDelegate>* focusDelegate;

@end


text:
package com.gentics.mesh.core.migration;

import java.util.List;

import com.gentics.mesh.context.BranchMigrationContext;

import com.gentics.mesh.core.data.node.HibNode;
import io.reactivex.Completable;

public interface BranchMigration {

	/**
	 * Migrate all nodes from one branch to the other
	 *
	 * @param context
	 * @return
	 */
	Completable migrateBranch(BranchMigrationContext context);

	/**
	 * Called before batch migrating to prepare the nodes for the migration.
	 * The returned nodes are the one that will be used for the migration
	 * @param nodes
	 * @return
	 */
	default List<? extends HibNode> beforeBatchMigration(List<? extends HibNode> nodes) {
		return nodes;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="app_name">Slide</string>

  <string name="tutorial_text">SLIDE\n\nChaque paragraphe\nest une diapo\n\nCeci est une diapo\n.\navec une ligne vide\n\nTouchez l\'aperçu\npour commencer la présentation.\nVous pouvez également choisir\n un ensemble de couleurs ici.\n\nVoilà !\n\nN\'oubliez pas d\'exporter\nau format PDF et de partager.</string>

  <string name="pdf_name_prefix">Slide-</string>
  <string name="failed_export_pdf">L\'export au format PDF a échoué</string>
  <string name="default_new_doc_name">NewSlideDoc</string>
  <string name="failed_open_doc">L\'ouverture du document a échoué</string>
  <string name="failed_save_doc">Le document n\'a pas été trouvé</string>

  <string name="dlg_style_picker_title">Choisir un style</string>
  <string name="btn_ok">Ok</string>

  <string name="om_open">Ouvrir</string>
  <string name="om_insert_image">Insérer une image</string>
  <string name="om_style">Style</string>
  <string name="om_settings">Réglages</string>
  <string name="om_export_pdf">Exporter en PDF</string>
</resources>


text:
konyLua.ScrollBox = function(bconfig, lconfig, pspconfig) {

	konyLua.ScrollBox.baseConstructor.call(this, bconfig, lconfig, pspconfig);

	this.totalWt = 0;
	this.position = bconfig.position || constants.BOX_POSITION_AS_NORMAL;
	this.enablescrollbypage = bconfig.enablescrollbypage || false;
	this.scrolldirection = bconfig.scrolldirection || constants.SCROLLBOX_SCROLL_HORIZONTAL;
	this.isvisible = bconfig.isvisible === undefined ? true : bconfig.isvisible;
	this.showscrollbars = bconfig.showscrollbars === undefined ? true : bconfig.showscrollbars;
	this.scrollbar = this.showscrollbars ? "scrollbar" : "none";

	this.containerheight = lconfig.containerheight;
	this.containerheightreference = lconfig.containerheightreference;

	this.scrollarrowconfig = (pspconfig.scrollarrowconfig && (pspconfig.scrollarrowconfig[0] || pspconfig.scrollarrowconfig[1] || pspconfig.scrollarrowconfig[2] || pspconfig.scrollarrowconfig[3])) ? pspconfig.scrollarrowconfig : undefined;
	if (this.scrollarrowconfig) this.scrollbar = "arrows";

	if (this.scrollarrowconfig && this.scrollarrowconfig.length >= 4) {
	this.leftarrowimage = this.scrollarrowconfig[1];
	this.toparrowimage = this.scrollarrowconfig[2];
	this.rightarrowimage = this.scrollarrowconfig[3];
	this.bottomarrowimage = this.scrollarrowconfig[4];
	}

	// scrollingevents
	this.scrollingevents = bconfig.scrollingEvents;

	this.wType = "ScrollBox";
	this.name = "konyLua.ScrollBox";
};

kony.inherits(konyLua.ScrollBox, konyLua.Box);

konyLua.ScrollBox.prototype.scrollToBeginning = function(){
  $KW.ScrollBox.scrollToBegining(this);
};

konyLua.ScrollBox.prototype.scrollToEnd = function(){
  $KW.ScrollBox.scrollToBegining(this);
};


text:
import {find, pick, uniq} from 'lodash';
import {SparkPlugin} from '@ciscospark/spark-core';
import querystring from 'querystring';

const Team = SparkPlugin.extend({
  namespace: `Team`,

  /**
   * Move an existing group conversation into a team.
   * @param {TeamObject} team
   * @param {ConversationObject} conversation
   * @param {Object} activity Reference to the activity that will eventually be
   * posted. Use this to (a) pass in e.g. clientTempId and (b) render a
   * provisional activity
   * @returns {Promise} Resolves with the add activity
   */
  addConversation(team, conversation, activity) {
    return this._ensureGeneralConversation(team)
      .then((generalConversation) => this.spark.conversation.prepare(activity, {
        verb: `add`,
        target: this.spark.conversation.prepareConversation(generalConversation),
        object: {
          id: conversation.id,
          objectType: `conversation`
        },
        kmsMessage: {
          method: `create`,
          uri: `/authorizations`,
          resourceUri: conversation.kmsResourceObjectUrl,
          userIds: [generalConversation.kmsResourceObjectUrl]
        }
      }))
      .then((a) => this.spark.conversation.submit(a));
  },

  /**
   * Add a member to a team
   * @param {TeamObject} team
   * @param {Object} participant
   * @param {Object} activity Reference to the activity that will eventually be
   * posted. Use this to (a) pass in e.g. clientTempId and (b) render a
   * provisional activity
   * @returns {Promise} Resolves with activity that was posted
   */
  addMember(team, participant, activity) {
    return this._ensureGeneralConversation(team)
      .then((generalConversation) => this.spark.conversation.add(generalConversation, participant, activity));
  },

  /**
   * Create a team
   * @param {NewTeamObject} params
   * @param {string} params.displayName
   * @param {string} params.summary
   * @param {Array} params.participants
   * @returns {Promise} Resolves with the created team
   */
  create(params) {

    if (!params.displayName) {
      return Promise.reject(new Error(`\`params.displayName\` is required`));
    }

    if (!params.participants || params.participants.length === 0) {
      return Promise.reject(new Error(`\`params.participants\` is required`));
    }

    return Promise.all(params.participants.map((participant) => this.spark.user.asUUID(participant, {create: true})))
      .then((participants) => {
        participants.unshift(this.spark.device.userId);
        params.participants = uniq(participants);
      })
      .then(() => this._prepareTeam(params))
      .then((payload) => this.spark.request({
        method: `POST`,
        service: `conversation`,
        resource: `teams`,
        body: payload
      }))
      .then((res) => res.body);
  },

  /**
   * Create a conversation within a team. Currently does not support
   * activities besides add (ie no post or share activities).
   * @param {TeamObject} team
   * @param {NewConversationObject} params
   * @param {string} params.displayName
   * @param {string} params.summary
   * @param {Array} params.participants
   * @param {Object} options
   * @param {boolean} options.includeAllTeamMembers
   * @returns {Promise} Resolves with the newly created conversation
   */
  createConversation(team, params, options) {
    options = options || {};

    if (!params.displayName) {
      return Promise.reject(new Error(`\`params.displayName\` is required`));
    }

    return this._inferTeamUrl(team)
      .then(() => this._ensureGeneralConversation(team))
      .then((generalConversation) => Promise.all(
        params.participants.map((participant) => this.spark.user.asUUID(participant, {create: true}))
      )
        .then((participants) => {
          participants.unshift(this.spark.device.userId);
          params.participants = uniq(participants);
        })
        .then(() => this._prepareTeamConversation(generalConversation, params))
      )
      .then((payload) => this.spark.request({
        method: `POST`,
        uri: `${team.url}/conversations`,
        resource: `teams`,
        qs: pick(options, `includeAllTeamMembers`),
        body: payload
      }))
      .then((res) => res.body);
  },

  /**
   * Retrieve a single team
   * @param {Object|Team~TeamObject} team
   * @param {string} team.id
   * @param {Object} options
   * @param {boolean} options.includeTeamConversations
   * @param {boolean} options.includeTeamMembers
   * @returns {Promise} Resolves with the requested team
   */
  get(team, options) {
    options = options || {};

    const params = Object.assign({
      includeTeamConversations: false,
      includeTeamMembers: false
    }, options);

    return this._inferTeamUrl(team)
      .then(() => this.spark.request({
        uri: team.url,
        qs: params
      }))
      .then((res) => this._recordUUIDs(res.body)
        .then(() => res.body));
  },

  /**
   * Get the list of conversations for a particular team
   * @param {TeamObject} team
   * @returns {Promise} Resolves with an array of conversations
   */
  listConversations(team) {
    return this._inferTeamUrl(team)
      .then(() => this.spark.request({
        uri: `${team.url}/conversations`
      }))
      .then((res) => res.body.items);
  },

  /**
   * Join a team conversation
   * @param {TeamObject} team
   * @param {ConversationObject} conversation
   * @returns {Promise} Resolves with the conversation
   */
  joinConversation(team, conversation) {
    return this.spark.request({
      method: `POST`,
      uri: `${team.url}/conversations/${conversation.id}/participants`
    })
      .then((res) => res.body);
  },

  /**
   * Retrieve all teams
   * @param {Object} options
   * @param {boolean} options.includeTeamConversations
   * @param {boolean} options.includeTeamMembers
   * @returns {Promise} Resolves with the requested teams
   */
  list(options) {
    options = options || {};

    const params = Object.assign({
      includeTeamConversations: false,
      includeTeamMembers: false
    }, options);

    return this.spark.request({
      api: `conversation`,
      resource: `teams`,
      qs: params
    })
      .then((res) => Promise.all(res.body.items.map((team) => this._recordUUIDs(team)))
        .then(() => res.body.items));
  },

  /**
   * Remove a member from a team
   * @param {TeamObject} team
   * @param {Object} participant
   * @param {Object} activity Reference to the activity that will eventually be
   * posted. Use this to (a) pass in e.g. clientTempId and (b) render a
   * provisional activity
   * @returns {Promise} Resolves with activity that was posted
   */
  removeMember(team, participant, activity) {
    return this._ensureGeneralConversation(team)
      .then((generalConversation) => this.spark.conversation.leave(generalConversation, participant, activity));
  },

  /**
   * Remove a team conversation from a team.
   * @param {TeamObject} team
   * @param {ConversationObject} conversation to be removed
   * @param {Object} activity Reference to the activity that will eventually be
   * posted. Use this to (a) pass in e.g. clientTempId and (b) render a
   * provisional activity
   * @returns {Promise} Resolves with the leave activity
   */
  removeConversation(team, conversation, activity) {
    return this._ensureGeneralConversation(team)
      .then((generalConversation) => {
        const properties = {
          verb: `remove`,
          object: pick(conversation, `id`, `url`, `objectType`),
          target: pick(generalConversation, `id`, `url`, `objectType`),
          kmsMessage: {
            method: `delete`,
            uri: `<KRO>/authorizations?${querystring.stringify({authId: conversation.id})}`
          }
        };

        return this.spark.conversation.prepare(activity, properties);
      })
      .then((a) => this.spark.conversation.submit(a));
  },

  /**
   * Update the displayName, summary, or teamColor field for a team.
   * @param {TeamObject} team to be updated
   * @param {Object} object with updated displayName, summary, and/or teamColor
   * @param {Object} activity Reference to the activity that will eventually be
   * posted. Use this to (a) pass in e.g. clientTempId and (b) render a
   * provisional activity
   * @returns {Promise} Resolves with posted activity
   */
  update(team, object, activity) {
    return this.spark.conversation.update(team, object, activity);
  },

  _ensureGeneralConversation(team) {
    if (!team.generalConversationUuid) {
      return Promise.reject(new Error(`\`team.generalConversationUuid\` must be present`));
    }

    if (team.conversations.items.length) {
      const generalConversation = find(team.conversations.items, {id: team.generalConversationUuid});

      if (generalConversation) {
        return Promise.resolve(generalConversation);
      }
    }

    return this.spark.conversation.get({id: team.generalConversationUuid});
  },

  _inferTeamUrl(team) {
    if (!team.url && team.id) {
      return this.spark.device.getServiceUrl(`conversation`)
        .then((url) => {
          team.url = `${url}/teams/${team.id}`;
          /* istanbul ignore else */
          if (process.env.NODE_ENV !== `production`) {
            this.logger.warn(`team: inferred team url from conversation id; please pass whole team objects to Team methods`);
          }
          return team;
        });
    }

    return Promise.resolve(team);
  },

  _prepareTeam: function _prepareTeam(params) {
    const payload = this.spark.conversation._prepareConversationForCreation(params);

    payload.objectType = `team`;

    if (params.summary) {
      payload.summary = params.summary;
    }

    return Promise.resolve(payload);
  },

  _prepareTeamConversation(teamConversation, params) {
    if (!teamConversation.kmsResourceObjectUrl) {
      return Promise.reject(new Error(`Team general conversation must have a KRO`));
    }

    const payload = this.spark.conversation._prepareConversationForCreation(params);

    // Push the general conversation KRO on so that team members can
    // decrypt the title of this open room without joining it.
    payload.kmsMessage.userIds.push(teamConversation.kmsResourceObjectUrl);
    return Promise.resolve(payload);
  },

  _recordUUIDs(team) {
    if (!team.teamMembers || !team.teamMembers.items) {
      return Promise.resolve(team);
    }

    return Promise.all(team.teamMembers.items.map((participant) => this.spark.user.recordUUID(participant)));
  }

});

/**
 * Assign or unassign a team member to be a moderator of a team
 * @param {TeamObject} team
 * @param {Object} participant
 * @param {Object} activity
 * @returns {Promise} Resolves with activity that was posted
 */
[
  `assignModerator`,
  `unassignModerator`
].forEach((verb) => {
  Team.prototype[verb] = function submitModerationChangeActivity(team, member, activity) {
    return this._ensureGeneralConversation(team)
      .then((teamConversation) => this.spark.conversation[verb](teamConversation, member, activity));
  };
});

/**
 * Archive or unarchive a team or team conversation.
 * @param {TeamObject|ConversationObject} target team or team conversation that should be archived
 * @param {Object} activity Reference to the activity that will eventually be
 * posted. Use this to (a) pass in e.g. clientTempId and (b) render a
 * provisional activity
 * @returns {Promise} Resolves with the posted activity
 */
[
  `archive`,
  `unarchive`
].forEach((verb) => {
  Team.prototype[verb] = function submitArchiveStateChangeActivity(target, activity) {
    if (!target.objectType) {
      return Promise.reject(new Error(`\`target.objectType\` is required`));
    }

    const properties = {
      verb,
      object: pick(target, `id`, `url`, `objectType`),
      target: pick(target, `id`, `url`, `objectType`)
    };

    return this.spark.conversation.prepare(activity, properties)
      .then((a) => this.spark.conversation.submit(a));
  };
});

export default Team;


text:
#ifndef __ARCH_LINKER_H
#define __ARCH_LINKER_H

#include <util.h>

/* code that is linked to physical addresses */
#define PHYS_CODE SECTION(".phys.text")

/* code that is only used during kernel bootstrapping */
#define BOOT_CODE SECTION(".boot.text")

/* node-local data that is only used during kernel bootstrapping */
#define BOOT_DATA SECTION(".boot.node")

/* global data (shared by all nodes) but only used during kernel bootstrapping */
#define BOOT_DATA_GLOB SECTION(".boot.glob")

/* global data (shared by all nodes) */
#define DATA_GLOB SECTION(".glob")

#endif


text:
Parallelspace ModelMate data extensions to the ArchiMate language for Enterprise Architecture

COPYRIGHT © 2016-2017 by Michael Herman, Toronto Canada. All rights reserved. Applies to all the contents of this repository.

The files in this repository are free for you to use subject to the BSD 2-part (Simplified) license attached to this repository.

This repository over time will include several different collections of files.  Currently, this repository contains:
- Parallelspace ModelMate Master Datasets (CSV, MS Excel 2016, MS Access 2016, and Neo4j CQL formats)

# Parallelspace ModelMate Master Datasets

Each new version of the Parallelspace ModelMate Master Dataset will be published in its own folder.

The current version (and folder name) is: ModelMate30_Parallelspace/Parallelspace_ModelMate_MasterDataset_Complete10

URL: https://github.com/mwherman2000/ModelMate30_Parallelspace/tree/master/Parallelspace_ModelMate_MasterDataset_Complete10

There are 5 files of interest (in other words, ignore any odd looking files):

- Parallelspace_ModelMate_MasterDatasets_CompleteXX.csv - MS Excel 2016 CSV-format text file containing the current ModelMate Master Dataset
- Parallelspace_ModelMate_MasterDatasets_CompleteXX.csv - MS Excel 2016 Workbook containing the current ModelMate Master Dataset
- Parallelspace_ModelMate_MasterDatasets_CompleteXX.accdb - MS Access 2016 version of the ModelMate Master Dataset CSV file
- Parallelspace_ModelMate_MasterDatasets_CompleteXX.cql - Neo4j Cypher Query Language (CQL) version of the ModelMate Master Dataset CSV file
- Parallelspace_ModelMate_MasterDatasets_CompleteXX.zip - Compressed archive containing the above 4 files

Best regards,
- Michael Herman (Toronto)
- Parallelspace Corporation
- mwherman@parallelspace.net

# Credits, Copyrights and Trademarks

1. ArchiMate is a registered trademark of The Open Group
2. The primary data source for this project is the Mastering ArchiMate blog article "The ArchiMate 3.0 Relations Table…" (https://masteringarchimate.com/2017/02/07/the-archimate-3-0-relations-table/). Thank you to Gerben Wierda (https://www.linkedin.com/in/gerbenwierda/) for leading the creation of the Mastering ArchiMate master dataset for ArchiMate 3.0.
3. A secondary data source for the Archi project (https://github.com/archimatetool/archi) - in particular, the relationships.xml data file (https://github.com/archimatetool/archi/tree/master/com.archimatetool.model/model).
4. Parallelspace, ModelMate, and Parallelspace ModelMate are trademarks of Parallelspace Corporation, Toronto, Canada.